几个算法基础
1. 求1-N的和:
def sum1(self, sum) sum = 0 val = 1 for val in range(n - 1): sum += val val += 1
求数组数据的和
def sum1(self, a): sum = 0 i = 0 size = len(a) for i in range(size): sum += a[i] i += 1 return sum
2. 求斐波那契数列
# 非递归 def fibs(n): a = [1, 1] for i in range(n - 2): a.append(a[-2] + a[-1]) return a[n-1] print(fibs(n = 5))
# 递归
def fibs(n):
if n < 1:
return 0
elif n == 1:
return 1
return fibs(n - 2) + fibs(n - 1)
print(fibs(6))
3. 求最大最小值
def maxmin(self, a): max = a[0] i = 1 size = len(a) for i in range(size): if a[i] > max: max = a[i] i += 1 return max
4. 为数组元素排序(将数组SCORE名次降序保存到数组RANK中)
class Solution(object): def rank1(self, SCORE): size = len(SCORE) RANK = [1, 1, 1, 1, 1] i = 0 for i in range(0, size): j = 0 for j in range(0, size): if SCORE[i] < SCORE[j]: RANK[i] += 1 j += 1 i += 1 return RANK
5. 二维数组的操作(求二维数组不同行的总和)
class Solution(object): def dyadic_array(self, SCORE): i = 0 n = len(SCORE) for i in range(0, n): SCORE[i][3] = 0 j= 0 while j < 3: SCORE[i][3] += SCORE[i][j] j += 1 print(SCORE[i][3]) i += 1 if __name__ == "__main__": s = Solution() print(s.dyadic_array(SCORE = [[11, 12, 13, 0], [21, 22, 23, 0], [31, 32, 33, 0]]))
6. 欧几里得互除法&辗转相除法(求两数最大公约数)
class Solution(object): def dyadic_array(self, X, Y): R = X % Y while R != 0: X = Y Y = R R = X % Y GCD = Y print(GCD)