Python via Strings

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

  • 0

    you are amazing!

  • 2

    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

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

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

    [('0', '1', '0'), ('1', '1', '0'), ('0', '1', '1'), ('0', '0', '0')]

  • 5

    @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

    @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

    @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]);


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

  • -1

    @StefanPochmann said in Python via Strings:


    Since the string passed back expands automatically, would just
    '{:b}'.format be better?

Log in to reply

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