ASKSAGE: Sage Q&A Forum - Individual question feedhttps://ask.sagemath.org/questions/Q&A Forum for SageenCopyright Sage, 2010. Some rights reserved under creative commons license.Tue, 12 Nov 2019 08:18:50 -0600Output of a sequence in Display and as a txt-Filehttps://ask.sagemath.org/question/48691/output-of-a-sequence-in-display-and-as-a-txt-file/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` ?Sun, 10 Nov 2019 09:44:39 -0600https://ask.sagemath.org/question/48691/output-of-a-sequence-in-display-and-as-a-txt-file/Answer by slelievre for <p>Hello. This </p>
<pre><code>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))))
</code></pre>
<p>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 <code>collatz19.txt</code> ?</p>
https://ask.sagemath.org/question/48691/output-of-a-sequence-in-display-and-as-a-txt-file/?answer=48694#post-id-48694One 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.Sun, 10 Nov 2019 23:27:07 -0600https://ask.sagemath.org/question/48691/output-of-a-sequence-in-display-and-as-a-txt-file/?answer=48694#post-id-48694Comment by geroyx for <p>One way would be as follows:</p>
<pre><code>with open('collatz_{}_{}.txt'.format(X, N), 'w') as file:
file.writelines(str(k) + '\n' for k in f(X, N))
</code></pre>
<p>Also, you could use <code>x = x // 2</code> in your code to always work with integers rather than rational numbers.</p>
https://ask.sagemath.org/question/48691/output-of-a-sequence-in-display-and-as-a-txt-file/?comment=48708#post-id-48708Very good. Thx!Tue, 12 Nov 2019 08:18:50 -0600https://ask.sagemath.org/question/48691/output-of-a-sequence-in-display-and-as-a-txt-file/?comment=48708#post-id-48708