STUDY/Algorithm

[프로그래머스] LEVEL2 숫자 야구, python3, 완전탐색

sinawi95 2019. 11. 18. 10:43
728x90

from itertools import permutations 
def solution(baseball): 
    answer = 0 
    correct=list(permutations([1,2,3,4,5,6,7,8,9], 3)) 
    for i in range(len(baseball)): 
        tmp=tuple(map(int,list(str(baseball[i][0])))) 
        #print("tmp:",tmp) 
        cr_num=0 
        try: 
            while correct!=[]: 
                st_chk=0 
                b_chk=0
                #check strike and ball 
                if tmp[0]==correct[cr_num][0]: 
                    st_chk+=1 
                elif tmp[0]==correct[cr_num][1]: 
                    b_chk+=1 
                elif tmp[0]==correct[cr_num][2]: 
                    b_chk+=1 
                if tmp[1]==correct[cr_num][1]: 
                    st_chk+=1 
                elif tmp[1]==correct[cr_num][0]: 
                    b_chk+=1 
                elif tmp[1]==correct[cr_num][2]: 
                    b_chk+=1 
                if tmp[2]==correct[cr_num][2]: 
                    st_chk+=1 
                elif tmp[2]==correct[cr_num][0]: 
                    b_chk+=1 
                elif tmp[2]==correct[cr_num][1]: 
                    b_chk+=1 
                if st_chk!=baseball[i][1]: 
                    del correct[cr_num] 
                elif b_chk!= baseball[i][2]: 
                    del correct[cr_num] 
                elif cr_num!=len(correct)-1: 
                    cr_num+=1 
                else: 
                    break 
        except: 
            pass
    answer=len(correct) 
    return answer