2017-10-15 64 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