Последовательность Рекамана

Содержание
Введение
Похожие статьи

Введение

В этой статье вы можете познакомиться с воспроизведением последовательности Рекамана на Python 3.

Подразумевается, что вы уже владеете материалом из статьи Основы работы с файлами в Python

Создайте файл recaman.py и копируйте туда код из примеров.

Запустить файл можно командой

python3 recaman.py

Banner image

Последовательность Рекамана

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]

Если в файле будут неподходящие данные ошибка будет показана в Traceback, а до закрытия файла дело не дойдёт.

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'

Это серьёзная проблема, и обычно решается использованием менеджера контекста , но можно решить и добавлением try , finally

Модифицируем функцию read_series() заодно добавив генератор списка

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 получается короче.

def read_series(filename): with open(filename, mode='rt', encoding='utf-8') as f: return [int(line.strip()) for line in f]

В write_sequence() из recaman.py тоже лучше применить 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

Похожие статьи
Python
Математика в Python
Решение квадратного уравнения на Python
Обучение программированию на Python

Search this site

Subscribe to Telegram channel @aofeed to follow new articles and updates to old ones

Go to channel

@aofeed

Ask a question in the Telegram group

@aofeedchat

Contacts and cooperation:
I recommend our hosting beget.ru
Write to info@urn.su, info@aredel.com if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: