简体   繁体   中英

Word Scrambler in python

I am trying to find every possible combination of a word.

def calculateScrambledWords(word):
   # In the case of a "cat"
   # While there is not 6 items in array
   # iterate through cat wapping letters each time
   # cat, act, atc - now the loop for the first loop 
   # Loop from atc 3 more times to get cta
   # Think of it as passes in a bubble sort
   # tac, tca, cta
   wordCombinations = []
   wordCombinations.append(word)
   wordIterations = factorial(len(word))
   scrambled = False
   wordArr = createWordArray(word)
   for x in range(wordIterations): 
       for x in range(1,len(word)):
           temp = wordArr[x-1]
           wordArr[x-1] = wordArr[x]
           wordArr[x] = temp
           wordstr = createString(wordArr)
           if wordstr not in wordCombinations:
               wordCombinations.append(wordstr)
   return wordCombinations

       



def createWordArray(word):
   arr = []
   for letter in word:
       arr.append(letter)
   return arr

def createString(arr):
   string = ""
   for letter in arr:
       string = f"{string}{letter}"
   return string

def factorial(number):
   if number == 1:
       return 1
   else:
       return (number* factorial(number-1))

print(calculateScrambledWords("toby"))

This solution works for a 3 letter word but when you increase the number of letters it stops working, if anyone has any ideas let me know!

You can use the itertools

from itertools import permutations

def find_permutations(s):
  return set(["".join(p) for p in permutations(s)])

Using the concept of backtracking:-

Code:-

#By backtracking
res=set()
def backtrack(word, index, length): 
    if index==length: 
        res.add(''.join(word))
    else: 
        for j in range(index,length): 
            word[index], word[j] = word[j], word[index] 
            backtrack(word, index+1, length) 
            word[index], word[j] = word[j], word[index]  
  
word = input("Enter the word: ")
word_in_list = list(word) 
backtrack(word_in_list, 0, len(word))
print(res)

Output:-

Enter the word: cat
{'tca', 'cat', 'atc', 'cta', 'act', 'tac'}

Enter the word: boo
{'oob', 'obo', 'boo'}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM