2017-10-15 135 views
-2

我想我想要做的是从一个定义的列表中显示一个选择部分。目前,这是我与合作:斐波那契数列的计数程序Python

#fibonacci sequence algorithm, user stops by either 
#entering a maximum Fibonacci value not to exceed or 
#a total count that the sequence of numbers must not 
#exceed. Use a loop that allows User to repeat program 
#as much as they wish, asking if they would like to 
#repeat the program each time. Validate that User input 
#is either a yes or a no and only allow User to continue 
#once a correct response has been given. 
import array 

array.listOfFibSeq = ['0','1','1','2','3','5','8','13','21','34','55','89','144','...'] 
startingNumber = '' 
endingNumber = '' 
continueYes = '' 

def getStartingNumber(): 
    print('Please enter a valid starting number of the Fibonacci Sequence') 
    print(listOfFibSeq) 
    startingNumber = input() 

def getEndingNumber(): 
    print('Please enter a valid ending number the the Fibonacci Sequence') 
    print(listOfFibSeq) 
    endingNumber = input() 

我不确定如何去了解这一点,但我相信,我想在Fibonacci序列中通过89来显示(例如)3或做某事如:

lsitOfFibSeq.remove(<3) and listOfFibSeq.remove(>89) 

或者我应该尝试显示一个范围的Fib序列与for循环?

回答

0

在用户进入一个范围之前没有合理的方法来预先计算斐波那契序列 - 你应该动态地做到这一点。

一个天真的方法是计算一个给定(a, b)的序列,一直到end,丢弃一切为start

我更喜欢在发电机的办法:

import itertools 
def fib(): 
    a, b = 0, 1 
    while 1: 
     yield a 
     a, b = b, a + b 

# Print the first 10 values of the sequence 
for i in itertools.islice(fib(), 0, 10): 
    print(i) 

或者,你的情况,是这样的:

start = input('Start index: ') 
end = input('End index: ') 

for i in itertools.islice(fib(), int(start), int(end)): 
    print(i) 
    if input('Continue [y/n]: ').rstrip() == 'n': 
     break