๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ’ป Programming/์•Œ๊ณ ๋ฆฌ์ฆ˜ ํ…Œ์ŠคํŠธ

[python] ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค_์นด์นด์˜ค21_๋ฉ”๋‰ด ๋ฆฌ๋‰ด์–ผ (์™„์ „ํƒ์ƒ‰, combinations)

by ๋ญ…์ฆค 2022. 2. 21.
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ

 

ํ’€์ด

 

itertools ์—์„œ combinations ์„ import ํ•ด์„œ ๋ฌธ์ž์—ด์˜ ์กฐํ•ฉ์„ ์ด์šฉํ•œ๋‹ค. combinations ๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ์•„๋ž˜์ฒ˜๋Ÿผ ๊ฐ ํŠœํ”Œ์— ํ•˜๋‚˜์˜ ์กฐํ•ฉ์ด ๊ฐ ์›์†Œ๋ณ„๋กœ ์ชผ๊ฐœ์ ธ์„œ ์ถœ๋ ฅ๋˜๋ฏ€๋กœ, ํ•„์š”์— ๋”ฐ๋ผ ํ›„์ฒ˜๋ฆฌ๊ฐ€ ํ•„์š”ํ•˜๋‹ค.

a = 'abcd'
b = list(combinations(a,2))
print(b)

for i in range(len(b)):
  b[i] = ''.join(b[i])
print(b)

 

๋ฌธ์ œ๋Š” order ๋ฌธ์ž์—ด์„ ์ˆœํšŒํ•˜๋ฉด์„œ ๊ฐ ์ฃผ๋ฌธ๋ณ„๋กœ ๋ชจ๋“  ์กฐํ•ฉ์˜ ๊ฐœ์ˆ˜๋ฅผ foodMap์œผ๋กœ ์นด์šดํŠธํ•˜๊ณ , ์„ธํŠธ์˜ ๋ฉ”๋‰ด ๊ฐœ์ˆ˜๋ณ„ max๊ฐ’์„ ์นด์šดํŠธํ•ด๋‘”๋‹ค. ๊ทธ๋ฆฌ๊ณ  ๋งˆ์ง€๋ง‰์— course๋ฅผ ์ˆœํšŒํ•˜๋ฉด์„œ foodMap์—์„œ value๊ฐ’์ด maxCnt์™€ ๋™์ผํ•œ key๋งŒ answer์— appendํ•˜๊ณ  ๋งˆ์ง€๋ง‰์— answer๋ฅผ sort ํ•˜๊ณ  ๋ฆฌํ„ดํ•œ๋‹ค.

 

* dictionary๋ฅผ for ๋ฌธ์„ ๋Œ๋ฉด์„œ key์™€ value๋ฅผ ๋ชจ๋‘ ์–ป๊ณ  ์‹ถ์„๋•Œ๋Š” .items()๋ฅผ ์ด์šฉํ•œ๋‹ค.

a={'a':1,'b':2,'c':3}
print(a,end='\n\n')

for key,value in a.items():
  print('key =',key,',','values =',value)

 

 

from itertools import combinations

def solution(orders, course):
    answer = []
    foodMap = [{} for _ in range(11)] 
    maxCnt = [0 for _ in range(11)]
    
    for str in orders:
        for num in range(2,len(str)+1):
            for i in combinations(sorted(str),num):
                key = ''.join(i)
                if key in foodMap[num]:
                    foodMap[num][key] +=1
                    maxCnt[num] = max(maxCnt[num],foodMap[num][key]) 
                else:
                    foodMap[num][key] = 1
                    
    for num in course:
        for key, value in foodMap[num].items():
            if value >=2 and maxCnt[num] == value:
                answer.append(key)
                
    answer=sorted(answer)
            
    
    return answer

 

๋ฐ˜์‘ํ˜•