Python A permutation of a list or string is a rearrangement of the elements in t
ID: 3802898 • Letter: P
Question
Python
A permutation of a list or string is a rearrangement of the elements in the list or string. For example, given the list [1,2,3,4], permutations would include [2,4,1,3], [4,3,1,2] and [3,2,4,1]. Likewise, given the string ’dome’, permutations would include ’edom’, ’emod’ and ’mode’.
Write a function permutations() that takes a string argument, opens the file words.txt (provided on Blackboard) and returns a list consisting of all permutations of the string argument found in the file (if any). The original word should not be included in the returned list. The function may return the words in any order inside the list.
Examples: Function Call Return Value permutations veil') evil', 'levi', 'live', vile' permutations 'tori') riot', 'trio' permutations dad') add' permutations ado'Explanation / Answer
#you did not give the value of file,still i have made a program doing
#permutation of string
def permutations(string): #function for permutation
if len(string) == 1: #if string length is 1 then permutation is string itself
return string
list_perm = [] #list to store string
for c in string:
for perm in permutations(string.replace(c,'',1)): #permutation of string
list_perm.append(c+perm) #appending the result in the list
return set(list_perm) #returning the resultant list
string=input("Enter the string") #taking the input from user
list_perm=permutations(string) #result storing in the list
list_perm.remove(string) #remove the exact string
print(list_perm) #printing the final list
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.