码迷,mamicode.com
首页 > 编程语言 > 详细

几个算法基础

时间:2017-05-25 23:21:08      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:turn   val   算法基础   维数   除法   div   添加   blog   最小值   

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)

 

几个算法基础

标签:turn   val   算法基础   维数   除法   div   添加   blog   最小值   

原文地址:http://www.cnblogs.com/llw1121/p/6858641.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!