简体   繁体   English

固定斐波那契数从 1 到 50 Python

[英]fixing Fibonacci numbers from a range of 1 to 50 Python

I have a set of numbers from 1 to 50 and from these numbers I have to find which are Fibonacci number, after that I have to find which of these numbers contain the number 1 and 2.我有一组从 1 到 50 的数字,我必须从这些数字中找到哪些是斐波那契数,然后我必须找到这些数字中的哪些包含数字 1 和 2。

For example in my code my Fibonacci numbers are 0, 1, 2, 3, 5, 8, 13, 21, 34 I have written a code, but I can't add the last part of the question, so it finds out which of these numbers contain a number 1 or 2 in them.例如,在我的代码中,我的斐波那契数是 0、1、2、3、5、8、13、21、34这些数字中包含数字 1 或 2。 here is my code这是我的代码

def isPerfectSquare(x):
    s = int(math.sqrt(x))
    return s * s == x


def isFibonacci(n):
    return isPerfectSquare(5 * n * n + 4) or isPerfectSquare(5 * n * n - 4)


for i in range(0, 51):
    if isFibonacci(i) == True:
        print(i, "is a Fibonacci Number")
    else:
        print(i, "is a not Fibonacci Number ")


for q in range(1, 51):
    if isFibonacci(i) == True and '1' in i and '2' in i:
        print(q)
    else:
        print('Error') 

the result is something like this is gives me all of these numbers 0, 1, 2, 3, 5, 8, 13, 21, 34 as Fibonacci and the rest are not which is perfect but then it keeps giving me error, what i wanted to do is it to write a loop that contains all Fibonacci numbers like these 0, 1, 2, 3, 5, 8, 13, 21, 34 and that contain a 1 and 2 in the number to be printed out but it just prints everything as Error.结果是这样的,它给了我所有这些数字 0、1、2、3、5、8、13、21、34 作为斐波那契和 rest 不是完美的,但它不断给我错误,我是什么想做的是编写一个循环,其中包含所有斐波那契数,例如 0、1、2、3、5、8、13、21、34,并且在要打印的数字中包含 1 和 2,但它只是将所有内容打印为错误。

for q in range(1, 51):
    if isFibonacci(q) == True and '1' in str(q) and '2' in str(q):
        print(q)
    else:
        print('Error') 
  1. This loop's variable is q , not i .这个循环的变量是q ,而不是i
  2. You have to convert the number to string using str(...) .您必须使用str(...)将数字转换为字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM