STUDY/Algorithm

[프로그래머스] LEVEL2 구명보트, python3, 탐욕법(greedy)

sinawi95 2019. 11. 14. 10:23
728x90

1차 시도

def solution(people, limit):
    answer = 0
    people.sort()
    #print(people)
    while people!=[]:
        answer+=1
        tmp1=people.pop()
        tmp2=limit-tmp1
        #print(tmp1,tmp2,people)

        if people==[]:
            break
        elif tmp1==limit:
            continue
        elif tmp2<people[0]:
            continue
        else: #tmp1            try:
                tmp_ind=people.index(tmp2)
                people.pop(tmp_ind)
            except:
                #print("except:",people)
                tmp3=people.pop()
                if tmp2>tmp3:
                    continue
                        
                    
    return answer


2차시도

def solution(people, limit):
    answer = 0
    people.sort()
    while people!=[]:
        answer+=1
        tmp=people.pop()
        remainder=limit-tmp
        if people==[]:
            break
        elif remainder<people[0]:
            continue
        else:    
            for num in (people):
                ind=0
                if remainder                    break
                elif remainder==num:
                    ind=people.index(num)
                    people.pop(ind)
                    break
                if num==people[-1]:
                    people.pop()
    return answer


3차시도

def solution(people, limit):
    answer = 0
    while people!=[]:
        answer+=1
        tmp=people.pop()
        if people==[]:
            break
        tmp_list=(list(p for p in people if (limit-tmp)>=p ))
        if tmp_list==[]:
            continue
        else:
            max_tmp=max(tmp_list)
            ind=people.index(max_tmp)
            people.pop(ind)
        
    return answer


4차시도

def solution(people, limit):
    answer = 0
    while people!=[]:
        answer+=1
        tmp=people.pop()
        remainder=limit-tmp
        if people==[]:
            break
        elif remainder==0:
            continue
        else:
            try:
                ind=people.index(remainder)
                people.pop(ind)
                continue
            except:
                for num in range(len(people)):
                    list_pp=list(i for i in people if remainder>i)
                    if list_pp==[]:
                        break
                    max_min=max(list_pp)
                    ind=people.index(max_min)
                    people.pop(ind)
                    break
                
        
    return answer

평균시간은 좀 줄었다!


다른사람 코드

def solution(people,limit):
    people.sort()
    length=len(people) 
    light=0
    heavy=length-1
    count=0
    while(light<heavy):
        if people[light]+people[heavy]<=limit:
            count+=1
            light+=1
            heavy-=1
        else:
            heavy-=1
    return length-count


시간이 많이 걸렸던 이유가 sort가 아니고 pop이었다.

sort에만 신경쏟고있었는데...