ASKSAGE: Sage Q&A Forum - RSS feedhttps://ask.sagemath.org/questions/Q&A Forum for SageenCopyright Sage, 2010. Some rights reserved under creative commons license.Tue, 12 Nov 2019 15:18:50 +0100Output 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 16:44:39 +0100https://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.Mon, 11 Nov 2019 06:27:07 +0100https://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 15:18:50 +0100https://ask.sagemath.org/question/48691/output-of-a-sequence-in-display-and-as-a-txt-file/?comment=48708#post-id-48708