1. 程式人生 > >幾個算法基礎

幾個算法基礎

size cnblogs pen array 二維 object return 二維數組 min

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(self, num):
    fib = [0, 1]
    for i in range(num - 2):
        fib.append(fib[-2] + fib[-1])  #  在末尾添加值
    return fib

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)

幾個算法基礎