TIL: Python Basics Day 14 - Breaking Down the Problem / Higer Lower Project

이다연·2020년 12월 18일
0

Udemy Python Course

목록 보기
14/64
  1. Breakdown the problem
  2. Make a to-do list: Start with the easiest -> Pick one task
  3. Picked Task: Turn the problem into commets
  4. Write code - Run code - Fix code

Project: Higer Lower

Purpose was to check if I can break down the problem into smaller problems.


logo = """
    __  ___       __             
   / / / (_)___ _/ /_  ___  _____
  / /_/ / / __ `/ __ \/ _ \/ ___/
 / __  / / /_/ / / / /  __/ /    
/_/ ///_/\__, /_/ /_/\___/_/     
   / /  /____/_      _____  _____
  / /   / __ \ | /| / / _ \/ ___/
 / /___/ /_/ / |/ |/ /  __/ /    
/_____/\____/|__/|__/\___/_/     
"""

vs = """
 _    __    
| |  / /____
| | / / ___/
| |/ (__  ) 
|___/____(_)
"""

data = [
    {
        'name': 'Instagram',
        'follower_count': 346,
        'description': 'Social media platform',
        'country': 'United States'
    },
    {
        'name': 'Cristiano Ronaldo',
        'follower_count': 215,
        'description': 'Footballer',
        'country': 'Portugal'
    },
    {
        'name': 'Ariana Grande',
        'follower_count': 183,
        'description': 'Musician and actress',
        'country': 'United States'
    },
    {
        'name': 'Dwayne Johnson',
        'follower_count': 181,
        'description': 'Actor and professional wrestler',
        'country': 'United States'
    },
    {
        'name': 'Selena Gomez',
        'follower_count': 174,
        'description': 'Musician and actress',
        'country': 'United States'
    },
    {
        'name': 'Kylie Jenner',
        'follower_count': 172,
        'description': 'Reality TV personality and businesswoman and Self-Made Billionaire',
        'country': 'United States'
    },
    {
        'name': 'Kim Kardashian',
        'follower_count': 167,
        'description': 'Reality TV personality and businesswoman',
        'country': 'United States'
    }]

#--------------------------------4th try----------------------

# Next execution: 
# A will hold winning figure from previous 
# B will hold regenerated random figure 

# Game() 
 

# User_input() 
# Compare : actual vs user() 
#     Show result and Score - if, win A = user_input/ actual answer 
#     Loop game() if correct

# Generate random data, format
#     A will hold winning data from previous 
#     B will hold regenerated random data 

import random
from game_data import data
from art import logo, vs
from replit import clear

def generate_random(account):
  """return statement about randomly selected account"""
  return f"{account['name']}, a {account['description']}, from {account['country']}"

# Actual answer
def actual_answer(account_a, account_b):
  if account_a > account_b:
    return account_a
  else:
    return account_b


def game():
  score = 0
  account_a = random.choice(data)
  should_continue = True
  print(logo)
  
  while should_continue:
    
    account_b = (random.choice(data))
    
    print(f"\nCompare A: {generate_random(account_a)}")
    #print(account_a['follower_count'])
    print(vs)
    print(f"Against B: {generate_random(account_b)}")
    #print(account_b['follower_count'])

    actual = actual_answer(account_a['follower_count'], account_b['follower_count'])
    #print(f"actual: {actual}")

    #get user's answer
    user = input("Who has more followers? Type 'A' or 'B': ")
    if user == "a":
      user_answer = account_a
    else:
      user_answer = account_b

    #compare actual answer to users
    if actual == user_answer['follower_count']:
      score += 1
      clear()
      print(logo)
      print((f"\nCorrect. Current score is {score}"))
      #move previous answer to first statement
      account_a = user_answer
      
    else:
      clear()  # ->  notice it's repeated. you can put it above if statement. it works perfectl fine. 
      print(logo)  # -> 
      print (f"Wrong. Final score is {score}")
      should_continue = False

game()

Learnings

To solve the problem of generating the same account data from random, I can use 'if statement'. check if account_a == account == b, if same, assign again. However, it's still imperfect.
So, I added while loop below instead of if, so it can run until it's false.

account_a = random.choice(data)
account_b = random.choice(data)
if account_a == account_b:
	account_b = random.choice(data)
    
----


def game():
  print(logo)
  score = 0
  game_should_continue = True
  account_a = get_random_account()
  account_b = get_random_account()

  while game_should_continue:
    account_a = account_b
    account_b = get_random_account()

    ## Bonus point debugging problem. 
    # What happens if acount_a == account_b multiple times?
    # How can you get the code to keep generating random accounts?
    # Solution: https://repl.it/@appbrewery/higher-lower-final-debugged

    while account_a == account_b:
      account_b = get_random_account()

when getting input. use lower() to keep it consistent. With lower() function, even though user input capital letter, it will convert it into lowercase.

 user = input("Who has more followers? Type 'A' or 'B': ")

Complex art of code. Play a computer...!

def check_answer(guess, a_followers, b_followers):
  """Checks followers against user's guess 
  and returns True if they got it right.
  Or False if they got it wrong.""" 
  if a_followers > b_followers:
    return guess == "a" # -> this means True
  else:
    return guess == "b" # this means False
    
    guess = input("Who has more followers? Type 'A' or 'B': ").lower()
    a_follower_count = account_a["follower_count"]
    b_follower_count = account_b["follower_count"]
    is_correct = check_answer(guess, a_follower_count, b_follower_count)

    clear()
    print(logo)
    if is_correct:
      score += 1
      print(f"You're right! Current score: {score}.")
    else:
      game_should_continue = False
      print(f"Sorry, that's wrong. Final score: {score}")

Angela's solution

from game_data import data
import random
from art import logo, vs
from replit import clear

def get_random_account():
  """Get data from random account"""
  return random.choice(data)

def format_data(account):
  """Format account into printable format: name, description and country"""
  name = account["name"]
  description = account["description"]
  country = account["country"]
  # print(f'{name}: {account["follower_count"]}')
  return f"{name}, a {description}, from {country}"

def check_answer(guess, a_followers, b_followers):
  """Checks followers against user's guess 
  and returns True if they got it right.
  Or False if they got it wrong.""" 
  if a_followers > b_followers:
    return guess == "a"
  else:
    return guess == "b"


def game():
  print(logo)
  score = 0
  game_should_continue = True
  account_a = get_random_account()
  account_b = get_random_account()

  while game_should_continue:
    account_a = account_b
    account_b = get_random_account()

    ## Bonus point debugging problem. 
    # What happens if acount_a == account_b multiple times?
    # How can you get the code to keep generating random accounts?
    # Solution: https://repl.it/@appbrewery/higher-lower-final-debugged
    if account_a == account_b:
      account_b = get_random_account()

    print(f"Compare A: {format_data(account_a)}.")
    print(vs)
    print(f"Against B: {format_data(account_b)}.")
    
    guess = input("Who has more followers? Type 'A' or 'B': ").lower()
    a_follower_count = account_a["follower_count"]
    b_follower_count = account_b["follower_count"]
    is_correct = check_answer(guess, a_follower_count, b_follower_count)

    clear()
    print(logo)
    if is_correct:
      score += 1
      print(f"You're right! Current score: {score}.")
    else:
      game_should_continue = False
      print(f"Sorry, that's wrong. Final score: {score}")

game()


# Generate a random account from the game data.

# Format account data into printable format.

# Ask user for a guess.

# Check if user is correct.
## Get follower count.
## If Statement

# Feedback.

# Score Keeping.

# Make game repeatable.

# Make B become the next A.

# Add art.

# Clear screen between rounds.
profile
Dayeon Lee | Django & Python Web Developer

0개의 댓글