I have a range from 1-50 and I had to find out which are Fibonacci number after that I have to find which of these numbers contain number 1 and 2 pyth

Issue

i have a set of numbers from 1 – 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.

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 cant add the last part of the question so it finds out which of these numbers contain a number 1 or 2 in them.
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.

Solution

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.
  2. You have to convert the number to string using str(...).

Answered By – Harshal Parekh

Answer Checked By – Mary Flores (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.