0

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!

3 Answers3

0
words = []
with open(file_name, "r") as fp:
    words = [line.replace('\n', '') for line in fp]
for wi in words:
    for wj in words:
        print(f"{wi}{wj}")
jsofri
  • 227
  • 1
  • 10
  • 2
    Please don't just write code for questions that have shown no attempt to solve the problem. – chepner Nov 11 '21 at 14:41
  • 2
    The `replace` function requires a replacement argument. Also, you don't need to declare `words` as an empty list if you will use a list comprehension later on. – Mitchell Olislagers Nov 11 '21 at 14:45
  • 2
    Also, don't post answers that have no explanation, only code. They _might_ seem interesting at the moment, but become problematic in the long run – MatBBastos Nov 11 '21 at 14:46
0
#say you have a list of words 
l = ['apple', 'banana', 'horse', 'love', 'purple']

for i in range(len(l)):
    for j in range(len(l)):
        if i != j:
            print(l[i]+l[j])
MirouDz
  • 11
  • 1
  • 2
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Nov 11 '21 at 15:06
0

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
...
S.B
  • 13,077
  • 10
  • 22
  • 49