hystehrichal
hystehrichal

Reputation: 39

Using "for x not in y"

I'm trying to make a dynamic function that executes the Fibonacci sequence. It starts with a hashtable that assigns values to positions and then returns it. But if the position isn't in the hashtable, the code stores the value in the hashtable along with that position. Here's the code:

 def dyn_fib(n):
     memo = {1:0, 2:1}
     if n <= 2:
         return memo[n]
     else:
         for n not in memo:
             memo[n] = memo[n-2] + memo[n-1]
     return memo[n]

All I have to do is edit the 'else' statement to store new values in the hashtable using

memo[n] = memo[n-2] + memo[n-1] 

for any position "n" in not yet listed in memo, and then loop that until you get to "n". I thought I could use

 for n not in memo:

but Geany is saying there is a syntax error. I think it's because if n = 5, it needs to compute 3 and 4 before 5 but I'm not sure how to put "for any position n not yet in memo" into a python statement. Anyone know how to do this? (I feel like it's simple but I'm not well versed in Python by any stretch.)

Upvotes: 1

Views: 16105

Answers (1)

John Gordon
John Gordon

Reputation: 33343

You can't generally say for x not in y because there are an infinite number of objects that aren't in y.

For your specific case, I think something like this might work:

[x for x in range(0, n) if x not in y]

Upvotes: 13

Related Questions