개발자로 가는길 :: '파이썬인강' 태그의 글 목록
반응형

파이썬인강에 해당하는 글
반응형
7

Python 인강 Day 9 / day 100 (비밀 경매 프로젝트)

개발/파이썬|2023. 3. 13. 19:10
728x90
반응형
from replit import clear
from art import logo
print(logo)

bids = {}
bidding_finished = False  

def find_highest_bidder(bidding_record):
  highest_bid = 0
  winner = ""
  # bidding_record = {"Angela": 123, "James": 321}
  for bidder in bidding_record:  
    bid_amount = bidding_record[bidder]
    if bid_amount > highest_bid: 
      highest_bid = bid_amount
      winner = bidder
  print(f"The winner is {winner} with a bid of ${highest_bid}")

while not bidding_finished:  
  name = input("What is your name?: ")
  price = int(input("What is your bid?: $"))
  bids[name] = price
  should_continue = input("Are there any other bidders? Type 'yes or 'no'.\n")
  if should_continue == "no":
    bidding_finished = True
    find_highest_bidder(bids)
  elif should_continue == "yes":
    clear()

얼마전부터 느꼈지만 해외강의다 보니 풀수있는 문제도 자막때문에 문제이해가 쉽지 않아 어려움을 겪는다...ㅠ

영어공부부터 해야하나...

728x90
반응형

댓글()

Python 인강 day 8 / day 100

개발/파이썬|2023. 3. 13. 08:03
728x90
반응형

카이사르 암호화 / 복호화

alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

def caesar(start_text, shift_amount, cipher_direction):
  end_text = ""
  if cipher_direction == "decode":
    shift_amount *= -1
  for char in start_text:
    #TODO-3: What happens if the user enters a number/symbol/space?
    #Can you fix the code to keep the number/symbol/space when the text is encoded/decoded?
    #e.g. start_text = "meet me at 3"
    #end_text = "•••• •• •• 3"
    if char in alphabet:
      position = alphabet.index(char)
      new_position = position + shift_amount
      end_text += alphabet[new_position]
    else:
      end_text += char
  print(f"Here's the {cipher_direction}d result: {end_text}")

#TODO-1: Import and print the logo from art.py when the program starts.
from art import logo
print(logo)

#TODO-4: Can you figure out a way to ask the user if they want to restart the cipher program?
#e.g. Type 'yes' if you want to go again. Otherwise type 'no'.
#If they type 'yes' then ask them for the direction/text/shift again and call the caesar() function again?
#Hint: Try creating a while loop that continues to execute the program if the user types 'yes'.
should_end = False
while not should_end:

  direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n")
  text = input("Type your message:\n").lower()
  shift = int(input("Type the shift number:\n"))
  #TODO-2: What if the user enters a shift that is greater than the number of letters in the alphabet?
  #Try running the program and entering a shift number of 45.
  #Add some code so that the program continues to work even if the user enters a shift number greater than 26. 
  #Hint: Think about how you can use the modulus (%).
  shift = shift % 26

  caesar(start_text=text, shift_amount=shift, cipher_direction=direction)

  restart = input("Type 'yes' if you want to go again. Otherwise type 'no'.\n")
  if restart == "no":
    should_end = True
    print("Goodbye")

이게 코딩이 문제가 아니라 강의가 영어인데 연습문제의 번역이 음.. 별로라 문제자체를 이해하고 시작하기 힘들다

어찌어찌 끝까지 하긴 했는데 아침부터 두시간을 진을 뺐다..ㅠ

728x90
반응형

댓글()

3/8 Python 인강 Day 6 / Day 100

개발/파이썬|2023. 3. 8. 20:57
728x90
반응형

첫번째 Exam 로봇 점프 ㅋ 꽤 재밌는 과제였다.

 

def 함수명() : 로 나만의 함수를 만들고 들여쓰기로 기능을 넣는 형태

 

#Day6 Exam1
def turn_right():
    turn_left()
    turn_left()
    turn_left()
    
def cycle():
    move()
    turn_left()
    move()
    turn_right()
    move()
    turn_right()
    move()
    turn_left()


cycle()
cycle()
cycle()
cycle()
cycle()
cycle()

해보고 싶으신분은 https://reeborg.ca/ 여기서 해볼수 있습니다.

 

Exam2

랜덤 골지점

 

#Day6 Exam2
#Goal 지점이 나올때까지 while 문 이용 반복
def turn_right():
    turn_left()
    turn_left()
    turn_left()
    
def cycle():
    move()
    turn_left()
    move()
    turn_right()
    move()
    turn_right()
    move()
    turn_left()


while not at_goal():
    cycle()

 

Exam3 

랜덤 장애물

 

#Day6 Exam3
def turn_right():
    turn_left()
    turn_left()
    turn_left()
    
def cycle():
    
    turn_left()
    move()
    turn_right()
    move()
    turn_right()
    move()
    turn_left()


while not at_goal():
    if front_is_clear():
        move()
    elif wall_in_front():
        cycle()

게임으로 하니까 쉬운것 같기도하고. 그냥 쉬운 문제를 내준건가 싶기도 하고.

 

Day6 Exam4

랜덤 장애물 피하기

 

def turn_right():
    turn_left()
    turn_left()
    turn_left()
    
def cycle1():
    turn_left()
    while wall_on_right():
        move()
    turn_right()
    move()
    turn_right()

    while front_is_clear():
            move()
    turn_left()
   


while not at_goal():
    if wall_in_front():
        cycle1()
    else:
        move()

오늘 수업은 여기까지.

728x90
반응형

'개발 > 파이썬' 카테고리의 다른 글

3/9 Python 인강 Day 7 / Day 100  (0) 2023.03.09
3/9 Java 인강 공부(feat.chatGPT)  (3) 2023.03.09
3/8 Java 인강 공부 (feat . chatGPT)  (1) 2023.03.08
3/7 Python 인강 Day 5 / Day 100  (0) 2023.03.07
3/6 Python 공부 day 4 / day 100  (0) 2023.03.06

댓글()

3/7 Python 인강 Day 5 / Day 100

개발/파이썬|2023. 3. 7. 23:25
728x90
반응형

이것저것 하다가 시간이 늦어져서 너무 피곤하지만..

그래도 해야지..

 

for문 시작했는데 대충 어떻게 실행될지는 알고 있지만서도 이해가 잘 안되었는데

지겹도록 반복하다 보니 오늘따라 아! 하고 느껴지는것이 조금 있었다.

 

# Day5 Exam2 
# 입력값 중 가장 높은 값 찾기

student_score = input("점수를 입력해주세요 (띄어쓰기로 구분) >> ").split()   #split 으로 띄어쓰기 구분해서 잘라줌
for i in range(0, len(student_score)):                             
    student_score[i] = int(student_score[i])                        #student_score 의 0부터~len만큼 반복하여
                                                                    #int값의 리스트를 작성

highest_score = 0
for score in student_score:
    if score > highest_score:                                       #조건이 True면 highest_score에 값 저장
        highest_score = score                                       #fals면 저장하지 않고 반복문으로 돌아감
    
print(f"최고점수는 {highest_score}점 입니다")

 

마지막 프로젝트는 내기준으론 좀 어려웠다..라기 보다 random 모듈에 있는 다른 기능을 안가르쳐줬는데

choice 와 shuffle 이 들어갔다. 모르는건 구글링 해보라는 뜻 같다

 

# Day5 Exam3
# 1~100까지의 모든 짝수의 합 (for range 문 이용)

result = 0
for i in range(2,101,2):
    result += i
print(f"모든 짝수의 합은 {result}")

result2 = 0
for j in range(1,101):
    if j%2 == 0:
        result2 += j
print(f"모든 짝수의 합은 {result2}")


# Day5 Exam4
# FizzBuzz 게임
# 3으로 나눌수있는 숫자일땐 Fizz , 5로 나눌수 있는 숫자일땐 Buzz 출력 , 3 5모두 나눌수있음 FizzBuzz
# (미국 아동용 게임이라고 한다 우리나라 369 비슷한 ㅋ)

for number in range(1,100):
    if number%3==0:
        print("Fizz")
    elif number%5==0:
        print("Buzz")
    elif number%5==0 and number%3==0:
        print("FizzBuzz")
    else:
        print(number)
        
        # Day5 Fianl Project
# 패스워드 만들기 아래는 미리 만들어져있던 리스트
import random
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+']

print("Welcome to the PyPassword Generator!")
nr_letters = int(input("How many letters would you like in your password?\n")) 
nr_symbols = int(input(f"How many symbols would you like?\n"))
nr_numbers = int(input(f"How many numbers would you like?\n"))

#Eazy Level
# password = ""

# for char in range(1, nr_letters + 1):
#   password += random.choice(letters)

# for char in range(1, nr_symbols + 1):
#   password += random.choice(symbols)

# for char in range(1, nr_numbers + 1):
#   password += random.choice(numbers)
# print(password)

#Hard Level
password_list = []          #최종 만들어질 패스워드의 리스트

for char in range(1, nr_letters + 1):
  password_list.append(random.choice(letters))  #letter에서 랜덤으로 초이스된 문자열을 리스트에 가장 뒤에 추가  (입력받은값까지) 

for char in range(1, nr_symbols + 1):           
  password_list += random.choice(symbols)       #마찬가지

for char in range(1, nr_numbers + 1):
  password_list += random.choice(numbers)       #마찬가지

print(password_list)
random.shuffle(password_list)                   #만들어진 리스트 섞어줌
print(password_list)                            #최종

password = ""
for char in password_list:
  password += char

print(f"Your password is: {password}")

 

오늘 공부 마무리

 

오늘은 시간이 좀 늦었다 피곤해서 눈앞이 좀 흐리다..ㅠ 굿나잇

728x90
반응형

댓글()

3/6 Python 공부 day 4 / day 100

개발/파이썬|2023. 3. 6. 21:52
728x90
반응형

마지막 가위바위보 게임은

이래저래 등호도 넣고 , 가위바위보 이미지를 리스트에 넣어 출력하고 하려고했는데

너무 복잡해서 알아보기 힘든것 같아 그냥 if 문으로 모든 조건을 넣어줬다...

이게 맞는건진 모르겠다..ㅋ

일단 실행은 잘됨.

# Day4 Exam1
# 이름 입력해서 랜덤으로 뽑기

# Split string method
names_string = input("Give me everybody's names, separated by a comma.")
names = names_string. split(", ") #입력받은 문자열을 , 로 구분하여 list 로 저장
# 🚨 Don't change the code above 👆

#Write your code below this line 👇
import random #랜덤 모듈 임포트

random_index = random.randint(0, len(names) - 1) 
#len(name)은 5로 나오기때문에 -1을 해서 리스트에서 뽑을수 있게함)
random_name = names[random_index]
#name 의 리스트에서 0~4 로 나온 랜덤수를 넣음
print(f"{random_name} is going to buy the meal today!") #출력


#Day4 Exam2
#입력받은 값 행,열 따져 x 표시 하기 

# 🚨 Don't change the code below 👇
row1 = ["⬜️","⬜️","⬜️"]
row2 = ["⬜️","⬜️","⬜️"]
row3 = ["⬜️","⬜️","⬜️"]
map = [row1, row2, row3]  			#3개의 리스트를 하나로 병합 
print(f"{row1}\n{row2}\n{row3}")
position = input("Where do you want to put the treasure? ")
# 🚨 Don't change the code above 👆

#Write your code below this row 👇

position_id = int(position)  		#입력받은값 변수에 저장

row = position_id % 10 -1			#변수 / 10 하면 나머지가 1~3으로 나오니 0~2로 나오게 -1해줌
column = int(position_id / 10) -1	#변수 / 10 하면 몫이 1~3으로 나오니 0~2로 나오게 =1 해줌

map[row][column] =  "X"				# map의 row , column 에 각값을 넣어 해당위치를 X로 바꿈

#Write your code above this row 👆

# 🚨 Don't change the code below 👇
print(f"{row1}\n{row2}\n{row3}")

#Day4 final Project
#가위바위보 게임

rock = '''
    _______
---'   ____)
      (_____)
      (_____)
      (____)
---.__(___)
'''

paper = '''
    _______
---'   ____)____
          ______)
          _______)
         _______)
---.__________)
'''

scissors = '''
    _______
---'   ____)____
          ______)
       __________)
      (____)
---.__(___)
'''

#Write your code below this line 👇

import random

user = int(input("1.가위 ,  2.바위 , 3.보 / 선택해주세요 >> "))
computer = random.randint(1,3)


if user == 1:
  print("user\n"+scissors)
  if computer == 2:
    print("computer\n"+rock+"\nComputer win!")
  elif computer == 3:
    print("computer\n"+paper+"\nUser win")
  else:
    print("computer\n"+scissors+"\nDraw")

if user == 2:
  print("user\n"+rock)
  if computer == 2:
    print("computer\n"+rock+"\nDraw!")
  elif computer == 3:
    print("computer\n"+paper+"\nComputer win")
  else:
    print("computer\n"+scissors+"\nUser win")

if user == 3:
  print("user\n"+paper)
  if computer == 2:
    print("computer\n"+rock+"\nUser win")
  elif computer == 3:
    print("computer\n"+paper+"\nDraw!")
  else:
    print("computer\n"+scissors+"\nComputer win")

 

728x90
반응형

댓글()

3/5 Python 공부 day 3 / day 100

개발/파이썬|2023. 3. 5. 23:19
728x90
반응형

오늘 느낀점

코드를 간결하게 쓸수있게 알고리즘을 그려보자

 

참고 : 아스키코드 아트 https://ascii.co.uk/art

 

ASCII ART

 

ascii.co.uk

여기서 korea 를 선택해서 진행했는데 동해가 sea of japan 으로 표기되어있어 수정했다. 관리자 이메일 찾아서 수정 요청을 해봐야겠다.

#Day3 Exam1
#입력받은 값이 홀수인지 , 짝수인지 판별
num = int(input("숫자를 입력해주세요 >"))
if num%2==0:
    print("짝수입니다!")
else:
    print("홀수입니다!")

#Day3 Exam2
#Bmi calculatpr v2.0
height = float(input("키를 입력해주세요(m 단위) >"))
weight = float(input("몸무게를 입력해주세요(kg단위) >"))
bmi = round(weight / height ** 2)

if bmi < 18.5 :
    print("저체중 입니다")
elif bmi <25 :
    print("정상체중 입니다")
elif bmi <30:
    print("과체중 입니다")
elif bmi <35:
    print("비만 입니다")
else:
    print("고도비만 입니다")

#Day3 Exam3
#윤년 계산하기
#윤년 조건 /년도%4 =0 , 년도%400=0 윤년 / 년도%4=0 ,년도%100=0,년도%400 = 0 윤년/
#평년 조건 /년도%4 =0 , 년도%100=0 년도%400!=0 /년도%4 !=0

years = int(input("년도를 입력해주세요 > "))

# 본인 작성 코드
# if years%4==0:
#     if years%100==0:
#         if years%400==0:
#             print("윤년입니다")
# elif years%4==0:
#     if years%100!=0:
#         if years%400==0:
#             print("윤년입니다")
# elif years%4!=0:
#     print("평년입니다")
# elif years%4==0:
#     if years%100==0:
#         if years%400!=0:
#             print("평년입니다")
# else:
#     print("평년입니다")

#정답코드

if years % 4 == 0:
    if years % 100== 0:
        if years % 400 == 0:
            print("윤년입니다")
        else:
            print("평년입니다")
    else:
        print("윤년입니다")            
else:
    print("평년입니다")
        
        
# #Day3 Exam4
# #피자가격 계산하기 feat.토핑추가
# #S:$15 , M:$20, L:$25 / 페퍼로니 추가 S:+$2 M,L:+$3  / 치즈추가 +$1

# 내가 쓴 코드
# size_info = str(input("사이즈를 입력해주세요 S , M , L >> "))
# add_pepperoni = str(input("페퍼로니를 추가하시겠습니까? Y,N >> "))
# add_cheese = str(input("치즈를 추가하시겠습니까? Y,N >>"))

# bill = 0

# if size_info == "S":
#     bill +=15
#     if add_pepperoni == "Y":
#         bill += 2
#     else:
#         bill += 0
#     if add_cheese == "Y":
#         bill += 1
#     else:
#         bill += 0
#     print(f"최종가격은 ${bill} 입니다")
    
# elif size_info =="M":
#     bill +=20
#     if add_pepperoni == "Y":
#         bill += 3
#     else:
#         bill += 0
#     if add_cheese == "Y":
#         bill += 1
#     else:
#         bill += 0
#     print(f"최종가격은 ${bill} 입니다")
    
# elif size_info =="L":
#     bill +=25
#     if add_pepperoni == "Y":
#         bill += 3
#     else:
#         bill += 0
#     if add_cheese == "Y":
#         bill += 1
#     else:
#         bill += 0
#     print(f"최종가격은 ${bill} 입니다")

# 정답코드

size_info = str(input("사이즈를 입력해주세요 S , M , L >> "))
add_pepperoni = str(input("페퍼로니를 추가하시겠습니까? Y,N >> "))
add_cheese = str(input("치즈를 추가하시겠습니까? Y,N >>"))

bill = 0

if size_info == "S":
    bill += 15
elif size_info == "M":
    bill += 20
elif size_info == "L":
    bill += 25

if add_pepperoni =="Y":
    if size_info =="S":
        bill += 2
    else:
        bill += 3       
if add_cheese =="Y":
    bill+=1

print(f"최종가격은 ${bill} 입니다!")


#Day3 Exam5 번역문제로 패스함. 대충 이름을 2개 입력받고 나오는 알파벳중 특정글자가 몇개 들어있나 세어서 사랑점수를 확인한다는 내용
#Agella.lower() / 대문자를 소문자로 바꿔줌  , Agella.count("l") 알파벳중 l 이 몇개 들어가있다 세어줌 이런걸로 계산


#Day3 final project 보물섬 게임 만들기

print('''                                         {'{러시아
                                         /   '.
                                       _/     _}
    중국                           __ __}      /
                                (  `        (
                          /'\____\          /
                         :                  |
                         /                  |
                        /                 _/
                  __.-='     DPRK        /
              .-='                   .-='
          .-='                 _.--='
         (                   .'
          \=._               }
              '-._          (
                 (           '=-.
                 / 평양           \
                (_ *              \
             _.='\\                \
            ;                       }         SEA OF
YELLOW      \__         _  _      .'\         ROK
 SEA         " \_ _ . -      - . -   \
                \                     \
              ,=.\ * 서울               \
             {_.                        }
              :`{                       |
                /                       /
                }                      .
                \           ROK        |
               _]                     <_.
               ',                       /
               /                       /
               \                _.____/
                }  _____.-.--=\{ /}
                \/" ,_}   \,      `


               __,=-.
dew           {__.--'   < *보물섬*                            \n\n''')

print("보물섬 게임을 시작합니다 , 선택은 한번 뿐 이니 신중하게 결정해주세요.")
lorr = str(input("보물섬에 도착했습니다. 양갈래 길이 나오네요. 왼쪽 또는 오른쪽 선택해주세요 >> "))
if lorr == "오른쪽":
    sorw = str(input("왼쪽엔 함정이 있었네요. 잘 선택하셨습니다. 앞에 바다가 있는데 수영 또는 대기 선택해주세요 >> "))
    if sorw == "대기":
        door = str(input("파도가 거새 수영을 했다면 위험했을껍니다. 둘러보니 문이 세개가 있습니다. 빨강,노랑,파랑 문중 어떤문을 들어가시겠습니까? >>"))
        if door =="노랑":
            print("축하합니다! 보물을 발견했습니다! 당신은 부자에요!")
        else:
            print("문을 열자마자 괴물 수백마리가 튀어나와서 공격당해 사망했습니다.")
    else:
        print("바다에 뛰어들었지만 크라켄을 만나 공격당해 사망했습니다.")
else:
    print("왼쪽 길에 들어서는 순간 함정에 빠져 사망했습니다.")
728x90
반응형

댓글()