ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 숫자 카드 나누기
    코딩 테스트/Level 2 2022. 11. 10. 22:40
    반응형

    https://school.programmers.co.kr/learn/courses/30/lessons/135807

    gcd를 이용하면 통과.

    from math import gcd
    
    
    def solution(nums1, nums2):
        gcd1, gcd2 = nums1[0], nums2[0]
        for each1, each2 in zip(nums1[1:], nums2[1:]):
            gcd1, gcd2 = gcd(each1, gcd1), gcd(each2, gcd2)
        answer = []
        for each1 in nums1:
            if each1 % gcd2 == 0:
                break
        else:
            answer.append(gcd2)
        for each2 in nums2:
            if each2 % gcd1 == 0:
                break
        else:
            answer.append(gcd1)
        return max(answer) if answer else 0

    all과 reduce를 이용해 줄일 수 있다. 

    from functools import reduce
    from math import gcd
    
    
    def solution(nums1, nums2):
        gcd1, gcd2 = reduce(gcd, nums1), reduce(gcd, nums2)
        answer = []
        if all(each % gcd2 for each in nums1):
            answer.append(gcd2)
        if all(each % gcd1 for each in nums2):
            answer.append(gcd1)
        return max(answer) if answer else 0
    반응형
Designed by Tistory.