개발일기

#8 프로그래머스 문자열을정수로바꾸기/주사위의개수/직각삼각형출력/문자열정렬/n의배수고르기 본문

오류 및 알고리즘정리본

#8 프로그래머스 문자열을정수로바꾸기/주사위의개수/직각삼각형출력/문자열정렬/n의배수고르기

츄98 2023. 4. 22. 02:40

오늘은 좀 많이 풀어서.. 정리할 게 많다. 부지런히 가보자고~

 

 

1. 문자열을 정수로 바꾸기

# 문자열을 정수로 바꾸기
def solution(s):
    answer = int(s)
    return answer

아주 단순하게 풀 수 있는 문제...!

그런데, 이걸 좀 창의적으로 풀어보자

# 다른 방식
def strToInt(str):
    result = 0
    for idx, number in enumerate(str[::-1]):
        if number == '-':
            result *= -1
        else:
            result += int(number) * (10 ** idx)
    return result

# str[::-1]은 주어진 스트링을 거꾸로 만들어버림
# 그 다음에 enumerate 함수를 이용하여 한 글자당 인덱스를 배정해서 각 자리에 10의 지수만큼 곱해서 더해주기
# 예를 들면 "-1234"는 str[::-1]에 의해 "4321-"가 되고,
# 4 * (10 ** 0) + 3 * (10 ** 1) + 2 * (10 **2) + 1 * (10 ** 3)를 한 이후에 "-" 는 이 숫자를 마이너스로 만든다.

def strToInt(str):
    result = 0
    size=len(str)
    temp = 0
    if str [0] == '-' :
        sign = -1
    else :
        sign = 1
    for i in range(0, size) :
        if str[i] == '1' :
            temp = 1
        elif str[i] == '2' :
            temp = 2
        elif str[i] == '3' :
            temp = 3
        elif str[i] == '4' :
            temp = 4
        elif str[i] == '5' :
            temp = 5
        elif str[i] == '6' :
            temp = 6
        elif str[i] == '7' :
            temp = 7
        elif str[i] == '8' :
            temp = 8
        elif str[i] == '9' :
            temp = 9
        else :
            temp = 0
        for i in range(size-i-1) :
            temp = temp * 10
        result = result + temp
    result = result * sign
    return result
    # 이 풀이도 위에랑 비슷하게 각 자리에 10의 지수만큼 곱해서 숫자로(정수로) 바꾼다.

 

 

2. 주사위의 개수

# 주사위의 개수
def solution(box, n):
    return (box[0]//n)*(box[1]//n)*(box[2]//n)

# 다른 풀이
def solution(box, n):
    x, y, z = box
    # 오.. 이렇게 둬도 되는군!!!
    # unpacking
    return (x // n) * (y // n) * (z // n )

import math
def solution(box, n):
    return math.prod(map(lambda v: v//n, box))

def solution(box, n):
    w,h,d = box[0]//n,box[1]//n,box[2]//n
    # 이런 표기법에도 앞으로 익숙해지자
    return w*d*h

unpacking하는 새로운 방식..!

x, y, z = box라고 두면, x = box[0], y = box[1], z = box[2] 를 의미하는 것..!

 

 

3. 직각삼각형 출력하기

# 직각삼각형 출력하기
n = int(input())
for i in range(n):
    print('*'*(i+1))

# 다른 풀이
print('\n'.join('*' * (i + 1) for i in range(int(input()))))

이건 그냥.. 한 줄의 마법... 정리가 깔끔해서 가지고 와보았다.

 

 

4. 문자열 정렬하기

문자열  my_string이 매개변수로 주어질 때, 
my_string 안에 있는 숫자만 골라 오름차순 정렬한 리스트를 return 하도록 solution 함수를 작성해보세요.

 

# 문자열 정렬하기
def solution(my_string):
    answer = []
    for string in my_string:
        if string.isnumeric():
            answer.append(int(string))
    return sorted(answer)

이렇게 풀면 된다.

 

여기서서 answer.append(int(string)) 을 하는 과정에서 다양하게 시도를 해봤다.

시도 ) answer += int(string) 또는 answer.extend(int(string))하면 오류가 난다.
TypeError: 'int' object is not iterable

이유가 뭘까?

이유는 에러메세지 그대로.. int(string) is not iterable
extend()의 개념.. 특징을 살펴보면, Extend list by appending elements from the iterable.
즉 iterable한 값들을 붙여준다.

하지만 append()는 Append object to the end of the list.
개념과 특징이, list def append(self, __object: _T) -> None
이렇다..!! iterable 하지 않아도 붙여준다는 것!!
그래서 append()를 이용해서 코드를 작성해주었다.

다음으로, isnumeric()에 대해 자세히 설명해보자.

Python의 isnumeric() 함수는 문자열이 숫자로 구성되어 있는지 판별해주는 함수이다.
isdigit()과 유사한 함수이고, 이 메소드는 문자열의 모든 문자가 숫자일 때 true를 반환하고 그렇지 않으면 false를 반환한다.

그렇다면 isdigit()은 무엇인가

Python의 isdigit() 함수는 문자열이 숫자로 구성되어 있는지 판별해주는 함수이다.
다만, 음수나 소숫점이 있을 경우에는 숫자임에도 불구하고 False를 리턴하게 된다.
이 메소드는 문자열의 모든 문자가 숫자일 때 true를 반환하고 그렇지 않으면 false를 반환한다.

다른 풀이로는 다음이 있다.

# 다른 풀이
def solution(my_string):
    return sorted([int(c) for c in my_string if c.isdigit()])

def solution(my_string):
    return sorted(map(int, filter(lambda s: s.isdigit(), my_string)))

 

여기서, sorted(map(int, filter(lambda s: s.isdigit(), my_string)))이 list로 잘 나오는 것은 왜 그럴까?

왜 이렇게 되는지 원리를 찾아보자.

직접 해보았다.
print(sorted(map(int, "1234"))) -> [1, 2, 3, 4]
리스트로 나온다!!!!

리스트로 나오는 이유를 sorted 함수의 개념에서 찾을 수 있었다.
def sorted(__iterable: Iterable[_T], *, key: (_T) -> SupportsLessThan, reverse: bool = ...) -> List[_T]
Return a new list containing all items from the iterable in ascending order.
리스트로 나온다!!!

다른 예제로도 직접 해보았다.
print(type(sorted({1,4,2}))) -> <class 'list'>
print(sorted({1,4,2})) -> [1, 2, 4]
print(sorted("521")) -> ['1', '2', '5']
와우~~~ iterable한 값들을 모두 리스트에 (오름차순으로) 담아 반환해준다.

기왕 이렇게 파보는 것.. map()도 살펴보자
print(map(int, "1234")) -> <map object at 0x0000024C92496FD0>
print(type(map(int,"1234"))) -> <class 'map'>
map type으로 값이 나온다.

The map() function returns an object of map class.
The returned value can be passed to functions like list() - to convert to list, set() - to convert to a set, and so on.
최대한 의미를 제대로 전달하고 싶어서 영어를 그대로 들고 왔다.
무슨 말이냐하면 map()은 list()를 통해 리스트가 될 수 있고, set()을 통해 set이 될 수 있다.

 

 

5. n의 배수 고르기

# n의 배수 고르기
def solution(n, numlist):
     answer = []
     for num in numlist:
         if num%n == 0:
             answer.append(num)
     return answer

#  다른 사람 풀이
def solution(n, numlist):
    return list(filter(lambda v: v%n==0, numlist))

def solution(n, numlist):
    answer = [i for i in numlist if i%n==0]
    return answer

이것도 이렇게 깔끔하게 정리된다는 것을 기록하고 싶었다..!!

 

 

 

오늘은 알고리즘 정리가 좀 길었다.

그래서 더 뿌듯하다!!!