Python study

11일차

문자열 심화 문제

  1. 문자열을 입력받고, 괄호가 잘 닫혀있는 문장인지 점검
  • 문장 내에서 괄호는 무조건 '('로 시작하고 ')'로 끝나야 한다.
  • ex. hell(o, my name (is zin)c!)

replace(), split()

user = input()

u = user.replace('(',' ( ').replace(')',' ) ')
x = u.split(' ')

print(x)

n = 0

for i in x:
    if n < 0:
        break
    elif i == '(':
        n += 1
    elif i == ')':
        n -= 1

if n == 0:
    print("괄호가 잘 닫혀있는 문장입니다.")
else:
    print("괄호가 잘 닫혀있지 않는 문장입니다.")
  • user.replace('(',' ( ').replace(')',' ) ') : 공백으로 나눠주기 위해 대체해준다.
  • if n < 0: break : 음수가 나온다는 것은 ')'가 '(' 보다 먼저 나왔거나 더 많이 존재한다는 것이기 때문에 break를 해준다.

  1. 영어 끝말잇기 프로그램 / 실패할 경우 종료

    인덱싱

user = input("끝말잇기 시작 : ")

while 1:
    print(f"{user} -> ", end='')
    next = input()

    if user[-1] == next[0]:
        pass
    else:
        print("game over!")
        break

    user = next
  • 첫 단어의 마지막 글자를 인덱싱 : user[-1]
  • 다음 단어의 첫 글자를 인덱싱 : next[0]
  • while문 마지막에 user = next해줌으로써 단어를 넘겨주는 과정이 필요하다.

  1. 1에서 N까지 이어서 적었을 때 문자열의 길이를 구하여라

    len()

N = int(input("수 입력 : "))

x =''

for i in range(1, N+1):
    x += str(i)

print(len(x))
  • N을 int형으로 받아줬기 때문에 str(i)로 형변환을 해주는 과정이 필요하다.
  • 문자열은 더하기 연산을 해주면 이어서 붙는다는 성질을 활용한다.

  1. 주민번호를 통해 남성과 여성의 비율을 구하여라

    split(), 인덱싱

num = ['150612-2******', '020900-2******', '910519-1******', '130218-2******', '130103-3******', '910316-0******', '970720-1******', '130717-3******', '070203-3******', '820114-1******', '910018-1******', '980803-0******', '820600-1******', '130628-3******', '150902-2******', '970220-0******', '830924-1******', '090712-3******', '901011-1******', '190910-3******', '861203-1******', '070704-3******', '970505-0******', '020222-3******', '810501-1******', '160326-2******', '190611-3******', '200506-3******', '100410-2******', '970028-0******', '851213-0******', '850418-1******', '031210-2******', '090113-3******', '810902-1******', '030726-3******', '020126-3******', '910215-1******', '081006-3******', '871209-0******', '170927-2******']

w = 0
m = 0

for i in num:
    nums = i.split('-')[1]
    
    if int(nums[0]) % 2 == 0:
        w += 1
    else :
        m += 1

wp = w / (w+m) * 100
mp = m / (w+m) * 100

print(f"여성 : {wp}%, 남성 : {mp}%")
  • nums = i.split('-')[1] : '-'로 나눠준 후 인덱싱을 활용하여 1번 자리의 요소를 불러온다.
  • 예를 들어 '2**' 이런식으로 불러와지기 때문에 int(nums[0])로 '2'만 가져와서 정수형으로 형변환 시켜준다.

문자열 + set

set : 중복을 제거하는 함수

  1. 노래가사에서 단어를 분리해서 중복을 제거하여라
music = """Cos ah ah I'm in the stars tonight
So watch me bring the fire and set the night alight
Shoes on get up in the morn
Cup of milk let's rock and roll
King Kong kick the drum rolling on like a rolling stone
Sing song when I'm walking home
Jump up to the top LeBron
Ding dong call me on my phone
Ice tea and a game of ping pong
This is getting heavy
Can you hear the bass boom, I'm ready
Life is sweet as honey
Yeah this beat cha ching like money
Disco overload I'm into that I'm good to go
I'm diamond you know I glow up
Hey, so let's go
Cos ah ah I'm in the stars tonight
So watch me bring the fire and set the night alight
Shining through the city with a little funk and soul
So I'mma light it up like dynamite, woah
Bring a friend join the crowd
Whoever wanna come along
Word up talk the talk just move like we off the wall
Day or night the sky's alight
So we dance to the break of dawn
Ladies and gentlemen,
I got the medicine so you should keep ya eyes on the ball, huh
This is getting heavy
Can you hear the bass boom, I'm ready
Life is sweet as honey
Yeah this beat cha ching like money
Disco overload I'm into that I'm good to go
I'm diamond you know I glow up
Let's go
Cos ah ah I'm in the stars tonight
So watch me bring the fire and set the night alight
Shining through the city with a little funk and soul
So I'mma light it up like dynamite, woah
Dynnnnnanana, life is dynamite
Dynnnnnanana, life is dynamite
Shining through the city with a little funk and soul
So I'mma light it up like dynamite, woah
Dynnnnnanana eh
Dynnnnnanana eh
Dynnnnnanana eh
Light it up like dynamite
Dynnnnnanana eh
Dynnnnnanana eh
Dynnnnnanana eh
Light it up like dynamite
Cos ah ah I'm in the stars tonight
So watch me bring the fire and set the night alight
Shining through the city with a little funk and soul
So I'mma light it up like dynamite
Cos ah ah I'm in the stars tonight
So watch me bring the fire and set the night alight
Shining through the city with a little funk and soul
So I'mma light it up like dynamite, woah
Dynnnnnanana, life is dynamite
Dynnnnnanana, life is dynamite
Shining through the city with a little funk and soul
So I'mma light it up like dynamite, woah"""

m = music.replace('\n', ' ').replace(',','').split(' ')

for i in set(m):
    print(f"{i}가 나오는 횟수 : {m.count(i)}")
  • set(m) : 노래가사를 단어로 분리해주고 거기서 중복된 것을 제거한 결과이다.

  1. N회를 입력받고, 로또번호를 출력하는 프로그램
  • set()으로 초기화, add()로 추가
  • a = set() : a라는 세트 선언 (초기확)
  • a.add(1) : a세트에 1추가
import random

N = int(input("횟수 입력 : "))

for i in range(1, N+1):

    x = set()

    while 1:
        ran = random.randint(1, 45)
        x.add(ran)

        if len(x) == 6:
            break

    print(f"{i}회 당첨번호는 {x}")

문자열 + dictionary

dictionary : 사전

  • 노래가사의 단어들의 중복을 제거해서 dictionary에 단어 : 단어등장횟수 로 저장.
  • a[1] = "four" : a라는 사전에 1 : "four" 이런식으로 저장된다.
music = """Cos ah ah I'm in the stars tonight
So watch me bring the fire and set the night alight
Shoes on get up in the morn
Cup of milk let's rock and roll
King Kong kick the drum rolling on like a rolling stone
Sing song when I'm walking home
Jump up to the top LeBron
Ding dong call me on my phone
Ice tea and a game of ping pong
This is getting heavy
Can you hear the bass boom, I'm ready
Life is sweet as honey
Yeah this beat cha ching like money
Disco overload I'm into that I'm good to go
I'm diamond you know I glow up
Hey, so let's go
Cos ah ah I'm in the stars tonight
So watch me bring the fire and set the night alight
Shining through the city with a little funk and soul
So I'mma light it up like dynamite, woah
Bring a friend join the crowd
Whoever wanna come along
Word up talk the talk just move like we off the wall
Day or night the sky's alight
So we dance to the break of dawn
Ladies and gentlemen,
I got the medicine so you should keep ya eyes on the ball, huh
This is getting heavy
Can you hear the bass boom, I'm ready
Life is sweet as honey
Yeah this beat cha ching like money
Disco overload I'm into that I'm good to go
I'm diamond you know I glow up
Let's go
Cos ah ah I'm in the stars tonight
So watch me bring the fire and set the night alight
Shining through the city with a little funk and soul
So I'mma light it up like dynamite, woah
Dynnnnnanana, life is dynamite
Dynnnnnanana, life is dynamite
Shining through the city with a little funk and soul
So I'mma light it up like dynamite, woah
Dynnnnnanana eh
Dynnnnnanana eh
Dynnnnnanana eh
Light it up like dynamite
Dynnnnnanana eh
Dynnnnnanana eh
Dynnnnnanana eh
Light it up like dynamite
Cos ah ah I'm in the stars tonight
So watch me bring the fire and set the night alight
Shining through the city with a little funk and soul
So I'mma light it up like dynamite
Cos ah ah I'm in the stars tonight
So watch me bring the fire and set the night alight
Shining through the city with a little funk and soul
So I'mma light it up like dynamite, woah
Dynnnnnanana, life is dynamite
Dynnnnnanana, life is dynamite
Shining through the city with a little funk and soul
So I'mma light it up like dynamite, woah"""

m = music.replace('\n', ' ').replace(',', '').split(' ')

dynamite = {}

for i in set(m):
    dynamite[i] = m.count(i)

for i in dynamite:
    print(f"key = {i} : value = {dynamite[i]}")
profile
내 꿈은 멋쟁이개발자

0개의 댓글