简体   繁体   中英

My function doesn't evaluate some values properly

Background

For a coding activity online, I was asked to create a function that took value and returned true if the product of any two consecutive numbers in the Fibonacci Sequence equal that number 1 .

Example

An example is 5895, no two numbers multiply to this in the Fibonacci Sequence, but the two numbers that multiply the closest to it while being greater than it are 89 and 144, so you would return [89,144, False].

Problem

But I've run into a problem: my function doesn't work for numbers 1 and 0 . You can see that numbers in the Fibonacci sequence both multiply to these two values, but my function returns none.

Question

Does anyone have a fix?

def productFib(prod):
    num = [0]
    n1 = 0
    n2 = 1
    while max(num) < prod: 
        nth = n1 + n2
        n1 = n2
        n2 = nth
        num.append(n1)
    q = 0
    w = 1
    while w+1 < len(num):
        for nums in num:
            if num[q] * num[w] == prod:
                return [num[q], num[w], True]
            if num[q] * num[w] > prod:
                return [num[q], num[w], False] 
            q += 1
            w += 1

1. More: If two consecutive numbers did multiply out to the target number you would return the two numbers and the boolean True (num1, num2, True). If there were not two numbers that multiplied out to the target number, you would return two consecutive numbers from the Fibonacci Sequence that multiplied to the closest number to the target number , the number had to be greater than the target number , and would have to return the boolean False (num1, num2, False).

The edits I made fix the function to work for prod=0 and prod=1.

def productFib(prod):
    num = [0]
    n1 = 0
    n2 = 1
    while max(num) <= prod:
        nth = n1 + n2
        n1 = n2
        n2 = nth
        num.append(n1)
    q = 0
    w = 1
    while w+1 <= len(num):
        for nums in num:
            if num[q] * num[w] == prod:
                return [num[q], num[w], True]
            if num[q] * num[w] > prod:
                return [num[q], num[w], False]
            q += 1
            w += 1

I did not check a multitude of inputs, but it seems to work.

From comment: The while loops were not being run. In the case of zero: w+1 was not less than len(num) because both were equal to 2. In the case of one: max(num) was not less than prod as both were 1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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