Python에서 버전 비교 로직

2019. 6. 17. 18:12서버 프로그래밍

http://codingdojang.com/scode/493

 

코딩도장

프로그래밍 문제풀이를 통해서 코딩 실력을 수련

codingdojang.com

from itertools import zip_longest

def compare(left, right):
    left_vars = map(int, left.split('.'))
    right_vars = map(int, right.split('.'))
    for a, b in zip_longest(left_vars, right_vars, fillvalue = 0):
        if a > b:
            return '>'
        elif a < b:
            return '<'
    return '='

여기서 주의할 점은 for 문 안에서 equal은 체크하면 안된다는 것이다. 비교 도중 크거나 작으면 return을 하도록 되어 있는데 eaual이 들어가면 비교 도중에 리턴이 될수도 있기 때문에 오동작을 한다. 이것 때문에 헛고생을 했다. ㅠㅠ

위의 예제에는 그냥 map만 사용했는데 이것은 Python 2.x에서만 사용되는 것으로 보인다. 다음과 같이 list로 감싸주면 숫자 배열로 결과를 만들어 준다.

results = list(map(int, results))

https://stackoverflow.com/questions/7368789/convert-all-strings-in-a-list-to-int

 

Convert all strings in a list to int

In Python, I want to convert all strings in a list to integers. So if I have: results = ['1', '2', '3'] How do I make it: results = [1, 2, 3]

stackoverflow.com

zip_longest() 함수에 대한 설명은 다음 내용을 참고하자.

https://excelsior-cjh.tistory.com/100

 

내장함수 zip() 과 itertools.zip_longest() 함수

Python - Built in Function : zip(*iterables) Python에는 다양한 내장함수(Built-in Function)를 제공한다. 그 중에서 알아두면 유용한 내장함수인 zip() 함수를 알아보도록 하자. 1. zip(*iterables) 함수 zip(..

excelsior-cjh.tistory.com