Python Playground
Python Playground
Playground
Dive into Coding with 19 Fun
and Educational Projects
Learn Python by Creating 19
Projects
Project 02 Store
How to use dictionaries to track sales of unknown items.
Prompting for user input.
Converting string input to integers.
Setting default values in a dictionary.
Iterating over dictionary key-value pairs.
Project 04 ELIZA
The project allows for exploration and experimentation
with natural language processing techniques.
It provides an opportunity to learn about rule-based
programming and develop programming skills.
Creating ELIZA requires analyzing and interpreting user
input, identifying keywords and patterns, and generating
appropriate responses.
There are many online resources and examples available to
guide beginners and experienced programmers alike.
ELIZA provides a fun way to simulate human-like
conversation through programming.
Project 05 Fibonacci
The educational aspects of programming, such as loops,
conditionals, and recursion.
The development of efficient algorithms using Fibonacci
numbers.
Mathematical modeling of natural phenomena that utilize
the Fibonacci sequence.
Cryptography algorithms that use Fibonacci numbers for
encryption and decryption.
By the end of the program, you will have the confidence and
expertise to use Python libraries and frameworks to solve
complex problems and build powerful applications.
Rune
00 - Leet Speak
Input and output. The program will need to take input from
the user, in the form of a string of text, and output the
corresponding leet speak translation. A Python developer can
learn how to accept user input, and output the results in a
formatted way.
Project Description
Leet (or “1337”), also known as eleet or leetspeak, is a system of
modified spellings used primarily on the Internet. (wiki).
This will create a leet speak program with Python and an example
input-output pair.
Example
'TAKE ME TO ANOTHER LEVEL' → '74K3 M3 70 4N07H3R 13V31'
00 - Leet Speak
Project Breakdown
The first step in creating a project is to break it down into
individual steps of what needs to be done.
This will simply prompt the user and return the input from the
user to the variable phrase.
00 - Leet Speak
phrase = phrase.upper()
If the user wrote ‘take me to another level’ then this will return
‘TAKE ME TO ANOTHER LEVEL’.
lookup = {
'A': '4',
'E': '3',
'I': '1',
'L': '1',
'O': '0',
'S': '5',
'T': '7'
}
leet = ''
for char in phrase:
leet += lookup.get(char, char)
The loop iterates over each character in the string phrase and
uses the dictionary get-method that will return the value if the key
exists (the first argument) else it will use the default value (the
second argument).
What it does if the character char is, say ‘L’, is to use lookup.get(‘L’,
‘L’) – in this case, it will return ‘1’ because it exists. On the other
hand if lookup.get(‘K’, ‘K’) then it would return ‘K’because ‘K’ does
not exist in the dictionary lookup.
print(leet)
leet = ''
for char in phrase:
leet += lookup.get(char, char)
# 4: Display output
print(leet)
01 - Temperature Converter
User Input and Output. You will learn how to accept user
input and display output in the terminal using Python’s built-in
input() and print() functions.
Variables and Data Types. You will learn how to use variables
to store data and manipulate it using arithmetic operators.
Additionally, you will learn about data types such as integers,
floats, and strings.
Float precision You will learn how to work with float precision
and how it matters for the user experience.
Project Description
°𝐶=(°𝐹−32)×5/9
Project
Example
75 → 23.89
°C=(°F−32)×5/9
This is a great project that will teach how things can be easily
modeled with Python built-in data structures.
User input. You will learn how to prompt the user for input.
Default values. You will learn how to use a dictionary and give
a default value if the key does not exist already. This is by far
one of my favorite things about Python dictionaries.
Iterate over the dictionary. You will also learn how to iterate
over the key-value pairs in a dictionary.
Project Description
You will start to sell items from the awesome store you implement
in Python in this project.
You count items sold, i.e. if you sell the three following items.
1. apple
2. pear
3. orange
To keep track of how many items you sell, you can use a
dictionary.
The dictionary can use the items as keys, and the number of sold
items as the value.
sold_items = {'apple': 0}
Yes, you could keep a long list of all items sold during the day.
Then at the end of the day, you could count the occurrences of
each item in the list.
You keep the same item multiple times, and it does not give
any value here.
It will be more complicated to make a status of the sold items
(you will see that in the end).
sold_items = {}
All you need is to print the key-value pairs from the dictionary.
As you see, this step gets easy, because we used the dictionary as
a data structure and not a list.
sold_items = {}
All you need is to print the key-value pairs from the dictionary.
As you see, this step gets easy, because we used the dictionary as
a data structure and not a list.
sold_items = {}
Loop. You will learn how to make a loop that will run until the
user quits the program. Also, you will learn how to iterate over
a Python list.
Project Description
The ToDo list Python program you will write can do 4 things.
It can show the content of your ToDo list – This can be done by
iterating over the list and showing items.
It can remove an item from your ToDo list – This can be done
by removing an item from the list.
todo = []
while True:
# print the options to the user
print('1: Show content')
print('2: Add an item to list')
print('3: Remove an item from the list')
print('4: Quit')
# prompt the user
option = input('Choose option: ')
if option == '1':
pass
elif option == '2':
pass
elif option == '3':
pass
elif option == '4':
print('Goodbye')
break
else:
print('Not understood')
Step 3 Implementation
The full code is implemented here.
todo = []
while True:
# print the options to the user
print('1: Show content')
print('2: Add an item to list')
print('3: Remove an item from the list')
print('4: Quit')
# prompt the user
option = input('Choose option: ')
if option == '1':
for idx, item in enumerate(todo):
print(idx, item)
elif option == '2':
item = input('Add item to list: ')
todo.append(item)
elif option == '3':
idx_str = input('What item to remove (use
index): ')
idx = int(idx_str)
todo.pop(idx)
elif option == '4':
print('Goodbye')
break
else:
print('Not understood')
What is ELIZA?
To understand the Python project on ELIZA, we need a bit of
background.
The program was named after the character Eliza Doolittle from
the play “Pygmalion,” who undergoes a transformation from a
working-class girl to a refined lady through language training.
ELIZA became famous in the late 1960s and early 1970s, as it was
one of the first programs to create the illusion of a human-like
conversation. It has since inspired numerous chatbots and
conversational agents, and its legacy can still be seen in the
development of modern AI-powered chatbots and virtual
assistants.
Example
You write I need cake it can look for a pattern I need *
Then it can ask Why do you need cake?
04 - ELIZA
while True:
s = input(eliza_response + ' ')
elif s == 'quit':
break
else:
eliza_response = 'Can you tell me why?'
You can expand on this idea to make the conversation more real
05 - Fibonacci
Project Description
The Fibonacci sequence is as follows.
0 1 1 2 3 5 8 13 21 34 ... (continues)
It is generated as follows.
0+1=1
1+1=2
1+2=3
2+3=5
3+5=8
8 + 13 = 21
13 + 21 = 34
21 + 34 = 55
...
def fib(n):
if n <= 1:
return n
i = 0
j = 1
for _ in range(n):
i, j = j, i + j
return i
05 - Fibonacci
You try to follow how the sequence is calculated and this can be
done but seems easy to get lost in the code.
for i in range(10):
print(fib(i))
But after inspecting the following code, you might find it easier to
write and follow.
def fib(n):
if n <= 1:
return n
for i in range(10):
print(fib(i))
06 - Guess a Number Game
Project Description
In this tutorial we will create the classical game: Guess a Number.
The game can be described as follows.
random.randrange(stop)
random.randrange(start, stop[, step])
Return a randomly selected element from range(start, stop, step).
# Alternatively
random_number = randrange(1, 101)
Another thing we need is to make sure that the input from the
user is in the correct range.
random_number = randrange(100) + 1
while True:
guess_str = input('What is your guess (1-100): ')
guess = int(guess_str)
if guess < 1:
print('Out of bound')
continue
WARNING: the above code will continue forever, but we are not
done with the project.
We first use continue in the loop, if the user input is not in the
expected bound. What continue does, is, it jumps up to the top of
the loop and starts all over.
06 - Guess a Number Game
random_number = randrange(100) + 1
guesses = 0
while True:
guess_str = input('What is your guess (1-100): ')
guess = int(guess_str)
if guess < 1:
print('Out of bound')
continue
guesses += 1
if guess == random_number:
print('Awesome! You guesses it!')
print('You used', guesses, 'guesses')
break
Notice that we use break to break out of the loop if the user
guesses correctly.
07 - Maze Game
Project Description
You will create a maze game in Python.
In the end, you will have an interactive game, where you can
create the most amazing and complex mazes on your own.
maze = [
list('######################'),
list('#### ### # # ### #'),
list('# # ## # # # # '),
list('# # # # ##### # #'),
list('# # # ######## # # #'),
list('# # # # # # # #'),
list('# # ## # # # #'),
list('######################'),
]
The walls in the maze are represented by # and you place the
player somewhere in the maze.
maze = [
list('######################'),
list('#### ### # # ### #'),
list('# # ## # # # # '),
list('# # # # ##### # #'),
list('# # # ######## # # #'),
list('# # # # # # # #'),
list('# # ## # # # #'),
list('######################'),
]
x = 2
y = 1
But this will look the location above (x – 1, y), left (x, y – 1), right (x,
y + 1), and below (x + 1, y).
If you change the player’s location, you can see it will update the
player view accordingly.
07 - Maze Game
maze = [
list('######################'),
list('#### ### # # ### #'),
list('# # ## # # # # '),
list('# # # # ##### # #'),
list('# # # ######## # # #'),
list('# # # # # # # #'),
list('# # ## # # # #'),
list('######################'),
]
x = 2
y = 1
while True:
print('###' + maze[x-1][y]*3 + '###')
print('###' + maze[x-1][y]*3 + '###')
print(maze[x][y-1]*3 + ' o ' + maze[x][y+1]*3)
print('###' + maze[x+1][y]*3 + '###')
print('###' + maze[x+1][y]*3 + '###')
if move == 'w': # up
pass
elif move == 's': # down
pass
elif move == 'a': # left
pass
elif move == 'd': # right
pass
elif move == 'h': # show map
pass
elif move == 'q': # quit
break
For now, we have not implemented the controls except the quit.
Notice we use a while True loop, which is an infinite loop, and we
exit the loop by using the break in the quit option q.
07 - Maze Game
while True:
print('###' + maze[x-1][y]*3 + '###')
print('###' + maze[x-1][y]*3 + '###')
print(maze[x][y-1]*3 + ' o ' + maze[x][y+1]*3)
print('###' + maze[x+1][y]*3 + '###')
print('###' + maze[x+1][y]*3 + '###')
if move == 'w': # up
pass
elif move == 's': # down
pass
elif move == 'a': # left
pass
elif move == 'd': # right
pass
elif move == 'h': # show map
maze[x][y] = 'o'
for row in maze:
print(''.join(row))
maze[x][y] = ' '
input('Press enter to continue')
clear_output()
elif move == 'q': # quit
break
Also notice, that after we have displayed the map, we change the
player position to space again.
Finally, we prompt the user to press enter to continue and remove
the map.
maze = [
list('######################'),
list('#### ### # # ### #'),
list('# # ## # # # # '),
list('# # # # ##### # #'),
list('# # # ######## # # #'),
list('# # # # # # # #'),
list('# # ## # # # #'),
list('######################'),
]
x = 2
y = 1
while True:
print('###' + maze[x-1][y]*3 + '###')
print('###' + maze[x-1][y]*3 + '###')
print(maze[x][y-1]*3 + ' o ' + maze[x][y+1]*3)
print('###' + maze[x+1][y]*3 + '###')
print('###' + maze[x+1][y]*3 + '###')
if move == 'w': # up
if maze[x - 1][y] == '#':
print('Illegal move')
else:
x -= 1
elif move == 's': # down
if maze[x + 1][y] == '#':
print('Illegal move')
else:
x += 1
07 - Maze Game
if y == len(maze[0]) - 1:
print('You finished')
break
Finally, we have kept the maze simple and only have one exit on
the far right. This way, a simple way to check if the player has
finished the maze is to see if the move results in a position on the
far right side of the maze.
You can create your own maze now. If you keep the only exit in
your maze at the far right, keep the maze rectangular, then you
can use the code as it is.
If you make further changes, you might need to modify the code
to your specific needs.
08 - Heads or Tails
Randomness. You need to flip a coin and for that, you need
randomness.
Project Description
This is a simple project to create a heads-or-tails game in Python,
we need to learn to work with functions.
Game description.
Your goal is not to write the code, it is to use functions to create it.
Note: An advantage of writing functions is that it enables you to
test it isolated.
08 - Heads or Tails
That could actually be one simple way to break it down into the
above 3 pieces.
Now your job is to implement them isolated and test that they
work as expected.
This organizes the code in blocks of code that you can use with a
call to a function. But more importantly, you can test it isolated.
def input_from_user():
while True:
guess = input('head or tails? ')
This uses the infinite loop (while True) to prompt the user
(input()), until the input is valid (if guess in…).
Now you can test that function isolated to see if it does what is
expected.
def flips_a_coin():
coin = randrange(2)
if coin == 0:
return 'tails'
else:
return 'head'
print_result('tails', 'tails')
print_result('head', 'tails')
print_result('tails', 'head')
print_result('head', 'head')
user_guess = input_from_user()
coin = flips_a_coin()
print_result(user_guess, coin)
Project Description
In this project, you will create a simple calculator.
The calculator will take input from the user and create the
calculation.
1+4
6*10
100-90
1000/50
1+2+3
1/3*6
-10/3
10*-1
Examples
What happens if the user inputs data in the wrong format
(invalid input)?
How should it output the result data?
What to do?
Sometimes you can clarify these issues with the user.
Other times you can make choices based on your knowledge
or best guesses.
When to do what?
Who is the user or owner of the code you develop?
How big an impact does the decision have?
09 - Basic Calculator
One thing you can do before that is to make sure the input
functionality works independently of the validation.
def is_input_format_correct(input_str):
return False
# Input from user and validation of input
def input_calculation():
"""
Prompts the user for a calculation.
Repeat until input from user is on format [num][op][num]
Return the input from user.
"""
while True:
input_str = input('Input calculation: ')
if is_input_format_correct(input_str):
return input_str
def valid_chars(input_str):
"""
Returns True if input_str only contains chars from
'0123456789+-*/'
"""
for c in input_str:
if c not in '0123456789+-*/':
return False
return True
assert valid_chars('123+456')
assert valid_chars('0123456789+-*/')
assert valid_chars('123b123') == False
09 - Basic Calculator
if no_operators == 1:
return True
else:
return False
assert one_operator('123+123')
assert one_operator('123-123')
assert one_operator('123*123')
assert one_operator('123/123')
assert one_operator('123123/')
assert one_operator('123++123') == False
assert one_operator('123+/123') == False
assert one_operator('123+*123') == False
assert one_operator('123--123') == False
The power of writing a doc string here, is, that you can give
assumptions to the user. The function uses the string method
count. This function will only work correctly if the input is of a
certain format (a format passing the previously defined function).
def correct_format(input_str):
"""
Given input_str only contains chars '0123456789+-*/'
and input_str only has one operator (+, -, *, or /)
Return True if input_str is on the format [num][op][num]
"""
if input_str[0] in '+-*/':
return False
if input_str[-1] in '+-*/':
return False
return True
assert correct_format('0+0')
assert correct_format('1+1')
assert correct_format('2+2')
assert correct_format('3+3')
assert correct_format('4+4')
assert correct_format('5+5')
assert correct_format('6+6')
assert correct_format('7+7')
assert correct_format('8+8')
assert correct_format('9+9')
assert correct_format('99+') == False
assert correct_format('+99') == False
assert correct_format('99-') == False
assert correct_format('-99') == False
assert correct_format('99*') == False
assert correct_format('*99') == False
assert correct_format('99/') == False
assert correct_format('/99') == False
if not one_operator(input_str):
return False
if not correct_format(input_str):
return False
return True
assert is_input_format_correct('123+123')
assert is_input_format_correct('123b123') == False
assert is_input_format_correct('123++123') == False
assert is_input_format_correct('123123+') == False
def convert_to_ints(numbers_str):
"""
Input is a list of numbers as str.
Returns a list of the numbers as int.
"""
numbers = []
return numbers
def calculate_result(calc):
"""
If calc is on format [num][op][num]
Returns the result of the calculation calc.
"""
if '+' in calc:
numbers_str = calc.split('+')
numbers = convert_to_ints(numbers_str)
return numbers[0] + numbers[1]
if '-' in calc:
numbers_str = calc.split('-')
numbers = convert_to_ints(numbers_str)
return numbers[0] - numbers[1]
if '*' in calc:
numbers_str = calc.split('*')
numbers = convert_to_ints(numbers_str)
return numbers[0]*numbers[1]
if '/' in calc:
numbers_str = calc.split('/')
numbers = convert_to_ints(numbers_str)
return numbers[0]/numbers[1]
# Combine it all
calc = input_calculation()
result = calculate_result(calc)
display_result(calc, result)
3 lines of code and you have it all there. If you know something is
wrong with the way you calculate it, you know where to look.
Project Description
To implement an interactive board game in Python you can
consider the following board.
-------------
|O| | | | |X|
-------------
The player can move either 1 or 2 moves to left or right, but only
inside the board.
Importance of Design
Making a design of your Python project before starting to code is
crucial for several reasons, especially when you make an
interactive board game in Python.
The next part is to implement each part of the steps and finally
combine them. A great way to do that is to keep each step in one
or more functions.
How you represent the board will have an impact on most other
parts of your implementation.
10 - Interactive Board Game
board = ['O', ' ', ' ', ' ', ' ', 'X']
def display_board(board):
clear_output()
length = len(board)
print('-'*(length*2 + 1))
for item in board:
print('|', item, sep='', end='')
print('|')
print('-'*(length*2 + 1))
Why?
10 - Interactive Board Game
move = int(input_str)
pos = get_position(board, 'O')
return True
def user_input(board):
while True:
input_str = input('Choose move (-2, -1, 1,
2): ')
if valid_move(board, input_str):
return int(input_str)
print('invalid move')
return board
def get_random_move():
while True:
random_move = randrange(-2, 3)
if random_move in [-2, -1, 1, 2]:
return random_move
def get_computer_move(board):
pos = get_position(board, 'X')
while True:
move = get_random_move()
return move
This will make sense when you see the final code.
10 - Interactive Board Game
board = ['O', ' ', ' ', ' ', ' ', 'X']
moves = 0
while True:
display_board(board)
move = user_input(board)
computer_move = get_computer_move(board)
Project Description
Tic Tac Toe is a two-player game where each player takes turns
placing X’s or O’s on a 3×3 grid.
The game ends in a draw if the grid is full and neither player has
won.
Design of Project
As we have learned, it is important to make a design of your
project before you start to code. This is also true for implementing
the Tic Tac Toe game in Python.
win/draw?
End
display board
output result
board
11 - Tic Tac Toe Game
0. Setup board
1. Display board
2. Input from the user (including validation)
3. Update board (place the marker for the player)
4. Check if the player wins or the game is done then output it and
end.
5. Input from computer
6. Update board (place the marker for the computer)
7. Check if the computer wins or the game is done then output it
and end.
8. Repeat from 1.
Now we are ready to implement the tic tac toe game in Python
using functions.
How you represent the board will influence how other parts of the
code will be implemented.
Alternatively, you could have a list of lists. But try to think about
how you would implement other parts of the code later. It would
make it more complex.
board = ['#', '-', '-', '-', '-', '-', '-', '-', '-', '-']
Notice, we do not use the first entry (index 0) and keep a hash
symbol there. This actually doesn’t matter, because it will simplify
the code as we proceed.
def display_board(board):
clear_output()
print(board[7], board[8], board[9])
print(board[4], board[5], board[6])
print(board[1], board[2], board[3])
This makes it clear and concise what the board looks like and is
easy to understand as a programmer.
if board[move] != '-':
return False
return True
def player_input(board):
"""
Input player move. Prompts the user until valid move
meaning (1-9) and position available.
Returns the valid move.
"""
while True:
input_str = input('Input move (1-9): ')
if valid_move(board, input_str):
return int(input_str)
print('Invalid move')
You see, the user is prompted until a valid move has been made.
This is a great way to implement it, as it makes it easy for
somebody reading the code as well.
Always think about the future person reading the code. How can
you design and make the implementation easy?
11 - Tic Tac Toe Game
You may think creating a function for this is a bit too much, but it
will simplify and make your final code more readable and easier to
understand. The function name tells the reader of the code what
the intention is, also, the doc string tells about that.
If you just put the code somewhere, the reader can see what
happens, but not know what the intention was, making it difficult
to understand.
def is_done(board):
"""
Returns True if the board is filled and game is done.
"""
for pos in board[1:]:
if pos == '-':
return False
return True
return False
def get_random_postion():
"""
Returns a random integer from 1-9 (both inclusive)
"""
return randrange(1, 10)
def get_computer_move(board):
"""
Returns a random move by the computer which is valid.
"""
while True:
random_move = get_random_postion()
if board[random_move] == '-':
return random_move
while True:
display_board(board)
pos = player_input(board)
place_marker(board, 'O', pos)
c_pos = get_computer_move(board)
place_marker(board, 'X', c_pos)
Project Description
This project will teach you how to make data processing on IMDB
data in Python.
The job is to process the 5,000 rows and create a new csv file with
less metadata and only for movies rated above imdb_score 7.
Project Design
While this seems to be an easy task, it is always important to make
a few thoughts before starting to code.
One goal is to break the code down into smaller steps that can be
implemented isolated and have minimal functionality to it. This
will keep the code easier to understand and maintain.
12 - Process IMDB Data Easily
The idea is not to try to do it all at once, but to keep the code in
these steps.
The IMDB data is kept in CSV files and we will use Python to
process it.
import csv
filename = 'files/movie_metadata.csv'
with open(filename) as f:
csv_reader = csv.DictReader(f)
records = list(csv_reader)
You will notice, that this will keep all values in the dictionaries as
strings.
processed_records = []
Project Description
Consider the file files/bachelor.txt.
What are the most likely words after the name Holmes occurs in
the text.
Examples
...
friend Sherlock Holmes had a considerable share in clearing
...
still sharing rooms with Holmes in Baker Street, that he
...
In the two examples the word after Holmes is had and in.
Luckily, Python has made that easy for you to read files.
if 'Holmes' in word:
last_word_holmes = True
13 - Text Processing
Project Description
An acronym is a word created by combining the first letter or
syllable of each word in a phrase to create a new, single word.
Project Design
While this is a small project. an acronym generator in Python, it is
always a good idea to break it down.
def get_input():
"""
Prompts the user for an input phrase
and returns it as a string.
"""
input_str = input('Input word phrase: ')
return input_str
A great thing about breaking it down into functions, is, that you
can test each function isolated.
This can be done with a loop over the words. The function split()
returns all the words from a string in a list.
15 - Password Generator
Project Description
Create a password generator in Python.
vr)5-x?C(-8FNh-SkfD
lower = 'abcdefghijklmnopqrstuvwxyz'
upper = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
decimal = '01234567890'
special = '!@#$%^&*()?'
def strong_password(password):
if not contains(lower, password):
return False
if not contains(upper, password):
return False
if not contains(decimal, password):
return False
if not contains(special, password):
return False
return True
The logic is simple. For each group check if the password contains
the type of characters. If not, return False. If it passes all tests,
then the password must be strong.
import random
while True:
password = ''
for _ in range(16):
password += random.choice(legal_chars)
if strong_password(password):
password = password[:4] + '-' +
password[4:8] + '-' + password[8:12] + '-' +
password[12:]
print(password)
break
You see, keep making them until one succeeds. This way you don’t
compromise the randomness in the password generator.
16 - Anagram Game
Input and output. The game will require the ability to accept
user input (i.e., the word or phrase to be scrambled) and
output the resulting anagrams to the user. This will require the
use of Python input() function and the print() function.
Looping The game will need to iterate to prompt the user for
guesses until correct.
Project Description
What is an Anagram?
Example
words = [
'atrocity',
'fanatical',
'pensive',
'respite',
'discordant',
'eloquent',
'encompass',
'imperceptible',
'insuperable',
'stealthily',
'impassive',
]
import random
word = random.choice(words)
letters = list(word)
random.shuffle(letters)
anagram = ''.join(letters)
while True:
print(anagram)
guess = input()
if guess == word:
print('correct')
break
print('incorrect')
Project Description
A valid parentheses string satisfies the following:
Examples of valid
()
(())
()()
(()())
Examples of invalid
(()
)(
())(
((())
Advanced
Can you solve it if the string contains simple, curly, and square
braces: ()[]{}
Examples of valid
()[]
([])
(){}
([]{})
Examples of invalid
([)]
(}(]
()(}
({][})
While this is not the whole story you need to add a bit more.
def matching_parentheses(s):
no_open = 0
for c in s:
if c == ')':
no_open -= 1
elif c == '(':
no_open += 1
if no_open < 0:
return False
if no_open != 0:
return False
return True
17 - Valid Parentheses
Because now you need to keep track of the order of opening and
closing parentheses.
def matching_parentheses(s):
stack = []
for c in s:
if c in '([{':
stack.append(c)
if c in ')]}':
if len(stack) == 0:
return False
top = stack.pop()
if len(stack) != 0:
return False
return True
18 - Four in a Row Game
Project Description
Four-in-a-row is a two-player strategy game where the objective is
to connect four of your pieces vertically, horizontally, or diagonally
on a grid of six rows and seven columns.
Players take turns dropping their colored discs into one of the
columns, with the disc occupying the lowest unoccupied space in
that column.
The first player to connect four of their discs in a row wins the
game.
Project Design
We know that breaking a project down into smaller steps is a
great way to make it easier to implement.
If you think about it, you only need to implement the first 4 steps,
then you can implement the game.
empty = '·'
board = [[empty]*7 for _ in range(6)]
def display_board(board):
clear_output()
print(' 0123456')
print('+' + '-'*7 + '+')
for row in board:
print('|', end='')
for col in row:
print(col, end='')
print('|')
print('+' + '-'*7 + '+')
if board[0][int(move)] == empty:
return True
return False
To check if the game is done (but not won) is to check if the board
is full. This can be done simply like the following.
def is_full(board):
for col in board[0]:
if col == empty:
return False
return True
for i in range(len(board[0])):
col = []
for row in board:
col.append(row[i])
trans.append(col)
return trans
# Check columns
trans = get_transpose(board)
if four_in_row(trans, marker):
return True
# Check diagonal
diag = []
for idx, row in enumerate(board):
diag.append([empty]*idx + row + [empty]*(6 - idx))
diag_t = get_transpose(diag)
if four_in_row(diag_t, marker):
return True
diag = []
for idx, row in enumerate(board):
diag.append([empty]*(6 - idx) + row + [empty]*idx)
diag_t = get_transpose(diag)
if four_in_row(diag_t, marker):
return True
return False
18 - Four in a Row Game
empty = '·'
board = [[empty]*7 for _ in range(6)]
while True:
display_board(board)
move = get_player_move(board, 'O')
board = place_marker(board, move, 'O')
if game_won(board, 'O') or is_full(board):
display_board(board)
print('Done')
break
display_board(board)
move = get_player_move(board, 'X')
board = place_marker(board, move, 'X')
if game_won(board, 'X') or is_full(board):
display_board(board)
print('Done')
break
By the end of the program, you will have the confidence and
expertise to use Python libraries and frameworks to solve
complex problems and build powerful applications.
Rune