古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?
嗯?这个怎么这么跟斐波那契数列相像呢?
def fib(n):
if n == 1:
return [1]
if n == 2:
return [1,1]
fib_list = [1,1]
for index in range(2,n):
fib_list.append(fib_list[-1] + fib_list[-2])
return fib_list
print(fib(3))
判断101-200之间有多少个素数,并输出所有素数。
素数曾称质数。一个大于1的正整数,如果除了1和它本身以外,不能被其他正整数整除,就叫素数
import math
for index in range(101,201):
leap = 1
for i in range(2,int(math.sqrt(index))+1):
if index % i == 0:
leap = 0
break
if leap == 1:
print(index)
打印所有的水仙花数。
"水仙花数"是指一个三位数,其各位数字立方和等于该数本身。例如:153是一个"水仙花数",因为153=1的三次方+5的三次方+3的三次方。
for index in range(100,1000):
Bit = index % 10
TenPlace = index // 10 % 10
HundredBit = index // 100
if index == Bit ** 3 + TenPlace ** 3 + HundredBit ** 3:
print('%s is the number of daffodils'%index)
将一个正整数分解质因数
答案不是很满意,但是水平有限,先这样,以后水平提高了在改进。
def Factorization(num):
while num != 1:
for index in range(2,num+1):
if num % index == 0:
num //= index
if num == 1:
print(index)
else:
print('{} *'.format(index) )
break
Factorization(10)
def Factorization(num):
for index in range(2,num+1):
if num % index == 0:
print(index)
break
num //= index
if num == 1:
exit()
Factorization(num)
Factorization(10)
利用条件运算符的嵌套来完成此题:学习成绩>=90分的同学用A表示,60-89分之间的用B表示,60分以下的用C表示。
score = input('please input score:')
if score.isdecimal():
score = int(score)
if score >= 90:
print("Excellent! Get A")
elif score >= 60:
print("Pretty good! Get B")
else:
print("Come on. Only get C")
else:
print("please input right score!")