we are to write a function that takes a single parameter string, and then outputs each 4 letter permutation from the possible combinations of the string. so for example even if it is a 5 letter word you have to return all 4 letter combinations of the string. it can also only be solved iteratively so no recursion.
currently i've tried using nested for loops, so for instance
for i in word:
for x in word:
for z in word:
for y in word:
print(y)
print(z)
print(x)
print(i)
However the issue i'm coming across is that firstly, i'm not sure on how I would concatenate these outputs into a single string output given that i cannot use lists or any form of sets/dictionaries/tuples etc. secondly, how exactly would i avoid duplicate strings?
CodePudding user response:
You can just use a
operator to join two strings together:
a = 'str1'
b = 'str2'
c = a b
print(c)
output:
'st1str2'
So you can use this to join together i, x, z and y into one string, and print it as 1 'word'.
CodePudding user response:
The question is not very clear so I suppose that for word='abcd'
you have to print the words: 'abcd', 'aabc', aaab'
and so on. I suppose that a single letter can be present more than one time in the different combinations of letters.
In this condition try this code (that exactly the solution of @Emi OB)
word="abcd"
for i in word:
for x in word:
for z in word:
for y in word:
print(i x z y)