파이썬(python) 연습문제

박성현·2024년 6월 7일

python

목록 보기
2/5

python 연습문제 풀어보자 ! !

PizzBuzz 찍기

  • 규칙 !
    1에서 100까지 출력
    3의 배수는 Fizz 출력
    5의 배수는 Buzz 출력
    3과 5의 공배수는 FizzBuzz 출력
  • 2가지 방식을 사용했음!
for i in range(1, 101):              # 1부터 100까지 100번 반복
    if i % 3 == 0 and i % 5 == 0:    # 3과 5의 공배수일 때
        print('FizzBuzz', end=' ')            # FizzBuzz 출력
    elif i % 3 == 0:                 # 3의 배수일 때
        print('Fizz', end=' ')                # Fizz 출력
    elif i % 5 == 0:                 # 5의 배수일 때
        print('Buzz', end=' ')                # Buzz 출력
    else:
        print(i, end=' ')  
for i in range(1, 101):
    print('Fizz' * (i % 3 == 0) + 'Buzz' * (i % 5 == 0) or i, end=' ')


숫자 맞추기 게임

** 규칙
1~10사이의 Random한 값 1개 맞추기
맞출때까지 계속 진행
몇번만에 맞췄는 지 출력

import random

# 1 ~ 9 com 숫자 맞추기
com = int(random.random() * 9) + 1
print('com =',com)
count = 0
while True:
    count += 1 # count++ => X
    user = int(input('user > '))
    if com == user:        
        break;    

print(f'{count}번만에 빙고')


숫자 찍어보기

  • 1줄에 5숫자찍 나올 수 있도록 해보자 !
for i in range(1,26):    
    if i < 10:
        print(i, end='  ')
    else:
        print(i, end=' ')
    if i % 5 == 0:
        print()


주사위 눈 구하기

  • 두 개의 주사위를 던졌을 때 눈의 합이 6이 되는 모든 경우의 수
n = 6
for i in range(1,7):
    for j in range(1,7):
        if i + j == n:
            print(f'({i},{j})', end= '')


버블정렬 구하기

  • 먼저 sortNum 배열에 랜덤한 10개의 값을 넣어준다
import random

sortNum = []
for i in range(10):
    n = random.randint(1,45)
    sortNum.append(n)
sortNum
  • 넣은 배열값을들 이용하여 마지막값을 제외한((sortNum)-1) 배열을 비교한다
for i in range(len(sortNum)-1):
    if sortNum[i] > sortNum[i+1]:
        check = True
        tmp = sortNum[i]
        sortNum[i] = sortNum[i+1]
        sortNum[i+1] = tmp
    print(sortNum) # 변화 값 확인


로또 복권번호 뽑아보기 !

  • set 자료형을 사용해 로또번호 6개 (1~45, 중복불가) 뽑기
  • 먼저 1장만 뽑아보자 ! !
import random

lottoOne = set()
while True:
    lottoOne.add(random.randint(1,45))
    if len(lottoOne) == 6:
        break

lottoOne

  • 이번엔 5개를 한번에 뽑아보자!
import random

lottoOne = set()
lottoFive = list()
while True:
    lottoOne.add(random.randint(1,45))
    if len(lottoOne) == 6:
        lottoFive.append(lottoOne)
        lottoOne = set()
    if len(lottoFive) == 5:
        break

lottoFive


profile
개발기록장

0개의 댓글