Python Wife Logo

  • Computer Vision
  • Problem Solving in Python
  • Intro to DS and Algo
  • Analysis of Algorithm
  • Dictionaries
  • Linked Lists
  • Doubly Linked Lists
  • Circular Singly Linked List
  • Circular Doubly Linked List
  • Tree/Binary Tree
  • Binary Search Tree
  • Binary Heap
  • Sorting Algorithms
  • Searching Algorithms
  • Single-Source Shortest Path
  • Topological Sort
  • Dijkstra’s
  • Bellman-Ford’s
  • All Pair Shortest Path
  • Minimum Spanning Tree
  • Kruskal & Prim’s

Problem-solving is the process of identifying a problem, creating an algorithm to solve the given problem, and finally implementing the algorithm to develop a computer program .

An algorithm is a process or set of rules to be followed while performing calculations or other problem-solving operations. It is simply a set of steps to accomplish a certain task.

In this article, we will discuss 5 major steps for efficient problem-solving. These steps are:

  • Understanding the Problem
  • Exploring Examples
  • Breaking the Problem Down
  • Solving or Simplification
  • Looking back and Refactoring

While understanding the problem, we first need to closely examine the language of the question and then proceed further. The following questions can be helpful while understanding the given problem at hand.

  • Can the problem be restated in our own words?
  • What are the inputs that are needed for the problem?
  • What are the outputs that come from the problem?
  • Can the outputs be determined from the inputs? In other words, do we have enough information to solve the given problem?
  • What should the important pieces of data be labeled?

Example : Write a function that takes two numbers and returns their sum.

  • Implement addition
  • Integer, Float, etc.

Once we have understood the given problem, we can look up various examples related to it. The examples should cover all situations that can be encountered while the implementation.

  • Start with simple examples.
  • Progress to more complex examples.
  • Explore examples with empty inputs.
  • Explore examples with invalid inputs.

Example : Write a function that takes a string as input and returns the count of each character

After exploring examples related to the problem, we need to break down the given problem. Before implementation, we write out the steps that need to be taken to solve the question.

Once we have laid out the steps to solve the problem, we try to find the solution to the question. If the solution cannot be found, try to simplify the problem instead.

The steps to simplify a problem are as follows:

  • Find the core difficulty
  • Temporarily ignore the difficulty
  • Write a simplified solution
  • Then incorporate that difficulty

Since we have completed the implementation of the problem, we now look back at the code and refactor it if required. It is an important step to refactor the code so as to improve efficiency.

The following questions can be helpful while looking back at the code and refactoring:

  • Can we check the result?
  • Can we derive the result differently?
  • Can we understand it at a glance?
  • Can we use the result or mehtod for some other problem?
  • Can you improve the performance of the solution?
  • How do other people solve the problem?

Trending Posts You Might Like

  • File Upload / Download with Streamlit
  • Dijkstra’s Algorithm in Python
  • Seaborn with STREAMLIT
  • Greedy Algorithms in Python

Author : Bhavya

Python Practice for Beginners: 15 Hands-On Problems

Author's photo

  • online practice

Want to put your Python skills to the test? Challenge yourself with these 15 Python practice exercises taken directly from our Python courses!

There’s no denying that solving Python exercises is one of the best ways to practice and improve your Python skills . Hands-on engagement with the language is essential for effective learning. This is exactly what this article will help you with: we've curated a diverse set of Python practice exercises tailored specifically for beginners seeking to test their programming skills.

These Python practice exercises cover a spectrum of fundamental concepts, all of which are covered in our Python Data Structures in Practice and Built-in Algorithms in Python courses. Together, both courses add up to 39 hours of content. They contain over 180 exercises for you to hone your Python skills. In fact, the exercises in this article were taken directly from these courses!

In these Python practice exercises, we will use a variety of data structures, including lists, dictionaries, and sets. We’ll also practice basic programming features like functions, loops, and conditionals. Every exercise is followed by a solution and explanation. The proposed solution is not necessarily the only possible answer, so try to find your own alternative solutions. Let’s get right into it!

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).

Explanation

We initialize two variables, first_semester_total and second_semester_total , to store the total expenses for each semester. Then, we iterate through the monthly_spending list using enumerate() , which provides both the index and the corresponding value in each iteration. If you have never heard of enumerate() before – or if you are unsure about how for loops in Python work – take a look at our article How to Write a for Loop in Python .

Within the loop, we check if the index is less than 6 (January to June); if so, we add the expense to first_semester_total . If the index is greater than 6, we add the expense to second_semester_total .

After iterating through all the months, we calculate the average expenses for each semester by dividing the total expenses by 6 (the number of months in each semester). Finally, we print out the average expenses for each semester.

Python Practice Problem 2: Who Spent More?

John has a friend, Sam, who also kept a list of his expenses from last year:

They want to find out how many months John spent more money than Sam. Use a for loop to compare their expenses for each month. Keep track of the number of months where John spent more money.

We initialize the variable months_john_spent_more with the value zero. Then we use a for loop with range(len()) to iterate over the indices of the john_monthly_spending list.

Within the loop, we compare John's expenses with Sam's expenses for the corresponding month using the index i . If John's expenses are greater than Sam's for a particular month, we increment the months_john_spent_more variable. Finally, we print out the total number of months where John spent more money than Sam.

Python Practice Problem 3: All of Our Friends

Paul and Tina each have a list of their respective friends:

Combine both lists into a single list that contains all of their friends. Don’t include duplicate entries in the resulting list.

There are a few different ways to solve this problem. One option is to use the + operator to concatenate Paul and Tina's friend lists ( paul_friends and tina_friends ). Afterwards, we convert the combined list to a set using set() , and then convert it back to a list using list() . Since sets cannot have duplicate entries, this process guarantees that the resulting list does not hold any duplicates. Finally, we print the resulting combined list of friends.

If you need a refresher on Python sets, check out our in-depth guide to working with sets in Python or find out the difference between Python sets, lists, and tuples .

Python Practice Problem 4: Find the Common Friends

Now, let’s try a different operation. We will start from the same lists of Paul’s and Tina’s friends:

In this exercise, we’ll use a for loop to get a list of their common friends.

For this problem, we use a for loop to iterate through each friend in Paul's list ( paul_friends ). Inside the loop, we check if the current friend is also present in Tina's list ( tina_friends ). If it is, it is added to the common_friends list. This approach guarantees that we test each one of Paul’s friends against each one of Tina’s friends. Finally, we print the resulting list of friends that are common to both Paul and Tina.

Python Practice Problem 5: Find the Basketball Players

You work at a sports club. The following sets contain the names of players registered to play different sports:

How can you obtain a set that includes the players that are only registered to play basketball (i.e. not registered for football or volleyball)?

This type of scenario is exactly where set operations shine. Don’t worry if you never heard about them: we have an article on Python set operations with examples to help get you up to speed.

First, we use the | (union) operator to combine the sets of football and volleyball players into a single set. In the same line, we use the - (difference) operator to subtract this combined set from the set of basketball players. The result is a set containing only the players registered for basketball and not for football or volleyball.

If you prefer, you can also reach the same answer using set methods instead of the operators:

It’s essentially the same operation, so use whichever you think is more readable.

Python Practice Problem 6: Count the Votes

Let’s try counting the number of occurrences in a list. The list below represent the results of a poll where students were asked for their favorite programming language:

Use a dictionary to tally up the votes in the poll.

In this exercise, we utilize a dictionary ( vote_tally ) to count the occurrences of each programming language in the poll results. We iterate through the poll_results list using a for loop; for each language, we check if it already is in the dictionary. If it is, we increment the count; otherwise, we add the language to the dictionary with a starting count of 1. This approach effectively tallies up the votes for each programming language.

If you want to learn more about other ways to work with dictionaries in Python, check out our article on 13 dictionary examples for beginners .

Python Practice Problem 7: Sum the Scores

Three friends are playing a game, where each player has three rounds to score. At the end, the player whose total score (i.e. the sum of each round) is the highest wins. Consider the scores below (formatted as a list of tuples):

Create a dictionary where each player is represented by the dictionary key and the corresponding total score is the dictionary value.

This solution is similar to the previous one. We use a dictionary ( total_scores ) to store the total scores for each player in the game. We iterate through the list of scores using a for loop, extracting the player's name and score from each tuple. For each player, we check if they already exist as a key in the dictionary. If they do, we add the current score to the existing total; otherwise, we create a new key in the dictionary with the initial score. At the end of the for loop, the total score of each player will be stored in the total_scores dictionary, which we at last print.

Python Practice Problem 8: Calculate the Statistics

Given any list of numbers in Python, such as …

 … write a function that returns a tuple containing the list’s maximum value, sum of values, and mean value.

We create a function called calculate_statistics to calculate the required statistics from a list of numbers. This function utilizes a combination of max() , sum() , and len() to obtain these statistics. The results are then returned as a tuple containing the maximum value, the sum of values, and the mean value.

The function is called with the provided list and the results are printed individually.

Python Practice Problem 9: Longest and Shortest Words

Given the list of words below ..

ā€¦ find the longest and the shortest word in the list.

To find the longest and shortest word in the list, we initialize the variables longest_word and shortest_word as the first word in the list. Then we use a for loop to iterate through the word list. Within the loop, we compare the length of each word with the length of the current longest and shortest words. If a word is longer than the current longest word, it becomes the new longest word; on the other hand, if it's shorter than the current shortest word, it becomes the new shortest word. After iterating through the entire list, the variables longest_word and shortest_word will hold the corresponding words.

There’s a catch, though: what happens if two or more words are the shortest? In that case, since the logic used is to overwrite the shortest_word only if the current word is shorter – but not of equal length – then shortest_word is set to whichever shortest word appears first. The same logic applies to longest_word , too. If you want to set these variables to the shortest/longest word that appears last in the list, you only need to change the comparisons to <= (less or equal than) and >= (greater or equal than), respectively.

If you want to learn more about Python strings and what you can do with them, be sure to check out this overview on Python string methods .

Python Practice Problem 10: Filter a List by Frequency

Given a list of numbers …

… create a new list containing only the numbers that occur at least three times in the list.

Here, we use a for loop to iterate through the number_list . In the loop, we use the count() method to check if the current number occurs at least three times in the number_list . If the condition is met, the number is appended to the filtered_list .

After the loop, the filtered_list contains only numbers that appear three or more times in the original list.

Python Practice Problem 11: The Second-Best Score

You’re given a list of students’ scores in no particular order:

Find the second-highest score in the list.

This one is a breeze if we know about the sort() method for Python lists – we use it here to sort the list of exam results in ascending order. This way, the highest scores come last. Then we only need to access the second to last element in the list (using the index -2 ) to get the second-highest score.

Python Practice Problem 12: Check If a List Is Symmetrical

Given the lists of numbers below …

… create a function that returns whether a list is symmetrical. In this case, a symmetrical list is a list that remains the same after it is reversed – i.e. it’s the same backwards and forwards.

Reversing a list can be achieved by using the reverse() method. In this solution, this is done inside the is_symmetrical function.

To avoid modifying the original list, a copy is created using the copy() method before using reverse() . The reversed list is then compared with the original list to determine if it’s symmetrical.

The remaining code is responsible for passing each list to the is_symmetrical function and printing out the result.

Python Practice Problem 13: Sort By Number of Vowels

Given this list of strings …

… sort the list by the number of vowels in each word. Words with fewer vowels should come first.

Whenever we need to sort values in a custom order, the easiest approach is to create a helper function. In this approach, we pass the helper function to Python’s sorted() function using the key parameter. The sorting logic is defined in the helper function.

In the solution above, the custom function count_vowels uses a for loop to iterate through each character in the word, checking if it is a vowel in a case-insensitive manner. The loop increments the count variable for each vowel found and then returns it. We then simply pass the list of fruits to sorted() , along with the key=count_vowels argument.

Python Practice Problem 14: Sorting a Mixed List

Imagine you have a list with mixed data types: strings, integers, and floats:

Typically, you wouldn’t be able to sort this list, since Python cannot compare strings to numbers. However, writing a custom sorting function can help you sort this list.

Create a function that sorts the mixed list above using the following logic:

  • If the element is a string, the length of the string is used for sorting.
  • If the element is a number, the number itself is used.

As proposed in the exercise, a custom sorting function named custom_sort is defined to handle the sorting logic. The function checks whether each element is a string or a number using the isinstance() function. If the element is a string, it returns the length of the string for sorting; if it's a number (integer or float), it returns the number itself.

The sorted() function is then used to sort the mixed_list using the logic defined in the custom sorting function.

If you’re having a hard time wrapping your head around custom sort functions, check out this article that details how to write a custom sort function in Python .

Python Practice Problem 15: Filter and Reorder

Given another list of strings, such as the one below ..

.. create a function that does two things: filters out any words with three or fewer characters and sorts the resulting list alphabetically.

Here, we define filter_and_sort , a function that does both proposed tasks.

First, it uses a for loop to filter out words with three or fewer characters, creating a filtered_list . Then, it sorts the filtered list alphabetically using the sorted() function, producing the final sorted_list .

The function returns this sorted list, which we print out.

Want Even More Python Practice Problems?

We hope these exercises have given you a bit of a coding workout. If you’re after more Python practice content, head straight for our courses on Python Data Structures in Practice and Built-in Algorithms in Python , where you can work on exciting practice exercises similar to the ones in this article.

Additionally, you can check out our articles on Python loop practice exercises , Python list exercises , and Python dictionary exercises . Much like this article, they are all targeted towards beginners, so you should feel right at home!

You may also like

what are problem solving techniques in python

How Do You Write a SELECT Statement in SQL?

what are problem solving techniques in python

What Is a Foreign Key in SQL?

what are problem solving techniques in python

Enumerate and Explain All the Basic Elements of an SQL Query

  • Why Python?
  • The Anaconda Distribution of Python
  • Installing Anaconda on Windows
  • Installing Anaconda on MacOS
  • Installing Anaconda on Linux
  • Installing Python from Python.org
  • Review Questions

Orientation

Introduction.

Welcome to the world of problem solving with Python! This first Orientation chapter will help you get started by guiding you through the process of installing Python on your computer. By the end of this chapter, you will be able to:

Describe why Python is a useful computer language for problem solvers

Describe applications where Python is used

Detail advantages of Python over other programming languages

Know the cost of Python

Know the difference between Python and Anaconda

Install Python on your computer

Install Anaconda on your computer

Mastering Algorithms for Problem Solving in Python

Learning Python by doing

  • suggest edit

Computational Thinking

Computational thinking 1 #.

Finding the one definition of Computational Thinking (CT) is a task doomed to failure, mainly because it is hard to have a consensus on what CT means to everyone. To ease the communication and have a shared meaning, we consider CT as an approach to ā€œsolve problems using computers as toolsā€ (Beecher, 2017). Notice that CT is not exclusively considered in computer science. On the contrary, CT impacts a wide range of subject areas such as mathematics, engineering, and science in general.

There is a misunderstanding regarding the relationship between CT, computer science, and programming. Some people use them interchangeably, but the three terms are not equivalent. Computer science aims at building and understanding the principles of mathematical computation; while programming ā€“which happens to be a subfield of computer scienceā€“focuses on high-quality program writing. Although the three terms are related and might intersect in many points, CT should be seen as a method of problem-solving that is frequently (but not exclusively) used in programming. In essence, problem-solving is a creative process.

Some of the core concepts behind CT are:

Decomposition

Abstraction

Generalization

Hereafter, we will explore what these concepts mean and how they can help you when solving a problem.

Computational thinking

Computational thinking is an approach to problem-solving that involves using a set of practices and principles from computer science to formulate a solution thatā€™s executable by a computer. [ Bee07 ]

Logic is the study of the formal principles of reasoning. These principles determine what can be considered a correct or incorrect argument. An argument is ā€œa change of reasoning that ends up in a conclusionā€ [ Bee07 ] . Every statement within an argument is called a proposition , and it has a truth value . That is, it is either true or false . Thus, certain expressions like questions (e.g. ā€œare you hungry?ā€) or commands (e.g. ā€œclean your bedroom!ā€) cannot be propositions given that they do not have a truth value.

Below we present a very famous argument in the logic field:

Socrates is a man.

All men are mortal.

Therefore, Socrates is mortal.

This argument is composed of three propositions (each one is enumerated). These statements are propositions because all of them have a truth value. However, you can notice that some of these statements are used to arrive at a conclusion. The propositions that form the basis of an argument are known as premises . In our example, propositions 1 and 2 are premises. Lastly, the proposition that is derived from a set of premises is known as a conclusion .

Logic studies the formal principles of reasoning, which determine if an argument is correct or not. An argument is a sequence of premises. Each premise is a statement that has a truth value (i.e. true or false).

Types of Arguments #

Arguments can either be deductive or inductive.

Deductive Arguments #

Deductive arguments are considered a strong form of reasoning because the conclusion is derived from previous premises. However, deductive arguments can fail in two different scenarios:

False premises: One of the premises turns to be false. For example:

I eat healthy food.

Every person eating healthy food is tall.

I am tall. In this example, premise 2 is false. It is not true that every person eating healthy food is tall. Then, this argument fails.

Faulty logic: The conclusion is wrongly derived out from the premises. For example:

All bitterballen are round.

The moon is round.

The moon is a bitterbal. In this case, the conclusion presented in premise 3 is false. It is true that bitterballen are round and that the moon is round, but this does not imply that the moon is a bitterbal! By the way, a ā€œbitterbalā€ is a typical Dutch snack, to be eaten with a good glass of beer!

Inductive Arguments #

Although deductive arguments are strong, they follow very stern standards that make them difficult to build. Additionally, the real world usually cannot be seen just in black and whiteā€“there are many shades in between. This is where inductive arguments play an important role. Inductive arguments do not have an unquestionable truth value. Instead, they deal with probabilities to express the level of confidence in them. Thus, the conclusion of the argument cannot be guaranteed to be true, but you can have a certain confidence in it. An example of an inductive argument comes as follows:

Every time I go out home it is raining.

Tomorrow I will go out from home.

Tomorrow it will be raining.

There is no way you can be certain that tomorrow will rain, but given the evidence, there is a high chance that it will be the case. (The chance might be even higher if we mention that we are living in the Netherlands!)

Deductive and inductive arguments

Arguments can be either deductive or inductive. On the one hand, deductive arguments have premises that have a clear truth value. On the other hand, inductive arguments have premises associated with a level of confidence in them.

Boolean Logic #

Given their binary nature, computers are well suited to deal with deductive reasoning (rather than inductive). To allow them to reason about the correctness of an argument, we use Boolean logic. Boolean logic is a form of logic that deals with deductive argumentsā€“that is, arguments having propositions with a truth value that is either true or false. Boolean logic or Boolean algebra was introduced by George Boole (that is why it is called Boolean) in his book ā€œThe Mathematical Analysis of Logicā€ in 1847. It deals with binary variables (with true or false values) representing propositions and logical operations on them.

Logical Operators #

The main logical operators used in Boolean logic to connect propositions are:

And operator: It is also known as the conjunction operator. It chains premises in such a way that all of them must be true for the conclusion to be true.

Or operator: It is also known as the disjunction operator. It connects premises in such a way that at least one of them must be true for the conclusion to be true.

Not operator: It is also known as the negation operator. It modifies the value of a proposition by flipping its truth value.

Venn diagrams of logical operators

In Boolean logic, propositions are usually represented as letters or variables (see previous figure). For instance, going back to our Socrates argument, we can represent the three propositions as follows:

P: Socrates is a man.

Q: All men are mortal.

R: Therefore, Socrates is mortal.

In order for R to be true, P and Q most be true.

We can now translate this reasoning into Python. To do that use the following table and execute the cell below.

The previous translation to Python code of the deductive argument is correct, however we can do way better! Let us see:

Sometimes conditionals are not really needed; using a Boolean expression as the one shown above is sufficient. Having unneeded language constructs (e.g. conditionals) can negatively impact the readability of your code.

Algorithms #

We can use logic to solve everyday life problems. To do so, we rely on the so-called algorithms. Logic and algorithms are not equivalent. On the contrary, an algorithm uses logic to make decisions for it to solve a well-defined problem. In short, an algorithm is a finite sequence of well-defined instructions that are used to provide a solution to a problem. According to this definition, it seems that algorithms are what we create, refine, and execute every single day of our lives, isnā€™t it? Think for instance about the algorithm to dress up in the morning or the algorithm (or sequence of steps) that you follow to bake a cake or cook a specific recipe. Those are also algorithms that we have internalized and follow unconsciously.

To design an algorithm, we usually first need to specify the following set of elements:

the problem to be solved or question to be answered. If you do not have a well-defined problem you might end up designing a very efficient but useless algorithm that does not solve the problem at hand. Thus, ensure you understand the problem before thinking about a solution;

the inputs of the algorithmā€“that is, the data you require to compute the solution;

the output of the algorithmā€“that is, the expected data that you want to get out from your solution, and;

the algorithm or sequence of steps that you will follow to come up with an answer.

Without having a clear picture of your problem, and the expected inputs and output to solve that problem, it will be unlikely that you will be able to come up with a proper algorithm. Furthermore, beware that for algorithms to be useful, they should terminate at some point (they cannot just run forever without providing a solution!) and output a correct result. An algorithm is correct if it outputs the right solution to every possible input. Proving this might be unfeasible, which is why testing your algorithm (maybe after implementing a program) is crucial.

An algorithm is a finite sequence of clearly defined instructions used to solve a specific problem.

Appeltaart Algorithm #

To be conscious about the process of designing an algorithm, let us create an algorithm to prepare the famous Dutch Appeltaart . The recipe has been taken from the Heel Holland Bakt website .

Dutch Appeltaart

We will start by defining the problem we want to solve. In our case, we want to prepare a classical Dutch Appeltaart .

Inputs (Ingredients) #

The inputs to our algorithm correspond to the ingredients needed to prepare the pie. We list them below:

200 grams of butter

160 grams of brown sugar

0.50 teaspoon of cinnamon

300 grams of white flour

a pinch of salt

breadcrumbs

Apple filling

100 grams of raisins

100 grams of shelled walnuts

5 tablespoons of sugar

3 teaspoons of cinnamon

1 egg for brushing

25 white almonds

Output (Dish) #

The expected output of our algorithm is a delicious and well-prepared Dutch Appeltaart.

Algorithm (Recipe) #

Preparation

Grease a round pan and dust with flour.

Preheat the oven to 180Ā°C.

  • Mix the butter with brown sugar and cinnamon.
  • Add the flour with a pinch of salt to the butter mixture.
  • Add 1 egg to the mixture.
  • Knead into a smooth dough and let rest in the fridge for at least 15 minutes.
  • Roll out 2/3 of the dough and line the pan with it.
  • Spread the breadcrumbs over the bottom.
  • Place the pan in the fridge to rest.
  • Put the raisins in some rum.
  • Peel the apples and cut them into wedges.
  • Strain the raisins.
  • Mix the apples with raisins, walnuts, sugar, and cinnamon.
  • Pour the filling into the pan.
  • Cover the top of the pie with the remaining dough.
  • Brush the top with a beaten egg and sprinkle with the almonds.
  • Bake the apple pie for about 60 minutes.
  • Let cool and enjoy!
ā€œThe limits of my language mean the limits of my world.ā€ - Ludwig Wittgenstein

In the previous section, we were able to write down the algorithm to prepare a Dutch Appeltaart. Writing down an algorithm is of great importance given that you do not only guarantee that you can execute the algorithm in future opportunities, but you also provide a means to share the algorithm, so other people can benefit from what you designed. But to be able to write down the algorithm, we require an additional toolā€“that is, a language. In the previous example, we used English to describe our Appeltaart algorithm. However, if you remember correctly, computational thinking relies on computers to solve real-world problems. Thus, the algorithms we want to write down must be written in a language that can be understood by a computer. But beware! The computer is not the only other entity that needs to understand your algorithm: what you write down should be understood by both the machine and other people that might read it afterward (including the you from the future).

Language is a system of communication. It has a syntax and semantics :

The syntax of a language describes the form or structure of the language constructs. The syntax can be defined with a grammar , which is a set of rules that specify how to build a correct sentence in the language.

The semantics describes the meaning of language constructs.

Languages can also be classified as natural or formal :

Natural languages are languages used by people to communicate with each other (e.g. English, Spanish, Dutch, Arabic). They were not designed from the very beginning, on the contrary, they evolved naturally over time.

Formal languages are languages designed by humans for specific domains or purposes. They usually are simplified models of natural language. Examples of formal languages are the mathematical, chemical, or staff (standard music notation) notations. There is also a very important example that interests us the most: programming languages.

Programming Languages #

Programming languages are formal languages with very strict syntax and semantics . These languages are used to write down algorithms. A program is, then, an algorithm implemented using a programming language. To this point, we can make some connections with previous concepts: CT is a method of problem-solving where problems are solved by reusing or designing a new algorithm . This algorithm might later be written down as a program to compute a solution to the original problem.

Python is an example of a programming language. It was conceptualized in 1989 by Guido van Rossum when working at the Centrum Wiskunde & Informatica (CWI), in Amsterdam. Python saw its beginnings in the ABC language. Its nameā€“referring to this monumental sort of snakeā€“actually comes from an old BBC series called Monty Pythonā€™s Flying Circus. Guido was reading the scripts of the series and he found out that Python sounded ā€œshort, unique, and slightly mysteriousā€, which is why he decided to adopt the name.

Guido van Rossum

Please clarify that there is a difference between solving a problem, inventing an algorithm, and writing a program.

It maybe the case that to solve a problem you apply a known algorithm, think of sorting words, but it may also be the case that to solve the problem you have to come up with a new algorithm.

The Zen of Python #

In 1999, Tim Petersā€“one of Pythonā€™s main contributorsā€“ wrote a collection of 19 principles that influence the design of the Python programming language. This collection is now known as the Zen of Python. Peters mentioned that the 20 \(^{th}\) principle is meant to be filled in by Guido in the years to come. Have a look at the principles. You can consider them as guidelines for the construction of your own programs.

A language is a system of communication, that has syntax and semantics. The syntax describes the form of the language, while the semantics describes its meaning. A language can be either natural (evolves naturally) or formal (designed for a specific domain or purpose). Programming languages are a sort of formal languages and are used to allow communication between humans and computers.

Decomposition #

In 1945 (in the year that the II World War ended), George PĆ³lya, a Hungarian mathematician, wrote a book called ā€œHow to Solve Itā€. The book presents a systematic method of problem-solving that is still relevant today. In particular, he introduced problem-solving techniques known as heuristics . A heuristic is a strategy to solve a specific problem by yielding a good enough solution, but not necessarily an optimal one. There is one important type of heuristic known as decomposition . Decomposition is a divide-and-conquer approach that breaks complex problems into smaller and simpler subproblems, so we can deal with them more efficiently.

In programming, we have diverse constructs that will ease the implementation of decomposition. In particular, classes and functions (or methods ) are a means to divide a complex solution to a complex problem into smaller chunks of code. We will cover these topics later in the course.

Decomposition is a divide-and-conquer approach that breaks complex problems into smaller and simpler subproblems.

Abstraction & Generalization #

Abstraction is the process of hiding irrelevant details in a given context and preserving only the important information. Abstraction is required when generalizing. In fact, generalization is the process of defining general concepts by abstracting common properties from a set of instances. In other words, generalization allows you to formulate a unique concept out of similar but not necessarily identical entities. When generalizing a solution, it becomes simpler because there are fewer concepts to deal with. The solution also becomes more powerful in the sense that it can be applied to more problems of similar nature.

To be able to generalize a solution or algorithm, you need to start developing your ability to recognize patterns. For instance:

A sequence of instructions that are repeating multiple times can be generalized into loops .

Specialized instructions that are employed more than once in different scenarios can be encapsulated in subroutines or functions .

Constraints that determine the flow of execution of your algorithm can be generalized in conditionals .

Abstraction and generalization

Abstraction is the process of preserving relevant information in a given context and hiding irrelevant details. In addition, generalization is the process of defining general concepts by abstracting common properties from a set of instances.

Modelling #

All models are wrong, but some are useful. (Box, 1987)

Humans and computers are not able to completely grasp and understand the real world. Thus, to solve real-world problems, we usually need to create models that help us understand and solve the issue. A model is a representation of an entity. Thus, a model as a representation that, by definition, ignores certain details of the represented entity, is also a type of abstraction . A model in computer science usually consists of:

Entities: core concepts of the represented system.

Relationships: connections among entities within the represented system.

Models usually come in two flavors:

Static models: these models reflect a snapshot of the system at a given moment in time. The state of the system might change in the future but the changes are so small or unfrequent that the model is still useful and sufficient.

Dynamic models: these models explain changes in the state of a system over time. They always involve states (description of the system at a given point in time) and transitions (state changes). Some dynamic models can be executed to predict the state of the system in the future.

When creating a model you should verify that:

The model is useful to solve the problem at hand.

You are strictly following the rules , notation, and conventions to define a model.

The level of accuracy of your model is acceptable to solve the problem (i.e. you keep the strictly needed information).

You have defined the level of precision at which you represent your model (especially when dealing with decimal numbers; how many decimal points are required?).

A model is a representation of an entity. It is a type of abstraction.

Example: Aliceā€™s Adventures in Wonderland #

In this section, we will apply computational thinking to solve a problem from Aliceā€™s Adventures in Wonderland, written by Lewis Caroll. In chapter I, ā€œDown the Rabbit Holeā€, Alice found herself falling down into a rabbit hole. She finally reached the ground, coming upon ā€œa heap of sticks and dry leavesā€. Alice found herself in a ā€œlong, low hall, which was lit up by a row of lamps hanging from the roofā€.

ā€œThere were doors all around the hall, but they were all lockedā€. She started ā€œwondering how she was ever to get out againā€. She suddenly discovered a tiny golden key on a little three-legged table, all made of solid glass. After looking around, ā€œshe came upon a low curtain she had not noticed before, and behind it was a little door about fifteen inches high: she tried the little golden key in the lock, and to her great delight it fitted!ā€ But she was not able to go through it; the doorway was too small.

Later in the chapter, we find out that there was a bottle with a ā€˜DRINK MEā€™ label that makes shorter anyone drinking its content. There was also a very small cake with the words ā€˜EAT MEā€™ beautifully marked in currant. Anyone eating the cake will grow larger. How can we help Alice go out of the hall through the small doorway behind the curtain?

To solve this problem, assume that:

Alice is 60 inches tall;

Alice can go out of the doorway if she is taller than 10 inches (exclusive) and shorter than 15 inches (inclusive);

one sip of the ā€˜DRINK MEā€™ bottle makes anyone get 11 inches shorter;

Alice can only sip from the bottle at a point in time;

one bite of the ā€˜EAT MEā€™ cake makes anyone grow 1 inch larger;

Alice can only have a bite of the cake at a point in time, and;

Alice cannot sip from the bottle and a bite of the cake at the same time.

Alice holding the ā€˜DRINK MEā€™ bottle

Understanding the Problem #

Problem: Alice wants to go out of the hall. To do so, she needs to go through the doorway behind the curtain, but she is too tall to go through it.

Identifying the Inputs #

The inputs we have at hand are:

Aliceā€™s height (i.e. 60 inches)

Doorway height (i.e. 15 inches)

Height decrease after taking a sip from the ā€˜DRINK MEā€™ bottle (i.e. 11 inches)

Height increase after taking a bite from the ā€˜EAT MEā€™ cake (i.e. 1 inch)

We abstracted the relevant information to the problem. Details are removed if they are not needed;

thus, the inputs are useful to solve the problem.

The inputs were written in Python. They follow the syntax rules of the programming language.

The identified inputs are enough to accurately solve the problem.

We use integers to represent Aliceā€™s height. There is no need to use floats. Therefore, the level of precision of our model is acceptable to solve the problem.

Identifying the Expected Output #

As a solution to our problem, we want Alice to go out from the hall through the doorway. To do so, her height should be greater than 10 inches and less than or equal to 15 inches.

Output: Aliceā€™s height should be greater than 10 inches and less than or equal to 15 inches.

Designing the Algorithm #

To solve the problem we know that:

Alice must go out from the hall through the doorway if she is larger than 10 inches and shorter or exactly 15 inches.

Alice must drink out from the ā€˜DRINK MEā€™ bottle if she is taller than 15 inchesā€“that is, she will shorten 11 inches.

Alice must bite the ā€˜EAT MEā€™ cake if she is shorter or exactly 10 inchesā€“that is, she will grow 1 inch.

Steps 2 and 3 shall be repeated until she can to go out from the hall.

We decomposed the problem of getting the right height into two subproblems: making Alice get larger and making Alice get shorter.

We generalized our solution by identifying patterns in our algorithm (e.g. step 4).

Now, we will implement our algorithm in Python.

Let us try to improve our previous algorithm. We can always make it more beautiful , more explicit , simpler , and more readable . Remember that ā€œif the implementation is easy to explain, it may be a good ideaā€ (see the Zen of Python).

Note: In the following code, we will use f-Strings. We will talk more about later in the course, but now you can start grasping what is their use and how we can build them.

Well done! We have applied computational thinking to design a solution to Aliceā€™s problem.

(c) 2021, Lina Ochoa Venegas, Eindhoven University of Technology

This Jupyter Notebook is based on Chapter 1 of [ Bee07 ] and Chapter 1, 8, and 10 of [ Erw17 ] .

Say "Hello, World!" With Python Easy Max Score: 5 Success Rate: 96.24%

Python if-else easy python (basic) max score: 10 success rate: 89.71%, arithmetic operators easy python (basic) max score: 10 success rate: 97.41%, python: division easy python (basic) max score: 10 success rate: 98.68%, loops easy python (basic) max score: 10 success rate: 98.10%, write a function medium python (basic) max score: 10 success rate: 90.31%, print function easy python (basic) max score: 20 success rate: 97.27%, list comprehensions easy python (basic) max score: 10 success rate: 97.69%, find the runner-up score easy python (basic) max score: 10 success rate: 94.16%, nested lists easy python (basic) max score: 10 success rate: 91.70%, cookie support is required to access hackerrank.

Seems like cookies are disabled on this browser, please enable them to open this website

TechBeamers

  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
  • Python Quizzes
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python Selenium
  • General Tech

40 Python Exercises for Beginners

Python Exercises Beginners Should Start With.

If youā€™re new to Python and want to learn the basics, our free Python exercises for beginners are a great place to start. Our 40 exercises cover numbers, strings, loops, functions, and other data structures, and theyā€™re all designed to be easy to follow. So what are you waiting for? Start practicing today and build a strong foundation in Python.

Python Exercises Every Beginner Should Practice

Use our online Python IDE to run and test your Python scripts.

Python Basic Level-1 Exercises

Here are the first 5 Python exercises for beginners along with their descriptions and solutions. These are often given to interview candidates to assess their basic Python knowledge.

String Reversal

Description: Write a function that accepts a string as input and returns the reversed string. This exercise focuses on string manipulation using slicing in Python . You will learn how to reverse a string by leveraging Pythonā€™s Ā indexing and slicing features.

Also Try: 7 Ways to Reverse a List in Python

List Comprehension

Description: Write a program that takes a list of numbers and returns a new list containing only the even numbers. This exercise introduces list comprehension in Python , a concise way to create new lists based on existing ones. You will practice using conditional statements within list comprehensions to filter elements.

Flowchart: Here is a basic flowchart to cover the simple logic of finding even numbers.

check even numbers in list flow chart

Description: Write a program to print numbers from 1 to 100! Hereā€™s the catch:

For multiples of 3, print ā€œFizzā€. For multiples of 5, print ā€œBuzzā€. If a number is a multiple of both 3 and 5, print ā€œFizzBuzzā€.

This exercise will help you learn how to use if statements in Python Youā€™ll also get to practice with control flow and the modulo operator (%).

Flowchart: Below is a flowchart to illustrate the FizzBuzz algo.

Python exercise for fizzbuzz algo flow chart

Check if Two Strings are Anagrams

Description: Write a function that takes two strings as input and returns True if they are anagrams (contain the same characters with the same frequency), False otherwise. This exercise involves comparing the characters and their frequencies in two strings to determine if they are anagrams. You will practice string manipulation, sorting, and comparison.

Flowchart: Refer to this flowchart to create a mind map outlining the steps to solve this problem.

Python exercise to check for anagrams flow chart

Prime Number Check

Description: Write a function that takes a number and tells you if itā€™s prime. This exercise focuses on prime number determination using basic looping and mathematical operations. You will learn about loops, conditions, numbers, and Python range() .

Flowchart: Refer to this flowchart to understand the logic of filtering prime numbers.

check for prime numbers flow chart

Level-1 Practice Exercises

Good, now you must start feeling comfortable in solving Python programming problems. Next, we leave you with 5 basic Python exercises. Start building logic to solve these challenges.

  • Find the Maximum Number
  • Calculate the Average of a List
  • Check if a Number is Palindrome
  • Count Vowels in a String
  • Calculate the Factorial of a Number in Python

Donā€™t miss to check out the next 5 Python exercises for beginners. These are often asked in Pythonā€™s technical interview rounds, along with their descriptions and solutions.

Python Basic Level-2 Exercises

The difficulty of the exercises will increase gradually in this section. They start with a simple exercise and get more challenging in the end. We encourage you to attempt all of the exercises.

Greatest Common Divisor

Description: Write a function that takes two numbers and returns their greatest common divisor (GCD). This exercise requires implementing the Euclidean algorithm to find the GCD of two numbers. You will practice using loops and conditional statements to perform repetitive calculations.

Flowchart: Before jumping on the code, try to solve it using pen and paper.

logic to calculate gcd flow chart

Linear Search

Description: Write a function that takes a list and a target element and returns the index of the target element in the list, or -1 if it is not found. This exercise demonstrates the concept of linear search, which involves iterating through a list to find a specific element. You will practice using loops and conditions to perform element comparisons.

Flowchart: Letā€™s find out how the linear search works using the below flowchart.

Python exercise for linear search flow chart

FizzBuzz with a Twist

Description: Write a program that prints the numbers from 1 to 100. For multiples of three, print ā€œFizzā€. For multiples of five, print ā€œBuzzā€. Additionally, for numbers containing the digit 3, print ā€œFizzā€. This exercise builds upon the FizzBuzz concept while introducing additional conditions based on digit presence. You will practice using string manipulation, modulo operations, and conditions.

Binary Search

Description: Write a function that takes a sorted list and a target element and returns the index of the target element using binary search, or -1 if it is not found. This exercise involves implementing the binary search algorithm to locate an element in a sorted list. You will learn about the concept of divide and conquer, and how to use recursion or iterative approaches to perform a binary search.

Flowchart: Binary search is fancy, and implementing it can be tricky. So, itā€™s better to draw the flow on paper to avoid too many hits and trials on the computer.

Python exercise for binary search flow chart

Matrix Transposition

Description: Write a function that takes a matrix (2D list) and returns its transpose (rows become columns and vice versa). This exercise focuses on working with nested lists and performing matrix transposition. You will practice using list comprehension and indexing to transform rows into columns and vice versa.

Level-2 Practice Exercises

Here are 5 intermediate-level Python exercises for you to practice.

  • Reverse Words in a Sentence
  • Sort a List of Strings Alphabetically
  • Check if a Number is a Perfect Square
  • Find the Second Largest Number in a List
  • Remove Duplicate Elements from a List

So far, you have solved 20 (10 solved and 10 for practice ) Python exercises for beginners. Now is the time to take up a bit more challenging problems. You may now have reached the apex of problem-solving in Python programming.

Python Basic Level-3 Exercises

These exercises are all challenging, but their solutions comprise different concepts with a good understanding of Python. Solving these exercises will help you develop a sound knowledge of Python programming.

Armstrong Number Check

Description: Write a function that takes a number as input and returns True if it is an Armstrong number (the sum of cubes of its digits is equal to the number itself), False otherwise. This exercise involves decomposing a number into its digits, performing computations, and comparing the result with the original number. You will practice using loops, arithmetic operations, and conditionals.

Flowchart: Do you know that flowcharts are the magic key to solving many difficult problems? They are far away from any language barrier. So, you will get help irrespective of the language you use.

Check Armstrong number flow chart

Fibonacci Series

Description: Write a function that generates the Fibonacci series up to a specified number of terms. This exercise focuses on the Fibonacci sequence, where each number is the sum of the two preceding ones. You will practice using loops and variables to calculate and display the series.

Flowchart: The Fibonacci sequence, named after the Italian mathematician Leonardo of Pisa, also known as Fibonacci, is like a mathematical dance of numbers. Letā€™s first sketch it out using a flowchart.

Fibonacci series flow chart

Pascalā€™s Triangle

Description: Write a function that generates Pascalā€™s triangle up to a specified number of rows. This exercise involves constructing Pascalā€™s triangle, where each number is the sum of the two numbers directly above it. You will practice using nested loops, lists, and indexing to create and display the triangle.

Flowchart: Pascalā€™s Triangle is a special arrangement of numbers where each number is the sum of the two above it. It helps in probability, counting combinations, and solving problems in a structured way. Itā€™s like a math tool that makes certain calculations easier. Would you mind if we first solve it using a flowchart?

Python exercise for pascal triangle using range flow chart

Description: Write a function that implements the Merge Sort algorithm to sort a list of numbers. This exercise introduces the concept of merge sort, a recursive sorting algorithm that divides the list into smaller sublists, sorts them, and merges them back together. You will learn about recursion, list slicing , and merging sorted lists.

Flowchart: Merge Sort sorts a list by dividing it into tiny parts, sorting each part, and then getting them back together. Take it like, you are sorting toys by breaking them into groups, sorting each group, and then neatly combining them. Below is a flowchart depicting the flow code in the solution part.

Python exercise for merge sort algorithm flow chart

Find the Missing Number

Description: Write a function that takes a list of numbers from 1 to n (with one number missing) and returns the missing number. This exercise involves finding the missing number in a list by comparing the expected and actual sums. You will practice list iteration, arithmetic operations, and conditional statements.

Flowchart: Hereā€Find the Missing Numberā€ is like solving a number puzzle. You have a list with one number missing. To find it, you add up all the numbers in a special way and compare it with the sum of the given numbers. The difference is the missing number ā€“ like figuring out the secret code! Check out its flowchart.

Find missing number flow chart

Level-3 Practice Exercises

Take up the following advanced-level Python exercises and put your knowledge to the test.

  • Find the Median of a List
  • Implement a Stack Data Structure
  • Generate Permutations of a List
  • Calculate the Power of a Number
  • Reverse Bits of a Number

Finally, we are in the final lap of 40 Python exercises for beginners. So, brace for an ultimate test of your programming excellence. And, donā€™t forget to enter the last level of Python programming problems, hit the next button now.

Python Basic Level-4 Exercises

Hey there, beginners! Are you ready to take on the challenge of 5 expert-level Python exercises? Push your coding expertise to the limit and conquer complex problems with advanced algorithms and data structures. Get set to level up your Python skills and become a coding maestro!

Count Words in a Sentence

Description: Write a function that takes a sentence as input and returns the count of each word in the sentence. This exercise focuses on word frequency analysis, where you will split a sentence into words, create a frequency dictionary, and count the occurrences of each word. You will practice string manipulation, loop iteration, and Python dictionary operations.

Flowchart: ā€œCount Words in a Sentenceā€ is like keeping track of people in a group. Think of your sentence as the group. Your task is to figure out how many people (words) are there. You go through each word, and whenever you come across a new one, you mark it down. The final count tells you how many people, or words, are in the group. Letā€™s create the flowchart.

Count words in a sentence flow chart

Remove Duplicates from a List

Description: Write a function that takes a list and returns a new list with duplicate elements removed while preserving the order in the result This exercise focuses on removing duplicates from a list by iterating over it, checking for duplicates, and creating a new list without duplicates. You will practice list manipulation, element comparisons, and list comprehension.

Binary to Decimal Conversion

Description: Write a function that takes a binary number as input and returns its decimal equivalent. This exercise involves converting a binary number to its decimal representation using positional notation. You will practice string manipulation, arithmetic operations, and exponentiation.

Check if Linked List is Palindrome

Description: Write a function that takes the head of a linked list as input and returns True if the linked list is a palindrome (reads the same forward and backward), False otherwise. This exercise focuses on checking if a linked list is a palindrome by comparing elements from both ends. You will practice linked list traversal, stack data structure usage, and element comparisons.

These exercises cover a range of concepts and can help beginners improve their problem-solving skills in Python.

Reverse a Linked List

Description: Write a function that takes the head of a linked list and reverses the order of the elements in the list. Return the new head of the reversed list. This exercise tests your understanding of linked lists and requires you to manipulate pointers to reverse the order of the list efficiently.

In this exercise, you needed to implement the function reverse_linked_list that takes the head of a linked list as input. The function reverses the order of list elements by manipulating the pointers of each node. The new head of the reversed list is then returned. The code also includes an example to demonstrate the reversal of a linked list.

Level-4 Practice Exercises

Lastly, check out the 5 Python exercises you should practice to claim expert-level proficiency in your programming skills.

  • Find the Longest Consecutive Subsequence in a List
  • Implement a Binary Search Tree
  • Calculate the Nth Fibonacci Number in O(1) Space Complexity
  • Sort a List of Dates in Ascending Order
  • Detect a Cycle in a Directed Graph

Access More Exercises on Different Topics

10 python tricky coding exercises.

  • 50 Python Exercises List, Tuple, Dict
  • 45 Python Exercises On Loops/ If-Else
  • 30 Python Questions On List, Tuple, Dict
  • 20 Problems On Concatenated Strings
  • Python Data Class Exercises ā€“ Beginners
  • 20 Challenging Pseudo Code Questions

Learn Python by Practice: A Quick Summary

We have tried to cover a wide range of fundamental concepts and problem-solving techniques through these 40 Python exercises for beginners. These exercises included several topics such as string manipulation, sorting algorithms, anagram checks, and linked list manipulation.

Such programming tasks are useful for beginners to practice and strengthen their Python skills before interviews. By actively working through these exercises, beginners can gain confidence in their coding abilities.

Let us know, if you want us to create more such exercises. Also, share this tutorial on your social media accounts to let others get a chance to practice these exercises.

Happy learning, Team TechBeamers

You Might Also Like

How to connect to postgresql in python, generate random ip address (ipv4/ipv6) in python, python remove elements from a list, selenium python extent report guide, sign up for daily newsletter, be keep up get the latest breaking news delivered straight to your inbox..

Meenakshi Agarwal Avatar

Popular Tutorials

SQL Interview Questions List

Top 50 SQL Query Interview Questions for Practice

Demo Websites You Need to Practice Selenium

7 Demo Websites to Practice Selenium Automation in 2024

SQL Exercises with Sample Table and Demo Data

SQL Exercises ā€“ Complex Queries

Java Coding Questions for Software Testers

15 Java Coding Questions for Testers

30 Quick Python Programming Questions On List, Tuple & Dictionary

30 Python Programming Questions On List, Tuple, and Dictionary

what are problem solving techniques in python

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

python-problem-solving

Here are 11 public repositories matching this topic..., programminghero1 / 100-plus-python-coding-problems-with-solutions.

A list of python problems for beginners and intermediate developers

  • Updated Jun 20, 2023

alisharify7 / Programming-Questions

Solve Some Programming Question || Ų³ŁˆŲ§Ł„Ų§ŲŖ ŲØŲ±Ł†Ų§Ł…Ł‡ Ł†ŁˆŪŒŲ³ŪŒ ŲØŁ‡ Ł‡Ł…Ų±Ų§Ł‡ Ų¬ŁˆŲ§ŲØ

  • Updated May 20, 2024

UltiRequiem / hacker-rank-python

šŸŒ€ The best solutions to the Hacker Rank problems / All Problems Solved

  • Updated Apr 1, 2022

SAZZAD-AMT / PYTHON-CSE303-LAB-PROBLEM

CSE303 Lab Problem Solving apart. This course is really helpful for real life.

  • Updated Apr 30, 2022

jjanmo / python101

  • Updated Mar 31, 2024

itizarsa / python-workouts

Basic coding in python. Few micro-projects using python3.

  • Updated Jan 24, 2021

FardinHash / Python_Experiments

Python Techniques, Experiments for problem solving, real world solutions.

  • Updated Oct 1, 2022

P-create02 / Two-Special-Problems-With-Solutions

Two python recruitment tasks

  • Updated Feb 19, 2021

sci-c0 / codeforces-solutions

Solutions to CodeForces Challenges

  • Updated Sep 8, 2021

ekta-kapase / 100DaysOfPython

Config files for my GitHub profile.

  • Updated May 17, 2023

epythonlab / scripts

Python programming scripts

  • Updated Apr 25, 2024
  • Jupyter Notebook

Improve this page

Add a description, image, and links to the python-problem-solving topic page so that developers can more easily learn about it.

Curate this topic

Add this topic to your repo

To associate your repository with the python-problem-solving topic, visit your repo's landing page and select "manage topics."

How to Solve Coding Problems with a Simple Four Step Method

Madison Kanna

I had fifteen minutes left, and I knew I was going to fail.

I had spent two months studying for my first technical interview.

I thought I was prepared, but as the interview came to a close, it hit me: I had no idea how to solve coding problems.

Of all the tutorials I had taken when I was learning to code, not one of them had included an approach to solving coding problems.

I had to find a method for problem-solvingā€”my career as a developer depended on it.

I immediately began researching methods. And I found one. In fact, what I uncovered was an invaluable strategy. It was a time-tested four-step method that was somehow under the radar in the developer ecosystem.

In this article, Iā€™ll go over this four-step problem-solving method that you can use to start confidently solving coding problems.

Solving coding problems is not only part of the developer job interview processā€”itā€™s what a developer does all day. After all, writing code is problem-solving.

A method for solving problems

This method is from the book How to Solve It by George PĆ³lya. It originally came out in 1945 and has sold over one million copies.

His problem-solving method has been used and taught by many programmers, from computer science professors (see Udacityā€™s Intro to CS course taught by professor David Evans) to modern web development teachers like Colt Steele.

Letā€™s walk through solving a simple coding problem using the four-step problem-solving method. This allows us to see the method in action as we learn it. We'll use JavaScript as our language of choice. Hereā€™s the problem:

Create a function that adds together two numbers and returns that value. There are four steps to the problem-solving method:

  • Understand the problem.
  • Devise a plan.
  • Carry out the plan.

Letā€™s get started with step one.

Step 1: Understand the problem.

When given a coding problem in an interview, itā€™s tempting to rush into coding. This is hard to avoid, especially if you have a time limit.

However, try to resist this urge. Make sure you actually understand the problem before you get started with solving it.

Read through the problem. If youā€™re in an interview, you could read through the problem out loud if that helps you slow down.

As you read through the problem, clarify any part of it you do not understand. If youā€™re in an interview, you can do this by asking your interviewer questions about the problem description. If youā€™re on your own, think through and/or Google parts of the question you might not understand.

This first step is vital as we often donā€™t take the time to fully understand the problem. When you donā€™t fully understand the problem, youā€™ll have a much harder time solving it.

To help you better understand the problem, ask yourself:

What are the inputs?

What kinds of inputs will go into this problem? In this example, the inputs are the arguments that our function will take.

Just from reading the problem description so far, we know that the inputs will be numbers. But to be more specific about what the inputs will be, we can ask:

Will the inputs always be just two numbers? What should happen if our function receives as input three numbers?

Here we could ask the interviewer for clarification, or look at the problem description further.

The coding problem might have a note saying, ā€œYou should only ever expect two inputs into the function.ā€ If so, you know how to proceed. You can get more specific, as youā€™ll likely realize that you need to ask more questions on what kinds of inputs you might be receiving.

Will the inputs always be numbers? What should our function do if we receive the inputs ā€œaā€ and ā€œbā€? Clarify whether or not our function will always take in numbers.

Optionally, you could write down possible inputs in a code comment to get a sense of what theyā€™ll look like:

//inputs: 2, 4

What are the outputs?

What will this function return? In this case, the output will be one number that is the result of the two number inputs. Make sure you understand what your outputs will be.

Create some examples.

Once you have a grasp of the problem and know the possible inputs and outputs, you can start working on some concrete examples.

Examples can also be used as sanity checks to test your eventual problem. Most code challenge editors that youā€™ll work in (whether itā€™s in an interview or just using a site like Codewars or HackerRank) have examples or test cases already written for you. Even so, writing out your own examples can help you cement your understanding of the problem.

Start with a simple example or two of possible inputs and outputs. Let's return to our addition function.

Letā€™s call our function ā€œadd.ā€

Whatā€™s an example input? Example input might be:

// add(2, 3)

What is the output to this? To write the example output, we can write:

// add(2, 3) ---> 5

This indicates that our function will take in an input of 2 and 3 and return 5 as its output.

Create complex examples.

By walking through more complex examples, you can take the time to look for edge cases you might need to account for.

For example, what should we do if our inputs are strings instead of numbers? What if we have as input two strings, for example, add('a', 'b')?

Your interviewer might possibly tell you to return an error message if there are any inputs that are not numbers. If so, you can add a code comment to handle this case if it helps you remember you need to do this.

Your interviewer might also tell you to assume that your inputs will always be numbers, in which case you donā€™t need to write any extra code to handle this particular input edge case.

If you donā€™t have an interviewer and youā€™re just solving this problem, the problem might say what happens when you enter invalid inputs.

For example, some problems will say, ā€œIf there are zero inputs, return undefined.ā€ For cases like this, you can optionally write a comment.

// check if there are no inputs.

// If no inputs, return undefined.

For our purposes, weā€™ll assume that our inputs will always be numbers. But generally, itā€™s good to think about edge cases.

Computer science professor Evans says to write what developers call defensive code. Think about what could go wrong and how your code could defend against possible errors.  

Before we move on to step 2, letā€™s summarize step 1, understand the problem:

-Read through the problem.

-What are the inputs?

-What are the outputs?

Create simple examples, then create more complex ones.

2. Devise a plan for solving the problem.

Next, devise a plan for how youā€™ll solve the problem. As you devise a plan, write it out in pseudocode.

Pseudocode is a plain language description of the steps in an algorithm. In other words, your pseudocode is your step-by-step plan for how to solve the problem.

Write out the steps you need to take to solve the problem. For a more complicated problem, youā€™d have more steps. For this problem, you could write:

// Create a sum variable.

Add the first input to the second input using the addition operator .

// Store value of both inputs into sum variable.

// Return as output the sum variable. Now you have your step-by-step plan to solve the problem. For more complex problems, professor Evans notes, ā€œConsider systematically how a human solves the problem.ā€ That is, forget about how your code might solve the problem for a moment, and think about how you would solve it as a human. This can help you see the steps more clearly.

3. Carry out the plan (Solve the problem!)

Hand, Rubik, Cube, Puzzle, Game, Rubik Cube

The next step in the problem-solving strategy is to solve the problem. Using your pseudocode as your guide, write out your actual code.

Professor Evans suggests focusing on a simple, mechanical solution. The easier and simpler your solution is, the more likely you can program it correctly.

Taking our pseudocode, we could now write this:

Professor Evans adds, remember not to prematurely optimize. That is, you might be tempted to start saying, ā€œWait, Iā€™m doing this and itā€™s going to be inefficient code!ā€

First, just get out your simple, mechanical solution.

What if you canā€™t solve the entire problem? What if there's a part of it you still don't know how to solve?

Colt Steele gives great advice here: If you canā€™t solve part of the problem, ignore that hard part thatā€™s tripping you up. Instead, focus on everything else that you can start writing.

Temporarily ignore that difficult part of the problem you donā€™t quite understand and write out the other parts. Once this is done, come back to the harder part.

This allows you to get at least some of the problem finished. And often, youā€™ll realize how to tackle that harder part of the problem once you come back to it.

Step 4: Look back over what you've done.

Once your solution is working, take the time to reflect on it and figure out how to make improvements. This might be the time you refactor your solution into a more efficient one.

As you look at your work, here are some questions Colt Steele suggests you ask yourself to figure out how you can improve your solution:

  • Can you derive the result differently? What other approaches are there that are viable?
  • Can you understand it at a glance? Does it make sense?
  • Can you use the result or method for some other problem?
  • Can you improve the performance of your solution?
  • Can you think of other ways to refactor?
  • How have other people solved this problem?

One way we might refactor our problem to make our code more concise: removing our variable and using an implicit return:

With step 4, your problem might never feel finished. Even great developers still write code that they later look at and want to change. These are guiding questions that can help you.

If you still have time in an interview, you can go through this step and make your solution better. If you are coding on your own, take the time to go over these steps.

When Iā€™m practicing coding on my own, I almost always look at the solutions out there that are more elegant or effective than what Iā€™ve come up with.

Wrapping Up

In this post, weā€™ve gone over the four-step problem-solving strategy for solving coding problems.

Let's review them here:

  • Step 1: understand the problem.
  • Step 2: create a step-by-step plan for how youā€™ll solve it .
  • Step 3: carry out the plan and write the actual code.
  • Step 4: look back and possibly refactor your solution if it could be better.

Practicing this problem-solving method has immensely helped me in my technical interviews and in my job as a developer. If you don't feel confident when it comes to solving coding problems, just remember that problem-solving is a skill that anyone can get better at with time and practice.

If you enjoyed this post, join my coding club , where we tackle coding challenges together every Sunday and support each other as we learn new technologies.

If you have feedback or questions on this post, feel free to tweet me @madisonkanna ..

Read more posts .

If you read this far, thank the author to show them you care. Say Thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Programming with Python All in One

  • Post published: 21 May, 2024
  • Post category: 100% Free Courses / StudyBullet-18
  • Reading time: 4 mins read

what are problem solving techniques in python

What you will learn

basic programming skills

Computer science concept, python programming language, problem solving – put everything together with software.

Why take this course?

Welcome to **”Programming with Python: All-in-One”**, your comprehensive guide to mastering one of the most versatile programming languages out there ā€“ **Python!**

**Course Instructor**: Haichuan Lin šŸ‘©ā€šŸ’»

### **Unlock Your Potential with Python! šŸ**

Why Choose This Course? – **Foundational Knowledge**: Build a rock-solid foundation in programming that will serve as the stepping stone for advanced computer science concepts. – **Real-World Application**: Discover how Python can be a game-changer in problem solving for various industries, from science to software engineering. – **End-to-End Development Experience**: Learn the full lifecycle of product development through the lens of Python programming. – **Problem Solving Mastery**: Enhance your critical thinking and problem-solving skills by applying coding logic and computational thinking.

### **Course Highlights:**

šŸ”¹ **Interactive Learning**: Engage with interactive exercises that reinforce learning through practice. šŸ”¹ **Cross-Discipline Relevance**: Explore the intersection of programming and other fields like mathematics and physics, adding depth to your understanding of these subjects. šŸ”¹ **Self-Learning Empowerment**: Equip yourself with the tools to continue learning new programming languages and computer science topics independently after course completion. šŸ”¹ **Real-World Scenarios**: Understand how software updates can lead to significant product improvements and why developers play a crucial role from start to finish of a product’s lifecycle.

### **What You Will Learn:**

– **Python Syntax & Semantics**: Gain command of Python’s syntax, structure, and semantics. – **Effective Problem Solving**: Learn how to approach problems systematically using Python as your toolbox. – **Software Development Best Practices**: Familiarize yourself with the best practices that professional developers follow. – **Coding Projects & Real-World Case Studies**: Work on hands-on projects that reflect real-world challenges and solutions.

### **Course Breakdown:**

**Module 1: Introduction to Python Programming** – Basic syntax, variables, and types – Control structures: loops and conditionals – Writing your first Python program

**Module 2: Functions & Modules** – Understanding functions and their parameters – Creating and using modules – Organizing code for reusability and readability

**Module 3: Data Structures in Python** – Lists, dictionaries, sets, and tuples – Iterating over data structures – Managing complex data with lists of lists or nested dictionaries

**Module 4: Object-Oriented Programming (OOP)** – Classes and objects in Python – Encapsulation, inheritance, and polymorphism – Building robust and reusable code components with OOP principles

**Module 5: Working with Data** – Reading from and writing to files – Handling various file formats (CSV, JSON, etc.) – Data manipulation and analysis for actionable insights

**Module 6: Web Development with Python** – Introduction to web development with Flask or Django – Building simple yet functional web applications – Understanding web frameworks and their role in app development

**Module 7: Final Project & Review** – Apply what you’ve learned in a comprehensive project – Showcase your problem-solving skills through coding – Gain confidence and experience as a Python programmer

Join us on this journey to become a proficient Python developer and unlock the power of problem solving with code. Enroll now and transform the way you think about programming and problem solving! šŸ’»āœØ

šŸ’  Follow this Video to Get Free Courses on Every Needed Topics! šŸ’ 

University of Rhode Island

  • Future Students
  • Parents and Families

Rhody Today

Commencement 2024: for biological sciences graduate, problem solving is a core skill.

what are problem solving techniques in python

KINGSTON, R.I. ā€“ May 13, 2024 ā€“ For most of us, a botched do-it-yourself plumbing job that results in a flooded cellar would send us scrambling to call a pro. But for Alberto Paz, the would-be disaster only bolstered his confidence in his problem-solving skills.

Paz, born and raised in Providence, first came to the University of Rhode Island while still in Classical High School. He spent two weeks on campus in a program that had him doing experiments with chemicals, including some that could create fireworks. When he graduated high school, he became a full-time student in biological sciences in URIā€™s College of the Environment and Life Sciences.

He’s currently working with associate professor Ying Zhang in using metabolic modeling, meta-omics, and other data-intensive approaches to answering research questions in bioengineering and environmental microbiology. His research group develops open-source software and models for simulation of biological systems to achieve mechanistic understandings at molecular, organismal, and ecosystems scales.

Making information easier to access for everyone is important to Paz. That is why he focuses on bioinformatics, an interdisciplinary field of science that develops methods and software tools for understanding biological data. Professor Zhang allowed him to choose a project that interested him. Heā€™s been working on it since summer 2023 and feels confident that if he continues on the path heā€™s taken, the work will eventually be published.

ā€œThe goal of any single type of lab, whether it be cancer, aquatics, anything, is to get your research across so it can convince other people as well,ā€ Paz said. ā€œIā€™m also interested in coding, with a focus on biology. Iā€™d like to make information available for everyone, not just academics.ā€

Heā€™s currently researching an organism called foraminifera, which is only found in the first centimeter of water in salt marshes. Paz hopes to be the first to sequence its genetic code, upload it, and determine its behaviors.

Paz says his life experiences have made him even more certain that he has a knack for problem solving. ā€œFrom painting houses to tarring streets, to plumbing. I feel that having grown up with a proclivity toward fixing things and taking the unconventional route makes me a better researcher. I would like to encourage people to have a variety of experiences instead of boxing themselves into one area.ā€

He recalls a time when he and his father were renovating their house, including the plumbing. Paz looked over the project and, confident in his problem-solving abilities, persuaded his dad to let him take over one particular chore.

Things were going just fine, except for one thing: he had forgotten to turn off a valve. It wasnā€™t until the basement was flooded that he realized his mistake. Lucky for him his father didnā€™t blow his top. He just calmly told Alberto that he would have to clean the mess. Once that was completed, Paz returned to the task, this time fixing the problem as he said he would. The process took hours, but heā€™s still proud of the way it came out. ā€œThat one will always stick with me,ā€ he said.

When heā€™s not doing home renovations, Paz likes going to the gym and playing volleyball. He also enjoys being with his sister Naomi when he goes home on the weekend. Thatā€™s also a time when heā€™s likely to enjoy a plate of mangĆŗ, a Dominican dish often eaten as a breakfast. ā€œI grew up with it; itā€™s my comfort food.ā€

For Alberto Paz, challenging himself to excel at problem solving is a way of life. ā€œMost people donā€™t know how hard I work, especially behind the scenes in research, setting things up to be successful. But I really like the freedom that challenges an evolutionary thought. You canā€™t be complacent. I like things that are very difficult.ā€

This story was written by Hugh Markey.

COMMENTS

  1. Problem Solving in Python

    Problem Solving in Python. Problem-solving is the process of identifying a problem, creating an algorithm to solve the given problem, and finally implementing the algorithm to develop a computer program. An algorithm is a process or set of rules to be followed while performing calculations or other problem-solving operations.

  2. Python Practice for Beginners: 15 Hands-On Problems

    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).

  3. Lesson 3

    Lesson 3 - Problem solving techniques. In the last lesson, we learned control flow statements such as if-else and for. In this lesson, let us try to write a program for this problem: "Given a day, the program should print if it is a weekday or weekend.". $ python3 day_of_the_week.py monday. weekday. $ python3 day_of_the_week.py sunday. weekend.

  4. Python Practice Problems: Get Ready for Your Next Interview

    While this solution takes a literal approach to solving the Caesar cipher problem, you could also use a different approach modeled after the .translate() solution in practice problem 2. Solution 2. The second solution to this problem mimics the behavior of Python's built-in method .translate(). Instead of shifting each letter by a given ...

  5. Introduction

    Welcome to the world of problem solving with Python! This first Orientation chapter will help you get started by guiding you through the process of installing Python on your computer. By the end of this chapter, you will be able to: Describe why Python is a useful computer language for problem solvers. Describe applications where Python is used.

  6. Python Basics Course by University of Michigan

    This course is part of the Python Basics for Online Research Specialization. When you enroll in this course, you'll also be enrolled in this Specialization. Learn new concepts from industry experts. Gain a foundational understanding of a subject or tool. Develop job-relevant skills with hands-on projects.

  7. Python Exercises, Practice, Challenges

    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.

  8. Problem Solving Strategies and Techniques using Python

    šŸŽØ Learn Problem Solving Strategies and Techniques using Python | Session-1 ļø Enroll Now: https://bit.ly/3xAUmxL to get started!šŸ‘‰Attend a Free Demo On Ful...

  9. Mastering Algorithms for Problem Solving in Python

    As a developer, mastering the concepts of algorithms and being proficient in implementing them is essential to improving problem-solving skills. This course aims to equip you with an in-depth understanding of algorithms and how they can be utilized for problem-solving in Python. Starting with the basics, you'll gain a foundational understanding ...

  10. Computational Thinking

    To this point, we can make some connections with previous concepts: CT is a method of problem-solving where problems are solved by reusing or designing a new algorithm. This algorithm might later be written down as a program to compute a solution to the original problem. Python is an example of a programming language. It was conceptualized in ...

  11. Hands-On Linear Programming: Optimization With Python

    Linear programming is a set of techniques used in mathematical programming, sometimes called mathematical optimization, to solve systems of linear equations and inequalities while maximizing or minimizing some linear function. It's important in fields like scientific computing, economics, technical sciences, manufacturing, transportation ...

  12. Data Science skills 101: How to solve any problem

    It is not surprising then that research, including a 2023 report from the World Economic Forum, highlights that problem-solving is a top skill employers look for [1] and that the need for complex problem solving skills is only increasing. Cognitive Problem solving skills analytical and creative thinking were the top two in demand skills of 2023 ...

  13. PDF Introduction to Problem Solving and Programming in Python

    Course Description. CIS 1051 introduces students to computers, computer programming, and problem solving using programs written in the Python language. Topics covered include the general characteristics of computers; techniques of problem solving and algorithm specifications; and the implementation, debugging, and testing of computer programs.

  14. Cracking Coding Interviews: Python Solutions for Common Problems

    We will provide Python-based solutions to enhance your problem-solving skills in additional articles about each. ... String manipulation techniques: Python offers a variety of built-in string ...

  15. Solve Python

    Easy Python (Basic) Max Score: 10 Success Rate: 89.71%. Solve Challenge. Arithmetic Operators. ... Skills. Problem Solving (Basic) Python (Basic) Problem Solving (Advanced) Python (Intermediate) Difficulty. Easy. Medium. Hard. Subdomains. Introduction. Basic Data Types. Strings.

  16. Problem Solving, Python Programming, and Video Games

    This course is an introduction to computer science and programming in Python. Upon successful completion of this course, you will be able to: 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 ...

  17. Python Basic Exercise for Beginners with Solutions

    Python essential exercise is to help Python beginners to quickly learn basic skills by solving the questions.When you complete each question, you get more familiar with a control structure, loops, string, and list in Python. ... This Python essential exercise is to help Python beginners to learn necessary Python skills quickly. Immerse yourself ...

  18. The Python Problem-Solver's Toolkit: 300 Hands-On Exercises

    Description. "The Python Problem-Solver's Toolkit: 300 Hands-On Exercises for Mastery" is a comprehensive and engaging course designed to empower learners with advanced Python programming skills and effective problem-solving techniques. Whether you are a beginner looking to dive into the world of coding or an experienced Python programmer ...

  19. Best Way to Solve Python Coding Questions

    In this tutorial, we learned that solving a Python problem using different methods can enhance our coding and problem-solving skills by broadening our knowledge base. We looked at an example python coding question and went through the steps of solving it. We first planned how we were going to solve it using pseudocode.

  20. Python Programming Bootcamp: Learn Python Through Problem Solving

    Learn the Core Python 3 Language at a Deep Level. Learn how to Solve Real Programming Problems with a Focus on Teaching Problem Solving Skills. Understand Python as an Object Oriented and Functional Programming Language. Create GUI Applications using TkInter, Kivy and soon PyQt. Create Applications that Utilize Databases

  21. Python Exercises for Beginners: Build Your Coding Foundation

    You may now have reached the apex of problem-solving in Python programming. Python Basic Level-3 Exercises. ... We have tried to cover a wide range of fundamental concepts and problem-solving techniques through these 40 Python exercises for beginners. These exercises included several topics such as string manipulation, sorting algorithms ...

  22. Problem Solving Strategies and Techniques using Python

    šŸŽØ Learn Problem Solving Strategies and Techniques using Python | Session-2 ļø Enroll Now: https://bit.ly/3xAUmxL to get started!šŸ‘‰Attend a Free Demo On Ful...

  23. python-problem-solving Ā· GitHub Topics Ā· GitHub

    Python Techniques, Experiments for problem solving, real world solutions. ... Add a description, image, and links to the python-problem-solving topic page so that developers can more easily learn about it. Curate this topic Add this topic to your repo To associate your repository with ...

  24. How to Solve Coding Problems with a Simple Four Step Method

    In this post, we've gone over the four-step problem-solving strategy for solving coding problems. Let's review them here: Step 1: understand the problem. Step 2: create a step-by-step plan for how you'll solve it. Step 3: carry out the plan and write the actual code.

  25. Mastering Python: 7 Strategies for Writing Clear, Organized, and

    Python provides support for type hinting in function declarations that serve as an annotation of the function argument types and the return types. Even though Python doesn't enforce these types during runtime , it's still helpful because it makes your code easier to understand for other people (and yourself!).

  26. Boost Your Coding Prowess with Problem-Solving Skills

    Testing is a critical step in the problem-solving process. In every language, from Python to C#, you need to verify that your code works as intended.

  27. Python for Kids: Boosting Creativity & Problem-Solving Skills

    Python is a popular, high-level programming language known for its simplicity and versatility, which makes it an excellent choice for beginners, including children. For parents and teachers who may not be familiar with coding, introducing children to Python offers an exciting opportunity to explore creativity and problem-solving skills.

  28. Programming with Python All in One

    - Showcase your problem-solving skills through coding - Gain confidence and experience as a Python programmer ā€” Join us on this journey to become a proficient Python developer and unlock the power of problem solving with code. Enroll now and transform the way you think about programming and problem solving! šŸ’»

  29. Commencement 2024: For biological sciences graduate, problem solving is

    For Alberto Paz, challenging himself to excel at problem solving is a way of life. "Most people don't know how hard I work, especially behind the scenes in research, setting things up to be successful. But I really like the freedom that challenges an evolutionary thought. You can't be complacent. I like things that are very difficult."