-1

The following snippet gives me a comma-separated list in the display:

X = 19     # Start
N = 7      # Length
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))))
f = file('collatz\N.txt','w')  # gives an empty file and is not named correctly
# f.write(str(f(X,N))  Does not work

How can I have that line-separated (like at default) as a good named textfile, like collatz19.txt ?

So the display-output is ok. I need the textfile-output _too_, and do no know the commands.

cis
  • 135
  • 6

1 Answers1

1

You have two options to write to the file:

# Write the whole file in one string
with open('collatz\N.txt','w') as fn:
    one_string = "\n".join(map(str, f(X, N)))
    fn.write(one_string + '\n')

or write to the file a line at a time:

with open(r'collatz\Ng.txt','w') as fn:
    gen = f(X, N)
    for line in gen:
        fn.write(str(line)+'\n')
quamrana
  • 37,849
  • 12
  • 53
  • 71