예지의 개발 로그포스 (Yeji's Log Force)

[Programmers][Python] 주사위 게임 3 본문

CS/Algorithm & Data Structure

[Programmers][Python] 주사위 게임 3

Yeji Heo 2023. 9. 9. 20:33

주사위 숫자가 몇 번 '중복'등장하는 지에 따라 return값이 달라진다.

python에서 중복이라고 하면 set함수와 dictionary가 떠오른다.

 

1. Set

처음에는 set함수를 떠올렸다.

set을 통해 중복을 없앤 집합의 요소가 몇 개인지 판단하여,

집합을 배열로 변환해 값을 계산 후 return하려고 했다.

 

하지만 그렇게 할 경우

중복이 3개여도 집합에 2개가 남고,  예) [4, 1, 4, 4] => {4, 1}

중복이 2개여도 집합에 2개가 남아   예) [4, 4, 1, 1] => {4, 1}

구분이 모호해지는 문제가 있으므로, 다른 어떤 방식으로 또 처리해주긴 번거롭지 않을까 했다.

 

2.  Dictionary

그래서 남은 것의 개수를 보는 것이 아니라, 직접 중복 횟수를 세어주기로 했다.

그를 위해 dictionary가 유용하겠다고 생각했다. 

나온 수를 key, 등장 횟수를 value로 저장한다.

def solution(a, b, c, d):
    arr=[a, b, c, d]
    dic={1:0, 2:0, 3:0, 4:0, 5:0, 6:0}
    
    for item in arr:
        dic[item]+=1
                
    if max(dic.values())==4:
        for item in dic.keys():
            if dic[item] == 4: return item*1111
    
    elif max(dic.values()) == 3:
        p=0
        q=0
        for item in dic.keys():
            if dic[item] == 3: p=item
            elif dic[item] == 1: q=item
                
        return (10 * p + q) ** 2
    
    elif max(dic.values()) == 2:
        q=0
        r=0
        if 1 in dic.values():
            for item in dic.keys():
                if dic[item] == 1:
                    if q==0: q=item
                    else: r = item
            return q * r
        else:
            for item in dic.keys():
                if dic[item] == 2:
                    if q==0: q=item
                    else: r=item
        return (q+r) * abs(q-r)
        
    elif max(dic.values()) == 1:
        return min(arr)

 

3. List

막상 Dictionary로 해보니 key, value에 접근할 일이 많아 생각보다 번거롭고 코드도 길어졌다.

그래서 중복 등장 횟수를 담은 cnt라는 list를 만들어서 다시 풀었다.

def solution(a, b, c, d):
    arr = [a, b, c, d]
    cnt = [arr.count(item) for item in arr]
    
    if max(cnt)==4: return a*1111
    
    elif max(cnt)==3:
        return (10 * (arr[cnt.index(3)]) + (arr[cnt.index(1)]))**2       
    
    elif max(cnt)==2:    
        if 1 in cnt:
            return arr[cnt.index(1)] * arr[cnt.index(1, cnt.index(1)+1,4)]
        else:
            for item in arr:
                if a!=item:
                    return (a+item) * abs(a-item)
        
    else: return min(arr)

cnt는 중복 횟수를 담고 있는데,

그 중복 횟수의 index를 arr의 index로서 써주면 

해당 횟수만큼 중복 등장한 수가 무엇인지 가져올 수 있는 것이다. 

 

 

Comments