25. 05. 02 공부일지

behumble·2025년 5월 7일

공부일지

목록 보기
7/20

회고

  • 숫자야구가 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"
#파이썬의 문자열은 read only이다.
print(s) #인덱싱과 슬라이싱 - 0부터 시작을 한다
print(s[:4]) #0번부터 1,2,3 까지만 출력, 슬라이싱을 지원 다른언어 substring
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(words)

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}") #3.6 부터 사용 가능  

#배열 - 프로그램 수행전에 반드시 메모리를 확보해야함
#index를 통해 읽고 쓴다. 수행도중에 크기 변화 불가
#연속된 메모리 공간 => 파이썬의 list 는 배열구조가 아님
#인덱싱과 슬라이싱을 써서 접근한다는 부분만 배열구조와 일치한다.

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])
#list1[1:6]=8
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)

#리스트에 5의 배수를 10개 채우기
a = list(range(5, 5*10+1, 5))
print(a)

#리스트에 100부터 90, 80, 70 ... 역순으로 10까지 채워서 출력하기
a = list(range(100, 0, -10))
print(a)

#중복된 값이 포함된 리스트 a = [1, 2, 3, 2, 4, 3, 5, 1]가 있습니다.
#중복을 제거하고 정렬된 리스트를 출력해 보세요.
a = [1, 2, 3, 2, 4, 3, 5, 1]
b =[]
for i in a:
  if i not in b:
    b.append(i)
print(b)

#scores = [80, 95, 70, 100, 85]
#평균 점수보다 높은 점수만 골라 새로운 리스트로 만들고 출력해 보세요.

#이차원 : 본래의미의 배열이 아니다
#list of list로 표현해야 한다.
a = [ [1,2,3], [4,5,6], [7,8,9]]
for i in a:
  print(i)

print(a[0])
print( a[0][0])

#10 by 10 100개 1~100까지 채워서 출력하기

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)  #a.append(i)
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()


# 1 0 0  0 0 0 0 0 0 0
# 2 3 0  0 0 0 0 0 0 0
# 4 5 6  0 0 0 0 0 0 0
# 7 8 9 10 0 0 0 0 0 0
#  ...............

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]
# 1. 첫번째 방의 데이터가 젤 크다고 가정을 한다
#   max 라는 변수에 첫번째 방의 데이터를 저장해 놓는다
# 2. 두번째 방의 데이터를 비교해서 두번째 방의 값이 더 크면 값을 max의 값을 변경한다
# 3. 세번째 방의 데이터를 비교해서 두번째 방의 값이 더 크면 값을 max의 값을 변경한다
# ....... 마지막 방까지 가고 나면 max저장된 값이 제일 크다
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
  # 다른언어는 에러발생, 파이썬은 시스템이 알아서 tuple로 만들어서 던진다

m, p = getMax(a)
print(m,p)
max = a[0]
pos = 0
# if max < a[1]:
#   max = a[1]
# if max < a[2]:
#   max = a[2]
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] ) #함수가 3번이나 호출되고 있다
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)

#index와 key
for i, key in enumerate(person2.keys()):
  print(i, key)

#파이썬의 경우 연산자 중복 기능   s1 == "hello" : 완전히 새로운 데이터타입을 만들
#거나 아니면 우리가 새로운 언어 번역기를 만들때 필요하다 그밖에는 필요없다.
#java의 경우 문자열 비교   s1.equals("hello")

mydic = {}  #mydic = dict()
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를 이용한 유사예제

알파벳 코드 맞추기 게임

# 컴퓨터는 랜덤하게 4개의 알파벳(중복 없음)을 선택한다. 예: "abcf"
# 사용자는 알파벳 4개를 입력해서 맞춘다.
# 위치까지 맞으면 "정확히 맞음",
# 알파벳만 맞고 위치가 다르면 "위치 틀림",
# 틀리면 "틀림"으로 출력.
# 정답을 맞히면 시도 횟수와 함께 종료한다.

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자리 숫자 추리 게임

# 컴퓨터는 서로 다른 3자리 숫자를 고른다. 예: "836"
# 사용자는 3자리 숫자를 입력한다.
# 각 자리별로 다음처럼 출력:
# 정답이면 ✅
# 틀린 자리이면 ❌
# 예: 입력: 836 → 결과: ✅✅✅
# 예: 입력: 831 → 결과: ✅✅❌
# 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()

색상 맞추기 게임

# 컴퓨터가 빨강(red), 파랑(blue), 초록(green) 중 하나를 랜덤으로 선택합니다.
# 사용자가 색상을 입력해서 맞추는 게임입니다. 맞힐 때까지 반복합니다.

import random


def com():
    com_color = random.randint(1,3) # 빨강 = 1, 파랑 = 2, 초록 = 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 코드 맞추기

# 컴퓨터는 중복 없는 4자리 PIN 코드를 생성합니다. 예: [4, 1, 8, 7]
# 사용자는 4자리 숫자를 입력하고, 자릿수와 값이 맞는 경우 ‘맞음’을 알려줍니다.
# 모두 맞을 때까지 반복합니다.

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()

0개의 댓글