开发者

Proper output for the program

import itertools 

file = open('out.txt', 'w')
variations = itertools.product('abc', repeat=3) 

for variations in variations: 
    variation开发者_如何学Python_string = "" 

    for letter in variations: 
        variation_string += letter 

    file.write(variation_string)

file.close()

The output from the above program is like a clustered state:

aaaaabaacabaabbabcacaacbaccbaababbacbbabbbbbcbcabcbbcccaacabcaccbacbbcbcccaccb­ccc

Can you modify the program so that the output would be in a line after line that is the first line of the output would be aaa and the next line would be aab and the next would be aac and so on...

aaa
aab
aac


After your file.write, add another file.write('\n').


Here is a revised code that fixes a few other issues in addition to the mentioned problem:

import itertools
with open('out.txt', 'w') as f:
    for variation in itertools.product('abc', repeat=3):
        f.write(str.join("", variation) + "\n")


Here is how to print that list to stdout:

>>> for variation in itertools.product('abc', repeat=3):
...     print(''.join(variation) + '\n'),

Writing it to your file is left as an exercise...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜