Issue
I want to make a program that takes strings from a file - file.txt
apple
banana
horse
love
purple
and then joins the first word with every single other one and so on. The result should look like this:
applebanana
applehorse
applelove
applepurple
bananaapple
bananahorse
bananalove
bananapurple
horseapple
etc.
I get that I should probably use the join function, but I don't know how exactly? (If that makes sense, I am super sorry)
I tried also using zip, but couldn't make it word, so I leave it up to the professionals! <3 (I also use python 3) If u need more info I will try to respond as fast as I can! Thank you all!
Solution
This is exactly what itertools.permutations()
does.
Return successive
r
length permutations of elements in the iterable.
from itertools import permutations
with open(<your_file>) as f:
lst = [line.strip() for line in f]
for i, j in permutations(lst, r=2):
print(i + j)
output:
applebanana
applehorse
applelove
applepurple
bananaapple
bananahorse
...
Answered By - SorousH Bakhtiary
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.