I have tried using set()
, as it will print only unique elements of both sets. In my code, common_letters
is the set of common letters from both strings. I'm trying to print all the possible combinations of words which can be generated from the elements of common_letters
and also trying to convert that word list into one where the first letter of each string is capitalized.
This is my code so far:
import itertools as itr
def listtostring(s):
string =" "
return (string.join(s))
str1=input("Enter 1st string:")
str2=input("Enter 2nd string:")
common_letters=set(set(str1) & set(str2))
for letter in common_letters:
common_letters.add(letter)
print("list of common letters : ",common_letters)
mylist=list(itr.permutations(common_letters))
print("Words generated from common letters are : ",listtostring(mylist))
I am getting the following error however:
File "C:/Users/problem_1.py", line 18, in <module>
print("Words generated from common letters are : ",listtostring(mylist))
File "C:/Users/problem_1.py", line 5, in listtostring
return (string.join(s))
TypeError sequence item 0: expected str instance, tuple found
The expected output should be all combinations of common letters forming words (as String type) with first letter in uppercase.
You are using your listtostring
function wrong, you should use that on every permutation created, not on the whole list of permutations. And you can use capitalize()
to capitalize the first letters.
Here is the modified code, I removed your for loop as it wasn't doing anything:
import itertools as itr
def listtostring(s):
string = ""
return (string.join(s))
str1=input("Enter 1st string:")
str2=input("Enter 2nd string:")
common_letters=set(set(str1) & set(str2))
print("list of common letters : ",common_letters)
mylist=list(itr.permutations(common_letters))
finalList = [listtostring(x).capitalize() for x in mylist]
print("Words generated from common letters are : ", finalList)
You can change the last line to the following if you want it to all be one string:
print("Words generated from common letters are : ", " ".join(finalList))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.