Coding/Code in the Morning

220302_Code in the morning(์†Œ์ˆ˜ ๋งŒ๋“ค๊ธฐ)

๊น€์œ ๋‹ˆ์ฝ˜ 2022. 3. 2. 16:20

๐Ÿ’ฌ ๋ฌธ์ œ ์„ค๋ช…

ํ•œ์ž๋ฆฌ ์ˆซ์ž๊ฐ€ ์ ํžŒ ์ข…์ด ์กฐ๊ฐ์ด ํฉ์–ด์ ธ์žˆ์Šต๋‹ˆ๋‹ค. ํฉ์–ด์ง„ ์ข…์ด ์กฐ๊ฐ์„ ๋ถ™์—ฌ ์†Œ์ˆ˜๋ฅผ ๋ช‡ ๊ฐœ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋Š”์ง€ ์•Œ์•„๋‚ด๋ ค ํ•ฉ๋‹ˆ๋‹ค.

๊ฐ ์ข…์ด ์กฐ๊ฐ์— ์ ํžŒ ์ˆซ์ž๊ฐ€ ์ ํžŒ ๋ฌธ์ž์—ด numbers๊ฐ€ ์ฃผ์–ด์กŒ์„ ๋•Œ, ์ข…์ด ์กฐ๊ฐ์œผ๋กœ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋Š” ์†Œ์ˆ˜๊ฐ€ ๋ช‡ ๊ฐœ์ธ์ง€ return ํ•˜๋„๋ก solution ํ•จ์ˆ˜๋ฅผ ์™„์„ฑํ•ด์ฃผ์„ธ์š”.

 

๐Ÿ“ ์ œํ•œ ์‚ฌํ•ญ

 

  • numbers๋Š” ๊ธธ์ด 1 ์ด์ƒ 7 ์ดํ•˜์ธ ๋ฌธ์ž์—ด์ž…๋‹ˆ๋‹ค.
  • numbers๋Š” 0~9๊นŒ์ง€ ์ˆซ์ž๋งŒ์œผ๋กœ ์ด๋ฃจ์–ด์ ธ ์žˆ์Šต๋‹ˆ๋‹ค.
  • "013"์€ 0, 1, 3 ์ˆซ์ž๊ฐ€ ์ ํžŒ ์ข…์ด ์กฐ๊ฐ์ด ํฉ์–ด์ ธ์žˆ๋‹ค๋Š” ์˜๋ฏธ์ž…๋‹ˆ๋‹ค.

 

 

 

๐Ÿ’ก ๋‚˜์˜ ํ’€์ด 

from itertools import permutations
answer = []  
def solution(numbers):
                                 
    nums = [n for n in numbers]  # numbers๋ฅผ ํ•˜๋‚˜์”ฉ ์ž๋ฅธ ๊ฒƒ
    per = []                                      
    for i in range(1, len(numbers)+1):  # numbers์˜ ๊ฐ ์ˆซ์ž๋“ค์„ ์ˆœ์—ด๋กœ ๋ชจ๋“  ๊ฒฝ์šฐ ๋งŒ๋“ค๊ธฐ
        per += list(permutations(nums, i))   # i๊ฐœ์”ฉ ์ˆœ์—ด์กฐํ•ฉ
    new_nums = [int(("").join(p)) for p in per] # ๊ฐ ์ˆœ์—ด์กฐํ•ฉ์„ ํ•˜๋‚˜์˜ intํ˜• ์ˆซ์ž๋กœ ๋ณ€ํ™˜
    
    for n in new_nums:                           
        for i in range(2, n + 1): 
            if n % i == 0:       
                break
            elif n % i !=0:
                answer.append(n)                      
                # print(answer)
    return len(set(answer)) # set์„ ํ†ตํ•ด ์ค‘๋ณต ์ œ๊ฑฐ ํ›„ ๋ฐ˜ํ™˜

 

 

๐Ÿ’ก ๋‹ค๋ฅธ ํ•ด์„ค

from itertools import permutations
import math
answer = []  
def solution(numbers):
                                 
    nums = [n for n in numbers]  # numbers๋ฅผ ํ•˜๋‚˜์”ฉ ์ž๋ฅธ ๊ฒƒ
    per = []                                      
    for i in range(1, len(numbers)+1):  # numbers์˜ ๊ฐ ์ˆซ์ž๋“ค์„ ์ˆœ์—ด๋กœ ๋ชจ๋“  ๊ฒฝ์šฐ ๋งŒ๋“ค๊ธฐ
        per += list(permutations(nums, i))   # i๊ฐœ์”ฉ ์ˆœ์—ด์กฐํ•ฉ
    new_nums = [int(("").join(p)) for p in per] # ๊ฐ ์ˆœ์—ด์กฐํ•ฉ์„ ํ•˜๋‚˜์˜ intํ˜• ์ˆซ์ž๋กœ ๋ณ€ํ™˜
    
 
    for n in new_nums:                            # ๋ชจ๋“  intํ˜• ์ˆซ์ž์— ๋Œ€ํ•ด ์†Œ์ˆ˜์ธ์ง€ ํŒ๋ณ„
        if n < 2:                                 # 2๋ณด๋‹ค ์ž‘์€ 1,0์˜ ๊ฒฝ์šฐ ์†Œ์ˆ˜ ์•„๋‹˜
            continue
        check = True            
        for i in range(2,int(n**0.5) + 1):        # n์˜ ์ œ๊ณฑ๊ทผ ๋ณด๋‹ค ์ž‘์€ ์ˆซ์ž๊นŒ์ง€๋งŒ ๋‚˜๋ˆ—์…ˆ
            if n % i == 0:                        # ํ•˜๋‚˜๋ผ๋„ ๋‚˜๋ˆ ๋–จ์–ด์ง„๋‹ค๋ฉด ์†Œ์ˆ˜ ์•„๋‹˜!
                check = False
                break
        if check:
            answer.append(n)                      # ์†Œ์ˆ˜์ผ๊ฒฝ์šฐ answer ๋ฐฐ์—ด์— ์ถ”๊ฐ€

    return len(set(answer))                       # set์„ ํ†ตํ•ด ์ค‘๋ณต ์ œ๊ฑฐ ํ›„ ๋ฐ˜ํ™˜

 

๐Ÿ‘‰๐Ÿป ๋ฌธ์ œ ๋ฐ”๋กœ๊ฐ€๊ธฐ