简体   繁体   中英

Comparing output to a list

I wanna take, for example the Fibonacci sequence formula, run it and compare the output to a list that. But can't find how to either save the output to a list or straight up compare the output to the list.

New to Python so I apologies if I have just missed something simple and/or obvious.

Let's take, for example, the example of the Fibonacci sequence, with a very simple implementation.

def fibonacci(n):
  if n == 0: return 0
  elif n == 1: return 1
  else: return fibonacci(n-1) + fibonacci(n-2)

(note that this is far from being efficient)

Let's say I want to test that the first 10 results match the actual sequence.

First, let's create a list of the expected results.

fibonacci_sequence = [0, 1, 1, 2, 3, 5, 8, 13, 21, 33]

Then, let's generate a list with the computed results.

computed_values = [fibonacci(n) for n in range(10)]

(to understand better this line of code, see list comprehension )

Finally, let's compare the two lists.

print(computed_values == fibonacci_sequence)

This will compare the two lists at once.

An other option would be to verify the results one at a time.

for n in range(10):
  print(fibonacci(n) == computed_values[n])

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