Python经典数学算法

i = 2
while(i < 100):
   j = 2
   while(j <= (i/j)):
      if not(i%j): break
      j = j + 1
   if (j > i/j) : print i, " 是素数"
   i = i + 1
 
print "Good bye!"

Python素数

def power(x, n):
    s = 1
    while n > 0:
        n = n - 1
        s = s * x
    return s

Python的n次方

def calc(numbers):
    sum = 0
    for n in numbers:
        sum = sum + n * n
    return sum

Python平方相加

def fact(n):
    if n==1:
        return 1
    return n * fact(n - 1)

Python的n!

def fact(n):
    if n == 1:
        return 1
    return n * fact(n-1)

print('fact(1) =', fact(1))
print('fact(5) =', fact(5))
print('fact(10) =', fact(10))

# 利用递归函数移动汉诺塔:
def move(n, a, b, c):
    if n == 1:
        print('move', a, '-->', c)
    else:
        move(n-1, a, c, b)
        move(1, a, b, c)
        move(n-1, b, a, c)

move(4, 'A', 'B', 'C')

Python汉诺塔的移动

def fib(max):
    n, a, b = 0, 0, 1
    while n < max:
        print(b)
        a, b = b, a + b
        n = n + 1
    return 'done'

# a, b = b, a + b
# 相当于
# t = (b, a + b) # t是一个tuple
# a = t[0]
# b = t[1]

Python斐波那契数列

你可能感兴趣的:(python,开发语言)