-1

There is a dictionary d of letters and frequencies which represents a hand in a game similar to scrabble. If the letters in word are contained within d then the frequencies are changed or the letter is removed (if the value == 0) and the function update returns True, otherwise d is unchanged and the function returns `False':

d = {'a': 1, 'p': 2, 'c': 1, }

dCopy = d.copy()

matching_lets = 0


def update():

    for let in word:
        if not let in dCopy:
            return False
        else:
            if dCopy[let] == 1:
                del dCopy[let]
            else: 
                dCopy[let] -= 1
    d = dCopy
    return True 

word = 'pap'
print update()

This is part of problem set 5 from the EDX course MITx 6.00.1, Introduction to Computer Science and Programming Using Python

David Hancock
  • 1,063
  • 4
  • 16
  • 28
  • i think instead of `return false` in first for loop must be changed to `continue` and use a flag to check is `d` manipulated or not in order to return `false` if not – Mehrdad Dadvand Oct 20 '16 at 10:47
  • `d = dCopy` is not going to do anything unless you declare in `update()` that `d` is global. You would be better off using returns and arguments and getting rid of your global variables. – khelwood Oct 20 '16 at 10:52

1 Answers1

1

There's no faster solution in Python, given your question. dict() is same as a hashmap and so your update function has O(|word_length| + |dict_length|) average case complexity where word_length is the number of characters in the given word and dict_length is the number of key-value pairs in your dict.

Note: @khelwood is correct about d = dCopy. Figure out how to solve that problem yourself.

User_Targaryen
  • 4,125
  • 4
  • 30
  • 51