I am defining a Fibonacci sequence and saving the data to a file. However, I would like to save only the distinct sequence, not the repeating ones. For example, [0,1] should be saved only once and not three times. I present the current and expected outputs.
def fibonacci(n):
sequence = [0, 1]
while len(sequence) < n:
next_number = sequence[-1] + sequence[-2]
sequence.append(next_number)
return sequence
n = 10
for i in range(0,n):
result = fibonacci(i)
print(result)
with open("Fibonacci.txt", 'a') as f:
f.writelines('\n')
f.write(str(result))
print(result)
The current saved data is
[0, 1]
[0, 1]
[0, 1]
[0, 1, 1]
[0, 1, 1, 2]
[0, 1, 1, 2, 3]
[0, 1, 1, 2, 3, 5]
[0, 1, 1, 2, 3, 5, 8]
[0, 1, 1, 2, 3, 5, 8, 13]
[0, 1, 1, 2, 3, 5, 8, 13, 21]
The data I expect to save
[0, 1]
[0, 1, 1]
[0, 1, 1, 2]
[0, 1, 1, 2, 3]
[0, 1, 1, 2, 3, 5]
[0, 1, 1, 2, 3, 5, 8]
[0, 1, 1, 2, 3, 5, 8, 13]
[0, 1, 1, 2, 3, 5, 8, 13, 21]
>Solution :
Just add a new variable last_result that stores the previous iteration value and use an If to check it:
def fibonacci(n):
sequence = [0, 1]
while len(sequence) < n:
next_number = sequence[-1] + sequence[-2]
sequence.append(next_number)
return sequence
last_result = None
n = 10
for i in range(0,n):
result = fibonacci(i)
print(result)
if result != last_result:
last_result = result
with open("Fibonacci.txt", 'a') as f:
f.writelines('\n')
f.write(str(result))
print(result)