Ask Your Question
1

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

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

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
        else:
            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
1

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

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

Comments

Very good. Thx!

geroyx gravatar imagegeroyx ( 2019-11-12 15:18:50 +0100 )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

Stats

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

Seen: 196 times

Last updated: Nov 11 '19