学习目标:
1.编程实现Fibonacci求值; 2.编程实现百钱百鸡; 3.编程实现有趣的24点。
学习内容:
示例一 求Fibonacci第20项的值。  思路:已知第一项和第二项为1,以后的每一项都是前两项的和。
方法一 代码演示:
first = 1
second = 1
for x in range(20 - 2):
next = first + second
print(next,end =" ")
first = second
second = next
运行结果演示:  方法二 我们利用列表,求出列表最后两项的和并添加到列表当中,已知循环到第20项即可。
代码演示:
ls = [1,1]
for x in range(18):
new = ls[-1] + ls[-2]
ls.append(new)
print(ls)
for i in ls:
print(i, end= " ")
运行结果演示: 
示例三 百钱百鸡的实现。  代码演示:
for x in range(0,100):
for y in range(0,100):
if (100-5*x-3*y)*3 + x + y ==100:
print("公鸡{}只,母鸡{}只,小鸡仔{}只".format(x, y, 100-x-y))
else:
continue
运行结果演示: 
示例三 有趣的24点,题目如下:  代码演示:
a, b, c, d = input().split(" ")
ops = ["+", "-", "*"]
count = 0
for x in ops:
for y in ops:
for z in ops:
result = a + x + b + y + c + z + d
if eval(result) == 24:
count +=1
print(count)
说明:只能使用加减乘,并且不能使用括号,我们要遍历出所有可能出现的情况。通过加号连接了字符串,从而形成了一个大的字符串,使用eval函数去除字符串的引号,从而形成运算式子,我们就可以求出该式子的数值了。
运行结果演示: 
|