Python via Strings


  • 29
    def totalHammingDistance(self, nums):
        return sum(b.count('0') * b.count('1') for b in zip(*map('{:032b}'.format, nums)))

  • 0
    F

    you are amazing!


  • 2
    A

    Nice solution dude.
    Here is my solution without using strings, 2 lines solution.
    what is the execution time? just wondering is dealing with strings make it faster ?

        f = lambda x: x.count(1) * x.count(0)
        return sum([f([num>>i & 1 for num in nums]) for i in xrange(32)])

  • 2
    A

    Pretty cool solution.
    But why add * before the list is correct,what's * meaning in this example?

    zip(['0100','1110','0010'])
    [('0100',), ('1110',), ('0010',)]

    zip(*['0100','1110','0010'])
    [('0', '1', '0'), ('1', '1', '0'), ('0', '1', '1'), ('0', '0', '0')]


  • 4

    @AngieYi The * unpacks the list to individual arguments, so zip(*['0100','1110','0010']) is like zip('0100','1110','0010').


  • 0

    Love the vectorized implementation!


  • 0
    G

    @atmali I have similar observation (not fully verified). It seems string operation is faster. My guess is that after building up the list of string, all of the remaining operation is reading, while bit shift operation might be slower.

    Here is my code to avoid count('0')

        xmap = map('{:032b}'.format, nums)
        N = len(nums)
        total = 0
        for b in zip(*xmap):
            cnt_1 = b.count('1')
            total += cnt_1 * (N-cnt_1)
        return total

  • 0
    M

    @atmali nice solution! In one line it can be:

    return sum([s.count(1)*s.count(0)   for s in [[(num>>i)&1 for num in nums] for i in range(32)]]+[0]);
    

    or

    return sum(map(lambda x: x.count(0)*x.count(1), [[(num>>i)&1 for num in nums] for i in range(32)])+[0]);
    

Log in to reply
 

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