Ask Your Question
1

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

asked 2019-11-10 11:11:36 -0600

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-10 23:27:07 -0600

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 08:18:50 -0600 )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 09:44:39 -0600

Seen: 43 times

Last updated: Nov 10 '19