Straitforward concise Python solutions ( 5 lines)


  • 1
    C

    Use 1 dictionary, 2 passes (one for making a dict d, another one for counting A and B)

    In the second pass, we subtract 1 from d[g] when the guessed g is a matching letter. The (d[g]<1) would take care of the cases where we have excess matching letters (subtract one from B)



    If we can use Counter from collections, it can be condensed into 5 lines.

    def getHint(self, secret, guess):
        d, A, B = Counter(secret), 0, 0
        for i, g in enumerate(guess):
            if g in secret:
                A, B, d[g] = A+(g==secret[i]), B+(g!=secret[i])-(d[g]<1), d[g]-1
        return '{}A{}B'.format(A,B)
    


    same idea without using Counter

    def getHint(self, secret, guess):
        d, A, B = {}, 0, 0
        for n in secret:
            d[n] = d.get(n,0)+1
        for i, g in enumerate(guess):
            if g in secret:
                A += (g==secret[i])
                B = B + (g!=secret[i]) - (d[g]<1)
                d[g] -= 1
        return '{}A{}B'.format(A,B)
    


    The full expansion of this idea

    def getHint(self, secret, guess):
        d, A, B = {}, 0, 0
        for n in secret:
            d[n] = d.get(n,0)+1
        for i, g in enumerate(guess):
            if g in secret:
                if g==secret[i]:
                    A += 1
                else:
                    B += 1
                if d[g]<1:
                    B -= 1
                d[g] -= 1
        return '{}A{}B'.format(A,B)

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.