Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Selective data saving to a file in Python

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading