Runtime error when removing known substrings from a master string

Viewed 55

I have a master string that is the combination and scrambling of the spelling of numbers, with all letters for each instance present and no spaces. If the spelling is found it is supposed to remove each letter from the master string and continue, but after finding what appears to be the last number, it gets caught in a runtime loop and the last remaining letters aren't a match for anything.

master_word = 'xtneiootnrnoeneeeeuoeoheetehounzoiuetrhfefeezuivirfwieotgoottfnrnneghetserhrwsgesfherhtiitrerevreernhveo'
known_answer = '0011122333334444567788899'

numbers = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']

def find_spelling(arr) -> bool: # arr is chars spelling the number
    return set(arr).issubset(master_word)


while len(master_word) > 0:
    for word in numbers:
        if find_spelling(word):
            print(f"########## Found match for {word} ##########") #debug
            letters = list(word)
            foundnums.append(word)
            print(foundnums)
            for letter in letters:
                master_word = master_word.replace(letter, '', 1)
                print(master_word)

The last print statement before getting in the infinite loop is:

['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'zero', 'one', 'two', 'three', 'four', 'five', 'eight', 'nine', 'one', 'three', 'four', 'one', 'three', 'three', 'three']
ugsrhe
ugsre
ugse
ugs
ugs
#loop gets stuck here
1 Answers

It seems your master word length is the while loop, and your while loop will go on forever until all the letters in the master word are gone. Since your code does not get rid of all the letters, it keeps going through the whole list. I think a way to resolve this would be to break the loop if the master word has not changed since the previous loop.

Related