2017-10-15 1 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() 

は私がこれについて移動する方法がわからないんだけど、私はフィボナッチ数列で89を通じて3(例えば)表示または何かをやろうとしていると考えていますlike:

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

また、forループを使用してFib Sequenceの範囲を表示する必要がありますか?

答えて

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 

私は発電機のアプローチを好みます