Team Code Analysis

Analyze how the code works by team.

Part 1. Easy

  1. calculator.py

result = 0

def add(num):
    global result
    # 결괏값(result)에 입력값(num) 더하기
    result += num
    # 결괏값 리턴
    return result

print(add(3))
print(add(4))
  1. calculator2.py

result1 = 0
result2 = 0

def add1(num):  # 계산기1
    global result1
    result1 += num
    return result1

def add2(num):  # 계산기2
    global result2
    result2 += num
    return result2

print(add1(3))
print(add1(4))
print(add2(3))
print(add2(7))
  1. calculator3.py

class Calculator:
def __init__(self):
    self.result = 0

def add(self, num):
    self.result += num
    return self.result

cal1 = Calculator()
cal2 = Calculator()

print(cal1.add(3))
print(cal1.add(4))
print(cal2.add(3))
print(cal2.add(7))
  1. hello_world.py

# Print a Sentence "Hello World!"

def hello_world():
    # Print "Hello World!"
    print("Hello World!")

# Run the function
hello_world()

Part 2. Intermediate

  1. guess_number.py

# Guess the Random Number

import random

def guess_the_number():
    # Generate a random target number between 1 and 100
    target_number = random.randint(1, 100)
    attempts = 0

    while True:
        # Get the user's guess
        user_guess = int(input("Guess the number between 1 and 100: "))
        attempts += 1

        # Compare user's guess with the target number
        if user_guess < target_number:
            print("Too low! Try again.")
        elif user_guess > target_number:
            print("Too high! Try again.")
        else:
            # User guessed the correct number
            print(f"Congratulations! You guessed the number in {attempts} attempts.")
            break

# Run the function to start the guessing game
guess_the_number()
  1. count_digits.py

# Guess the Digits
# ex) 4 -> 1 digit, 100 -> 3 digits, 7777 -> 4 digits

def count_digits(number):
    if number == 0:
        return 1  # Special case for the number 0 (which has 1 digit)

    count = 0  # Initialize a count to track the number of digits

    # Loop to count digits by repeatedly dividing the number by 10
    while number > 0:
        count += 1         # Increment the digit count
        number //= 10      # Remove the least significant digit by integer division

    return count  # Return the total count of digits

# Get input from the user
input_str = input("Enter a positive integer: ")

# Check if the input is a positive integer
if input_str.isdigit():
    input_number = int(input_str)

    # Check for non-positive input
    if input_number <= 0:
        print("Please enter a positive integer.")
    else:
        # Calculate the number of digits using the count_digits function
        num_digits = count_digits(input_number)
        print(f"The number {input_number} has {num_digits} digits.")
else:
    print("Invalid input. Please enter a positive integer.")
  1. factorial.py

# Calculate Factorial
# Factorial: Simply represented as n!, it means multiplying all natural numbers from 1 to n.
# ex) 3! = 1*2*3, 6! = 1*2*3*4*5*6

def factorial(n):
    # Base case: Factorial of 0 and 1 is 1
    if n == 0 or n == 1:
        return 1
    else:
        # Recursive case: Factorial of n is n times factorial of (n - 1)
        return n * factorial(n - 1)

# Get input from the user
num = int(input("Enter a number: "))

# Call the factorial function to calculate the factorial of the input number
result = factorial(num)

# Print the result
print(f"The factorial of {num} is {result}")
  1. rcp.py

# Rock, Paper, Scissors battle

import random

# Function to determine the winner of the game
def determine_winner(player_choice, computer_choice):
    if player_choice == computer_choice:
        return "It's a tie!"
    elif (player_choice == "r" and computer_choice == "s") or \
        (player_choice == "p" and computer_choice == "r") or \
        (player_choice == "s" and computer_choice == "p"):
        return "You win!"
    else:
        return "Computer wins!"

def main():
    # Print the welcome message and game instructions
    print("Welcome to Rock-Paper-Scissors!")
    print("Enter 'r' for rock, 'p' for paper, 's' for scissors, or 'q' to quit.")

    choices = ["r", "p", "s"]  # Possible choices for the game

    while True:
        player_choice = input("Your choice: ").lower()

        # Check if the player wants to quit
        if player_choice == "q":
            print("Thanks for playing!")
            break

        # Check if the player's choice is valid
        if player_choice in choices:
            computer_choice = random.choice(choices)  # Randomly select computer's choice

            print(f"You chose: {player_choice}")
            print(f"Computer chose: {computer_choice}")

            result = determine_winner(player_choice, computer_choice)  # Determine the winner
            print(result)  # Display the result of the game
        else:
            print("Invalid choice. Please enter 'r', 'p', 's', or 'q' to quit.")

if __name__ == "__main__":
    main()  # Run the main game loop

Part 3. Hard

  1. diamond.py

# Print Diamond Figure

def print_diamond(n):
    for i in range(n):
        spaces = abs(n // 2 - i)  # Calculate the number of spaces needed on each side

        # Calculate the number of diamonds needed in the middle based on spaces
        diamonds = n - 2 * spaces

        # Print the row with appropriate spaces and diamonds pattern
        print("□" * spaces + "■" * diamonds + "□" * spaces)

# Get user input for the size of the diamond
n = int(input("Enter Number (odd number) : "))

# Check if the input is a positive odd integer
if n % 2 == 0 or n <= 0:
    print("Please enter a positive odd integer.")
else:
    print_diamond(n)  # Print the diamond pattern
  1. br31.py

# Baskin Robbins 31 Game

import random

def player_turn(total):
    while True:
        try:
            # Get the player's choice of how many numbers to pick (1, 2, or 3)
            pick = int(input("Enter 1, 2, or 3: "))
            # Check if the input is within the valid range
            if pick < 1 or pick > 3:
                print("Invalid input. Please choose 1, 2, or 3.")
                continue
            # Check if the move exceeds the game limit (31)
            if total + pick > 31:
                print("Invalid move. Try again.")
                continue
            return pick
        except ValueError:
            print("Invalid input. Please enter a number.")

def computer_turn(total):
    # Calculate the maximum number of picks the computer can make
    max_pick = min(3, 31 - total)
    # Generate a random number of picks for the computer's turn
    return random.randint(1, max_pick)

def main():
    total = 0
    player_turns = True

    print("Welcome to Baskin Robbins 31!")

    while total < 31:
        if player_turns:
            print(f"Current total: {total}")
            # Get the player's turn choice
            pick = player_turn(total)
        else:
            # Get the computer's turn choice
            pick = computer_turn(total)
            print(f"Computer picks: {pick}")

        # Update the total count
        total += pick
        # Switch turns between player and computer
        player_turns = not player_turns

    # Determine the winner based on the last turn
    if player_turns:
        print("You win!")
    else:
        print("Computer wins!")

if __name__ == "__main__":
    main()
  1. maze.py

# Maze Escape Game

import random

# Function to generate a maze with walls and empty spaces
def generate_maze(size):
    maze = [["#" for _ in range(size)] for _ in range(size)]  # Initialize maze with walls
    for row in range(1, size - 1):
        for col in range(1, size - 1):
            if random.random() < 0.7:  # Adjust the density of walls (70% of cells are walls)
                maze[row][col] = " "  # Assign empty space to some cells
    return maze

# Function to print the maze
def print_maze(maze):
    for row in maze:
        print("".join(row))

# Function to find neighboring cells for generating paths
def find_neighbors(cell, size):
    neighbors = []
    row, col = cell

    # Add neighboring cells (up, down, left, right) if they are within bounds
    if row > 1: neighbors.append((row - 2, col))
    if row < size - 2: neighbors.append((row + 2, col))
    if col > 1: neighbors.append((row, col - 2))
    if col < size - 2: neighbors.append((row, col + 2))

    random.shuffle(neighbors)  # Shuffle neighbors to randomize path generation
    return neighbors

# Recursive function to generate a path through the maze
def generate_path(maze, cell, visited):
    maze[cell[0]][cell[1]] = " "  # Mark current cell as a path

    visited.add(cell)
    neighbors = find_neighbors(cell, len(maze))

    for neighbor in neighbors:
        if neighbor not in visited:
            row, col = neighbor
            # Carve a path by removing walls between the current cell and the neighbor
            if row == cell[0]:
                maze[row][min(col, cell[1]) + 1] = " "
            else:
                maze[min(row, cell[0]) + 1][col] = " "
            generate_path(maze, neighbor, visited)

# Main game function
def maze_game(size):
    maze = generate_maze(size)  # Generate the maze
    start = (random.randint(0, size // 2) * 2, 0)  # Random starting point on the left edge
    end = (random.randint(0, size // 2) * 2, size - 1)  # Random ending point on the right edge

    generate_path(maze, start, set())  # Generate path through the maze

    player = start
    maze[start[0]][start[1]] = "S"  # Mark start point
    maze[end[0]][end[1]] = "E"  # Mark end point
    print_maze(maze)  # Display maze to player

    print("S: Start, E: Exit")

    while player != end:
        move = input("Enter direction (up: u/ down: d/ left: l/ right: r): ").lower()

        next_row, next_col = player
        if move == "u":
            next_row -= 1
        elif move == "d":
            next_row += 1
        elif move == "l":
            next_col -= 1
        elif move == "r":
            next_col += 1
        else:
            print("Invalid move. Use up/down/left/right.")
            continue

        # Check if the next move is valid (within bounds and not a wall)
        if 0 <= next_row < size and 0 <= next_col < size and maze[next_row][next_col] != "#":
            if maze[next_row][next_col] != "#" and maze[(player[0] + next_row) // 2][(player[1] + next_col) // 2] != "#":
                maze[player[0]][player[1]] = " "  # Clear previous position
                player = (next_row, next_col)  # Update player's position
                maze[player[0]][player[1]] = "P"  # Mark new position as player

        print_maze(maze)  # Display maze with updated player position

    print("Congratulations! You reached the exit.")

# Get maze size from user input
maze_size = int(input("Enter maze size (odd number): "))
if maze_size % 2 == 0:
    maze_size += 1  # Make sure maze size is odd
maze_game(maze_size)  # Start the maze game
  1. notepad.py

# Create a Notepad

import sys

# Function to write the provided memo to the 'memo.txt' file
def write_memo(memo):
    with open('memo.txt', 'a') as f:
        f.write(memo + '\n')

# Function to read the contents of the 'memo.txt' file
def read_memo():
    with open('memo.txt') as f:
        memo = f.read()
    return memo

# Function to erase all text from the 'memo.txt' file
def erase_memo():
    with open('memo.txt', 'w') as f:
        f.truncate(0)

# Main function to handle command-line arguments and perform actions
def main():
    # Get the option from the command-line argument
    option = sys.argv[1]

    if option == '-w':
        # Check if memo text is provided as an argument
        if len(sys.argv) < 3:
            print("Please provide memo text to write.")
            return
        memo = sys.argv[2]
        # Call the function to write memo to the file
        write_memo(memo)

    elif option == '-r':
        # Call the function to read memo from the file and print it
        memo = read_memo()
        print("Memo contents:\n", memo)

    elif option == '-e':
        # Call the function to erase all text from the file
        erase_memo()
        print("All text has been erased from the memo.")

    else:
        # Print an error message for incorrect argument
        print("Invalid argument. Use '-w' to write, '-r' to read, or '-e' to erase.")

# Ensure the main function is executed when the script is run
if __name__ == "__main__":
    main()