【问题标题】:Counting program for fibonacci sequence Python斐波那契数列 Python 的计数程序
【发布时间】:2017-10-15 20:21:55
【问题描述】:

我想我想做的是从定义的列表中显示一个选择部分。目前这是我正在使用的:

#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()

我不确定该怎么做,但我相信我正在尝试在斐波那契数列中显示(例如)3 到 89 或执行以下操作:

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

或者我应该尝试使用 for 循环显示 Fib 序列的范围?

【问题讨论】:

    标签: python python-3.x append fibonacci


    【解决方案1】:

    没有合理的方法可以在用户输入范围之前预先计算斐波那契数列——您应该动态地执行此操作。

    一种天真的方法是使用一个函数计算给定(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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-03
      • 2013-02-24
      • 2017-07-22
      • 2010-12-20
      • 2020-01-18
      • 2014-05-23
      • 2015-06-05
      相关资源
      最近更新 更多