과제1
가위, 바위, 보 게임 만들기
- 가위, 바위, 보 중 하나를 입력하세요: 가위
- 컴퓨터:바위,유저:가위->결과 컴퓨터 승!
- random함수 사용 가능
# 풀이1
import random
user = input('가위, 바위, 보, 중 하나를 입력하세요: ')
entry = ['가위','바위','보']
com = random.choice(entry)
msg1 = '컴퓨터 승!'
msg2 = '유저 승!'
msg3 = '무승부!'
if com == user:
result = msg3
elif com == '가위' and user == '보':
result = msg1
elif com == '바위' and user == '가위':
result = msg1
elif com == '보' and user == '바위':
result = msg1
elif user == '가위' and com == '보':
result = msg2
elif user == '보' and com == '바위':
result = msg2
elif user == '바위' and com == '가위':
result = msg2
print(f'컴퓨터: {com} 유저: {user} 결과: {result}')
# 풀이2
import random
entry = ['가위', '바위', '보']
user = input('가위, 바위, 보 중 하나를 입력하세요: ')
computer = random.choice(entry)
msg1 = '컴퓨터 승!'
msg2 = '유저 승!'
msg3 = '무승부!'
if user == computer:
result = msg3
elif user == '가위':
if computer == '바위':
result = msg1
elif computer == '보':
result = msg2
elif user == '바위':
if computer == '가위':
result = msg2
elif computer == '보':
result = msg1
elif user == '보':
if computer == '가위':
result = msg1
elif computer == '바위':
result = msg2
print(f'컴퓨터: {computer} 유저: {user} 결과: {result}')
위의 두 풀이는 if문이 너무많아 가독성이 안좋고 코드를 더 단축할 수 있을거같다.
# 풀이3
import random
entry = ['가위', '바위', '보'] # 리스트로 가위 바위보 지정
user = input('가위, 바위, 보 중 하나를 입력하세요: ') # 유저는 인풋을 받음
computer = random.choice(entry) # 컴퓨터는 리스트 값에서 랜덤한값 1개를 반환
use = entry.index(user) # 유저가 입력한 값의 인덱스 출력
com = entry.index(computer) # 컴퓨터가 반환한 값의 인덱스 출력
# 결과 메세지 지정
msg1 = '컴퓨터 승!'
msg2 = '유저 승!'
msg3 = '무승부!'
# 유저와 컴퓨터의 인덱스 값으로 비교
if use == com: # 경우의수가 가장 많은 무승부를 먼저처리 했다.
result = msg3
elif use == 0 and com == 2 :# 유저가 가위 컴퓨터가 보인 경우를 따로 처리
result = msg2
elif use == 2 and com == 0:# 컴퓨터가 가위 유저가 보인 경우를 따로 처리
result = msg1
elif use > com:
result = msg2
else: # 나머지 경우의수 컴퓨터가 이기는 경우
result = msg1
print(f'컴퓨터: {computer} 유저: {user} 결과: {result}')
두 값을 숫자로 비교해 if문을 줄였다.
# 풀이4
import random
entry = ['가위', '바위', '보']
user = input('가위, 바위, 보 중 하나를 입력하세요: ')
computer = random.choice(entry)
use = entry.index(user)
com = entry.index(computer)
msg = ['유저승!','컴퓨터승!','무승부!','유저승!','컴퓨터승!']
ind = use - com
result = msg[ind + 2]
print(f'컴퓨터: {computer} 유저: {user} 결과: {result}')
list와 인데스 만으로 비교해 코드를 최대한으로 줄여보았다.
과제2
로또 예측 프로그램을 작성해보자
- 1 ~ 45까지의 임의의 수 6개를 출력
- 중복된 숫자가 없어야 함
- 오름차순으로 출력
nums = {0,} # 세트 선언
while len(nums) < 7: # 6개의 숫자를 받아야 하기 때문에 len이 7이 될 때 까지 숫자를 받음
num = int(random.randrange(1,46)) # 1~46사이에 랜덤한 숫자를 반환
nums.add(num) # 세트에 add 하면서 중복을 없애줌
li0 = list(nums) # 정렬을 위해 리스트로 선언
result = (sorted(li0[1:7])) # 받은 값을 정렬을 하면서 필요없는 값 0 을 뺀 6개의 값을 담아줌
print(result)
'코딩 > 과제' 카테고리의 다른 글
과제 sql 파이썬을 이용한 프로그램 (2) | 2024.04.01 |
---|---|
과제 - 파이썬 파일 관련 프로그램 (1) | 2024.03.22 |
과제 4 - 파일 입출력을 이용한 단어장 만들기 (0) | 2024.03.22 |
과제 - 주민등록번호 유효검사 (0) | 2024.03.19 |
과제 0.1 + 1.1 == 1.2 가 False 인 이유 (0) | 2024.03.12 |