python--Fibonacii序列

背景

Python看了一段时间了,对yield还是了解不透彻。

原来自定的函数里,含有yield的话,就变成了generator了,直接调用函数的话,是没有反应的。最后看一个视频的时候看到演示里面使用type()查看的到了是generator。才知道是怎么回事了。


对象是使用Fibonacii数列。

代码如下:

# -*- encoding = utf-8 -*-

import string
import sys

# continue ?
def isContinueDone():
	propt = input("Continue?[Y/y, N/n]: ").strip()
	if propt.isalpha:
		if propt in ("Y", "y", "N", "n"):
			if propt.lower() == "y":
				fibonacii()
			else:
				print("Quit soon.")
				sys.exit(0)
		else:
			print("Out of choice. try again.")
			isContinueDone()
	else:
		print("Invalid choice, try again.")
		isContinueDone()

# definied fibonacii method
def fibonaciiAlgorithm(max):
	n, a, b = 0, 0, 1
	while n<max:
		yield b
		a,b = b, a+b
		n = n+1
	print("{}-th fibonacii number is {}".format(max, a))


# definied main() method
def fibonacii():
	while True:
		propt = input("Enter number[>=1]: ").strip()
		if propt.isdigit():
			num = int(propt)
			if num < 1:
				print("Specified number is out of range. try again.")
				fibonacii()
			else:
				number = fibonaciiAlgorithm(num)
				for tmp_num in number:
					pass
				isContinueDone()
		else:
			print("Invalid number...try again.")
			fibonacii()

if __name__ == '__main__':
	fibonacii()


测试结果如下:

Enter number[>=1]: 10
10-th fibonacii number is 55
Continue?[Y/y, N/n]: y 
Enter number[>=1]: 12
12-th fibonacii number is 144
Continue?[Y/y, N/n]: 10
Out of choice. try again.
Continue?[Y/y, N/n]: y 
Enter number[>=1]: 1
1-th fibonacii number is 1
Continue?[Y/y, N/n]: y 
Enter number[>=1]: 2
2-th fibonacii number is 1
Continue?[Y/y, N/n]: y 
Enter number[>=1]: 3
3-th fibonacii number is 2
Continue?[Y/y, N/n]: y 
Enter number[>=1]: 4
4-th fibonacii number is 3
Continue?[Y/y, N/n]: y
Enter number[>=1]: 5
5-th fibonacii number is 5
Continue?[Y/y, N/n]: y
Enter number[>=1]: 6
6-th fibonacii number is 8
Continue?[Y/y, N/n]: y
Enter number[>=1]: 7
7-th fibonacii number is 13
Continue?[Y/y, N/n]: y
Enter number[>=1]: 8
8-th fibonacii number is 21
Continue?[Y/y, N/n]: y
Enter number[>=1]: 9
9-th fibonacii number is 34
Continue?[Y/y, N/n]: y
Enter number[>=1]: 10
10-th fibonacii number is 55
Continue?[Y/y, N/n]: y
Enter number[>=1]: 11
11-th fibonacii number is 89
Continue?[Y/y, N/n]: y
Enter number[>=1]: 12
12-th fibonacii number is 144
Continue?[Y/y, N/n]: n 
Quit soon.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值