Harvard and MIT’s $800 Million Mistake
![](http://writinghelp.online/777/templates/cheerup/res/banner1.gif)
Harvard and MIT’s $800 Million Mistake: The Triple Failure of 2U, edX, and Axim Collaborative
The future of Coursera’s only credible alternative for universities rests in the hands of 2U’s creditors.
- 10 Best Data Science Courses for 2024
- 7 Best Free OCaml Courses for 2024
- 6 Best Free Ecology Courses for 2024
- [2024] Massive List of Thousands of Free Certificates and Badges
- Learn Something New: 100 Most Popular Courses For September
600 Free Google Certifications
Most common
- data science
Popular subjects
Communication Skills
Data Analysis
Digital Marketing
Popular courses
What is a Mind?
The Ancient Greeks
Quantum Mechanics for Everyone
Organize and share your learning with Class Central Lists.
View our Lists Showcase
Class Central is learner-supported. When you buy through links on our site, we may earn an affiliate commission.
Problem Solving, Python Programming, and Video Games
University of Alberta via Coursera Help
- Module 0: Introduction
- In Module 0, you will meet the instructional team and be introduced to the four themes of this course: computer science, problem solving, Python programming, and how to create video games.
- Module 1: Design Hacking Version 1
- In Module 1, you will explore the game creation process that is used in this course. You will use this process to design Version 1 of the first game, Hacking. You will use two problem-solving techniques: problem decomposition and algorithms. You will explore five criteria for problem decomposition: experiential decomposition, feature selection, problem refinement, spatial decomposition, and temporal decomposition. To create your design for Hacking Version 1, you will use three interactive learning objects: the description builder, functional test plan builder, and algorithm builder.
- Module 2: Program Hacking Version 1
- In Module 2, you will discover how lexics, syntax, and semantics can be used to understand and describe programming languages. You will use these concepts to understand your first Python statement (expression statement), first three Python expressions (literal, identifier, function call), and first five Python types (int, str, float, function, NoneType). You will use these Python constructs to write, test, and debug Hacking Version 1, a text-based game version. You will then reflect on your game version by using a third problem-solving technique called abstraction, including the specific technique of solution generalization, to solve similar problems.
- Module 3: Hacking Version 2
- In Module 3, you will identify solution issues in your game. You will apply a second form of the abstraction problem-solving technique, called using templates, to solve a solution issue by using a graphics library. You will then use lexics, syntax, and semantics to learn two new Python statements (assignment, import), two new Python expressions (binary expression, attribute reference), and one new Python type (module). You will employ these Python constructs and a simple graphics library to write, test, and debug Hacking Version 2.
- Module 4: Hacking Version 3
- In Module 4, you will modify your game design to support multiple gameplay paths using a new problem decomposition criteria called case-based decomposition, which utilizes a selection control structure. You will learn one new Python statement (if), one new Python expression (unary expression), and one new Python type (bool). You will employ these Python constructs to write, test, and debug Hacking Version 3.
- Module 5: Hacking Version 4 & 5
- In Module 5, you will modify your game design using two new abstraction techniques, called control abstraction and data abstraction. You will explore two different control abstractions, called definite and indefinite repetition. You will learn two new Python statements (for, while), four new Python expressions (subscription expression, expression list, parenthesized expression, list display), and three new Python types (tuple, list, range). You will employ these Python constructs to write, test, and debug Hacking Version 4 and Hacking Version 5.
- Module 6: Hacking Version 6
- In Module 6, you will learn a new control abstraction called a user-defined function. You will learn how to implement user-defined functions using two new Python statements (function definition, return). You will employ these Python constructs to significantly improve the quality of your code in Hacking Version 6.
- Module 7: Hacking Version 7
- In Module 7, you will not learn any new problem-solving techniques or Python language features. Instead you will exercise your problem-solving skills and practice the language constructs you already know to improve your proficiency. You will add some fun features to the Hacking game by designing, coding, testing, and debugging Hacking Version 7.
- Module 8: Poke the Dots Version 1 & 2
- In Module 8, you will design and implement Version 1 of a new graphical game called Poke the Dots. You will then modify your game design using data abstraction to create user-defined classes. You will learn two new Python statements (class definition, pass) that will allow you to construct your own Python types. You will employ these Python constructs to implement Poke the Dots Version 2.
- Module 9: Poke the Dots Version 3
- In Module 9, you will not learn any new problem-solving techniques or Python language features. Instead you will exercise your problem-solving skills and practice the language constructs you already know to improve your proficiency. You will add some fun features to the Poke the Dots game by designing, coding, testing, and debugging Poke the Dots Version 3.
- Module 10: Poke the Dots Version 4
- In Module 10, you will modify your game design using a new form of control abstraction called user-defined methods. User-defined methods allow you to restrict access to the attributes of a class to improve data abstraction. You will employ user-defined methods to implement Poke the Dots Version 4.
- Module 11: Poke the Dots Version 5
- In Module 11, you will not learn any new problem-solving techniques or Python language features. Instead you will exercise your problem-solving skills and practice the language constructs you already know to improve your proficiency. You will add some fun features to the Poke the Dots game by designing, coding, testing, and debugging Poke the Dots Version 5.
Duane Szafron and Paul Lu
Related Courses
Computational thinking for problem solving, introduction to python, computer science fundamentals, python basics: create a guessing number game from scratch, introduction to programming, algorithmic thinking (part 2), related articles, 1700 coursera courses that are still completely free, 250 top free coursera courses of all time, massive list of mooc-based microcredentials.
4.0 rating, based on 4 Class Central reviews
4.3 rating at Coursera based on 227 ratings
Select rating
Start your review of Problem Solving, Python Programming, and Video Games
- AA Anonymous 4 years ago A great introduction to concepts in coding. I now feel much more confident in my ability to solve coding problems, even if the way forward isn't immediately obvious. I felt that the learning materials were well presented and put together, and that the instructor feedback in the forums was vary helpful. I also thought that the exercises were well designed in teaching you not just the syntax of python, but in getting the learner to solve problems and read the language documentation on their own. It is one thing to be shown how to solve a problem, an other to be given the tools to do so on your own. Helpful
- AA Anonymous 3 years ago As a complete newbie, I made extensive use of the generous and available tutoring. The responses to my queries were promptly answered and helpful. Helpful
- AA Anonymous 3 years ago The program should have a main menu, through which the user can choose whether he wants to encrypt a text or decrypt it. Helpful
- AA Anonymous 2 years ago I am very disappointed. They are mixing a parsing class, a beginner python class and a video game course. It is not at all needed. Those who are writing video games are probably not going deep into theory of computer science. They discuss assignment statements and creating a graphics based game in the same lesson! I think they mix up too much into one course. Helpful
Never Stop Learning.
Get personalized course recommendations, track subjects and courses with reminders, and more.
Say "Hello, World!" With Python Easy Max Score: 5 Success Rate: 96.19%
Python if-else easy python (basic) max score: 10 success rate: 89.62%, arithmetic operators easy python (basic) max score: 10 success rate: 97.35%, python: division easy python (basic) max score: 10 success rate: 98.67%, loops easy python (basic) max score: 10 success rate: 98.07%, write a function medium python (basic) max score: 10 success rate: 90.28%, print function easy python (basic) max score: 20 success rate: 97.30%, list comprehensions easy python (basic) max score: 10 success rate: 97.64%, find the runner-up score easy python (basic) max score: 10 success rate: 94.21%, nested lists easy python (basic) max score: 10 success rate: 91.79%, cookie support is required to access hackerrank.
Seems like cookies are disabled on this browser, please enable them to open this website
- Python Course
- Python Basics
- Interview Questions
- Python Quiz
- Popular Packages
Python Projects
- Practice Python
- AI With Python
- Learn Python3
- Python Automation
- Python Web Dev
- DSA with Python
- Python OOPs
- Dictionaries
Python Exercise with Practice Questions and Solutions
Python Exercise: Practice makes you perfect in everything. This proverb always proves itself correct. Just like this, if you are a Python learner, then regular practice of Python exercises makes you more confident and sharpens your skills. So, to test your skills, go through these Python exercises with solutions.
Python is a widely used general-purpose high-level language that can be used for many purposes like creating GUI, web Scraping, web development, etc. You might have seen various Python tutorials that explain the concepts in detail but that might not be enough to get hold of this language. The best way to learn is by practising it more and more.
The best thing about this Python practice exercise is that it helps you learn Python using sets of detailed programming questions from basic to advanced. It covers questions on core Python concepts as well as applications of Python in various domains. So if you are at any stage like beginner, intermediate or advanced this Python practice set will help you to boost your programming skills in Python.
![problem solving python programming and video games answers problem solving python programming and video games answers](https://media.geeksforgeeks.org/wp-content/uploads/20210105234135/PythonPracticeExercisesQuestionsandSolutionsmin.png)
- List of Python Programming Exercises
In the below section, we have gathered chapter-wise Python exercises with solutions. So, scroll down to the relevant topics and try to solve the Python program practice set.
Table of Content
Python List Exercises
Python string exercises, python tuple exercises, python dictionary exercises, python set exercises, python matrix exercises, python functions exercises, python lambda exercises.
- Python Pattern printing Exercises
Python DateTime Exercises
Python oops exercises, python regex exercises, python linkedlist exercises, python searching exercises, python sorting exercises, python dsa exercises, python file handling exercises, python csv exercises, python json exercises, python os module exercises, python tkinter exercises, numpy exercises, pandas exercises, python web scraping exercises, python selenium exercises.
In this section, we have compiled a variety of Python list exercises that range from basic to advanced levels. These exercises are designed to help you master the fundamentals of Python lists, including list creation, indexing, slicing, and common operations like appending, inserting, and removing elements.
- Python program to interchange first and last elements in a list
- Python program to swap two elements in a list
- Python | Ways to find length of list
- Maximum of two numbers in Python
- Minimum of two numbers in Python
>> More Programs on List
In this section, we provide a variety of Python string exercises designed to enhance your understanding of string manipulation and operations. Explore these exercises and upsacle your Python programming skills.
- Python program to check whether the string is Symmetrical or Palindrome
- Reverse words in a given String in Python
- Ways to remove i’th character from string in Python
- Find length of a string in python (4 ways)
- Python program to print even length words in a string
>> More Programs on String
Here, you’ll find a range of Python tuple exercises designed to help you understand and master this essential data structure. Tuples are immutable sequences used to store collections of items, and they’re a fundamental part of Python programming.
- Python program to Find the size of a Tuple
- Python – Maximum and Minimum K elements in Tuple
- Python – Sum of tuple elements
- Python – Row-wise element Addition in Tuple Matrix
- Create a list of tuples from given list having number and its cube in each tuple
>> More Programs on Tuple
In this section, you’ll find a variety of Python dictionary exercises designed to help you master the use of dictionaries, one of Python’s most powerful and versatile data structures.
- Python | Sort Python Dictionaries by Key or Value
- Handling missing keys in Python dictionaries
- Python dictionary with keys having multiple inputs
- Python program to find the sum of all items in a dictionary
- Python program to find the size of a Dictionary
>> More Programs on Dictionary
This section offers a range of Python set exercises that will help you build a strong understanding of set operations in Python. You’ll practice adding and removing elements, performing operations like union, intersection, and difference, and using set comprehensions.
- Find the size of a Set in Python
- Iterate over a set in Python
- Python – Maximum and Minimum in a Set
- Python – Remove items from Set
- Python – Check if two lists have atleast one element common
>> More Programs on Sets
Here, in this section you’ll find a collection of Python matrix exercises tailored for beginners and advanced Python programmers. These exercises focus on essential skills such as creating and manipulating matrices, performing operations like addition, subtraction, multiplication, and more.
- Python – Assigning Subsequent Rows to Matrix first row elements
- Adding and Subtracting Matrices in Python
- Python – Group similar elements into Matrix
- Create an n x n square matrix, where all the sub-matrix have the sum of opposite corner elements as even
>> More Programs on Matrices
This section offers a variety of exercises focused on Python functions to help you master this essential programming concept. You’ll learn how to define functions, work with parameters and return values, and explore advanced topics like lambda functions, decorators, and recursion.
- How to get list of parameters name from a function in Python?
- How to Print Multiple Arguments in Python?
- Python program to find the power of a number using recursion
- Sorting objects of user defined class in Python
- Functions that accept variable length key value pair as arguments
>> More Programs on Functions
In this section, we’ve compiled a series of exercises focused on Python’s lambda functions, which allow you to write small, anonymous functions with concise syntax. These exercises will help you understand how to use lambda functions for quick data manipulation, sorting, filtering, and mapping operations.
- Lambda with if but without else in Python
- Python | Sorting string using order defined by another string
- Python | Find fibonacci series upto n using lambda
- Python program to count Even and Odd numbers in a List
- Python | Find the Number Occurring Odd Number of Times using Lambda expression and reduce function
>> More Programs on Lambda
- Program to print half Diamond star pattern
- Programs for printing pyramid patterns in Python
- Program to print the diamond shape
- Python | Print an Inverted Star Pattern
- Python Program to print digit pattern
>> More Programs on Python Pattern Printing
Enhance your Python skills by diving into various DateTime exercises that focus on handling dates and times effectively. These exercises will teach you how to use the datetime module to format dates, calculate time differences, manage time zones, and build time-sensitive applications.
- Python program to get Current Time
- Get Yesterday’s date using Python
- Python program to print current year, month and day
- Python – Convert day number to date in particular year
- Get Current Time in different Timezone using Python
>> More Programs on DateTime
Here in this practice section, you’ll find exercises focused on Object-Oriented Programming (OOP) concepts in Python. These exercises are designed to help you understand and implement key OOP principles such as classes, objects, inheritance, polymorphism, encapsulation, and abstraction.
- Python program to build flashcard using class in Python
- Shuffle a deck of card with OOPS in Python
- How to create an empty class in Python?
- Student management system in Python
>> More Programs on Python OOPS
Python Regex exercises to help you master the art of pattern matching and text manipulation. Regular expressions, or Regex, are powerful tools used to search, match, and manipulate strings based on specific patterns.
- Python program to find the type of IP Address using Regex
- Python program to find Indices of Overlapping Substrings
- Python program to extract Strings between HTML Tags
- Python – Check if String Contain Only Defined Characters using Regex
- Python program to find files having a particular extension using RegEx
>> More Programs on Python Regex
In this section, we’ve compiled a series of exercises focused on implementing and manipulating linked lists using Python. These exercises cover various operations, such as inserting nodes, deleting nodes, reversing linked lists, and detecting cycles, allowing you to practice and master linked list concepts.
- Python program to Search an Element in a Circular Linked List
- Pretty print Linked List in Python
- Python | Stack using Doubly Linked List
- Python | Queue using Doubly Linked List
- Python program to find middle of a linked list using one traversal
>> More Programs on Linked Lists
This section offers a range of exercises designed to help you master searching algorithms in Python. You’ll learn how to implement techniques like linear search and binary search, as well as more advanced methods such as interpolation and exponential search.
- Python Program for Linear Search
- Python Program for Binary Search (Recursive and Iterative)
- Python Program for Anagram Substring Search (Or Search for all permutations)
>> More Programs on Python Searching
This section provides a collection of exercises to help you practice and understand sorting in Python. You’ll explore various sorting algorithms, like bubble sort, merge sort, quicksort, and others, each with its unique approach to arranging data.
- Python Program for Bubble Sort
- Python Program for QuickSort
- Python Program for Insertion Sort
- Python Program for Selection Sort
- Python Program for Heap Sort
>> More Programs on Python Sorting
Strengthen your Python skills with Data Structures and Algorithms (DSA) exercises tailored to help you master the fundamental concepts of programming. These exercises cover a wide range of topics, including arrays, linked lists, stacks, queues, trees, graphs, and sorting algorithms, providing a hands-on approach to learning.
- Python program to reverse a stack
- Multithreaded Priority Queue in Python
- Check whether the given string is Palindrome using Stack
- Program to Calculate the Edge Cover of a Graph
- Python Program for N Queen Problem
>> More Programs on Python DSA
In this section, you’ll find a variety of exercises focused on Python file handling to help you master reading from and writing to files. These exercises will guide you through the essentials, such as opening, reading, writing, closing files and more.
- Read content from one file and write it into another file
- Write a dictionary to a file in Python
- How to check file size in Python?
- Find the most repeated word in a text file
- How to read specific lines from a File in Python?
>> More Programs on Python File Handling
Working with CSV (Comma-Separated Values) files is a fundamental skill in data handling and analysis with Python. These exercises are designed to help you learn how to read, write, and manipulate CSV files using Python’s built-in csv module and libraries like pandas.
- Update column value of CSV in Python
- How to add a header to a CSV file in Python?
- Get column names from CSV using Python
- Writing data from a Python List to CSV row-wise
- Convert multiple JSON files to CSV Python
>> More Programs on Python CSV
In this section, we provide a variety of exercises to help you master JSON (JavaScript Object Notation) in Python. JSON is a popular data format used for exchanging information between web clients and servers.
- Convert class object to JSON in Python
- Convert JSON data Into a Custom Python Object
- Flattening JSON objects in Python
- Convert CSV to JSON using Python
>> More Programs on Python JSON
Here in this section, we have compiled a list of exercises that will help you practice using the Python OS module to create, delete, and navigate directories, manage files, and interact with system processes.
- How to get file creation and modification date or time in Python?
- Menu Driven Python program for opening the required software Application
- Python Script to change name of a file to its timestamp
- Kill a Process by name using Python
- Finding the largest file in a directory using Python
>> More Programs on OS Module
Python’s Tkinter library is a powerful tool for creating graphical user interfaces (GUIs). These exercises are designed to help you learn the basics of GUI development, such as creating buttons, labels, text boxes, and handling events.
- Python | Create a GUI Marksheet using Tkinter
- Python | ToDo GUI Application using Tkinter
- Python | GUI Calendar using Tkinter
- File Explorer in Python using Tkinter
- Visiting Card Scanner GUI Application using Python
>> More Programs on Python Tkinter
Enhance your Python programming skills by diving into NumPy exercises designed to teach you the fundamentals of this powerful library. NumPy is essential for numerical computing in Python, providing support for large, multi-dimensional arrays and matrices, along with a collection of mathematical functions to operate on them.
- How to create an empty and a full NumPy array?
- Create a Numpy array filled with all zeros
- Create a Numpy array filled with all ones
- Replace NumPy array elements that doesn’t satisfy the given condition
- Get the maximum value from given matrix
>> More Programs on NumPy
In this section, you’ll find a variety of exercises designed to help you master the Pandas library in Python, a powerful tool for data manipulation and analysis. These exercises range from basic operations like data filtering, sorting, and grouping.
- Make a Pandas DataFrame with two-dimensional list | Python
- How to iterate over rows in Pandas Dataframe
- Create a pandas column using for loop
- Create a Pandas Series from array
- Pandas | Basic of Time Series Manipulation
>> More Programs on Python Pandas
Explore a variety of Python web scraping exercises that will help you learn how to extract data from websites efficiently.
- How to extract youtube data in Python?
- How to Download All Images from a Web Page in Python?
- Test the given page is found or not on the server Using Python
- How to Extract Wikipedia Data in Python?
- How to extract paragraph from a website and save it as a text file?
>> More Programs on Web Scraping
Here you’ll find exercises that help you master web automation using Selenium, a powerful tool for controlling web browsers through Python scripts.
- Download File in Selenium Using Python
- Bulk Posting on Facebook Pages using Selenium
- Google Maps Selenium automation using Python
- Count total number of Links In Webpage Using Selenium In Python
- Extract Data From JustDial using Selenium
>> More Programs on Python Selenium
- Number guessing game in Python
- 2048 Game in Python
- Get Live Weather Desktop Notifications Using Python
- 8-bit game using pygame
- Tic Tac Toe GUI In Python using PyGame
>> More Projects in Python
In closing, we just want to say that the practice or solving Python problems always helps to clear your core concepts and programming logic. Hence, we have designed this Python exercises after deep research so that one can easily enhance their skills and logic abilities.
Please Login to comment...
Similar reads.
- California Lawmakers Pass Bill to Limit AI Replicas
- Best 10 IPTV Service Providers in Germany
- Python 3.13 Releases | Enhanced REPL for Developers
- IPTV Anbieter in Deutschland - Top IPTV Anbieter Abonnements
- Content Improvement League 2024: From Good To A Great Article
Improve your Coding Skills with Practice
What kind of Experience do you want to share?
Navigation Menu
Search code, repositories, users, issues, pull requests..., provide feedback.
We read every piece of feedback, and take your input very seriously.
marinskiy/HackerrankPractice
Folders and files.
Name | Name | |||
---|---|---|---|---|
338 Commits | ||||
Statistics and Machine Learning | Statistics and Machine Learning | |||
01. Introduction | 01. Introduction | |||
01. Arrays | 01. Arrays | |||
01. 10 Days of Statistics | 01. 10 Days of Statistics | |||
Repository files navigation
Solutions to Hackerrank practice problems
This repository contains 185 solutions to Hackerrank practice problems with Python 3 and Oracle SQL.
Updated daily :) If it was helpful please press a star.
- Solve Me First | Problem | Solution | Score: 1
- Simple Array Sum | Problem | Solution | Score: 10
- Compare the Triplets | Problem | Solution | Score: 10
- A Very Big Sum | Problem | Solution | Score: 10
- Diagonal Difference | Problem | Solution | Score: 10
- Plus Minus | Problem | Solution | Score: 10
- Staircase | Problem | Solution | Score: 10
- Mini-Max Sum | Problem | Solution | Score: 10
- Birthday Cake Candles | Problem | Solution | Score: 10
- Time Conversion | Problem | Solution | Score: 15
- Grading Students | Problem | Solution | Score: 10
- Apple and Orange | Problem | Solution | Score: 10
- Kangaroo | Problem | Solution | Score: 10
- Between Two Sets | Problem | Solution | Score: 10
- Breaking the Records | Problem | Solution | Score: 10
- Birthday Chocolate | Problem | Solution | Score: 10
- Electronics Shop | Problem | Solution | Score: 15
- Cats and a Mouse | Problem | Solution | Score: 15
- Forming a Magic Square | Problem | Solution | Score: 20
- Picking Numbers | Problem | Solution | Score: 20
- Climbing the Leaderboard | Problem | Solution | Score: 20
- The Hurdle Race | Problem | Solution | Score: 15
- Intro to Tutorial Challenges | Problem | Solution | Score: 30
- Big Sorting | Problem | Solution | Score: 20
- Pairs | Problem | Solution | Score: 50
- Minimum Absolute Difference in an Array | Problem | Solution | Score: 15
- Marc's Cakewalk | Problem | Solution | Score: 15
- Permuting Two Arrays | Problem | Solution | Score: 40
- The Coin Change Problem | Problem | Solution | Score: 60
- Equal | Problem | Solution | Score: 30
- Sherlock and Cost | Problem | Solution | Score: 50
- Construct the Array | Problem | Solution | Score: 35
- Fibonacci Modified | Problem | Solution | Score: 45
- Laptop Battery Life | Problem | Solution | Score: 10
- Say Hello, World! With Cpp | Problem | Solution | Score: 10
- Arrays - DS | Problem | Solution | Score: 10
- Sock Merchant | Problem | Solution | Score: 10
- Counting Valleys | Problem | Solution | Score: 15
- Jumping on the Clouds | Problem | Solution | Score: 20
- Repeated String | Problem | Solution | Score: 20
- 2D Array - DS | Problem | Solution | Score: 15
- Arrays - Left Rotation | Problem | Solution | Score: 20
- New Year Chaos | Problem | Solution | Score: 40
- Minimum Swaps 2 | Problem | Solution | Score: 40
- Array Manipulation | Problem | Solution | Score: 60
- Hash Tables - Ransom Note | Problem | Solution | Score: 25
- Two Strings | Problem | Solution | Score: 25
- Count Triplets | Problem | Solution | Score: 25
- Frequency Queries | Problem | Solution | Score: 40
- Sherlock and Anagrams | Problem | Solution | Score: 50
- Sorting - Bubble Sort | Problem | Solution | Score: 30
- Mark and Toys | Problem | Solution | Score: 35
- Hash Tables - Ice Cream Parlor | Problem | Solution | Score: 35
- Minimum Time Required | Problem | Solution | Score: 35
- Triple sum | Problem | Solution | Score: 40
- Max Array Sum | Problem | Solution | Score: 20
- Say Hello, World! With Python | Problem | Solution | Score: 5
- Python If-Else | Problem | Solution | Score: 10
- Arithmetic Operators | Problem | Solution | Score: 10
- Python Division | Problem | Solution | Score: 10
- Loops | Problem | Solution | Score: 10
- Write a function | Problem | Solution | Score: 10
- Print Function | Problem | Solution | Score: 20
- List Comprehensions | Problem | Solution | Score: 10
- Find the Runner-Up Score! | Problem | Solution | Score: 10
- Nested Lists | Problem | Solution | Score: 10
- Finding the percentage | Problem | Solution | Score: 10
- Lists | Problem | Solution | Score: 10
- Tuples | Problem | Solution | Score: 10
- sWAP cASE | Problem | Solution | Score: 10
- String Split and Join | Problem | Solution | Score: 10
- What's Your Name | Problem | Solution | Score: 10
- Mutations | Problem | Solution | Score: 10
- Find a string | Problem | Solution | Score: 10
- String Validators | Problem | Solution | Score: 10
- Text Alignment | Problem | Solution | Score: 10
- Text Wrap | Problem | Solution | Score: 10
- Designer Door Mat | Problem | Solution | Score: 10
- String Formatting | Problem | Solution | Score: 10
- Capitalize! | Problem | Solution | Score: 20
- Introduction to Sets | Problem | Solution | Score: 10
- No Idea! | Problem | Solution | Score: 50
- Symmetric Difference | Problem | Solution | Score: 10
- Set add() | Problem | Solution | Score: 10
- Set discard() remove() pop() | Problem | Solution | Score: 10
- Set union() Operation | Problem | Solution | Score: 10
- Set intersection() Operation | Problem | Solution | Score: 10
- Set difference() Operation | Problem | Solution | Score: 10
- Set symmetric_difference() Operation | Problem | Solution | Score: 10
- Set Mutations | Problem | Solution | Score: 10
- The Captain's Room | Problem | Solution | Score: 10
- Check Subset | Problem | Solution | Score: 10
- Check Strict Superset | Problem | Solution | Score: 10
- itertoolsproduct() | Problem | Solution | Score: 10
- itertoolscombinations() | Problem | Solution | Score: 10
- itertoolspermutations() | Problem | Solution | Score: 10
- itertoolscombinations_with_replacement() | Problem | Solution | Score: 10
- Compress the String! | Problem | Solution | Score: 20
- Iterables and Iterators | Problem | Solution | Score: 40
- Maximize It! | Problem | Solution | Score: 50
- collectionsCounter() | Problem | Solution | Score: 10
- DefaultDict Tutorial | Problem | Solution | Score: 20
- Collections namedtuple() | Problem | Solution | Score: 20
- Collections OrderedDict() | Problem | Solution | Score: 20
- Word Order | Problem | Solution | Score: 50
- Collections deque() | Problem | Solution | Score: 20
- Company Logo | Problem | Solution | Score: 30
- Piling Up! | Problem | Solution | Score: 50
- Calendar Module | Problem | Solution | Score: 10
- Time Delta | Problem | Solution | Score: 30
- Exceptions | Problem | Solution | Score: 10
- Incorrect Regex | Problem | Solution | Score: 20
- Arrays | Problem | Solution | Score: 10
- Shape and Reshape | Problem | Solution | Score: 20
- Revising the Select Query I | Problem | Solution | Score: 10
- Revising the Select Query II | Problem | Solution | Score: 10
- Select All | Problem | Solution | Score: 10
- Select By ID | Problem | Solution | Score: 10
- Japanese Cities' Attributes | Problem | Solution | Score: 10
- Japanese Cities' Names | Problem | Solution | Score: 10
- Weather Observation Station 1 | Problem | Solution | Score: 15
- Weather Observation Station 3 | Problem | Solution | Score: 10
- Weather Observation Station 4 | Problem | Solution | Score: 10
- Weather Observation Station 5 | Problem | Solution | Score: 30
- Weather Observation Station 6 | Problem | Solution | Score: 10
- Weather Observation Station 7 | Problem | Solution | Score: 10
- Weather Observation Station 8 | Problem | Solution | Score: 15
- Weather Observation Station 9 | Problem | Solution | Score: 10
- Weather Observation Station 10 | Problem | Solution | Score: 10
- Weather Observation Station 11 | Problem | Solution | Score: 15
- Weather Observation Station 12 | Problem | Solution | Score: 15
- Higher Than 75 Marks | Problem | Solution | Score: 15
- Employee Names | Problem | Solution | Score: 10
- Employee Salaries | Problem | Solution | Score: 10
- Type of Triangle | Problem | Solution | Score: 20
- The PADS | Problem | Solution | Score: 30
- Binary Tree Nodes | Problem | Solution | Score: 30
- Revising Aggregations - The Count Function | Problem | Solution | Score: 10
- Revising Aggregations - The Sum Function | Problem | Solution | Score: 10
- Revising Aggregations - Averages | Problem | Solution | Score: 10
- Average Population | Problem | Solution | Score: 10
- Japan Population | Problem | Solution | Score: 10
- Population Density Difference | Problem | Solution | Score: 10
- The Blunder | Problem | Solution | Score: 15
- Top Earners | Problem | Solution | Score: 20
- Weather Observation Station 2 | Problem | Solution | Score: 15
- Weather Observation Station 13 | Problem | Solution | Score: 10
- Weather Observation Station 14 | Problem | Solution | Score: 10
- Weather Observation Station 15 | Problem | Solution | Score: 15
- Weather Observation Station 16 | Problem | Solution | Score: 10
- Weather Observation Station 17 | Problem | Solution | Score: 15
- Weather Observation Station 18 | Problem | Solution | Score: 25
- Weather Observation Station 19 | Problem | Solution | Score: 30
- Weather Observation Station 20 | Problem | Solution | Score: 40
- Asian Population | Problem | Solution | Score: 10
- African Cities | Problem | Solution | Score: 10
- Average Population of Each Continent | Problem | Solution | Score: 10
- The Report | Problem | Solution | Score: 20
- Day 0 - Mean, Median, and Mode | Problem | Solution | Score: 30
- Day 0 - Weighted Mean | Problem | Solution | Score: 30
- Day 1 - Quartiles | Problem | Solution | Score: 30
- Day 1 - Interquartile Range | Problem | Solution | Score: 30
- Day 1 - Standard Deviation | Problem | Solution | Score: 30
- Day 4 - Binomial Distribution I | Problem | Solution | Score: 30
- Day 4 - Binomial Distribution II | Problem | Solution | Score: 30
- Day 4 - Geometric Distribution I | Problem | Solution | Score: 30
- Day 4 - Geometric Distribution II | Problem | Solution | Score: 30
- Day 5 - Poisson Distribution I | Problem | Solution | Score: 30
- Day 5 - Poisson Distribution II | Problem | Solution | Score: 30
- Day 5 - Normal Distribution I | Problem | Solution | Score: 30
- Day 5 - Normal Distribution II | Problem | Solution | Score: 30
- Day 6 - The Central Limit Theorem I | Problem | Solution | Score: 30
- Day 6 - The Central Limit Theorem II | Problem | Solution | Score: 30
- Day 6 - The Central Limit Theorem III | Problem | Solution | Score: 30
Contributors 2
- Python 58.7%
PrepBytes Blog
ONE-STOP RESOURCE FOR EVERYTHING RELATED TO CODING
Sign in to your account
Forgot your password?
Login via OTP
We will send you an one time password on your mobile number
An OTP has been sent to your mobile number please verify it below
Register with PrepBytes
Top 20 python coding questions and answers for programming.
Last Updated on June 6, 2024 by Abhishek Sharma
![problem solving python programming and video games answers problem solving python programming and video games answers](https://prepbytes-misc-images.s3.ap-south-1.amazonaws.com/assets/1661859264335-Article.jpg)
Python is a versatile, high-level programming language known for its readability, simplicity, and wide range of applications. From web development and data analysis to artificial intelligence and automation, Python’s extensive libraries and frameworks make it a go-to choice for developers and engineers. As Python continues to gain popularity, it has become an essential skill for aspiring programmers and professionals seeking to excel in the tech industry. Python is one of the most widely used coding languages in the world. Python is used in web development, machine learning, web scraping and web automation and lots more in other fields. Let’s discuss the Coding Questions related to the basic Python programming language in detail.
![problem solving python programming and video games answers problem solving python programming and video games answers](https://prepbytes-misc-images.s3.ap-south-1.amazonaws.com/assets/1661943388243-Image-03.png)
FAQ Related to Top 20 Python Coding Questions and Answers for Programming
Below are some of the FAQs related to Top 20 Python Coding Questions and Answers for Programming:
1. What are some common Python coding interview questions? Common Python coding interview questions include:
- Write a function to reverse a string.
- How do you remove duplicates from a list?
- Explain the difference between a list and a tuple.
- How do you implement a stack using a list?
- Write a function to check if a number is prime.
2. How can I prepare for Python coding interviews? To prepare for Python coding interviews:
- Practice solving coding problems on platforms like LeetCode, HackerRank, and CodeSignal.
- Review Python basics and advanced concepts.
- Understand common data structures and algorithms.
- Work on real-world projects to enhance problem-solving skills.
- Participate in mock interviews.
3. What is the best way to learn Python for beginners? For beginners, the best way to learn Python includes:
- Taking online courses on platforms like Coursera, Udemy, or Codecademy.
- Reading books such as "Automate the Boring Stuff with Python" and "Python Crash Course."
- Practicing coding problems on websites like LeetCode and HackerRank.
- Building small projects to apply concepts practically.
4. What is the difference between a list and a tuple in Python? The main differences between a list and a tuple are:
- Mutability: Lists are mutable (can be modified), whereas tuples are immutable (cannot be modified).
- Syntax: Lists use square brackets [], while tuples use parentheses ().
- Performance: Tuples are generally faster than lists due to their immutability.
Conclusion In the ever-evolving landscape of programming, mastering Python can open doors to numerous opportunities and projects across various domains. This guide has covered a range of Python coding questions and answers, addressing fundamental concepts, common interview problems, and practical coding techniques. By exploring these topics, you can build a strong foundation in Python, enhancing your ability to write efficient, effective code and solve complex problems.
As you continue to practice and apply what you’ve learned, remember that coding is both an art and a science. Developing proficiency in Python requires not only understanding theoretical concepts but also gaining hands-on experience through real-world projects and challenges. Engage with the Python community, contribute to open-source projects, and continuously seek to improve your skills. To practice more problems you can check out MYCODE | Competitive Programming at Prepbytes .
Leave a Reply Cancel reply
Your email address will not be published. Required fields are marked *
Save my name, email, and website in this browser for the next time I comment.
- Linked List
- Segment Tree
- Backtracking
- Dynamic Programming
- Greedy Algorithm
- Operating System
- Company Placement
- Interview Tips
- General Interview Questions
- Data Structure
- Other Topics
- Computational Geometry
- Game Theory
Related Post
Python list functions & python list methods, python interview questions, namespaces and scope in python, what is the difference between append and extend in python, python program to check for the perfect square, python program to find the sum of first n natural numbers.
![problem solving python programming and video games answers problem solving python programming and video games answers](https://www.practicepython.org/assets/img/logo.png)
Practice Python
![problem solving python programming and video games answers follow us in feedly](https://s3.feedly.com/img/follows/feedly-follow-rectangle-volume-medium_2x.png)
Beginner Python exercises
- Why Practice Python?
- Why Chilis?
- Resources for learners
All Exercises
![problem solving python programming and video games answers problem solving python programming and video games answers](https://www.practicepython.org/assets/img/chili-liz-20x20.png)
All Solutions
- 1: Character Input Solutions
- 2: Odd Or Even Solutions
- 3: List Less Than Ten Solutions
- 4: Divisors Solutions
- 5: List Overlap Solutions
- 6: String Lists Solutions
- 7: List Comprehensions Solutions
- 8: Rock Paper Scissors Solutions
- 9: Guessing Game One Solutions
- 10: List Overlap Comprehensions Solutions
- 11: Check Primality Functions Solutions
- 12: List Ends Solutions
- 13: Fibonacci Solutions
- 14: List Remove Duplicates Solutions
- 15: Reverse Word Order Solutions
- 16: Password Generator Solutions
- 17: Decode A Web Page Solutions
- 18: Cows And Bulls Solutions
- 19: Decode A Web Page Two Solutions
- 20: Element Search Solutions
- 21: Write To A File Solutions
- 22: Read From File Solutions
- 23: File Overlap Solutions
- 24: Draw A Game Board Solutions
- 25: Guessing Game Two Solutions
- 26: Check Tic Tac Toe Solutions
- 27: Tic Tac Toe Draw Solutions
- 28: Max Of Three Solutions
- 29: Tic Tac Toe Game Solutions
- 30: Pick Word Solutions
- 31: Guess Letters Solutions
- 32: Hangman Solutions
- 33: Birthday Dictionaries Solutions
- 34: Birthday Json Solutions
- 35: Birthday Months Solutions
- 36: Birthday Plots Solutions
- 37: Functions Refactor Solution
- 38: f Strings Solution
- 39: Character Input Datetime Solution
- 40: Error Checking Solution
Python Programming
Python Object-Oriented Programming (OOP) Exercise: Classes and Objects Exercises
Updated on: December 8, 2021 | 52 Comments
This Object-Oriented Programming (OOP) exercise aims to help you to learn and practice OOP concepts. All questions are tested on Python 3.
Python Object-oriented programming (OOP) is based on the concept of “objects,” which can contain data and code: data in the form of instance variables (often known as attributes or properties), and code, in the form method. I.e., Using OOP, we encapsulate related properties and behaviors into individual objects.
What is included in this Python OOP exercise?
This OOP classes and objects exercise includes 8 different programs, questions, and challenges. All solutions are tested on Python 3.
This OOP exercise covers questions on the following topics :
- Class and Object creation
- Instance variables and Methods, and Class level attributes
- Model systems with class inheritance i.e., inherit From Other Classes
- Parent Classes and Child Classes
- Extend the functionality of Parent Classes using Child class
- Object checking
When you complete each question, you get more familiar with the Python OOP. Let us know if you have any alternative solutions . It will help other developers.
Use Online Code Editor to solve exercise questions.
- Guide on Python OOP
- Inheritance in Python
Table of contents
Oop exercise 1: create a class with instance attributes, oop exercise 2: create a vehicle class without any variables and methods, oop exercise 3: create a child class bus that will inherit all of the variables and methods of the vehicle class, oop exercise 4: class inheritance, oop exercise 5: define a property that must have the same value for every class instance (object), oop exercise 6: class inheritance, oop exercise 7: check type of an object, oop exercise 8: determine if school_bus is also an instance of the vehicle class.
Write a Python program to create a Vehicle class with max_speed and mileage instance attributes.
- Classes and Objects in Python
- Instance variables in Python
Create a Bus object that will inherit all of the variables and methods of the parent Vehicle class and display it.
Expected Output:
Refer : Inheritance in Python
Create a Bus class that inherits from the Vehicle class. Give the capacity argument of Bus.seating_capacity() a default value of 50.
Use the following code for your parent Vehicle class.
Expected Output :
- Polymorphism in Python
- First, use method overriding.
- Next, use default method argument in the seating_capacity() method definition of a bus class.
Define a class attribute” color ” with a default value white . I.e., Every Vehicle should be white.
Use the following code for this exercise.
Refer : Class Variable in Python
Define a color as a class variable in a Vehicle class
Variables created in .__init__() are called instance variables . An instance variable’s value is specific to a particular instance of the class. For example, in the solution, All Vehicle objects have a name and a max_speed, but the name and max_speed variables’ values will vary depending on the Vehicle instance.
On the other hand, the class variable is shared between all class instance s. You can define a class attribute by assigning a value to a variable name outside of .__init__() .
Create a Bus child class that inherits from the Vehicle class. The default fare charge of any vehicle is seating capacity * 100 . If Vehicle is Bus instance, we need to add an extra 10% on full fare as a maintenance charge. So total fare for bus instance will become the final amount = total fare + 10% of the total fare.
Note: The bus seating capacity is 50 . so the final fare amount should be 5500. You need to override the fare() method of a Vehicle class in Bus class.
Use the following code for your parent Vehicle class. We need to access the parent class from inside a method of a child class.
Write a program to determine which class a given Bus object belongs to.
Use Python’s built-in function type() .
Use isinstance() function
Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.
![](http://writinghelp.online/777/templates/cheerup/res/banner1.gif)
About Vishal
![problem solving python programming and video games answers problem solving python programming and video games answers](https://pynative.com/wp-content/uploads/2024/02/vishal_hule_gravatar.jpeg)
I’m Vishal Hule , the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter .
Related Tutorial Topics:
Python exercises and quizzes.
Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.
- 15+ Topic-specific Exercises and Quizzes
- Each Exercise contains 10 questions
- Each Quiz contains 12-15 MCQ
Loading comments... Please wait.
About PYnative
PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills .
Explore Python
- Learn Python
- Python Basics
- Python Databases
- Python Exercises
- Python Quizzes
- Online Python Code Editor
- Python Tricks
To get New Python Tutorials, Exercises, and Quizzes
Legal Stuff
We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our Terms Of Use , Cookie Policy , and Privacy Policy .
Copyright © 2018–2024 pynative.com
35 Python Programming Exercises and Solutions
To understand a programming language deeply, you need to practice what you’ve learned. If you’ve completed learning the syntax of Python programming language, it is the right time to do some practice programs.
1. Python program to check whether the given number is even or not.
2. python program to convert the temperature in degree centigrade to fahrenheit, 3. python program to find the area of a triangle whose sides are given, 4. python program to find out the average of a set of integers, 5. python program to find the product of a set of real numbers, 6. python program to find the circumference and area of a circle with a given radius, 7. python program to check whether the given integer is a multiple of 5, 8. python program to check whether the given integer is a multiple of both 5 and 7, 9. python program to find the average of 10 numbers using while loop, 10. python program to display the given integer in a reverse manner, 11. python program to find the geometric mean of n numbers, 12. python program to find the sum of the digits of an integer using a while loop, 13. python program to display all the multiples of 3 within the range 10 to 50, 14. python program to display all integers within the range 100-200 whose sum of digits is an even number, 15. python program to check whether the given integer is a prime number or not, 16. python program to generate the prime numbers from 1 to n, 17. python program to find the roots of a quadratic equation, 18. python program to print the numbers from a given number n till 0 using recursion, 19. python program to find the factorial of a number using recursion, 20. python program to display the sum of n numbers using a list, 21. python program to implement linear search, 22. python program to implement binary search, 23. python program to find the odd numbers in an array, 24. python program to find the largest number in a list without using built-in functions, 25. python program to insert a number to any position in a list, 26. python program to delete an element from a list by index, 27. python program to check whether a string is palindrome or not, 28. python program to implement matrix addition, 29. python program to implement matrix multiplication, 30. python program to check leap year, 31. python program to find the nth term in a fibonacci series using recursion, 32. python program to print fibonacci series using iteration, 33. python program to print all the items in a dictionary, 34. python program to implement a calculator to do basic operations, 35. python program to draw a circle of squares using turtle.
For practicing more such exercises, I suggest you go to hackerrank.com and sign up. You’ll be able to practice Python there very effectively.
I hope these exercises were helpful to you. If you have any doubts, feel free to let me know in the comments.
12 thoughts on “ 35 Python Programming Exercises and Solutions ”
I don’t mean to nitpick and I don’t want this published but you might want to check code for #16. 4 is not a prime number.
You can only check if integer is a multiple of 35. It always works the same – just multiply all the numbers you need to check for multiplicity.
v_str = str ( input(‘ Enter a valid string or number :- ‘) ) v_rev_str=” for v_d in v_str: v_rev_str = v_d + v_rev_str
Leave a Reply Cancel reply
Your email address will not be published. Required fields are marked *
Recent Posts
10 Python Practice Exercises for Beginners with Solutions
![problem solving python programming and video games answers Author's photo](https://learnpython.com/authors/luke-hande/luke-hande_hu57a668798a0cff0a86d4d9289908e0c0_273420_50x50_fill_box_center_2.png)
- python basics
- get started with python
- online practice
A great way to improve quickly at programming with Python is to practice with a wide range of exercises and programming challenges. In this article, we give you 10 Python practice exercises to boost your skills.
Practice exercises are a great way to learn Python. Well-designed exercises expose you to new concepts, such as writing different types of loops, working with different data structures like lists, arrays, and tuples, and reading in different file types. Good exercises should be at a level that is approachable for beginners but also hard enough to challenge you, pushing your knowledge and skills to the next level.
If you’re new to Python and looking for a structured way to improve your programming, consider taking the Python Basics Practice course. It includes 17 interactive exercises designed to improve all aspects of your programming and get you into good programming habits early. Read about the course in the March 2023 episode of our series Python Course of the Month .
Take the course Python Practice: Word Games , and you gain experience working with string functions and text files through its 27 interactive exercises. Its release announcement gives you more information and a feel for how it works.
Each course has enough material to keep you busy for about 10 hours. To give you a little taste of what these courses teach you, we have selected 10 Python practice exercises straight from these courses. We’ll give you the exercises and solutions with detailed explanations about how they work.
To get the most out of this article, have a go at solving the problems before reading the solutions. Some of these practice exercises have a few possible solutions, so also try to come up with an alternative solution after you’ve gone through each exercise.
Let’s get started!
Exercise 1: User Input and Conditional Statements
Write a program that asks the user for a number then prints the following sentence that number of times: ‘I am back to check on my skills!’ If the number is greater than 10, print this sentence instead: ‘Python conditions and loops are a piece of cake.’ Assume you can only pass positive integers.
Here, we start by using the built-in function input() , which accepts user input from the keyboard. The first argument is the prompt displayed on the screen; the input is converted into an integer with int() and saved as the variable number. If the variable number is greater than 10, the first message is printed once on the screen. If not, the second message is printed in a loop number times.
Exercise 2: Lowercase and Uppercase Characters
Below is a string, text . It contains a long string of characters. Your task is to iterate over the characters of the string, count uppercase letters and lowercase letters, and print the result:
We start this one by initializing the two counters for uppercase and lowercase characters. Then, we loop through every letter in text and check if it is lowercase. If so, we increment the lowercase counter by one. If not, we check if it is uppercase and if so, we increment the uppercase counter by one. Finally, we print the results in the required format.
Exercise 3: Building Triangles
Create a function named is_triangle_possible() that accepts three positive numbers. It should return True if it is possible to create a triangle from line segments of given lengths and False otherwise. With 3 numbers, it is sometimes, but not always, possible to create a triangle: You cannot create a triangle from a = 13, b = 2, and c = 3, but you can from a = 13, b = 9, and c = 10.
The key to solving this problem is to determine when three lines make a triangle regardless of the type of triangle. It may be helpful to start drawing triangles before you start coding anything.
![problem solving python programming and video games answers Python Practice Exercises for Beginners](https://learnpython.com/1.png)
Notice that the sum of any two sides must be larger than the third side to form a triangle. That means we need a + b > c, c + b > a, and a + c > b. All three conditions must be met to form a triangle; hence we need the and condition in the solution. Once you have this insight, the solution is easy!
Exercise 4: Call a Function From Another Function
Create two functions: print_five_times() and speak() . The function print_five_times() should accept one parameter (called sentence) and print it five times. The function speak(sentence, repeat) should have two parameters: sentence (a string of letters), and repeat (a Boolean with a default value set to False ). If the repeat parameter is set to False , the function should just print a sentence once. If the repeat parameter is set to True, the function should call the print_five_times() function.
This is a good example of calling a function in another function. It is something you’ll do often in your programming career. It is also a nice demonstration of how to use a Boolean flag to control the flow of your program.
If the repeat parameter is True, the print_five_times() function is called, which prints the sentence parameter 5 times in a loop. Otherwise, the sentence parameter is just printed once. Note that in Python, writing if repeat is equivalent to if repeat == True .
Exercise 5: Looping and Conditional Statements
Write a function called find_greater_than() that takes two parameters: a list of numbers and an integer threshold. The function should create a new list containing all numbers in the input list greater than the given threshold. The order of numbers in the result list should be the same as in the input list. For example:
Here, we start by defining an empty list to store our results. Then, we loop through all elements in the input list and test if the element is greater than the threshold. If so, we append the element to the new list.
Notice that we do not explicitly need an else and pass to do nothing when integer is not greater than threshold . You may include this if you like.
Exercise 6: Nested Loops and Conditional Statements
Write a function called find_censored_words() that accepts a list of strings and a list of special characters as its arguments, and prints all censored words from it one by one in separate lines. A word is considered censored if it has at least one character from the special_chars list. Use the word_list variable to test your function. We've prepared the two lists for you:
This is another nice example of looping through a list and testing a condition. We start by looping through every word in word_list . Then, we loop through every character in the current word and check if the current character is in the special_chars list.
This time, however, we have a break statement. This exits the inner loop as soon as we detect one special character since it does not matter if we have one or several special characters in the word.
Exercise 7: Lists and Tuples
Create a function find_short_long_word(words_list) . The function should return a tuple of the shortest word in the list and the longest word in the list (in that order). If there are multiple words that qualify as the shortest word, return the first shortest word in the list. And if there are multiple words that qualify as the longest word, return the last longest word in the list. For example, for the following list:
the function should return
Assume the input list is non-empty.
The key to this problem is to start with a “guess” for the shortest and longest words. We do this by creating variables shortest_word and longest_word and setting both to be the first word in the input list.
We loop through the words in the input list and check if the current word is shorter than our initial “guess.” If so, we update the shortest_word variable. If not, we check to see if it is longer than or equal to our initial “guess” for the longest word, and if so, we update the longest_word variable. Having the >= condition ensures the longest word is the last longest word. Finally, we return the shortest and longest words in a tuple.
Exercise 8: Dictionaries
As you see, we've prepared the test_results variable for you. Your task is to iterate over the values of the dictionary and print all names of people who received less than 45 points.
Here, we have an example of how to iterate through a dictionary. Dictionaries are useful data structures that allow you to create a key (the names of the students) and attach a value to it (their test results). Dictionaries have the dictionary.items() method, which returns an object with each key:value pair in a tuple.
The solution shows how to loop through this object and assign a key and a value to two variables. Then, we test whether the value variable is greater than 45. If so, we print the key variable.
Exercise 9: More Dictionaries
Write a function called consonant_vowels_count(frequencies_dictionary, vowels) that takes a dictionary and a list of vowels as arguments. The keys of the dictionary are letters and the values are their frequencies. The function should print the total number of consonants and the total number of vowels in the following format:
For example, for input:
the output should be:
Working with dictionaries is an important skill. So, here’s another exercise that requires you to iterate through dictionary items.
We start by defining a list of vowels. Next, we need to define two counters, one for vowels and one for consonants, both set to zero. Then, we iterate through the input dictionary items and test whether the key is in the vowels list. If so, we increase the vowels counter by one, if not, we increase the consonants counter by one. Finally, we print out the results in the required format.
Exercise 10: String Encryption
Implement the Caesar cipher . This is a simple encryption technique that substitutes every letter in a word with another letter from some fixed number of positions down the alphabet.
For example, consider the string 'word' . If we shift every letter down one position in the alphabet, we have 'xpse' . Shifting by 2 positions gives the string 'yqtf' . Start by defining a string with every letter in the alphabet:
Name your function cipher(word, shift) , which accepts a string to encrypt, and an integer number of positions in the alphabet by which to shift every letter.
This exercise is taken from the Word Games course. We have our string containing all lowercase letters, from which we create a shifted alphabet using a clever little string-slicing technique. Next, we create an empty string to store our encrypted word. Then, we loop through every letter in the word and find its index, or position, in the alphabet. Using this index, we get the corresponding shifted letter from the shifted alphabet string. This letter is added to the end of the new_word string.
This is just one approach to solving this problem, and it only works for lowercase words. Try inputting a word with an uppercase letter; you’ll get a ValueError . When you take the Word Games course, you slowly work up to a better solution step-by-step. This better solution takes advantage of two built-in functions chr() and ord() to make it simpler and more robust. The course contains three similar games, with each game comprising several practice exercises to build up your knowledge.
Do You Want More Python Practice Exercises?
We have given you a taste of the Python practice exercises available in two of our courses, Python Basics Practice and Python Practice: Word Games . These courses are designed to develop skills important to a successful Python programmer, and the exercises above were taken directly from the courses. Sign up for our platform (it’s free!) to find more exercises like these.
We’ve discussed Different Ways to Practice Python in the past, and doing interactive exercises is just one way. Our other tips include reading books, watching videos, and taking on projects. For tips on good books for Python, check out “ The 5 Best Python Books for Beginners .” It’s important to get the basics down first and make sure your practice exercises are fun, as we discuss in “ What’s the Best Way to Practice Python? ” If you keep up with your practice exercises, you’ll become a Python master in no time!
You may also like
![problem solving python programming and video games answers problem solving python programming and video games answers](https://learnpython.com/blog/how-to-master-python/cover_huc3603a6441c236eb314dc07b95af168d_492217_262x262_fill_box_center_2.png)
How Do You Write a SELECT Statement in SQL?
![problem solving python programming and video games answers problem solving python programming and video games answers](https://learnpython.com/blog-img/newsletter-woman2.png)
What Is a Foreign Key in SQL?
![problem solving python programming and video games answers problem solving python programming and video games answers](https://learnpython.com/blog-img/tab-photo.png)
Enumerate and Explain All the Basic Elements of an SQL Query
Looking to get started in the video game industry? PVG will teach you the fundamentals of computer programming and problem solving and give you a basic skillset to help launch your journey in the world of video game development with Python.
![problem solving python programming and video games answers pvg_1](https://onlea.org/content/images/2018/08/pvg_1.png)
This course is an introduction to computer science and programming in Python. Upon successful completion of this course, you will be able to:
- Take a new computational problem and develop a plan to solve it through problem understanding and decomposition.
- Follow a design creation process that includes specifications, algorithms, and testing.
- Code, test, and debug a program in Python, based on your design.
Important computer science concepts such as problem solving (computational thinking), problem decomposition, algorithms, abstraction, and software quality are emphasized throughout. The Python programming language and video games are used to demonstrate computer science concepts in a concrete and fun manner. However, a learner can take the knowledge and skills from this course and apply them to non-game problems, other programming languages, and other computer science courses.
You can enroll in the course through Coursera.
![problem solving python programming and video games answers pvg_divider_apple](https://onlea.org/content/images/2018/08/pvg_divider_apple.png)
![problem solving python programming and video games answers Advent of Code](https://files.realpython.com/media/Python-Puzzles-with-Advent-of-Code_Watermarked.b6877d55d680.jpg)
Advent of Code: Solving Your Puzzles With Python
Table of Contents
Puzzling in Programming?
Exploring options for solving programming puzzles online, advent of code puzzles, how to participate in advent of code, the anatomy of a puzzle, the structure of a solution, a starting template, solution strategies, part 1: puzzle description, part 1: solution, part 1: solution using templates, part 2: puzzle description, part 2: solution, part 1: input parsing.
Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Advent of Code: Solving Puzzles With Python
Advent of Code is an online Advent calendar where you’ll find new programming puzzles offered each day from December 1 to 25. While you can solve the puzzles at any time, the excitement when new puzzles unlock is really something special. You can participate in Advent of Code in any programming language—including Python!
With the help of this tutorial, you’ll be ready to start solving puzzles and earning your first gold stars.
In this tutorial, you’ll learn:
- What an online Advent calendar is
- How solving puzzles can advance your programming skills
- How you can participate in Advent of Code
- How you can organize your code and tests when solving Advent of Code puzzles
- How test-driven development can be used when solving puzzles
Advent of Code puzzles are designed to be approachable by anyone with an interest in problem-solving. You don’t need a heavy computer science background to participate. Instead, Advent of Code is a great arena for learning new skills and testing out new features of Python.
Source Code: Click here to download the free source code that shows you how to solve Advent of Code puzzles with Python.
Working on puzzles may seem like a waste of your available programming time. After all, it seems like you’re not really producing anything useful and you’re not advancing your current projects forward.
However, there are several advantages to taking some time off to practice with programming puzzles:
Programming puzzles are usually better specified and more contained than your regular job tasks. They offer you the chance to practice logical thinking on problems that are less complex than the ones you typically need to handle in your day job.
You can often challenge yourself with several similar puzzles. This allows you to build procedural memory , much like muscle memory, and get experience with structuring certain kinds of code.
Puzzles are often designed with an eye towards a solution. They allow you to learn about and apply algorithms that are tried and tested and are an important part of any programmer’s toolbox.
For some puzzle solutions, even the greatest supercomputers can be too slow if the algorithm is inefficient. You can analyze the performance of your solution and get experience to help you understand when a straightforward method is fast enough and when a more optimized procedure is necessary.
Most programming languages are well-suited for solving programming puzzles. This gives you a great opportunity to compare different programming languages for different tasks. Puzzles are also a great way of getting to know a new programming language or trying out some of the newest features of your favorite language.
On top of all of this, challenging yourself with a programming puzzle is often pretty fun! When you add it all up, setting aside some time for puzzles can be very rewarding.
Luckily, there are many websites where you can find programming puzzles and try to solve them. There are often differences in the kinds of problems these websites present, how you submit your solutions, and what kind of feedback and community the sites can offer. You should therefore take some time to look around and find those that appeal the most to you.
In this tutorial, you’ll learn about Advent of Code , including what kind of puzzles you can find there and which tools and tricks you can employ to solve them. However, there are also other places where you can get started solving programming puzzles:
Exercism has learning tracks in many different programming languages. Each learning track offers coding challenges, small tutorials about different programming concepts, and mentors who give you feedback on your solutions.
Project Euler has been around for a long time. The site offers hundreds of puzzles, usually formulated as math problems. You can solve the problems in any programming language, and once you’ve solved a puzzle, you get access to a community thread where you can discuss your solution with others.
Code Wars offers tons of coding challenges, which they call katas . You can solve puzzles in many different programming languages with their built-in editor and automated tests. Afterward, you can compare your solutions to others’ and discuss strategies in the forums.
HackerRank has great features if you’re looking for a job. They offer certifications in many different skills, including problem-solving and Python programming, as well as a job board that lets you show off your puzzle-solving skills as part of your job applications.
There are many other sites available where you can practice your puzzle-solving skills. In the rest of this tutorial, you’ll focus on what Advent of Code has to offer.
Preparing for Advent of Code: 25 Fresh Puzzles for Christmas
It’s time for Advent of Code! It was started by Eric Wastl in 2015. Since then, a new Advent calendar of twenty-five new programming puzzles has been published every December. The puzzles have gotten more and more popular over the years. More than 235,000 people have solved at least one of the puzzles from 2021.
Note: Traditionally, an Advent calendar is a calendar used to count the days of Advent while waiting for Christmas. Over the years, Advent calendars have become more commercial and have lost some of their Christian connection.
Most Advent calendars start on December 1 and end on December 24, Christmas Eve, or December 25, Christmas Day. Nowadays, there are all kinds of Advent calendars available, including LEGO calendars , tea calendars , and cosmetics calendars .
In traditional Advent calendars, you open one door every day to reveal what’s inside. Advent of Code mimics this by giving you access to one new puzzle each day from December 1 to December 25. For each puzzle you solve, you’ll earn gold stars that are yours to keep.
In this section, you’ll get more familiar with Advent of Code and see a glimpse of your first puzzle. Later , you’ll look at the details of how you can solve these puzzles and practice solving a few of the puzzles yourself.
Advent of Code is an online Advent calendar where a new puzzle is published every day from December 1 to December 25. Each puzzle becomes available at midnight, US Eastern Time . An Advent of Code puzzle has a few typical characteristics:
- Each puzzle consists of two parts, but the second part isn’t revealed until you finish the first part.
- You’ll earn one gold star (⭐) for each part that you finish. This means you can earn two stars per day and fifty stars if you solve all the puzzles for one year.
- The puzzle is the same for everyone, but you need to solve it based on personalized input that you get from the Advent of Code site. This means that your answer to a puzzle will be different from someone else’s, even if you use the same code to calculate it.
You can participate in a global race to be the first to solve each puzzle. However, this is usually pretty crowded with highly skilled, competitive programmers. Advent of Code is probably going to be more fun if you use it as practice for yourself or if you challenge your friends and coworkers to a small, friendly competition.
To get a feeling for how an Advent of Code puzzle works, consider the Day 1 puzzle of 2020:
Before you leave, the Elves in accounting just need you to fix your expense report (your puzzle input); apparently, something isn’t quite adding up. Specifically, they need you to find the two entries that sum to 2020 and then multiply those two numbers together.
Each year, there’s a wonderfully silly backstory that binds the puzzles together. The 2020 story describes your attempts at leaving for a well-deserved vacation, now that you’ve saved Christmas several years in a row. The story usually has no effect on the puzzles, but it’s still fun to follow along.
In between the plot elements of the story, you’ll find the puzzles themselves. In this example, you’re looking for two entries in your puzzle input that sum to 2,020. After the explanation that describes the problem, you’ll usually find an example showing the calculations that you’re expected to do:
For example, suppose your expense report contained the following: 1721 979 366 299 675 1456 In this list, the two entries that sum to 2020 are 1721 and 299 . Multiplying them together produces 1721 * 299 = 514579 , so the correct answer is 514579 .
The example shows you the answer for this particular list of numbers. If you were about to jump in and start solving this puzzle, you would now start thinking about how you can find the two entries in any valid list of numbers. Before getting deeper into this puzzle, however, you’ll explore how to use the Advent of Code site.
You’ve seen an example of an Advent of Code puzzle. Next, you’ll learn how you can submit your answer for it. You never submit any code to solve the puzzles. You just submit the answer, which is usually a number or a text string.
In general, you’ll follow a series of steps to solve a puzzle on the site:
Log in on the Advent of Code website . You do this by using your credentials from another service like GitHub, Google, Twitter, or Reddit.
Read the puzzle text and pay special attention to the given example. You should make sure you understand the solution for the example data.
Download your personalized input for the puzzle. You’ll need this input to find your unique answer to the problem.
Code up your solution . This is the fun part, which you’ll get a lot of practice for in the rest of this tutorial.
Enter your answer to the puzzle on the puzzle page. If your answer is correct, then you earn a gold star, and part two of the puzzle opens up.
Repeat steps 2 and 4 for part two of the puzzle. This second part is similar to the first, but it usually adds a twist requiring you to adapt your code.
Enter your second answer on the puzzle page to earn your second star and finish the puzzle.
Remember, you don’t submit any code—only your puzzle answers. This means that Advent of Code puzzles can be solved in any programming language. Many people use Advent of Code to practice and learn a new programming language. Eric Wastl , the creator of Advent of Code, gave a talk in 2019 where he talked about the diverse background and motivation of the people participating, among other things.
Note: There’s a leaderboard for Advent of Code. In general, you should ignore this leaderboard ! It only shows who submitted the first 100 solutions after a puzzle opened up. To have a shot at joining the leaderboard, you need a lot of preparation, dedication, and experience with competitive programming.
Instead, you should look at the private leaderboards . These become available after you’ve logged in, and they give you a chance to invite your friends and colleagues to a more relaxed community. You can choose to score your private leaderboard either based on when puzzles were solved or simply based on the number of puzzles people have solved.
You can also link your name in the private leaderboards to your GitHub account, which allows you to share your solutions with your friends. You set this up by clicking Settings in the menu on the Advent of Code site after you’ve logged in.
Advent of Code is completely free to use, but there are still a few different ways you can support the project:
- Share information about Advent of Code on your social media to get the word out.
- Help others by taking part in the r/adventofcode subreddit or other forums.
- Invite your friends to take part in Advent of Code, sharing your results on a private leaderboard .
- Donate to Advent of Code. If you do, then you’ll get an AoC++ badge next to your name on the site.
In the next sections, you’ll see some suggestions on how you can prepare for solving Advent of Code with Python. There’s also an awesome list you can check out that links to many different resources related to Advent of Code, including several other people’s solutions.
Solving Advent of Code With Python
The Advent of Code has become an annual highlight for many coders around the world. In 2021, more than 235,000 people submitted their solutions. Since Advent of Code started in 2015, programmers have collected more than ten million stars . Many participants use Python to solve the puzzles.
Well, now it’s your turn! Head over to the Advent of Code website and have a look at the latest puzzles. Then, come back to this tutorial to get some tips and help to start solving Advent of Code puzzles with Python.
In this section, you’ll explore the typical anatomy of an Advent of Code puzzle. Additionally, you’ll learn about some tools you can use to interact with it.
Each Advent of Code puzzle is split into two parts. When you start working on a puzzle, you only see the first part. The second part unlocks once you’ve submitted the correct answer to the first part. This is often a twist on the problem that you solved in the first part. Sometimes, you’ll find it necessary to refactor your solution from part one, while other times you can solve the second part quickly based on the work you’ve already done.
Both parts always use the same puzzle input. You can download your puzzle input from the puzzle page for that day. You’ll find a link after the puzzle description.
Note: As mentioned earlier, your puzzle input is personalized. This means that if you discuss solutions with other people, their final answers will likely be different from yours.
Everything you need to do in order to submit your puzzle solutions—except actually solving the puzzle—you can do from the Advent of Code website. You should use it to submit your first solutions so that you can get familiar with the flow.
Later, there are several tools that you can use to organize your Advent of Code setup and work more efficiently. For example, you can use the advent-of-code-data package to download data. It’s a Python package that you can install with pip :
You can use advent-of-code-data to download a particular puzzle input set on the command line with its aocd tool. Another fun possibility is automatically downloading and caching your personalized puzzle input within your Python code:
You need to set your session ID in either an environment variable or a file before you can download your personalized data with advent-of-code-data . You’ll find an explanation for this in the documentation . If you’re interested, then you can also use advent-of-code-data or aocd to submit your solutions and review your earlier answers.
As part of the puzzle text, you’ll also find one or several examples typically calculated based on smaller data than your personalized input data. You should read these examples carefully and make sure you understand what you’re asked to do before you start coding.
You can use the examples to set up tests for your code. One way is to manually run your solution on the example data and confirm that you’re getting the expected answer. Alternatively, you can use a tool like pytest to automate the process.
Note: Test-driven development (TDD) is a process where you write tests before implementing your code. Because Advent of Code provides you with expected answers to small examples, it gives you a great opportunity to try out test-driven development on your own.
You’ll learn more about TDD later when you try to solve some puzzles by yourself.
You can solve all Advent of Code puzzles using just plain Python and the standard library. However, there are a few packages that can aid you as you’re putting together your solutions:
- advent-of-code-data can download your input data and submit your solutions.
- advent-of-code-ocr can convert the ASCII art solutions of some puzzles to strings.
- pytest can check your solution on the example data automatically.
- parse can parse strings with a simpler syntax than regular expressions .
- numpy can effectively compute with arrays of numbers.
- colorama can animate your solutions in the terminal.
- rich can render your terminal output more visually appealing.
If you create a virtual environment and install those packages, then you’ll have a very solid toolbox for your Advent of Code adventures. Later , you’ll see examples of how you can use parse , numpy , and colorama to solve puzzles.
In the last section, you got familiar with how to read and understand Advent of Code puzzles. In this section, you’ll learn how you can solve them. You don’t need to do a lot of setup before you solve the Advent of Code puzzles.
Have you thought about how you’d solve the puzzle that you saw earlier ? Recall that you’re looking for the product of the two numbers in a list that sum to 2,020. Before moving on, think about—and maybe code up—how you’d find which two entries of the following list sum to 2,020:
The following script shows one way to solve this first part of the Day 1, 2020 , puzzle:
The nested for loop finds all combinations of two numbers from the list. The test on line 3 is actually slightly more complicated than it needs to be: you only need to test that the numbers sum to 2,020. However, by adding the condition that num1 should be smaller than num2 , you avoid solutions being found twice.
In this example, one solution looks like num1 = 1721 and num2 = 299 , but since you can add numbers in any order, that means that num1 = 299 and num2 = 1721 also form a solution. With the extra check, only the latter combination is reported.
Once you have this solution in place, you can copy your personalized input data into the numbers list and calculate your answer to the puzzle.
Note: There are more efficient ways of calculating this answer than trying all possibilities. However, it’s usually a good idea to start with a basic approach. Joe Armstrong is quoted as saying:
Make it work, then make it beautiful, then if you really, really have to, make it fast. 90 percent of the time, if you make it beautiful, it will already be fast. So really, just make it beautiful! ( Source ) — Joe Armstrong
Now that you’ve seen a working solution for this puzzle, can you make it beautiful?
As you’re working through more puzzles, you might start feeling that copying your data into your code and rewriting it into valid Python gets tiresome. Similarly, adding a few functions to your code gives you more flexibility later. You could use them to add tests to your code, for example.
Python has many powerful features for parsing strings. In the long run, you’ll be better off leaving the input data just as you downloaded them and letting Python parse them into a usable data structure. In fact, dividing your code into two functions is often beneficial. One function will parse the string input, and the other will solve the puzzle. Based on these principles, you can rewrite your code:
On lines 12 to 15, you’ll recognize your solution from earlier. First of all, you’ve wrapped it in a function. This makes it easier to add automatic tests to your code later. You’ve also added a parse() function that can convert lines of strings into a list of numbers.
On line 20, you use pathlib to read the contents of a file as text and strip off any blank lines at the end. Looping through sys.argv gives you all the filenames entered at the command line.
These changes give you more flexibility as you’re working on your solution. Say that you’ve stored the example data in a file called example.txt and your personalized input data in a file named input.txt . You can then run your solution on any one of them, or even both, by supplying their names on the command line:
514579 is indeed the answer to the problem when using the example input data. Remember, the solution for your personalized input data will be different from the one shown above.
Now it’s time to give the Advent of Code website a spin! Go to the 2020 Advent of Code calendar and find the puzzle for Day 1. If you haven’t already, download your input data and calculate your solution to the puzzle. Then, enter your solution on the website and click Submit .
Congratulations! You’ve just earned your first star!
As you’ve seen above, Advent of Code puzzles follow a set structure. Therefore, it makes sense to create a template for yourself that you can use as a starting point when you start to code up a solution. Exactly how much structure you want in such a template is a matter of personal taste. To get started, you’ll explore one example of a template that’s based on the principles you saw in the previous section:
The template has separate functions for parsing the input as well as for solving both parts of a puzzle. You don’t need to touch lines 15 to 28 at all. They take care of reading text from an input file, calling parse() , part1() , and part2() , and then reporting the solutions to the console.
You can create a similar template for testing your solutions.
Note: As you learned earlier, the example data are useful for creating tests, as they represents known data with corresponding solutions.
The following template uses pytest as a test runner. It’s prepared for several different tests, testing each of the functions parse() , part1() , and part2() :
You’ll see an example of how you can use this template later . Until then, there are a few things you should note:
- As indicated on line 1, you should name your pytest files with a test_ prefix.
- Similarly, each test is implemented in a function named with a test_ prefix. You can see examples of these on lines 20, 25, 30, and 35.
- You should change the import on line 5 to import your solution code.
- The template assumes that the example data are stored in files named example1.txt and example2.txt .
- You should remove the skip marks on lines 19, 24, 29, and 34 when you’re ready to start testing.
- You’ll need to fill in the ellipses ( ... ) on lines 22, 27, 32, and 37 according to the example data and the corresponding solutions.
For example, if you were to adapt this template to the rewritten solution of the first part of the Day 1, 2020, puzzle from the previous section, then you’d need to create a file, example1.txt , with the following contents:
Next, you’d remove the skip marks for the first two tests and implement them as follows:
Finally, you’d need to make sure that you’re importing your solution. If you used the filename aoc202001.py , then you should change line 5 to import aoc202001 :
You would then run pytest to check your solution. If you implemented your solution correctly, then you’d see something like this:
Note the two dots ( .. ) in front of ss . They represent two tests that passed. If the tests had failed, you’d see F instead of each dot, along with a detailed explanation of what went wrong.
Tools like Cookiecutter and Copier make it easier to work with templates like these. If you install Copier, then you can use a template similar to the one you’ve seen here by running the following command:
This will set up the template for one particular puzzle in a subdirectory of the advent_of_code directory on your computer.
Advent of Code puzzles are very diverse. As you advance through the calendar, you’ll solve many different problems and discover many different strategies for approaching them.
Some of these strategies are quite general and can be applied to any puzzle. If you find that you’re stuck on a puzzle, here are some things you can try to get unstuck:
- Reread the description . Advent of Code puzzles are typically very well specified, but some of them can be quite information heavy. Make sure you’re not missing a vital part of the puzzle.
- Use the example data actively. Make sure you understand how those results are achieved, and check that your code is able to reproduce those examples.
- Some puzzles may get a bit involved. Break the problem into smaller steps , and implement and test each step individually.
- If your code works for the example data but not for your personalized input data, then you can build additional test cases based on numbers that you’re able to calculate by hand to see whether your code covers all corner cases.
- If you’re still stuck, then reach out to your friends and other puzzle solvers on some of the forums dedicated to Advent of Code and ask for hints about how they’ve solved the puzzle.
As you do more and more puzzles, you’ll start to recognize some general kinds of puzzles that come up again and again.
Some puzzles deal with text and passwords . Python has several powerful tools for manipulating text strings, including many string methods . To read and parse strings, it’s helpful to know the basics of regular expressions . However, you can often get very far with the third-party parse library as well.
For example, say that you have the string "shiny gold bags contain 2 dark red bags." and want to parse the relevant information from it. You can use parse and its pattern syntax:
In the background, parse builds a regular expression, but you use a simpler syntax similar to the one that f-strings use.
In some of these text problems, you’re explicitly asked to work with code and parsers , often building a small custom assembly language . After parsing the code, you often need to run the given program. In practice, this means that you build a small state machine that can track its current state, including the contents of its memory.
You can use classes to keep state and behavior together. In Python, data classes are great for quickly setting up a state machine. In the following example, you implement a small state machine that can handle two different instructions:
The two instructions set and inc are parsed and handled within .run() . Note that the type hints on lines 7 and 8 use a newer syntax that only works on Python 3.9 and later versions. If you’re using an older version of Python, then you can import Dict and List from typing instead.
To run your state machine, you first initialize it with an initial memory and load the program into the machine. Next, you call .run() . When the program is done, you can inspect .memory to see the new state of your machine:
This program first set g to the value of 45 , then increased it, leaving it at its final value of 46 .
Some fun puzzles involve grids and labyrinths . If your grid has a fixed size, then you can use NumPy to get an effective representation of it. Labyrinths are often useful to visualize. You can use Colorama to draw directly in your terminal :
This script shows an example of storing a grid using a NumPy array and then using Cursor.POS from Colorama to position the cursor in the terminal to print out the grid. When you run this script, you’ll see an output like the following:
Visualizing your code as it runs can be fun and also give you some good insights. It can also be an invaluable help when you’re debugging and don’t quite understand what’s happening.
So far in the tutorial, you’ve gotten some general tips on how you can work with Advent of Code puzzles. In the next sections, you’ll get more explicit and solve three puzzles from earlier years.
Practicing Advent of Code: Day 1, 2019
The first puzzle you’ll attempt to solve on your own is Day 1, 2019 , called The Tyranny of the Rocket Equation . This is a typical Day 1 puzzle in that the solution isn’t very involved. It’s a great exercise to get used to how Advent of Code works and to check that your environment is properly set up.
In the 2019 story line, you’re rescuing Santa, who’s become stranded at the edge of the solar system. In the first puzzle, you’re getting your rocket ready for launch:
The Elves quickly load you into a spacecraft and prepare to launch. At the first Go / No Go poll, every Elf is Go until the Fuel Counter-Upper. They haven’t determined the amount of fuel required yet. Fuel required to launch a given module is based on its mass . Specifically, to find the fuel required for a module, take its mass, divide by three, round down, and subtract 2.
The example data look like this:
For a mass of 12 , divide by 3 and round down to get 4 , then subtract 2 to get 2 . For a mass of 14 , dividing by 3 and rounding down still yields 4 , so the fuel required is also 2 . For a mass of 1969 , the fuel required is 654 . For a mass of 100756 , the fuel required is 33583 .
You need to calculate the total fuel requirements for your spacecraft:
The Fuel Counter-Upper needs to know the total fuel requirement. To find it, individually calculate the fuel needed for the mass of each module (your puzzle input), then add together all the fuel values. What is the sum of the fuel requirements for all of the modules on your spacecraft?
Now it’s time to try to solve the puzzle on your own! It’s probably the most fun to download your personalized input data and check your solution on Advent of Code so that you can earn your stars. However, feel free to solve the puzzle based on the example data provided above if you’re not ready to sign in to Advent of Code yet.
Once you’re done with the puzzle and you’ve earned your star, you can expand the collapsed block to see a discussion of the puzzle solution:
Solution for Day 1, 2019, Part 1 Show/Hide
This solution discussion is a bit more involved than what’s necessary for the puzzle. The goal is that you’ll explore some extra detail in this first solution so that you’ll be even better prepared for the next puzzles.
This section is split into two parts:
- A short discussion of integer division and how that can help.
- A straightforward solution to the puzzle.
Then, in the next section, you’ll see another solution that uses the templates for solutions and tests that you’ve seen earlier.
To return to the current puzzle, take a second look at the calculation that you’re asked to perform:
[To] find the fuel required for a module, take its mass, divide by three, round down, and subtract 2.
You can carry out these steps one after another:
For positive numbers, you can use int() to round down . If your numbers may be negative, then you should use math.floor() instead.
Python, and many other programming languages, have support for dividing and rounding down in one step. This is called integer division and is done with the integer division operator ( // ). You can then rewrite your previous calculation:
Using mass // 3 divides by three and rounds down in one step. You can now calculate the fuel for each mass and add them together to solve the puzzle:
The four example modules need a total of 34241 fuel units. In the puzzle description, they’re listed as requiring 2 , 2 , 654 , and 33583 fuel units, respectively. Adding these up, you get 34241 , which confirms your calculations. You can replace the numbers in the masses list with your personalized input data to get your own answer to the puzzle.
If you’re familiar with comprehensions and generator expressions , then you can use sum() to shorten your code:
With sum() , you don’t need to manually add up each fuel requirement. Instead, you can solve the current puzzle in one line of code.
You’ve now solved the first part of the puzzle. However, before moving on to the second part of the puzzle, the next section shows how you can use the templates you saw earlier when solving this problem.
Expand the collapsed block below to see another solution to the first part of the Advent of Code puzzle for Day 1, 2019—this time using the templates you saw earlier to organize your code and simplify testing:
Templated solution for Day 1, 2019, Part 1 Show/Hide
If you’re going to do several Advent of Code puzzles, then it’s a good idea to organize your solutions into folders. This allows you to keep all the files related to a puzzle together. One nice way of keeping things tidy is to have one folder for each year of Advent of Code and to have folders for each day within each year’s folder.
For this puzzle, you might set up something like this:
You store your personalized input data in input.txt , while example1.txt contains the example data from the puzzle description:
You can then use these data to set up your first tests. Start with the test template from earlier, and fill in tests for parsing input and for solving part one:
You want the parser to read the text file and convert each line to a number in a list. You specify this on line 21 as the expected value in test_parse_example1() . The expected value for test_part1_example1() is the sum of the four fuel requirements mentioned in the text.
Finally, add aoc201901.py based on the solution template:
Before you start adding your solution to the template, take a minute to run pytest to confirm that the tests are indeed failing. In between a lot of details, you should get something like this:
Note that you have two tests that are failing—just as expected. This way of working is known as test-driven development (TDD) . You first write your tests and make sure they fail. Afterward, you implement the code necessary to make them pass. This may seem like overkill for this puzzle but can be a very useful habit for more challenging problems.
It’s time to add your solution to aoc201901.py . First, parse the input data. They’re delivered to parse() as a text string of numbers separated by newlines ( \n ) and should be converted into a list of integers:
The list comprehension assembles the lines into a list and converts them to integers. Run pytest again and confirm that your first test, test_parse_example1() , no longer fails.
Next, add your solution to the puzzle:
You’re solving part one by using sum() as discussed in the previous section. You can also change the name of the parameter for the general data to something more specific for the puzzle. As the data describe the mass of each rocket module, you call the parameter module_masses .
Confirm that your solution is correct by running pytest one more time:
With the tests passing, you can solve the puzzle for your personalized input data by running the program against input.txt :
Your own answer will be different from what’s shown here, 3550236 . The None output at the bottom represents the solution to the second part, which you haven’t implemented yet. Now might be a good time to look at part two!
You can now move on to the second part of the puzzle. Are you ready for the twist?
Every Advent of Code puzzle consists of two parts, where the second part is revealed only after you solve the first part. The second part is always related to the first and will use the same input data. However, you may often need to rethink your approach to the first half of the puzzle in order to account for the second half.
Expand the collapsed block below to have a look at the second part of the Advent of Code puzzle for Day 1, 2019:
Day 1, 2019, Part 2 Show/Hide
Your quest to get the rocket off the ground continues:
During the second Go / No Go poll, the Elf in charge of the Rocket Equation Double-Checker stops the launch sequence. Apparently, you forgot to include additional fuel for the fuel you just added. Fuel itself requires fuel just like a module - take its mass, divide by three, round down, and subtract 2. However, that fuel also requires fuel, and that fuel requires fuel, and so on. Any mass that would require negative fuel should instead be treated as if it requires zero fuel ; the remaining mass, if any, is instead handled by wishing really hard , which has no mass and is outside the scope of this calculation.
Of course, adding all that fuel to your spacecraft has made it heavier. You need to add more fuel to account for the added weight, but that fuel will also need to be accounted for. To see how this works in practice, have a look at the examples:
So, for each module mass, calculate its fuel and add it to the total. Then, treat the fuel amount you just calculated as the input mass and repeat the process, continuing until a fuel requirement is zero or negative. For example: A module of mass 14 requires 2 fuel. This fuel requires no further fuel (2 divided by 3 and rounded down is 0 , which would call for a negative fuel), so the total fuel required is still just 2 . At first, a module of mass 1969 requires 654 fuel. Then, this fuel requires 216 more fuel ( 654 / 3 - 2 ). 216 then requires 70 more fuel, which requires 21 fuel, which requires 5 fuel, which requires no further fuel. So, the total fuel required for a module of mass 1969 is 654 + 216 + 70 + 21 + 5 = 966 . The fuel required by a module of mass 100756 and its fuel is: 33583 + 11192 + 3728 + 1240 + 411 + 135 + 43 + 12 + 2 = 50346 .
The examples are still using the same numbers as for part one. The fuel needed for the module with mass 12 isn’t specified, but you can calculate that it’ll be 2 by using the same calculation as for the module with mass 14 . The question that you need to answer remains the same:
What is the sum of the fuel requirements for all of the modules on your spacecraft when also taking into account the mass of the added fuel? (Calculate the fuel requirements for each module separately, then add them all up at the end.)
Have a go at solving this part as well. Can you earn your second star?
You’ll see a possible solution to part two in the next section. However, try to solve the puzzle for yourself first. If you need a hint to get started, then expand the box below:
Hint for Day 1, 2019, Part 2 Show/Hide
Repeated calculations like the ones in this part of the puzzle often lend themselves well to recursion .
How did you do? Is your rocket ready for launch?
This section shows how you can solve part two, continuing with the template you saw above :
Solution for Day 1, 2019, Part 2 Show/Hide
Continuing with the test-driven development workflow, start with adding the new examples to your test file. The examples are using the same numbers as part one, so you can use the same example1.txt file. You can therefore remove the example2() fixture and the test_part2_example2() test from your test code. Next, remove the skip mark and implement test_part2_example1() :
As before, run pytest to confirm that your test is failing.
Note: pytest has a nice option, -k , that you can use to only run a subset of your tests. With -k , you can filter on the test names. For example, to only run the tests related to part two, you can use pytest -k part2 . This is also a nice incentive to use consistent and descriptive test names.
Next, it’s time for the actual implementation. Because you’re asked for repeated calculations of fuel, you’ll probably want to reach for recursion .
A recursive function is a function that calls itself. When implementing a recursive function, you should be conscious of including a stopping condition: When should the function stop calling itself? In this example, the stopping condition is mentioned quite explicitly in the puzzle description. You should stop when the fuel becomes zero or negative.
As your solutions become more complicated, it’s a good idea to use helper functions. For example, you can add a function that calculates all the fuel needed for one module. One benefit of helper functions is that you can test these independently of the puzzle solution.
Add the following as a new function in your aoc201901.py solution file:
You’ve added a doctest inside the docstring. You can tell pytest to run doctests by adding the --doctest-modules flag:
As part of the output from pytest , you’ll see a note that the all_fuel() doctest failed. Adding doctests is a great way to ensure that your helper functions do what you expect. Note that this test doesn’t rely on any input files. Instead, you directly check one of the examples given above.
Next, implement the fuel calculation:
Line 14 implements the stopping condition, while line 17 does the recursive call. You can run your tests to check that the calculation works as expected.
Before moving on to solve the whole puzzle, note that you can use the walrus operator ( := ) to write the function more concisely:
While the code is shorter, it’s also denser. Whether you find the end result more readable or not is a matter of taste and experience.
To finish off the puzzle, you also need to implement part2() . Your all_fuel() function calculates the fuel needed for each module, so what’s left is adding the fuel for all the modules together:
The implementation of part2() ends up being quite similar to part1() . You only need to change the fuel calculation for each mass.
To finish up, run pytest to confirm that everything works. Then run your program on your input to get your final puzzle answer:
Back at the Advent of Code website, enter your own answer, which will be different from the one above. Your second star is waiting!
Before leaving this puzzle completely, note that it’s possible to solve the second part without using recursion. You could do the same calculations using loops instead. Here’s one possible implementation:
For each mass, the while loop calculates all the fuel needed and adds it to the running total fuel count.
One of the fun things about challenging yourself with programming puzzles is that they give you a great opportunity to try out different solutions to problems and compare them.
Congratulations! You’ve now solved an entire Advent of Code puzzle. Are you ready for a more challenging one?
Practicing Advent of Code: Day 5, 2020
The second puzzle that you’ll attempt to solve is the one for Day 5, 2020 , called Binary Boarding . This puzzle is a bit more challenging than the previous one, but the final solution won’t require a lot of code. Start by having a look at the puzzle description for part one.
In 2020, you’re trying hard to get to your well-deserved vacation spot. On Day 5, you’re about to board your plane when trouble ensues:
You board your plane only to discover a new problem: you dropped your boarding pass! You aren’t sure which seat is yours, and all of the flight attendants are busy with the flood of people that suddenly made it through passport control. You write a quick program to use your phone’s camera to scan all of the nearby boarding passes (your puzzle input); perhaps you can find your seat through process of elimination. Instead of zones or groups, this airline uses binary space partitioning to seat people. A seat might be specified like FBFBBFFRLR , where F means “front”, B means “back”, L means “left”, and R means “right”. The first 7 characters will either be F or B ; these specify exactly one of the 128 rows on the plane (numbered 0 through 127 ). Each letter tells you which half of a region the given seat is in. Start with the whole list of rows; the first letter indicates whether the seat is in the front ( 0 through 63 ) or the back ( 64 through 127 ). The next letter indicates which half of that region the seat is in, and so on until you’re left with exactly one row. For example, consider just the first seven characters of FBFBBFFRLR : Start by considering the whole range, rows 0 through 127 . F means to take the lower half , keeping rows 0 through 63 . B means to take the upper half , keeping rows 32 through 63 . F means to take the lower half , keeping rows 32 through 47 . B means to take the upper half , keeping rows 40 through 47 . B keeps rows 44 through 47 . F keeps rows 44 through 45 . The final F keeps the lower of the two, row 44 . The last three characters will be either L or R ; these specify exactly one of the 8 columns of seats on the plane (numbered 0 through 7 ). The same process as above proceeds again, this time with only three steps. L means to keep the lower half , while R means to keep the upper half . For example, consider just the last 3 characters of FBFBBFFRLR : Start by considering the whole range, columns 0 through 7 . R means to take the upper half , keeping columns 4 through 7 . L means to take the lower half , keeping columns 4 through 5 . The final R keeps the upper of the two, column 5 . So, decoding FBFBBFFRLR reveals that it is the seat at row 44 , column 5 . Every seat also has a unique seat ID : multiply the row by 8, then add the column. In this example, the seat has ID 44 * 8 + 5 = 357 . Here are some other boarding passes: BFFFBBFRRR : row 70 , column 7 , seat ID 567 . FFFBBBFRRR : row 14 , column 7 , seat ID 119 . BBFFBBFRLL : row 102 , column 4 , seat ID 820 . As a sanity check, look through your list of boarding passes. What is the highest seat ID on a boarding pass?
There’s a lot of information in this puzzle description! However, most of it concerns how binary space partitioning works for this particular airline.
Now, try to solve the puzzle for yourself! Keep in mind that if you consider it from the right perspective, the conversion from a boarding pass specification to a seat ID isn’t as complicated as it might seem at first. If you find that you’re struggling with that part, then expand the box below to see a hint on how you can get started:
Hint for Day 5, 2020, Part 1 Show/Hide
The boarding pass specifications are based on the binary system , just camouflaged with different characters. Can you translate the boarding passes into binary numbers?
When you’re done with your solution, have a look in the next section to see a discussion about the puzzle.
Now that you’ve given it a shot yourself, you can go ahead and expand the following block to see one way that you could solve the puzzle:
Solution for Day 5, 2020, Part 1 Show/Hide
You can implement the calculation of the seat IDs based on the description in the text. The following function takes the same steps as the example:
You limit the range of possible rows or columns by start and end . While start is included in the range, end is not. This makes the math easier, as it keeps the difference of end - start divisible by two throughout the calculation. You lower the upper limit for each F or L , and you increase start , the lower limit, for each B or R . You can check that the function gives the same results as the examples:
Using decode() , you can calculate the row, the column, and the seat ID for a boarding pass. However, Python already has built-in tools to carry out the same calculation for you.
The name of the puzzle, Binary Boarding, and the mention of binary space partitioning are meant to start you thinking about (or reading about) the binary system . Binary is a number system composed of two digits, 0 and 1 , instead of the traditional ten digits.
In the puzzle, the boarding pass specifications are really binary numbers. The difference is that they use F or L in place of 0 , and B and R in place of 1 . For example, FBFBBFFRLR can be translated to the binary number 0101100101 2 . You can use Python to convert this to a regular decimal number:
Do you recognize that answer? 357 is indeed the seat ID of FBFBBFFRLR . In other words, in order to calculate seat IDs, you need to translate F , L , B , R into their respective binary digits. There are several ways you can do this, but str.translate() in Python’s standard library is probably the most convenient. Here’s how it works:
The .translate() method uses character codes like 70 instead of strings like "F" . You can set up the translation based on strings, though, with the convenience function str.maketrans() . You can now use these tools to solve the puzzle in three steps:
- Convert boarding pass specifications to binary numbers.
- Calculate the decimal value of the binary numbers to get the seat IDs.
- Find the maximal seat ID.
Set up your templates for the new puzzle, with input.txt containing your personalized puzzle input:
You can add the worked examples to example1.txt as usual:
Next, you’re going to prepare the tests for the first part. Before doing so, you should think about how you want to parse the puzzle input.
One option is to parse the input file into a list of strings. However, you can also think about the conversion from boarding pass specification to seat ID as part of the parsing process. One consideration to take into account is whether you think you’ll need the original boarding pass strings later—that is, in part two.
You decide to take the chance, and you parse the seat IDs immediately. If the boarding pass strings are needed in part two, then you can always go back and refactor your code. Add the following tests to your test file:
As usual, run pytest to confirm that your tests are failing. Then it’s time to start implementing your solution. Start with the parsing:
You set up the translation table between boarding pass strings and binary numbers. Then you use .translate() to translate each boarding pass in your input to a binary number and int() to convert the binary number to a seat ID.
Finding the highest seat ID is now straightforward:
Python’s built-in max() finds the highest value in a list. You can now run your tests to confirm that your solution works and then run your code against your personalized input to get your answer to the puzzle.
Time to move on to the second part of the puzzle. Will you be able to board the plane?
Expand the section below when you’re ready for the second part of the puzzle:
Day 5, 2020, Part 2 Show/Hide
Compared to the first part, the description of part two is quite short and concise:
Ding! The “fasten seat belt” signs have turned on. Time to find your seat. It’s a completely full flight, so your seat should be the only missing boarding pass in your list. However, there’s a catch: some of the seats at the very front and back of the plane don’t exist on this aircraft, so they’ll be missing from your list as well. Your seat wasn’t at the very front or back, though; the seats with IDs +1 and -1 from yours will be in your list. What is the ID of your seat?
Can you find your seat?
Take your time and work on your solution to this second part.
Open the box below when you’re ready to compare your solution to another one:
Solution for Day 5, 2020, Part 2 Show/Hide
In this second part of the puzzle, you’re looking for one missing number in a list of numbers.
There are several ways you can approach this. You can, for example, sort all the numbers and compare consecutive items in your sorted list. Another option is to use Python’s powerful sets . You can first create the full set of valid seat IDs. Then you can calculate the set difference between this full set and the set of seat IDs on your list.
Before you start on the implementation, though, you should add a test for it. In this case, the example data are actually not good to use for a test. They have many seat IDs missing rather than only one like the puzzle text specifies. You’re better off creating a small test manually. Here’s one way you can do it:
The list [3, 9, 4, 8, 5, 10, 7, 11] contains all seat IDs from 3 to 11 with the exception of 6. This smaller example fulfills the conditions of the puzzle. Your solution should therefore be able to pick out the missing seat ID.
In this implementation, you’ll use the set() approach:
On line 7, you create all the valid seat IDs. These are the numbers between the smallest seat ID and the highest seat ID in your dataset, inclusive. To find your seat ID, you convert your list of seat IDs to a set, compare it to the set of all IDs, and pop out the one remaining seat ID.
Great, you’ve finished another puzzle! To round things out, try your hand at one of the puzzles from 2021.
Practicing Advent of Code: Day 5, 2021
As a third example of an Advent of Code puzzle, you’ll look closely at Day 5, 2021 . The puzzle is called Hydrothermal Venture and will take you on a deep-sea adventure. The solution will be a bit more involved than the previous two puzzles. Check out the puzzle description.
The story line in 2021 starts with the Elves carelessly dropping the keys to Santa’s sleigh into the ocean. You end up in a submarine searching for them in order to save Christmas. On day 5, you come across a field of hydrothermal vents on the ocean floor.
It turns out that these vents are harmful to your submarine and you need to map out the field to avoid the most dangerous areas:
They tend to form in lines ; the submarine helpfully produces a list of nearby lines of vents (your puzzle input) for you to review. For example: Text 0,9 -> 5,9 8,0 -> 0,8 9,4 -> 3,4 2,2 -> 2,1 7,0 -> 7,4 6,4 -> 2,0 0,9 -> 2,9 3,4 -> 1,4 0,0 -> 8,8 5,5 -> 8,2 Copied! Each line of vents is given as a line segment in the format x1,y1 -> x2,y2 where x1 , y1 are the coordinates of one end the line segment and x2 , y2 are the coordinates of the other end. These line segments include the points at both ends. In other words: An entry like 1,1 -> 1,3 covers points 1,1 , 1,2 , and 1,3 . An entry like 9,7 -> 7,7 covers points 9,7 , 8,7 , and 7,7 . For now, only consider horizontal and vertical lines : lines where either x1 = x2 or y1 = y2 .
The example shows how the puzzle input describes lines at given coordinates. Your job is to find where these lines overlap:
To avoid the most dangerous areas, you need to determine the number of points where at least two lines overlap . In the above example, this is […] a total of 5 points. Consider only horizontal and vertical lines. At how many points do at least two lines overlap?
As in the previous puzzle, there’s a lot of information in the puzzle text. The information mostly pertains to how you should interpret your puzzle input.
Note: There’s some additional information in the full puzzle description . In particular, there’s a diagram that shows all the lines drawn on a grid.
Try to solve the puzzle for yourself. When you’re done, move on to the next sections to see one possible solution.
There are many ways to implement a solution to this puzzle. Expand the block below to start working with the input data:
Parse input for Day 5, 2021, Part 1 Show/Hide
Your task is to calculate how many points are covered by two or more lines. The most straightforward approach is probably the following:
- Convert each line in question to the set of points that make up the line.
- Count the number of times each point appears among all the lines.
- Count the number of points that appear two or more times.
Before you can start coding, you should think about how to represent the points and lines. This might be a good use case for using dedicated Point and Line classes, implemented with the help of data classes .
However, in this solution, you’ll opt for a basic representation using a 2-tuple of integers for each point and a 4-tuple of integers for each line. For example, (0, 9) represents the point 0,9 and (0, 9, 5, 9) represents the line 0,9 -> 5,9 .
It’s often good to start with simple data structures while being ready to move to more complex solutions if it can simplify calculations. Your first task is to parse the input data. Once you’ve set up your template, you should add some example data.
You can use the given example data, but it might be easier to create an even simpler dataset to start with. Add the following to example1.txt :
These data represent four lines: two diagonal ones, one horizontal line, and one vertical line. For completeness, you may also add the example data given in the puzzle description to example2.txt . Next, you’ll manually spell out how you want to represent the four lines in your test file:
As usual, you should run pytest to confirm that your test fails. There are several ways to parse the input as you want to extract four numbers from each line. You could, for example, use a regular expression . Here, you’ll use the string .split() method repeatedly:
This is certainly a mouthful. To understand how the parsing works, start with line 13. This sets up the main loop which looks at each line by splitting the puzzle input on newlines.
Next, the tuple comprehension on lines 8 to 12 is applied to each line. It first splits each line on the arrow symbol ( -> ) and then splits each resulting pair of numbers on comma ( , ). Finally, each number is converted from a string to an integer with int() .
Run your tests to confirm that parse() parses your input as expected.
Even though your code works, you may want to avoid the heavily nested comprehensions. You can, for example, rewrite it as follows:
In this version, you’re explicitly building the list of lines. For each line, you first split the string into two points and then each point into individual x- and y-coordinates.
Once you’ve represented the data in a structure that you can work with, then you can move on to solving the puzzle itself.
You’ll continue working on part 1 of the puzzle. The following solution takes advantage of the structural pattern matching feature introduced in Python 3.10 . Expand the collapsed section to read the details:
Solution for Day 5, 2021, Part 1 Show/Hide
The main challenge in this puzzle is to convert each line from its current representation to a list of individual points. You’ll tackle that next. Start by adding the signature of a function that can convert a line into a list of points, including a doctest documenting the expected output:
You want the function to return a list of points that you can count later. For now, you need to consider horizontal and vertical lines. You’ve added tests for both cases.
The puzzle description hints at how you can identify horizontal and vertical lines as those where one of the coordinates is constant. You can use an if test to find these. However, you can also use the occasion to practice using the match … case statement introduced in Python 3.10:
The match … case construct is very expressive, but can feel a bit magical if you haven’t worked with it before.
Each case tries to match the structure of line . So in line 16, you’re looking for a 4-tuple. Furthermore, you unpack the values of the 4-tuple into the variables x1 , y1 , x2 , and y2 , respectively. Finally, you guard the match by requiring that x1 and x2 have to be equal. In practice, this represents a vertical line.
Similarly, the case statement on line 18 picks out the horizontal lines. For each line, you use range() to list each point, taking care to include the endpoint.
Now, run your tests. If you include the doctests, then you’ll notice that something isn’t quite right:
The vertical line example returns an empty list. As you investigate, you realize that this example calls range(4, 1) , which is an empty range because 1 is less than 4 and you’re using the default step of 1 . To solve this, you can introduce a more complicated range() expression.
To avoid putting more logic into points() , you decide to create a new helper function that takes care of the necessary range() logic:
If start is bigger than stop , then you make sure to use a step of -1 . You can now update points() to use the new function:
By replacing range() with coords() , you should be able to handle all horizontal and vertical lines. Run your tests to confirm that your code now works properly.
You can now convert lines into individual points. The next step in your plan is to count how many lines each point is part of. You could loop through all points and count them explicitly, but Python has many power tools in its standard library. In this case, you can use Counter from the collections module:
On line 16, you loop over each point in each line and pass all the points to Counter . The resulting counter is essentially a dictionary whose values indicate how many times each key appeared.
To find the number of points where two or more lines overlap, you look at how many points in your counter were seen two or more times.
You’re almost done with part 1. You only need to connect the puzzle input with count_overlaps() and make sure that you do as asked—only “consider horizontal and vertical lines.”
You can filter all the lines by employing a few more comprehensions:
You’re only passing those lines where either the x or the y coordinates are constant. Run your code on your personal input to calculate your solution and submit it to earn your next star.
Phew! You’ve finished the first part of the puzzle. Time to look at what part 2 has in store for you.
Expand the section below to read the second part of the puzzle for Day 5, 2021:
Day 5, 2021, Part 2 Show/Hide
You might have suspected that you couldn’t ignore those diagonal lines forever:
Unfortunately, considering only horizontal and vertical lines doesn’t give you the full picture; you need to also consider diagonal lines . Because of the limits of the hydrothermal vent mapping system, the lines in your list will only ever be horizontal, vertical, or a diagonal line at exactly 45 degrees. In other words: An entry like 1,1 -> 3,3 covers points 1,1 , 2,2 , and 3,3 . An entry like 9,7 -> 7,9 covers points 9,7 , 8,8 , and 7,9 . You still need to determine the number of points where at least two lines overlap . In the above example, this is […] now a total of 12 points. Consider all of the lines. At how many points do at least two lines overlap?
You can probably reuse a lot of the work you did for part 1. How can you take those diagonal lines into account, though?
Play around with the second part and try to solve it yourself. Once you’re done, have a look in the next section for a possible solution.
Click to reveal the solution below when you’re ready to have a look at a solution and compare it with your own:
Solution for Day 5, 2021, Part 2 Show/Hide
The change in the second part is that you need to take diagonal lines into account. The problem still asks you to count the number of points that are part of two or more lines. In other words, you can still use count_overlaps() in part two, but you need to expand points() so that it can handle diagonals.
Luckily, all diagonal lines will be exactly 45 degrees. The practical consequence of this is that the coordinates of the points in these lines will still have consecutive integer coordinates.
For example, 5,5 -> 8,2 covers points 5,5 , 6,4 , 7,3 , and 8,2 . Note that the x-coordinates are 5 , 6 , 7 , and 8 , while the y-coordinates are 5 , 4 , 3 , and 2 . You can draw the line by hand on a grid as follows:
Here the numbers on top represent the x-coordinates while the numbers in the left-hand margin are y-coordinates. The dots ( . ) represent the grid, and the points of the line are marked with hash symbols ( # ).
To finish your solution, you need to make two adjustments to your current code:
- Change points() so that it can convert diagonal lines as well.
- Call count_overlaps() with the full list of lines.
Start with adapting points() . A good first change is to update the doctest to include an example of a diagonal line:
You’ve added the line 1,2 -> 3,4 , which covers points 1,2 , 2,3 , and 3,4 . Run your tests to confirm that the diagonal line isn’t handled yet.
You need to add a new case to your match … case statement. The case statements are checked one at a time from the top. If you add your new code below the existing statements, then you’ll know that you’re dealing with diagonal lines. Therefore, you don’t need a guard:
The third case statement handles diagonal lines by changing the x- and y-coordinates at the same time. Here, you’re also reaping some reward from creating coords() , as using range() directly for diagonal lines would’ve been even more complicated than for horizontal and vertical ones.
Now that you can convert diagonal lines to individual points, the only task that remains is to count the number of overlaps. Since count_overlaps() delegates to points() , it’ll now be able to handle diagonal lines as well. You can implement the solution to the second part in one line of code:
You should run your tests to make sure everything works as expected. Then calculate your answer to part two and submit it on the Advent of Code website.
Congratulations! By now, you’ve solved at least three Advent of Code puzzles. Luckily, there are hundreds more waiting for you !
Advent of Code is a great resource of fun programming puzzles! You can use it to practice your problem-solving skills and challenge your friends to a fun competition and common learning experience. You can hear even more about Advent of Code in the following episode of the Real Python Podcast: Solving Advent of Code Puzzles With Python .
If you haven’t already done so, then head over to the Advent of Code website and try out some of the new puzzles.
In this tutorial, you’ve learned:
- How you can approach different kinds of puzzles
Real Python hosts a private leaderboard and a community forum about Advent of Code. Become a Real Python member and join the #advent-of-code Slack channel to access it.
🐍 Python Tricks 💌
Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.
![problem solving python programming and video games answers Python Tricks Dictionary Merge](https://realpython.com/static/pytrick-dict-merge.4201a0125a5e.png)
About Geir Arne Hjelle
![problem solving python programming and video games answers Geir Arne Hjelle](https://realpython.com/cdn-cgi/image/width=800,height=800,fit=crop,gravity=auto,format=auto/https://files.realpython.com/media/gahjelle.470149ee709e.jpg)
Geir Arne is an avid Pythonista and a member of the Real Python tutorial team.
Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:
![problem solving python programming and video games answers Aldren Santos](https://realpython.com/cdn-cgi/image/width=959,height=959,fit=crop,gravity=auto,format=auto/https://files.realpython.com/media/PP.9b8b026f75b8.jpg)
Master Real-World Python Skills With Unlimited Access to Real Python
Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:
Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:
What Do You Think?
What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.
Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. Get tips for asking good questions and get answers to common questions in our support portal . Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session . Happy Pythoning!
Keep Learning
Related Topics: basics career testing
Recommended Video Course: Advent of Code: Solving Puzzles With Python
Keep reading Real Python by creating a free account or signing in:
Already have an account? Sign-In
Almost there! Complete this form and click the button below to gain instant access:
Advent of Code: Solving Your Puzzles With Python (Source Code)
🔒 No spam. We take your privacy seriously.
![](http://writinghelp.online/777/templates/cheerup/res/banner1.gif)
IMAGES
VIDEO
COMMENTS
1. Take a new computational problem and solve it, using several problem solving techniques including abstraction and problem decomposition. 2. Follow a design creation process that includes: descriptions, test plans, and algorithms. 3. Code, test, and debug a program in Python, based on your design. Important computer science concepts such as ...
Let's start your journey. Let's solve every problem you face. Let's do it. tags: programming-hero python python3 problem-solving programming coding-challenge interview learn-python python-tutorial programming-exercises programming-challenges programming-fundamentals programming-contest python-coding-challenges python-problem-solving
Hacking: This is a graphical password guessing game that displays a list of potential computer passwords. The player is allowed up to 4 attempts to guess the password. Each time the user guesses incorrectly, the number of correct letters in their correct locations is displayed and the user is prompted to make a new guess.
Each exercise has 10-20 Questions. The solution is provided for every question. Practice each Exercise in Online Code Editor. These Python programming exercises are suitable for all Python developers. If you are a beginner, you will have a better understanding of Python after solving these exercises. Below is the list of exercises.
In Module 0, you will meet the instructional team and be introduced to the four themes of this course: computer science, problem solving, Python programming, and how to create video games. Module 1: Design Hacking Version 1; In Module 1, you will explore the game creation process that is used in this course.
Join over 23 million developers in solving code challenges on HackerRank, one of the best ways to prepare for programming interviews.
About the Course. Problem Solving, Python Programming, and Video Games (PVG) course is an introduction to computer science and programming in Python. Important computer science concepts such as problem solving (computational thinking), problem decomposition, algorithms, abstraction, and software quality are emphasized throughout. PVG uses video ...
Number guessing game in Python; 2048 Game in Python; Get Live Weather Desktop Notifications Using Python; 8-bit game using pygame; Tic Tac Toe GUI In Python using PyGame >> More Projects in Python. Conclusion. In closing, we just want to say that the practice or solving Python problems always helps to clear your core concepts and programming logic.
170+ solutions to Hackerrank.com practice problems using Python 3, С++ and Oracle SQL - marinskiy/HackerrankPractice. 170+ solutions to Hackerrank.com practice problems using Python 3, С++ and Oracle SQL - marinskiy/HackerrankPractice ... Dynamic Programming Max Array Sum | Problem | Solution | Score: 20; Python Introduction Say Hello, World!
Python Practice Problem 5: Sudoku Solver. Your final Python practice problem is to solve a sudoku puzzle! Finding a fast and memory-efficient solution to this problem can be quite a challenge. The solution you'll examine has been selected for readability rather than speed, but you're free to optimize your solution as much as you want.
Let's discuss the Coding Questions related to the basic Python programming language in detail. Write a program to print the given number is odd or even. Write a program to find the given number is positive or negative. Write a program to find the sum of two numbers.
Beginner Python exercises. Home; Why Practice Python? Why Chilis? Resources for learners; All Exercises. 1: Character Input 2: Odd Or Even 3: List Less Than Ten 4: Divisors 5: List Overlap 6: String Lists 7: List Comprehensions 8: Rock Paper Scissors 9: Guessing Game One 10: List Overlap Comprehensions 11: Check Primality Functions 12: List Ends 13: Fibonacci 14: List Remove Duplicates
Escher. Maya. py.CheckiO - Python practice online. Improve your coding skills by solving coding challenges and exercises online with your friends in a fun way. Exchanges experience with other users online through fun coding activities.
The syntax is straightforward: You provide a condition to evaluate within the if. If that condition is true, the corresponding block of code is executed. If the condition is false, the code within the optional else block is executed instead. Here's a simple example: x = 10. if x > 5: print("x is greater than 5") else:
There is a single operator in Python, capable of providing the remainder of a division operation. Two numbers are passed as parameters. The first parameter divided by the second parameter will have a remainder, possibly zero. Return that value. Examples remainder(1, 3) 1 remainder(3, 4) 3 remainder(5, 5) 0 remainde …
This Object-Oriented Programming (OOP) exercise aims to help you to learn and practice OOP concepts. All questions are tested on Python 3. Python Object-oriented programming (OOP) is based on the concept of "objects," which can contain data and code: data in the form of instance variables (often known as attributes or properties), and code, in the form method.
To understand a programming language deeply, you need to practice what you've learned. If you've completed learning the syntax of Python programming language, it is the right time to do some practice programs. In this article, I'll list down some problems that I've done and the answer code for each exercise.
Boost your coding interview skills and confidence by practicing real interview questions with LeetCode. Our platform offers a range of essential problems for practice, as well as the latest questions being asked by top-tier companies.
Python Practice Problem 1: Average Expenses for Each Semester. John has a list of his monthly expenses from last year: He wants to know his average expenses for each semester. Using a for loop, calculate John's average expenses for the first semester (January to June) and the second semester (July to December).
Exercise 1: User Input and Conditional Statements. Write a program that asks the user for a number then prints the following sentence that number of times: 'I am back to check on my skills!'. If the number is greater than 10, print this sentence instead: 'Python conditions and loops are a piece of cake.'.
This course is an introduction to computer science and programming in Python. Important computer science concepts such as problem solving (computational thinking), problem decomposition, algorithms, abstraction, and software quality are emphasized throughout. The Python programming language and video games are used to demonstrate computer science concepts in a concrete and fun manner. However ...
Brief. This course is an introduction to computer science and programming in Python. Upon successful completion of this course, you will be able to: Take a new computational problem and develop a plan to solve it through problem understanding and decomposition. Follow a design creation process that includes specifications, algorithms, and testing.
In-depth articles and video courses Learning Paths ... They offer certifications in many different skills, including problem-solving and Python programming, as well as a job board that lets you show off your puzzle-solving skills as part of your job applications. ... 514579 is indeed the answer to the problem when using the example input data ...