s = "dog" perms = get_permutations(a) print(perms) Output: ['dog', 'dgo', 'odg', 'ogd', 'gdo', 'god']Rewrite the script for obtaining permutations and the end of the Comments, Hints, and Observersions section below to a script that defines the method get_permutations.
Define get_permutations method # Start main script. # Indicate in a comment the Jumble strings you # use for testing. Include at least two test strings. Input Jumble string from keyboard. Obtain array of permutations from array using get_permutations method. Open Unix dictionary file to obtain file object fin. Get first line of dictionary file. while line not equal to "" Get word from current line by removing \n at end of line. if word[0] is equal to word[0] converted to uppercase for each permutation in array called perm if perm is equal to word print word exit script (optional) end end end Get next line of dictionary file. end Close file object fin.The reason we only consider words that start with lower case letters is that Jumble strings never represent proper names.
Grading Breakdown: Functionality: 65%; Test strings included in a comment: 10%; Source code comments: 10%; Indentation: 10%; Properly Submitted: 5%.
import itertools print(list(itertools.permutations([1,2,3]))) # Output: [(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]We just have to convert our input string to a list of letters before running it through itertools.permutations:
import itertools input_string = input("Enter an input string: ") letters = list(input_string) permutation_list = itertools.permutations(letters) for perm in permutation_list: print perm # Output: Enter an input string: dog ('d', 'o', 'g') ('d', 'g', 'o') ('o', 'd', 'g') ('o', 'g', 'd') ('g', 'd', 'o') ('g', 'o', 'd')We just have to convert each of the permutations to a string.
# Function to find permutations of # a given string from itertools import permutations def allPermutations(str): # Get all permutations of string 'ABC' permList = permutations(str) # print all permutations for perm in list(permList): print(''.join(perm)) # Driver program if __name__ == "__main__": str = 'ABC' allPermutations(str)The missing piece is
for perm in list(permList): print (''.join(perm))which we can combine with the code from item to obtain
import itertools input_string = input("Enter an input string: ") letters = list(input_string) permutation_list = itertools.permutations(letters) for perm in permutation_list: print(''.join(perm)) # Output: Enter an input string: dog dog dgo odg ogd gdo godFinally, we don't want to print all of the permutations, but instead enter them into a list of strings. Here is code to accomplish this:
# Source code for obtaining permutations import itertools input_string = input("Enter an input string: ") letters = list(input_string) permutation_list = itertools.permutations(letters) permutations = [ ] for perm in permutation_list: permutations.append(''.join(perm)) print(permulations)