#๐Ÿ”’ Problem with outputting to a file

8 messages ยท Page 1 of 1 (latest)

solemn crystal
#

Hello everyone, I have to output a fibonacci sequence to a file, I tried to do this with a for loop and \n characters to output one number of the series on a new line, however both of these goals fail and I feel stuck, here's the code, my apologies for the Dutch variable names: ```py
fib_cache = {}
memoteller = 0
bestandsnaam = 'fib.txt'

def fibonacci_memoization(n):
global memoteller, fib_cache
if n <= 0:
return 0
elif n == 1:
return 1

Check if the result is already within the cache.

if n in fib_cache:
return fib_cache[n]

If not, calculate it recursively and store it in the cache.

fib_value = fibonacci_memoization(n - 1) + fibonacci_memoization(n - 2)
fib_cache[n] = fib_value
memoteller +=2
return fib_value
for i in range(500):
with open(bestandsnaam, 'w') as doc:
doc.write(str((fibonacci_memoization(i)))+'\n')

expected output: 0\n1\n1\n2\n3\n5\n8\n...
actual output for i in range(500): 86168291600238450732788312165664788095941068326060883324529903470149056115823592713458328176574447204501

Thanks in advance.
vague harborBOT
#

@solemn crystal

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

solemn crystal
#

It is also important to mention that I dont think that there are any malfunctions in the algorithm itself, I did test it but perhaps I'm wrong after all.

#

After taking a closer look, it only writes the last element to the document, when using the same logic but by printing it out to the terminal, both problems dont occur.

#

Nevermind, solved it.

#

!close

vague harborBOT
#
Python help channel closed with !close

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.