알고리즘 문제풀이

수학숙제 (백준2870)

wiojfe 2024. 3. 15. 17:39

https://www.acmicpc.net/problem/2870

 

2870번: 수학숙제

종이에서 찾은 숫자의 개수를 M이라고 하면, 출력은 M줄로 이루어져야 한다. 각 줄에는 종이에서 찾은 숫자를 하나씩 출력해야 한다. 이때, 비내림차순으로 출력해야 한다. 비내림차순은 내림차

www.acmicpc.net

 

영어 소문자와 숫자가 섞여있는 문자열에서 숫자들만 뽑아내서 새로운 배열을 만들고 정렬하면 된다. 

해당코드는 정규식을 사용한 알고리즘이다. \d+는 정규식에서 숫자들을 지칭하는 메타문자이다. 

 

import re
n =int(input())
def extract_numbers(s):
    # 문자열 s에서 숫자만 찾아 리스트로 반환
    numbers = re.findall(r'\d+', s)
    return numbers

onlynums=[]
for i in range(n):
    string = input().rstrip()
    numbs = extract_numbers(string)
    for num in numbs:
        onlynums.append(int(num))
# print
onlynums.sort()
for num in onlynums :
    print(num)