Python Forum
fibonacci ***Time limit exceeded***
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
fibonacci ***Time limit exceeded***
#14
So normally, for generating infinite sequences, you'd use a generator:
>>> def find_fibs():
...   last_two = (1, 1)
...   yield 1
...   yield 1
...   while True:
...     new_num = sum(last_two)
...     yield new_num
...     last_two = (last_two[1], new_num)
...
>>> fibs = find_fibs()
>>> for _ in range(10):
...   print(next(fibs))
...
1
1
2
3
5
8
13
21
34
55
But, as ichabod801 mentioned, if the point is that you'll be finding similar numbers repeatedly, you want to keep track of what the old numbers were, and only calculate new numbers if needed. Similar to this:
>>> def fibs(num, results=[1, 1]):
...   while num > len(results):
...     print("**generating new fib**")
...     results.append(results[-1] + results[-2])
...   return results[:num]
...
>>> fibs(2)
[1, 1]
>>> fibs(5)
**generating new fib**
**generating new fib**
**generating new fib**
[1, 1, 2, 3, 5]
>>> fibs(3)
[1, 1, 2]
>>> fibs(10)
**generating new fib**
**generating new fib**
**generating new fib**
**generating new fib**
**generating new fib**
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
>>> fibs(6)
[1, 1, 2, 3, 5, 8]
The difference being a memory issue. If you want to generate the 500 millionth fibonacci number, the generator will give you what that number is, while keeping track of what every previous number is might use up all your memory before giving an answer, which would throw an error instead of getting a result.
Reply


Messages In This Thread
fibonacci ***Time limit exceeded*** - by frequency - Nov-24-2018, 02:49 AM
RE: fibonacci ***Time limit exceeded*** - by nilamo - Nov-27-2018, 10:43 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Fibonacci Yasunaga 7 3,024 May-16-2021, 02:36 PM
Last Post: csr
  Assign a value if datetime is in between a particular time limit klllmmm 2 2,819 Jan-02-2021, 07:00 AM
Last Post: klllmmm
  Time Limit Exceeded error loves 5 3,230 Dec-03-2020, 07:15 AM
Last Post: Sofia_Grace
Bug maximum recursion depth exceeded while calling a Python object error in python3 Prezess 4 3,828 Aug-02-2020, 02:21 PM
Last Post: deanhystad
  RecursionError: maximum recursion depth exceeded in comparison ? leoahum 11 13,229 Mar-18-2019, 01:53 PM
Last Post: leoahum
  'Time Limit Exceeded' Problem bkpee3 2 5,510 Nov-14-2018, 03:51 AM
Last Post: bkpee3
  If conditions with time limit unknowntothem 4 3,156 Nov-09-2018, 08:59 PM
Last Post: nilamo
  Fibonacci sequence Darbandiman123 2 2,751 Sep-26-2018, 02:32 PM
Last Post: Darbandiman123
  Help debug my fibonacci implementation dineshpabbi10 6 4,071 May-16-2018, 12:12 PM
Last Post: dineshpabbi10
  maximum recursion depth exceeded saba_keon 3 7,520 Apr-08-2018, 07:30 AM
Last Post: Gribouillis

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020