Clean python with izip_longest() from itertools


  • 3
    C

    I don't get to use python's nifty for : else: construct often. This seems a perfect place to use it.
    Update : (else removed! As pointed out it seems useless ;)

    from itertools import izip_longest
    class Solution:
        # @param {string} version1
        # @param {string} version2
        # @return {integer}
        def compareVersion(self, version1, version2):
            v1 = (int(n) for n in version1.split('.'))
            v2 = (int(n) for n in version2.split('.'))
            for n1, n2 in izip_longest(v1, v2, fillvalue=0):
                if n1> n2:
                    return 1
                elif n1< n2:
                    return -1
            return 0

  • 1

    Actually, that else: is 100% pointless there. You can simply do return 0 after the loop. If you have else: after a loop with no break, you're doing it wrong.

    Also, instead of

    v1 = (int(n) for n in version1.split('.'))
    

    try

    v1 = map(int, version1.split('.'))
    

  • 0
    C

    Thanks! I updated my code to reflect your suggestions. I prefer generator expressions to map() which returns a list in python2.7. itertools.imap() and eventually python3 map() has solved it.


  • 0

    Oh, right... outside of LeetCode I usually use Python 3 so I forget to care, and most cases also don't need that care. And I prefer short code.

    Your text still says "This seems a perfect place to use [for .. else]", btw. That's the reason I responded, because I disagreed with that statement :-)


  • 0
    C

    Ah! I forgot about my own comment ;D


  • 0
    This post is deleted!

Log in to reply
 

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