功能名称:p rintFibonacci() 你的工作是编写一个函数,它接受两个参数并使用这些参数打印出斐波那契序列(在同一行,用逗号分隔!)。通过将前两个数字相加以产生下一个整数来产生斐波纳契数列。用户输入的两个参数将是您添加以开始序列的前两个数字。当打印的最后一个数字超过300时,该功能应该停止。请记住,数字必须打印在同一行,并用逗号分隔它们。如果输出换行到新行就没问题。关键是你打印一个字符串。您无需将参数作为输出的一部分进行打印。您还可以假设用户将始终输入至少1个非零参数。
它应该是这样的:
>>> printFibonacci(1,9)
10,19,29,48,77,125,202,327
>>> printFibonacci(2,3)
5,8,13,21,34,55,89,144,233,377
python>>> printFibonacci(1,1)
2,3,5,8,13,21,34,55,89,144,233,377
到目前为止,我有这个
def printFibonacci(a,b):
count = 0
max_count = 10
while count < max_count:
count = count + 1
old_a = a
old_b = b
a = old_b
b = old_a + old_b
print (old_a)
但它不会在一行中打印出昏迷,而且我不知道如何让它停在300点。
好的,所以我已经研究过了,现在我有了更好的方法:
def printFibonacci(a,b):
count = 0
maxnumber = 299
while b < 200:
begin = a+b
a , b = b , begin
start = a
end = b
print ((start)+ (end),end=",")
我只有两个小问题,一个是在字符串末尾打印出昏迷,我怎么摆脱它?它给我的第一个数字已经是前两个的总和而不是两个参数
答案 0 :(得分:2)
做自己的功课! (不要提交这个解决方案;它可能会使用你尚未学到的概念)。
#!/usr/bin/env python2.7
def printFibonacci(a, b):
while b < 300:
a, b = b, a+b
yield b
def main():
tests = [(1, 9), (2, 3), (1, 1)]
for test in tests:
print ', '.join(str(n) for n in printFibonacci(*test))
if __name__ == '__main__':
main()
输出:
10,19,29,48,77,125,202,327
5,8,13,21,34,55,89,144,233,377
2,3,5,8,13,21,34,55,89,144,233,377
答案 1 :(得分:0)
我也在学习Python。我不是在课堂上或任何事情,但随时可以查看代码并给我反馈。
#!/usr/bin/python
#fib.py
#array to hold series of fib numbers
fibSequence = []
#expects two integers, the lesser number first
def printFibonacci(lesserNumber, greaterNumber):
#access the array declared outside the function
global fibSequence
#check if the list is empty; if it is then start it
if not fibSequence:
fibSequence=[lesserNumber, greaterNumber]
#the next number in the sequence will be the sum of the two parameters
sumNumber = lesserNumber + greaterNumber
if greaterNumber> 300:
print ",".join(str(i) for i in fibSequence)
else:
#add the summed number to the list that will eventually be our answer
fibSequence.append(sumNumber)
#call the function again, this time with the formerly greatest number as the smaller number
printFibonacci(greaterNumber, sumNumber)
#call the function for the first time
printFibonacci(2,3)
答案 2 :(得分:-1)
通常,使用递归最容易解决斐波那契类型问题:
def printFibonacci(x,y):
if y > 300:
return
z = x + y
print z,
printFibonacci(y,z)
return