Ask Your Question

Output of a sequence in Display and as a txt-File

asked 2019-11-10 18:11:36 +0200

geroyx gravatar image

Hello. This

X = 19     # Start
N = 7      # Width
def f(x, n):
    yield x
    for k in range(0, n):
        if x % 2 == 0:
            x = x / 2
            x = 3*x + 1
        yield x
print(", ".join(map(str, f(X, N))))

gives me a sequence comma-separated in the display. How can I have that line-separated (like at default) as a good-named txt-File, like collatz19.txt ?

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2019-11-11 06:27:07 +0200

slelievre gravatar image

One way would be as follows:

with open('collatz_{}_{}.txt'.format(X, N), 'w') as file:
        file.writelines(str(k) + '\n' for k in f(X, N))

Also, you could use x = x // 2 in your code to always work with integers rather than rational numbers.

edit flag offensive delete link more


Very good. Thx!

geroyx gravatar imagegeroyx ( 2019-11-12 15:18:50 +0200 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower


Asked: 2019-11-10 16:44:39 +0200

Seen: 186 times

Last updated: Nov 11 '19