The Recamán sequence
Introduction
In this article you can get acquainted with reproducing the Recamán sequence in Python 3.
It is assumed that you already know the material from the article
Basics of working with files in Python
Create the file
recaman.py
and copy the code from the examples into it.
You can run the file with the command
python3 recaman.py
The Recamán sequence
import sys from itertools import count, islice def sequence(): """Generate Recaman's sequence.""" seen = set() a = 0 for n in count(1): yield a seen.add(a) c = a - n if c < 0 or c in seen: c = a + n a = c def write_sequence(filename, num): """Write Recaman's sequence to a text file.""" f = open(filename, mode='wt', encoding='utf-8') f.writelines( f"{r}\n" for r in islice(sequence(), num + 1)) f.close() if __name__ == '__main__': write_sequence(filename=sys.argv[1], num=int(sys.argv[2]))
python recaman.py recaman.dat 1000
cat recaman.dat
1 3 6 2 7 … 2687 3685 2686 3686
"""Read and print an integer series.""" import sys def read_series(filename): f = open(filename, mode='rt', encoding='utf-8') series = [] for line in f: a = int(line.strip()) series.append(a) f.close() return series def main(filename): series = read_series(filename) print(series) if __name__ == "__main__": filename = sys.argv[1] main(filename)
python series.py recaman.dat
[0, 1, 3, 6, 2, 7 … 3684, 2687, 3685, 2686, 3686]
If the file contains unsuitable data, the error will be shown in the Traceback, and it will not get as far as closing the file.
echo badidea >> recaman.dat
python series.py recaman.dat
Traceback (most recent call last): File "/home/andrei/series.py", line 21, in <module> main(filename) File "/home/andrei/series.py", line 15, in main series = read_series(filename) File "/home/andrei/series.py", line 8, in read_series a = int(line.strip()) ValueError: invalid literal for int() with base 10: 'badidea'
This is a serious problem, and it is usually solved by using
a context manager
, but it can also be solved by adding
try
,
finally
Let us modify the function read_series() and at the same time add
a list comprehension
def read_series(filename): try: f = open(filename, mode='rt', encoding='utf-8') return [int(line.strip()) for line in f] finally: f.close()
With with it is shorter.
def read_series(filename): with open(filename, mode='rt', encoding='utf-8') as f: return [int(line.strip()) for line in f]
In write_sequence() from recaman.py it is also better to use with
def write_sequence(filename, num): """Write Recaman's sequence to a text file.""" with open(filename, mode='wt', encoding='utf-8') as f: f.writelines( f"{r}\n" for r in islice(sequence(), num + 1))
Article author: Andrei Olegovich