회고
- 숫자야구가 gpt 예제보다 어려웠다.... gpt예제들 역시 시간이 조금 오래걸렸지만 결국 혼자 힘으로 풀어냈다. 뿌듯하다. 너무 뿌듯하다. 코드를 볼줄도 모르고 어떻게 꾸려 나가야할지 감도 못잡았는데 지금 이렇게 만들어내는거보니 노력은 그래도 배신은 안하나보다. 진짜 힘드네 어우 화이팅이다! 조금은 가능성이 보인다!!!!!!!
필기
- 오늘은 지금까지 배웠던 파이썬의 기초부터 함수까지 복습을 하는 날이었다. 나에게 꼭 필요한 시간이었는데 다행이다. 다음주부터는 객체지향에 들어간다고하니 빡세게 복습하자. 각 형태의 특징과 코드의 전체적인 구조에 집중하면서 공부하자!
a=10
b=20
print(a+b)
print("Hello")
a = 10
b = 3
print( f"{a} + {b} = {a+b}")
print( f"{a} - {b} = {a-b}")
print( f"{a} * {b} = {a*b}")
print( f"{a} / {b} = {a/b}")
print( f"{a} // {b} = {a//b}")
print( f"{a} % {b} = {a%b}")
print( f"{a} ** {b} = {a**b}")
s ="Life is too short, You need Python"
print(s)
print(s[:4])
print(s[8:11])
print(s[0])
print(s[1])
s = s.replace("short", "long")
print(s)
data = """
홍길동,90,90,80
임꺽정,80,80,80
장길산,100,100,90
"""
lines = data.split("\n")
lines = lines[1:len(lines)-1]
print(lines)
dataList=[]
for line in lines:
words = line.split(",")
w = {"name":words[0], "kor":words[1], "eng":words[2], "mat":words[2]}
dataList.append(w)
print(dataList)
name="홍길동"
age=23
phone="010-0000-0001"
kor = 90
eng = 90
mat = 80
total = kor+eng+mat
avg = total/3
print("%s %d %s %d %d" % (name, age, phone, kor, eng) )
print("{} {} {} {} {}".format(name, age, phone, kor, eng))
print(f"{name} {age} {phone} {kor} {eng}")
list1 = [1,2,3,4,5,6,7,8,9,10]
print(list1[0])
print(list1[3])
print(list1[4])
print(list1[:4])
print(list1[2:3])
print( list1)
list1.append(11)
list1.append(12)
list1.extend([10,20,30,40])
print(list1)
list1.clear()
list1.insert(0, 10)
list1.insert(1, 10)
a = list(range(5, 5*10+1, 5))
print(a)
a = list(range(100, 0, -10))
print(a)
a = [1, 2, 3, 2, 4, 3, 5, 1]
b =[]
for i in a:
if i not in b:
b.append(i)
print(b)
a = [ [1,2,3], [4,5,6], [7,8,9]]
for i in a:
print(i)
print(a[0])
print( a[0][0])
a = []
a.append(1)
a.append(2)
a.append(3)
a.append(4)
a.append(5)
a.append(6)
a.append(7)
a.append(8)
a.append(9)
a.append(10)
print( a)
totalList=[]
for k in range(0,10):
a = []
for i in range(k*10+1, (k+1)*10+1):
a.append(i)
totalList.append(a)
for i in range(0, 10):
for j in range(0, 10):
print("%4d" % totalList[i][j], end="" )
print()
totalList=[]
kk=1
for k in range(0,10):
a = []
for i in range(0, 10):
if i < (k+1):
a.append(kk)
kk+=1
else:
a.append(0)
totalList.append(a)
for i in range(0, 10):
for j in range(0, 10):
print("%4d" % totalList[i][j], end="" )
print()
a = [5,4,1,7,8,3,6]
def getMax(a):
max = a[0]
pos = 0
for i in range(1, len(a)):
if max < a[i]:
max = a[i]
pos = i
return max, pos
m, p = getMax(a)
print(m,p)
max = a[0]
pos = 0
for i in range(1, len(a)):
if max < a[i]:
max = a[i]
pos = i
print(max, pos)
def add(x,y,z):
print("Call me")
return x*2, y*2, z*2
a = add(3,4,5)
print( type(a) )
print( a[0] )
print( a[1] )
print( a[2] )
print( add(6,7,8)[0] )
print( add(6,7,8)[1] )
print( add(6,7,8)[2] )
person = dict()
person["name"] = "홍길동"
person["age"] = 23
person["phone"] = "010-0000-0001"
print(person)
person2 = {"name":"장길산", "age":21, "phone":"010-0000-0002"}
print(person2)
for key in person.keys():
print(key, person[key])
for key in person2.keys():
print(key, person2[key])
for value in person2.values():
print(value)
for key,value in person2.items():
print(key, value)
for i, key in enumerate(person2.keys()):
print(i, key)
mydic = {}
mydic["color"]="색"
mydic["red"]="빨간색"
mydic["green"]="초록색"
mydic["blue"]="파란색"
mydic["cyan"]="청녹색"
mydic["black"]="검정색"
color = input("알고싶은색 ? ")
if color in mydic.keys():
print(mydic[color])
else:
print("없는색")
s1 = set([1,2,3,4,5,3,4])
print(type(s1), s1 )
s2 = list(s1)
print( type(s2), s2)
s3 = tuple(s1)
print( type(s3), s3)
s2 = set( [3,4,5,6,7,8])
s3 = s1.intersection(s2)
print( s3 )
s3 = s1.union(s2)
print( s3 )
s3 = s1.difference(s2)
print( s3 )
과제
숫자야구게임(김성재풀이)
- 숫자야구게임.. 무한도전에서 옛날에 봤던 기억이 난다. 예능으로 볼때는 재밌어보였는데 코딩을 직접하니 다큐다.. 진짜 너무 다큐다. 싸늘하고 가슴에 비수가 날아와 꽃혔다. 겨우겨우 만들어내긴 했다. 강사님은 어떻게 푸실지 정말 궁금하다.
import random
def computer_numbers():
com_numbers = []
while len(com_numbers) < 3:
num = random.randint(1,9)
if num not in com_numbers:
com_numbers.append(num)
return com_numbers
def user_numbers():
while True:
user_number = input("서로 다른 숫자 3개를 입력하세요 : ")
if len(user_number) != 3:
print("3자리 숫자를 입력해주세요")
continue
user_number_list = [int(n) for n in user_number]
if len(set(user_number_list)) != "3" or "0" in user_number_list:
print("서로 다른 1~9 사이의 숫자를 입력해주세요.")
return user_number_list
def compare(user_number, com_number):
strike = 0
ball = 0
for i in range(3):
if user_number[i] == com_number[i]:
strike += 1
elif user_number[i] in com_number:
ball += 1
return strike, ball
def start():
print("숫자 야구 시작")
com_number = computer_numbers()
attempts = 0
while True:
user = user_numbers()
attempts += 1
strike, ball = compare(user, com_number)
print(f"{strike} 스트라이크, {ball} 볼")
if strike == 3:
print(f"{attempts}번 만에 정답을 맞췄습니다! 축하해요!! ")
break
start()
복습
gpt를 이용한 유사예제
알파벳 코드 맞추기 게임
import random
def com():
com_choice = random.sample("abcddfghizklmnopqresuvwxyz",4)
return com_choice
def user():
while True:
user_choice = input("a~z 중 4가지 알파벳을 중복없이 입력하세요 : ").lower()
if len(user_choice) < 4:
print("4자리를 다시 입력하세요")
continue
if len(user_choice) == 4:
return user_choice
def compare(user_choice, com_choice):
correct = 0
nothere = 0
error = 0
for i in range(4):
if user_choice[i] == com_choice[i]:
correct += 1
elif user_choice[i] in com_choice[i]:
nothere += 1
else:
user_choice[i] not in com_choice[i]
error += 1
return correct, nothere, error
def startment():
print("알파벳 맞추기를 시작합니다.")
def main():
startment()
com_choice = com()
attempts = 1
while True:
user_choice = user()
attempts += 1
correct, nothere, error = compare(user_choice, com_choice)
print(f"{correct}개 맞음, {nothere}개 자리변경필요, {error}개 틀림")
if correct == 4:
print(f"축하합니다. {attempts}번만에 맞추셨어요!")
break
main()
3자리 숫자 추리 게임
import random
def com():
com_num = random.sample(range(1,10),3)
return com_num
def user():
while True:
user_input = input("3자리 숫자를 입력하세요 (서로 다른 숫자): ")
if len(user_input) != 3 or not user_input.isdigit():
print("입력이 잘못되었습니다. 다시 입력하세요.")
continue
if len(set(user_input)) != 3 or '0' in user_input:
print("중복 없이 1~9 범위의 숫자를 입력해주세요.")
continue
user_num = [int(i) for i in user_input]
return user_num
def compare(user_num, com_num):
correct = 0
error = 0
for i in range(3):
if user_num[i] == com_num[i]:
correct += 1
elif user_num[i] in com_num:
error += 1
return correct, error
def start():
print("숫자 맞추기를 시작합니다!")
def main():
start()
com_num = com()
while True:
user_num = user()
correct, error = compare(user_num, com_num)
print(f"{correct}개 맞고 {error}개 틀렸습니다.")
if user_num == com_num:
print("맞췄습니다. 축하합니다.")
break
main()
색상 맞추기 게임
import random
def com():
com_color = random.randint(1,3)
return com_color
def user():
while True:
user_color = int(input("1.빨강, 2.파랑, 3.초록 중 색깔을 숫자로 입력하세요. "))
if user_color not in [1,2,3]:
print("1,2,3중에 선택하세요.")
continue
return user_color
def startment():
print("색상 맞추기 게임을 시작합니다!")
def compare(user_color, com_color):
if user_color == com_color:
return True
else:
print("틀렸습니다. 다시 입력하세요.")
return False
def main():
startment()
com_color = com()
attempts = 0
while True:
user_color = user()
attempts += 1
if compare(user_color,com_color):
print(f"축하합니다. {attempts}번만에 맞췄습니다.")
break
main()
4자리 PIN 코드 맞추기
import random
def com():
com_num = random.sample(range(1,10),4)
return com_num
def user():
while True:
user_num = input("4자리 숫자를 입력하세요 : ")
if len(user_num) != 4 or not user_num.isdigit():
print("다시 입력하세요. 4자리 숫자입니다.")
continue
if len(set(user_num)) != 4:
print("서로 다른 숫자를 입력하세요.")
continue
return [int(i) for i in user_num]
def compare(user_num, com_num):
correct = 0
misdisplay = 0
error = 0
while True:
for i in range(0,4):
if user_num[i] == com_num[i]:
correct += 1
elif user_num[i] in com_num:
misdisplay += 1
else :
error += 1
return correct, misdisplay, error
def start():
print("4자리 pin 코드 맞추기를 시작합니다.")
def main():
start()
com_num = com()
while True:
user_num = user()
correct, misdisplay, error = compare(user_num, com_num)
if correct == 4:
print(f"정답입니다. 4자리 pin번호는 {com_num}입니다.")
break
else:
print(f"맞음 : {correct}개, 자리틀림 : {misdisplay}개, 틀림 {error}입니다.")
continue
main()