Search code examples
pythonpython-3.xcounter

Looking for something like subtracting Counters to get negative keys for the difference


I've recently started learning python, and I am attempting to optimize a scrabble solving program to practice. I have written a working program but, after adding the ability to take into account blank tiles, I realized I was doing it wrong, and it was taking ages to run. I was building a giant list of possible racks, then running my program against each possible rack. Now, to optimize things, I am looking to build a list of available letters, and then once I have a list of possible words, score them against the rack (to account for blanks).

What I was doing before was:

for item in word_list:
    for letter in item:
        if item.count(letter) > players_rack.count(letter):
            valid_words.append(item)

I was wondering if there was a way to simplify this using Counter() What I would want to do, is subtract Counter(word) from Counter(letters_to_work_with) and if any items are negative...which is probably not possible with Counter(), say that it can't be a valid word.

Is there a data type that would work better here? Or is there a method I am just not seeing?

Thanks.


Solution

  • Your question is not quite clear to me - posting at least some examples inputs and outputs might help (ie : "given this and this as input, I'd like to get this as output").

    It's indeed possible to substract a Counter from another one but that doesn't yield the expected result. Now you can still substract values for specific keys, ie

    >>> c1 = Counter("word")
    >>> c2 = Counter("oawrc")
    >>> [(k, c2.get(k, 0) - v) for k, v in c1.items()]
    [('r', 0), ('o', 0), ('w', 0), ('d', -1)]