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
  • Seaborn with STREAMLIT
  • Dijkstra’s Algorithm in Python
  • 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

techniques of problem solving in python

How Do You Write a SELECT Statement in SQL?

techniques of problem solving in python

What Is a Foreign Key in SQL?

techniques of problem solving in python

Enumerate and Explain All the Basic Elements of an SQL Query

Mastering Algorithms for Problem Solving in Python

  • Runestone in social media: Follow @iRunestone Our Facebook Page
  • Table of Contents
  • Assignments
  • Peer Instruction (Instructor)
  • Peer Instruction (Student)
  • Change Course
  • Instructor's Page
  • Progress Page
  • Edit Profile
  • Change Password
  • Scratch ActiveCode
  • Scratch Activecode
  • Instructors Guide
  • About Runestone
  • Report A Problem
  • This Chapter
  • 1. Introduction' data-toggle="tooltip" >

Problem Solving with Algorithms and Data Structures using Python Âś

PythonDS Cover

By Brad Miller and David Ranum, Luther College

There is a wonderful collection of YouTube videos recorded by Gerry Jenkins to support all of the chapters in this text.

  • 1.1. Objectives
  • 1.2. Getting Started
  • 1.3. What Is Computer Science?
  • 1.4. What Is Programming?
  • 1.5. Why Study Data Structures and Abstract Data Types?
  • 1.6. Why Study Algorithms?
  • 1.7. Review of Basic Python
  • 1.8.1. Built-in Atomic Data Types
  • 1.8.2. Built-in Collection Data Types
  • 1.9.1. String Formatting
  • 1.10. Control Structures
  • 1.11. Exception Handling
  • 1.12. Defining Functions
  • 1.13.1. A Fraction Class
  • 1.13.2. Inheritance: Logic Gates and Circuits
  • 1.14. Summary
  • 1.15. Key Terms
  • 1.16. Discussion Questions
  • 1.17. Programming Exercises
  • 2.1.1. A Basic implementation of the MSDie class
  • 2.2. Making your Class Comparable
  • 3.1. Objectives
  • 3.2. What Is Algorithm Analysis?
  • 3.3. Big-O Notation
  • 3.4.1. Solution 1: Checking Off
  • 3.4.2. Solution 2: Sort and Compare
  • 3.4.3. Solution 3: Brute Force
  • 3.4.4. Solution 4: Count and Compare
  • 3.5. Performance of Python Data Structures
  • 3.7. Dictionaries
  • 3.8. Summary
  • 3.9. Key Terms
  • 3.10. Discussion Questions
  • 3.11. Programming Exercises
  • 4.1. Objectives
  • 4.2. What Are Linear Structures?
  • 4.3. What is a Stack?
  • 4.4. The Stack Abstract Data Type
  • 4.5. Implementing a Stack in Python
  • 4.6. Simple Balanced Parentheses
  • 4.7. Balanced Symbols (A General Case)
  • 4.8. Converting Decimal Numbers to Binary Numbers
  • 4.9.1. Conversion of Infix Expressions to Prefix and Postfix
  • 4.9.2. General Infix-to-Postfix Conversion
  • 4.9.3. Postfix Evaluation
  • 4.10. What Is a Queue?
  • 4.11. The Queue Abstract Data Type
  • 4.12. Implementing a Queue in Python
  • 4.13. Simulation: Hot Potato
  • 4.14.1. Main Simulation Steps
  • 4.14.2. Python Implementation
  • 4.14.3. Discussion
  • 4.15. What Is a Deque?
  • 4.16. The Deque Abstract Data Type
  • 4.17. Implementing a Deque in Python
  • 4.18. Palindrome-Checker
  • 4.19. Lists
  • 4.20. The Unordered List Abstract Data Type
  • 4.21.1. The Node Class
  • 4.21.2. The Unordered List Class
  • 4.22. The Ordered List Abstract Data Type
  • 4.23.1. Analysis of Linked Lists
  • 4.24. Summary
  • 4.25. Key Terms
  • 4.26. Discussion Questions
  • 4.27. Programming Exercises
  • 5.1. Objectives
  • 5.2. What Is Recursion?
  • 5.3. Calculating the Sum of a List of Numbers
  • 5.4. The Three Laws of Recursion
  • 5.5. Converting an Integer to a String in Any Base
  • 5.6. Stack Frames: Implementing Recursion
  • 5.7. Introduction: Visualizing Recursion
  • 5.8. Sierpinski Triangle
  • 5.9. Complex Recursive Problems
  • 5.10. Tower of Hanoi
  • 5.11. Exploring a Maze
  • 5.12. Dynamic Programming
  • 5.13. Summary
  • 5.14. Key Terms
  • 5.15. Discussion Questions
  • 5.16. Glossary
  • 5.17. Programming Exercises
  • 6.1. Objectives
  • 6.2. Searching
  • 6.3.1. Analysis of Sequential Search
  • 6.4.1. Analysis of Binary Search
  • 6.5.1. Hash Functions
  • 6.5.2. Collision Resolution
  • 6.5.3. Implementing the Map Abstract Data Type
  • 6.5.4. Analysis of Hashing
  • 6.6. Sorting
  • 6.7. The Bubble Sort
  • 6.8. The Selection Sort
  • 6.9. The Insertion Sort
  • 6.10. The Shell Sort
  • 6.11. The Merge Sort
  • 6.12. The Quick Sort
  • 6.13. Summary
  • 6.14. Key Terms
  • 6.15. Discussion Questions
  • 6.16. Programming Exercises
  • 7.1. Objectives
  • 7.2. Examples of Trees
  • 7.3. Vocabulary and Definitions
  • 7.4. List of Lists Representation
  • 7.5. Nodes and References
  • 7.6. Parse Tree
  • 7.7. Tree Traversals
  • 7.8. Priority Queues with Binary Heaps
  • 7.9. Binary Heap Operations
  • 7.10.1. The Structure Property
  • 7.10.2. The Heap Order Property
  • 7.10.3. Heap Operations
  • 7.11. Binary Search Trees
  • 7.12. Search Tree Operations
  • 7.13. Search Tree Implementation
  • 7.14. Search Tree Analysis
  • 7.15. Balanced Binary Search Trees
  • 7.16. AVL Tree Performance
  • 7.17. AVL Tree Implementation
  • 7.18. Summary of Map ADT Implementations
  • 7.19. Summary
  • 7.20. Key Terms
  • 7.21. Discussion Questions
  • 7.22. Programming Exercises
  • 8.1. Objectives
  • 8.2. Vocabulary and Definitions
  • 8.3. The Graph Abstract Data Type
  • 8.4. An Adjacency Matrix
  • 8.5. An Adjacency List
  • 8.6. Implementation
  • 8.7. The Word Ladder Problem
  • 8.8. Building the Word Ladder Graph
  • 8.9. Implementing Breadth First Search
  • 8.10. Breadth First Search Analysis
  • 8.11. The Knight’s Tour Problem
  • 8.12. Building the Knight’s Tour Graph
  • 8.13. Implementing Knight’s Tour
  • 8.14. Knight’s Tour Analysis
  • 8.15. General Depth First Search
  • 8.16. Depth First Search Analysis
  • 8.17. Topological Sorting
  • 8.18. Strongly Connected Components
  • 8.19. Shortest Path Problems
  • 8.20. Dijkstra’s Algorithm
  • 8.21. Analysis of Dijkstra’s Algorithm
  • 8.22. Prim’s Spanning Tree Algorithm
  • 8.23. Summary
  • 8.24. Key Terms
  • 8.25. Discussion Questions
  • 8.26. Programming Exercises

Acknowledgements Âś

We are very grateful to Franklin Beedle Publishers for allowing us to make this interactive textbook freely available. This online version is dedicated to the memory of our first editor, Jim Leisy, who wanted us to “change the world.”

Indices and tables Âś

Search Page

Creative Commons License

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.68%, find the runner-up score easy python (basic) max score: 10 success rate: 94.17%, 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

techniques of problem solving in python

Challenging Programming in Python: A Problem Solving Perspective

  • © 2024
  • Habib Izadkhah 0 ,
  • Rashid Behzadidoost 1

Department of Computer Science, University of Tabriz, Tabriz, Iran

You can also search for this author in PubMed   Google Scholar

  • Demonstrates with a lot of examples how to solve problems with Python
  • Provides an accessible introduction to Python
  • Presents challenging problems and its programming solutions from different areas of applied sciences

4507 Accesses

This is a preview of subscription content, log in via an institution to check access.

Access this book

  • Available as EPUB and PDF
  • Read on any device
  • Instant download
  • Own it forever
  • Durable hardcover edition
  • Dispatched in 3 to 5 business days
  • Free shipping worldwide - see info

Tax calculation will be finalised at checkout

Other ways to access

Licence this eBook for your library

Institutional subscriptions

Table of contents (8 chapters)

Front matter, introduction.

Habib Izadkhah, Rashid Behzadidoost

Python Basics

Miscellaneous problems.

  • Problem Solving with Phyton
  • Programming Language
  • Introduction to Phyton
  • Phyton Basics

About this book

This book aims to strengthen programming skills and foster creative thinking by presenting and solving 90 challenging problems. The book is intended for individuals with elementary, intermediate, and advanced Python programming skills who aspire to take their abilities to the next level. Additionally, the book is valuable for individuals interested in enhancing their creative thinking and logical reasoning skills. It is a self-instructional book meant to provide readers with the ability to solve challenging problems independently. The presented challenges are lucidly and succinctly expressed, facilitating readers to follow along and comprehend the problem-solving process. The challenges cover various fields, making it suitable for a wide range of individuals.

The book is divided into eight chapters, beginning with an introduction in chapter one. The second chapter presents essential Python basics for programming challenging problems, while the subsequent chapters focuson specific types of challenges. These include math-based challenges in chapter three, number-based challenges in chapter four, string-based challenges in chapter five, game-based challenges in chapter six, count-based challenges in chapter seven, and miscellaneous challenges in chapter eight. Each chapter comprises a set of challenges with examples, hints, algorithms, and Python code solutions. The target audience of the book includes computer science and engineering students, teachers, software developers, and participants in programming competitions.

Authors and Affiliations

About the authors.

Dr. Habib Izadkhah is an associate professor at the Department of Computer Science, University of Tabriz, Iran. He worked in the industry for a decade as a software engineer before becoming an academic. His research interests include algorithms and graphs, software engineering, and bioinformatics. More recently, he has been working on developing and applying deep learning to a variety of problems, dealing with biomedical images, speech recognition, text understanding, and generative models. He has contributed to various research projects, authored a number of research papers in international conferences, workshops, and journals, and also has written five books, including Source Code Modularization: Theory and Techniques from Springer and Deep Learning in Bioinformatics from Elsevier.

Rashid Behzadidoost is a Ph.D. candidate in Computer Science at the University of Tabriz, Iran. He is currently pursuing his doctoral degree in Computer Science, specializing in artificial intelligence and natural language processing. Rashid has a deep passion for coding and enjoys solving challenging problems. He has obtained his skills through years of study, practice, and teaching. He has taught several courses on computer sciences including challenging programming, microprocessor, and data structure at the University of Tabriz.

Bibliographic Information

Book Title : Challenging Programming in Python: A Problem Solving Perspective

Authors : Habib Izadkhah, Rashid Behzadidoost

DOI : https://doi.org/10.1007/978-3-031-39999-2

Publisher : Springer Cham

eBook Packages : Engineering , Engineering (R0)

Copyright Information : The Editor(s) (if applicable) and The Author(s), under exclusive license to Springer Nature Switzerland AG 2024

Hardcover ISBN : 978-3-031-39998-5 Published: 18 October 2023

Softcover ISBN : 978-3-031-40001-8 Due: 18 November 2023

eBook ISBN : 978-3-031-39999-2 Published: 17 October 2023

Edition Number : 1

Number of Pages : XI, 280

Number of Illustrations : 3 b/w illustrations, 7 illustrations in colour

Topics : Mathematical and Computational Engineering , Control, Robotics, Mechatronics , Professional Computing

  • Publish with us

Policies and ethics

  • Find a journal
  • Track your research
  • MapReduce Algorithm
  • Linear Programming using Pyomo
  • Networking and Professional Development for Machine Learning Careers in the USA
  • Predicting Employee Churn in Python
  • Airflow Operators

Machine Learning Geek

Solving Transportation Problem using Linear Programming in Python

Learn how to use Python PuLP to solve transportation problems using Linear Programming.

In this tutorial, we will broaden the horizon of linear programming problems. We will discuss the Transportation problem. It offers various applications involving the optimal transportation of goods. The transportation model is basically a minimization model.

The transportation problem is a type of Linear Programming problem. In this type of problem, the main objective is to transport goods from source warehouses to various destination locations at minimum cost. In order to solve such problems, we should have demand quantities, supply quantities, and the cost of shipping from source and destination. There are m sources or origin and n destinations, each represented by a node. The edges represent the routes linking the sources and the destinations.

techniques of problem solving in python

In this tutorial, we are going to cover the following topics:

Transportation Problem

The transportation models deal with a special type of linear programming problem in which the objective is to minimize the cost. Here, we have a homogeneous commodity that needs to be transferred from various origins or factories to different destinations or warehouses.

Types of Transportation problems

  • Balanced Transportation Problem :  In such type of problem, total supplies and demands are equal.
  • Unbalanced Transportation Problem : In such type of problem, total supplies and demands are not equal.

Methods for Solving Transportation Problem:

  • NorthWest Corner Method
  • Least Cost Method
  • Vogel’s Approximation Method (VAM)

Let’s see one example below. A company contacted the three warehouses to provide the raw material for their 3 projects.

techniques of problem solving in python

This constitutes the information needed to solve the problem. The next step is to organize the information into a solvable transportation problem.

Formulate Problem

Let’s first formulate the problem. first, we define the warehouse and its supplies, the project and its demands, and the cost matrix.

Initialize LP Model

In this step, we will import all the classes and functions of pulp module and create a Minimization LP problem using LpProblem class.

Define Decision Variable

In this step, we will define the decision variables. In our problem, we have various Route variables. Let’s create them using  LpVariable.dicts()  class.  LpVariable.dicts()  used with Python’s list comprehension.  LpVariable.dicts()  will take the following four values:

  • First, prefix name of what this variable represents.
  • Second is the list of all the variables.
  • Third is the lower bound on this variable.
  • Fourth variable is the upper bound.
  • Fourth is essentially the type of data (discrete or continuous). The options for the fourth parameter are  LpContinuous  or  LpInteger .

Let’s first create a list route for the route between warehouse and project site and create the decision variables using LpVariable.dicts() the method.

Define Objective Function

In this step, we will define the minimum objective function by adding it to the LpProblem  object. lpSum(vector)is used here to define multiple linear expressions. It also used list comprehension to add multiple variables.

In this code, we have summed up the two variables(full-time and part-time) list values in an additive fashion.

Define the Constraints

Here, we are adding two types of constraints: supply maximum constraints and demand minimum constraints. We have added the 4 constraints defined in the problem by adding them to the LpProblem  object.

Solve Model

In this step, we will solve the LP problem by calling solve() method. We can print the final value by using the following for loop.

From the above results, we can infer that Warehouse-A supplies the 300 units to Project -2. Warehouse-B supplies 150, 150, and 300 to respective project sites. And finally, Warehouse-C supplies 600 units to Project-3.

In this article, we have learned about Transportation problems, Problem Formulation, and implementation using the python PuLp library. We have solved the transportation problem using a Linear programming problem in Python. Of course, this is just a simple case study, we can add more constraints to it and make it more complicated. In upcoming articles, we will write more on different optimization problems such as transshipment problem, assignment problem, balanced diet problem. You can revise the basics of mathematical concepts in  this article  and learn about Linear Programming  in this article .

  • Solving Cargo Loading Problem using Integer Programming in Python
  • Solving Blending Problem in Python using Gurobi

You May Also Like

techniques of problem solving in python

Demystifying Mathematical Concepts for Deep Learning

techniques of problem solving in python

Agglomerative Clustering

techniques of problem solving in python

AdaBoost Classifier in Python

#May Motivation Use code MAY10 for extra 10% off

30-days Money-Back Guarantee

Programming and Problem Solving Using Python

Learn Python Programming from installation to application development

English [CC]

Lectures - 32

Duration - 8 hours

Training 5 or more people ?

Get your team access to 10000+ top Tutorials Point courses anytime, anywhere.

Course Description

This is Beginners Course, which helps you to understand Python programming language from scratch.

This course has comprehensive collection of

Theory & Programming videos

18 Online MCQ Tests, Notes as per SPPU

Theory Question Bank

Program Source Codes

Mini Projects and 

numerous coding problems

Why should I take this course?

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

Explained each and every point in very lucid and detailed way

when you complete our course you will be expert in python

Much useful for SPPU students struggling with PPS subject without having any knowledge of computer science

You can build your own logic to answer every question in exam without mugging up answers from the textbooks

What will you learn in this course:

Prime objective is to give students a basic introduction to programming and problem solving with computer language Python. And to introduce students not merely to the coding of computer programs, but to computational thinking, the methodology of computer programming, and the principles of good program design including modularity and encapsulation.

  • To understand problem solving, problem solving aspects, programming and to know about various program design tools.
  • To learn problem solving with computers
  • To learn basics, features and future of Python programming.
  • To acquaint with data types, input output statements, decision making, looping and functions in Python
  • To learn features of Object Oriented Programming using Python
  • To acquaint with the use and benefits of files handling in Python

Prerequisites

What are the prerequisites for this course?

No programming or knowledge of computer needed. You will learn everything you need to know

Programming and Problem Solving Using Python

Check out the detailed breakdown of what’s inside the course

Instructor Details

EnggTutes

Course Certificate

Use your certificate to make a career change or to advance in your current career.

sample Tutorialspoint certificate

Our students work with the Best

adobe logo

Related Video Courses

Annual membership.

Become a valued member of Tutorials Point and enjoy unlimited access to our vast library of top-rated Video Courses

Annual Membership

Online Certifications

Master prominent technologies at full length and become a valued certified professional.

Online Certifications

1800-202-0515

  • Python as a Calculator
  • String Operations
  • Print Statements
  • Review Questions

The Python REPL

Introduction.

In this chapter, you will learn how to write and run your first lines of Python code at the Python REPL also called the Python prompt. You will learn how to use Python as a calculator and be introduced to Python variables and Python's print() function. By the end of this chapter, you will be able to:

Open and close the Python REPL

Compute mathematical calculations using the Python REPL

Use the output from the Python REPL as input in another problem

Import the math and statistics modules from the Python Standard Library and use their functions

Assign values to variables

Use variables in calculations

Create strings

Combine and compare strings

Prompt Engineering

  • Latest Modern Advances in Prompt Engineering: A Comprehensive Guide

mm

Table Of Contents

techniques of problem solving in python

Prompt engineering , the art and science of crafting prompts that elicit desired responses from LLMs, has become a crucial area of research and development.

From enhancing reasoning capabilities to enabling seamless integration with external tools and programs, the latest advances in prompt engineering are unlocking new frontiers in artificial intelligence. In this comprehensive technical blog, we'll delve into the latest cutting-edge techniques and strategies that are shaping the future of prompt engineering.

Prompt Engineering

Advanced Prompting Strategies for Complex Problem-Solving

While CoT prompting has proven effective for many reasoning tasks, researchers have explored more advanced prompting strategies to tackle even more complex problems. One such approach is Least-to-Most Prompting, which breaks down a complex problem into smaller, more manageable sub-problems that are solved independently and then combined to reach the final solution.

Another innovative technique is the Tree of Thoughts (ToT) prompting, which allows the LLM to generate multiple lines of reasoning or “thoughts” in parallel, evaluate its own progress towards the solution, and backtrack or explore alternative paths as needed. This approach leverages search algorithms like breadth-first or depth-first search, enabling the LLM to engage in lookahead and backtracking during the problem-solving process.

Integrating LLMs with External Tools and Programs

While LLMs are incredibly powerful, they have inherent limitations, such as an inability to access up-to-date information or perform precise mathematical reasoning. To address these drawbacks, researchers have developed techniques that enable LLMs to seamlessly integrate with external tools and programs.

One notable example is Toolformer, which teaches LLMs to identify scenarios that require the use of external tools, specify which tool to use, provide relevant input, and incorporate the tool's output into the final response. This approach involves constructing a synthetic training dataset that demonstrates the proper use of various text-to-text APIs.

Another innovative framework, Chameleon, takes a “plug-and-play” approach, allowing a central LLM-based controller to generate natural language programs that compose and execute a wide range of tools, including LLMs, vision models, web search engines, and Python functions. This modular approach enables Chameleon to tackle complex, multimodal reasoning tasks by leveraging the strengths of different tools and models.

Fundamental Prompting Strategies

Zero-shot prompting.

Zero-shot prompting involves describing the task in the prompt and asking the model to solve it without any examples. For instance, to translate “cheese” to French, a zero-shot prompt might be:

This approach is straightforward but can be limited by the ambiguity of task descriptions.

Few-Shot Prompting

Few-shot prompting improves upon zero-shot by including several examples of the task. For example:

This method reduces ambiguity and provides a clearer guide for the model, leveraging the in-context learning abilities of LLMs.

Instruction Prompting

Instruction prompting explicitly describes the desired output, which is particularly effective with models trained to follow instructions. For example:

Models like GPT-4 have been specifically fine-tuned to follow such instructions accurately.

Advanced Prompting Techniques

Enhancing reasoning capabilities with chain-of-thought prompting.

One of the most significant breakthroughs in prompt engineering has been the development of Chain-of-Thought (CoT) prompting . This technique aims to elicit and improve the reasoning capabilities of LLMs by encouraging them to generate a step-by-step thought process or rationale before providing the final answer.

Left: Traditional methods of prompting LLMs rely on generic inputs (0-shot CoT) or necessitate labeled examples (few-shot CoT). Right: The novel approach prompts LLMs to self-create relevant examples prior to problem-solving, removing the need for labeling while customizing examples to each unique problem

Left: Traditional methods of prompting LLMs rely on generic inputs (0-shot CoT) or necessitate labeled examples (few-shot CoT). Right: The novel approach prompts LLMs to self-create relevant examples prior to problem-solving, removing the need for labeling while customizing examples to each unique problem

CoT prompting works by presenting the LLM with examples that include not only the input and output but also the intermediate reasoning steps or “chain of thought” that leads to the solution. By learning from these exemplars, the LLM can then generate its own chain of thought when presented with new problems, improving its ability to tackle complex reasoning tasks.

Input: Natalie has 3 apples, and she wants to share them equally with her 2 friends. How many apples will each person get? Chain of Thought: Okay, let's break this down step-by-step:

  • Natalie has 3 apples
  • She wants to share them equally with 2 friends
  • So there are 3 people in total (Natalie and her 2 friends)
  • To share the apples equally, we divide the total number of apples (3) by the number of people (3)
  • 3 divided by 3 is 1
  • Therefore, each person will get 1 apple. Output: Each person will get 1 apple.

By explicitly generating the reasoning process, LLMs like GPT-3 and Codex have demonstrated significant improvements in arithmetic, commonsense, and symbolic reasoning tasks.

Self-Consistency

Self-consistency improves the reliability of CoT prompting by generating multiple chains of thought and taking a majority vote on the final answer. This method mitigates the impact of any single incorrect reasoning path.

Least-to-Most Prompting

Least-to-most prompting breaks down complex problems into simpler sub-problems, solving each one sequentially and using the context of previous solutions to inform subsequent steps. This approach is beneficial for multi-step reasoning tasks.

Recent Advances in Prompt Engineering

Prompt engineering is evolving rapidly, and several innovative techniques have emerged to improve the performance of large language models (LLMs). Let's explore some of these cutting-edge methods in detail:

Auto-CoT (Automatic Chain-of-Thought Prompting)

What It Is: Auto-CoT is a method that automates the generation of reasoning chains for LLMs, eliminating the need for manually crafted examples. This technique uses zero-shot Chain-of-Thought (CoT) prompting, where the model is guided to think step-by-step to generate its reasoning chains.

How It Works:

  • Zero-Shot CoT Prompting: The model is given a simple prompt like “Let's think step by step” to encourage detailed reasoning.
  • Diversity in Demonstrations: Auto-CoT selects diverse questions and generates reasoning chains for these questions, ensuring a variety of problem types and reasoning patterns.

Advantages:

  • Automation: Reduces the manual effort required to create reasoning demonstrations.
  • Performance: On various benchmark reasoning tasks, Auto-CoT has matched or exceeded the performance of manual CoT prompting.

Complexity-Based Prompting

What It Is: This technique selects examples with the highest complexity (i.e., the most reasoning steps) to include in the prompt. It aims to improve the model's performance on tasks requiring multiple steps of reasoning.

  • Example Selection: Prompts are chosen based on the number of reasoning steps they contain.
  • Complexity-Based Consistency: During decoding, multiple reasoning chains are sampled, and the majority vote is taken from the most complex chains.
  • Improved Performance: Substantially better accuracy on multi-step reasoning tasks.
  • Robustness: Effective even under different prompt distributions and noisy data.

Progressive-Hint Prompting (PHP)

What It Is: PHP iteratively refines the model’s answers by using previously generated rationales as hints. This method leverages the model's previous responses to guide it toward the correct answer through multiple iterations.

  • Initial Answer: The model generates a base answer using a standard prompt.
  • Hints and Refinements: This base answer is then used as a hint in subsequent prompts to refine the answer.
  • Iterative Process: This process continues until the answer stabilizes over consecutive iterations.
  • Accuracy: Significant improvements in reasoning accuracy.
  • Efficiency: Reduces the number of sample paths needed, enhancing computational efficiency.

Decomposed Prompting (DecomP)

What It Is: DecomP breaks down complex tasks into simpler sub-tasks, each handled by a specific prompt or model. This modular approach allows for more effective handling of intricate problems.

  • Task Decomposition: The main problem is divided into simpler sub-tasks.
  • Sub-Task Handlers: Each sub-task is managed by a dedicated model or prompt.
  • Modular Integration: These handlers can be optimized, replaced, or combined as needed to solve the complex task.
  • Flexibility: Easy to debug and improve specific sub-tasks.
  • Scalability: Handles tasks with long contexts and complex sub-tasks effectively.

Hypotheses-to-Theories (HtT) Prompting

What It Is: HtT uses a scientific discovery process where the model generates and verifies hypotheses to solve complex problems. This method involves creating a rule library from verified hypotheses, which the model uses for reasoning.

  • Induction Stage: The model generates potential rules and verifies them against training examples.
  • Rule Library Creation: Verified rules are collected to form a rule library.
  • Deduction Stage: The model applies these rules to new problems, using the rule library to guide its reasoning.
  • Accuracy: Reduces the likelihood of errors by relying on a verified set of rules.
  • Transferability: The learned rules can be transferred across different models and problem forms.

Tool-Enhanced Prompting Techniques

Toolformer integrates LLMs with external tools via text-to-text APIs, allowing the model to use these tools to solve problems it otherwise couldn't. For example, an LLM could call a calculator API to perform arithmetic operations.

Chameleon uses a central LLM-based controller to generate a program that composes several tools to solve complex reasoning tasks. This approach leverages a broad set of tools, including vision models and web search engines, to enhance problem-solving capabilities.

GPT4Tools finetunes open-source LLMs to use multimodal tools via a self-instruct approach, demonstrating that even non-proprietary models can effectively leverage external tools for improved performance.

Gorilla and HuggingGPT

Both Gorilla and HuggingGPT integrate LLMs with specialized deep learning models available online. These systems use a retrieval-aware finetuning process and a planning and coordination approach, respectively, to solve complex tasks involving multiple models.

Program-Aided Language Models (PALs) and Programs of Thoughts (PoTs)

In addition to integrating with external tools, researchers have explored ways to enhance LLMs' problem-solving capabilities by combining natural language with programming constructs. Program-Aided Language Models (PALs) and Programs of Thoughts (PoTs) are two such approaches that leverage code to augment the LLM's reasoning process.

PALs prompt the LLM to generate a rationale that interleaves natural language with code (e.g., Python), which can then be executed to produce the final solution. This approach addresses a common failure case where LLMs generate correct reasoning but produce an incorrect final answer.

Similarly, PoTs employ a symbolic math library like SymPy, allowing the LLM to define mathematical symbols and expressions that can be combined and evaluated using SymPy's solve function. By delegating complex computations to a code interpreter, these techniques decouple reasoning from computation, enabling LLMs to tackle more intricate problems effectively.

Understanding and Leveraging Context Windows

LLMs' performance heavily relies on their ability to process and leverage the context provided in the prompt. Researchers have investigated how LLMs handle long contexts and the impact of irrelevant or distracting information on their outputs.

The “Lost in the Middle” phenomenon highlights how LLMs tend to pay more attention to information at the beginning and end of their context, while information in the middle is often overlooked or “lost.” This insight has implications for prompt engineering, as carefully positioning relevant information within the context can significantly impact performance.

Another line of research focuses on mitigating the detrimental effects of irrelevant context, which can severely degrade LLM performance. Techniques like self-consistency, explicit instructions to ignore irrelevant information, and including exemplars that demonstrate solving problems with irrelevant context can help LLMs learn to focus on the most pertinent information.

Improving Writing Capabilities with Prompting Strategies

While LLMs excel at generating human-like text, their writing capabilities can be further enhanced through specialized prompting strategies. One such technique is Skeleton-of-Thought (SoT) prompting, which aims to reduce the latency of sequential decoding by mimicking the human writing process.

SoT prompting involves prompting the LLM to generate a skeleton or outline of its answer first, followed by parallel API calls to fill in the details of each outline element. This approach not only improves inference latency but can also enhance writing quality by encouraging the LLM to plan and structure its output more effectively.

Another prompting strategy, Chain of Density (CoD) prompting, focuses on improving the information density of LLM-generated summaries. By iteratively adding entities into the summary while keeping the length fixed, CoD prompting allows users to explore the trade-off between conciseness and completeness, ultimately producing more informative and readable summaries.

Emerging Directions and Future Outlook

ChatGPT & Advanced Prompt Engineering

Advanced Prompt Engineering

The field of prompt engineering is rapidly evolving, with researchers continuously exploring new frontiers and pushing the boundaries of what's possible with LLMs. Some emerging directions include:

  • Active Prompting : Techniques that leverage uncertainty-based active learning principles to identify and annotate the most helpful exemplars for solving specific reasoning problems.
  • Multimodal Prompting : Extending prompting strategies to handle multimodal inputs that combine text, images, and other data modalities.
  • Automatic Prompt Generation: Developing optimization techniques to automatically generate effective prompts tailored to specific tasks or domains.
  • Interpretability and Explainability: Exploring prompting methods that improve the interpretability and explainability of LLM outputs, enabling better transparency and trust in their decision-making processes.

As LLMs continue to advance and find applications in various domains, prompt engineering will play a crucial role in unlocking their full potential. By leveraging the latest prompting techniques and strategies, researchers and practitioners can develop more powerful, reliable, and task-specific AI solutions that push the boundaries of what's possible with natural language processing.

The field of prompt engineering for large language models is rapidly evolving, with researchers continually pushing the boundaries of what's possible. From enhancing reasoning capabilities with techniques like Chain-of-Thought prompting to integrating LLMs with external tools and programs, the latest advances in prompt engineering are unlocking new frontiers in artificial intelligence.

techniques of problem solving in python

What is Chain-of-Thought (CoT) Prompting? Examples & Benefits

mm

I have spent the past five years immersing myself in the fascinating world of Machine Learning and Deep Learning. My passion and expertise have led me to contribute to over 50 diverse software engineering projects, with a particular focus on AI/ML. My ongoing curiosity has also drawn me toward Natural Language Processing, a field I am eager to explore further.

You may like

techniques of problem solving in python

Unveiling ChatGPT-4o: Next-Gen Features and Their Transformative Impact

Decoder-Based Large Language Models: A Complete Guide

Decoder-Based Large Language Models: A Complete Guide

Meta Llama 3 open source LLM OUTPERFORM GPT 4

Everything You Need to Know About Llama 3 | Most Powerful Open-Source Model Yet | Concepts to Usage

BlackMamba: Mixture of Experts for State-Space Models

BlackMamba: Mixture of Experts for State-Space Models

techniques of problem solving in python

A Full Guide to Fine-Tuning Large Language Models

techniques of problem solving in python

Recent Posts

  • Banking on AI: Fraud Detection, Credit Risk Analysis, and the Future of Financial Services
  • 5 Best Affiliate Networks to Launch AI & SaaS Affiliate Programs
  • UltaHost Review – Outstanding Performance and Protection
  • Could “Robot-Phobia” Worsen the Hospitality Industry’s Labor Shortage?
  • Share full article

Advertisement

Supported by

The Algebra Problem: How Middle School Math Became a National Flashpoint

Top students can benefit greatly by being offered the subject early. But many districts offer few Black and Latino eighth graders a chance to study it.

The arms of a student are seen leaning on a desk. One hand holds a pencil and works on algebra equations.

By Troy Closson

From suburbs in the Northeast to major cities on the West Coast, a surprising subject is prompting ballot measures, lawsuits and bitter fights among parents: algebra.

Students have been required for decades to learn to solve for the variable x, and to find the slope of a line. Most complete the course in their first year of high school. But top-achievers are sometimes allowed to enroll earlier, typically in eighth grade.

The dual pathways inspire some of the most fiery debates over equity and academic opportunity in American education.

Do bias and inequality keep Black and Latino children off the fast track? Should middle schools eliminate algebra to level the playing field? What if standout pupils lose the chance to challenge themselves?

The questions are so fraught because algebra functions as a crucial crossroads in the education system. Students who fail it are far less likely to graduate. Those who take it early can take calculus by 12th grade, giving them a potential edge when applying to elite universities and lifting them toward society’s most high-status and lucrative professions.

But racial and economic gaps in math achievement are wide in the United States, and grew wider during the pandemic. In some states, nearly four in five poor children do not meet math standards.

To close those gaps, New York City’s previous mayor, Bill de Blasio, adopted a goal embraced by many districts elsewhere. Every middle school would offer algebra, and principals could opt to enroll all of their eighth graders in the class. San Francisco took an opposite approach: If some children could not reach algebra by middle school, no one would be allowed to take it.

The central mission in both cities was to help disadvantaged students. But solving the algebra dilemma can be more complex than solving the quadratic formula.

New York’s dream of “algebra for all” was never fully realized, and Mayor Eric Adams’s administration changed the goal to improving outcomes for ninth graders taking algebra. In San Francisco, dismantling middle-school algebra did little to end racial inequities among students in advanced math classes. After a huge public outcry, the district decided to reverse course.

“You wouldn’t think that there could be a more boring topic in the world,” said Thurston Domina, a professor at the University of North Carolina. “And yet, it’s this place of incredibly high passions.”

“Things run hot,” he said.

In some cities, disputes over algebra have been so intense that parents have sued school districts, protested outside mayors’ offices and campaigned for the ouster of school board members.

Teaching math in middle school is a challenge for educators in part because that is when the material becomes more complex, with students moving from multiplication tables to equations and abstract concepts. Students who have not mastered the basic skills can quickly become lost, and it can be difficult for them to catch up.

Many school districts have traditionally responded to divergent achievement levels by simply separating children into distinct pathways, placing some in general math classes while offering others algebra as an accelerated option. Such sorting, known as tracking, appeals to parents who want their children to reach advanced math as quickly as possible.

But tracking has cast an uncomfortable spotlight on inequality. Around a quarter of all students in the United States take algebra in middle school. But only about 12 percent of Black and Latino eighth graders do, compared with roughly 24 percent of white pupils, a federal report found .

“That’s why middle school math is this flashpoint,” said Joshua Goodman, an associate professor of education and economics at Boston University. “It’s the first moment where you potentially make it very obvious and explicit that there are knowledge gaps opening up.”

In the decades-long war over math, San Francisco has emerged as a prominent battleground.

California once required that all eighth graders take algebra. But lower-performing middle school students often struggle when forced to enroll in the class, research shows. San Francisco later stopped offering the class in eighth grade. But the ban did little to close achievement gaps in more advanced math classes, recent research has found.

As the pendulum swung, the only constant was anger. Leading Bay Area academics disparaged one another’s research . A group of parents even sued the district last spring. “Denying students the opportunity to skip ahead in math when their intellectual ability clearly allows for it greatly harms their potential for future achievement,” their lawsuit said.

The city is now back to where it began: Middle school algebra — for some, not necessarily for all — will return in August. The experience underscored how every approach carries risks.

“Schools really don’t know what to do,” said Jon R. Star, an educational psychologist at Harvard who has studied algebra education. “And it’s just leading to a lot of tension.”

In Cambridge, Mass., the school district phased out middle school algebra before the pandemic. But some argued that the move had backfired: Families who could afford to simply paid for their children to take accelerated math outside of school.

“It’s the worst of all possible worlds for equity,” Jacob Barandes, a Cambridge parent, said at a school board meeting.

Elsewhere, many students lack options to take the class early: One of Philadelphia’s most prestigious high schools requires students to pass algebra before enrolling, preventing many low-income children from applying because they attend middle schools that do not offer the class.

In New York, Mr. de Blasio sought to tackle the disparities when he announced a plan in 2015 to offer algebra — but not require it — in all of the city’s middle schools. More than 15,000 eighth graders did not have the class at their schools at the time.

Since then, the number of middle schools that offer algebra has risen to about 80 percent from 60 percent. But white and Asian American students still pass state algebra tests at higher rates than their peers.

The city’s current schools chancellor, David Banks, also shifted the system’s algebra focus to high schools, requiring the same ninth-grade curriculum at many schools in a move that has won both support and backlash from educators.

And some New York City families are still worried about middle school. A group of parent leaders in Manhattan recently asked the district to create more accelerated math options before high school, saying that many young students must seek out higher-level instruction outside the public school system.

In a vast district like New York — where some schools are filled with children from well-off families and others mainly educate homeless children — the challenge in math education can be that “incredible diversity,” said Pedro A. Noguera, the dean of the University of Southern California’s Rossier School of Education.

“You have some kids who are ready for algebra in fourth grade, and they should not be denied it,” Mr. Noguera said. “Others are still struggling with arithmetic in high school, and they need support.”

Many schools are unequipped to teach children with disparate math skills in a single classroom. Some educators lack the training they need to help students who have fallen behind, while also challenging those working at grade level or beyond.

Some schools have tried to find ways to tackle the issue on their own. KIPP charter schools in New York have added an additional half-hour of math time to many students’ schedules, to give children more time for practice and support so they can be ready for algebra by eighth grade.

At Middle School 50 in Brooklyn, where all eighth graders take algebra, teachers rewrote lesson plans for sixth- and seventh-grade students to lay the groundwork for the class.

The school’s principal, Ben Honoroff, said he expected that some students would have to retake the class in high school. But after starting a small algebra pilot program a few years ago, he came to believe that exposing children early could benefit everyone — as long as students came into it well prepared.

Looking around at the students who were not enrolling in the class, Mr. Honoroff said, “we asked, ‘Are there other kids that would excel in this?’”

“The answer was 100 percent, yes,” he added. “That was not something that I could live with.”

Troy Closson reports on K-12 schools in New York City for The Times. More about Troy Closson

IMAGES

  1. Problem Solving using Python

    techniques of problem solving in python

  2. How to solve a problem in Python

    techniques of problem solving in python

  3. learn problem solving with python

    techniques of problem solving in python

  4. Exploring Problem Solving with Python and Jupyter Notebook #1

    techniques of problem solving in python

  5. Best Python Real Life Problem Solving Project #Python

    techniques of problem solving in python

  6. PROBLEM SOLVING IN PYTHON

    techniques of problem solving in python

VIDEO

  1. Problem Solving Using Python Programming

  2. Solving a Python problem!

  3. The Process of Computational problem solving

  4. Python Problem Solving Class 2 (List)

  5. Problem solving & python programming important questions from AU question papers

  6. Python Problem solving Question #technologies #leetcode #hackerrank #python3 #problemsolving

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

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

    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.

  4. Python Basics: Problem Solving with Code

    In this course you will see how to author more complex ideas and capabilities in Python. In technical terms, you will learn dictionaries and how to work with them and nest them, functions, refactoring, and debugging, all of which are also thinking tools for the art of problem solving.

  5. Hands-On Linear Programming: Optimization With Python

    In this tutorial, you'll learn about implementing optimization in Python with linear programming libraries. Linear programming is one of the fundamental mathematical optimization techniques. You'll use SciPy and PuLP to solve linear programming problems.

  6. Introduction

    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.

  7. 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 of what algorithms are, with topics ranging from ...

  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. Problem Solving with Algorithms and Data Structures using Python

    An interactive version of Problem Solving with Algorithms and Data Structures using Python.

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

  11. Python Exercises, Practice, Challenges

    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.

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

    Are you a Python developer brushing up on your skills before an interview? If so, then this tutorial will usher you through a series of Python practice problems meant to simulate common coding test scenarios.

  13. Problem Solving with Python

    Website companion for the book Problem Solving with Python by Peter D. Kazarinoff

  14. PDF Introduction to Problem Solving and Programming in Python

    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.

  15. PDF Introduction to Problem Solving

    Problem solving is a process of transforming the description of a problem into the solution of that problem by using our knowledge of the problem domain and by relying on our ability to select and use appropriate problem-solving Strategies, Techniques and Tools.

  16. Solve Python

    Join over 23 million developers in solving code challenges on HackerRank, one of the best ways to prepare for programming interviews.

  17. Challenging Programming in Python: A Problem Solving Perspective

    This book aims to strengthen programming skills and foster creative thinking by presenting and solving 90 challenging problems. The book is intended for individuals with elementary, intermediate, and advanced Python programming skills who aspire to take their abilities to the next level. Additionally, the book is valuable for individuals ...

  18. Solving Transportation Problem using Linear Programming in Python

    The transportation problem is a type of Linear Programming problem. In this type of problem, the main objective is to transport goods from source warehouses to various destination locations at minimum cost. In order to solve such problems, we should have demand quantities, supply quantities, and the cost of shipping from source and destination.

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

  20. Programming and Problem Solving Using Python

    Prime objective is to give students a basic introduction to programming and problem solving with computer language Python. And to introduce students not merely to the coding of computer programs, but to computational thinking, the methodology of computer programming, and the principles of good program design including modularity and encapsulation.

  21. Python Basic Exercise for Beginners

    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.

  22. Introduction

    Introduction. In this chapter, you will learn how to write and run your first lines of Python code at the Python REPL also called the Python prompt. You will learn how to use Python as a calculator and be introduced to Python variables and Python's print() function. By the end of this chapter, you will be able to: Open and close the Python REPL.

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

    Creating a separate but related problem can be a very effective technique in problem solving. It is particularly relevant where you have expertise/resources/skills in a particular area and want to exploit this. By re-imagining the problem aligned to this area of expertise you can better exploit it to solve the problem.

  24. Mastering Optimization Techniques with Python: Enhancing ...

    Optimization techniques and tools, often powered by mathematical models and algorithms, provide a structured approach to decision-making. Python, with its rich ecosystem of libraries and packages ...

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

    In this article, I will be sharing 7 tips that I use in my production code for clearer and more organized code. 1. Type Hinting and Annotations. Python is a dynamically typed programming language, where the variable types are inferred at runtime.

  26. Latest Modern Advances in Prompt Engineering: A Comprehensive Guide

    From enhancing reasoning capabilities to enabling seamless integration with external tools and programs, the latest advances in prompt engineering are unlocking new frontiers in artificial intelligence. In this comprehensive technical blog, we'll delve into the latest cutting-edge techniques and strategies that are shaping the future of prompt engineering.

  27. Problem Solving, Python Programming, and Video Games

    Learn Problem Solving, Python Programming, and Video Games course/program online & get a Certificate on course completion from University of Alberta. Get fee details, duration and read reviews of Problem Solving, Python Programming, and Video Games program @ Shiksha Online.

  28. The Algebra Problem: How Middle School Math Became a National

    The central mission in both cities was to help disadvantaged students. But solving the algebra dilemma can be more complex than solving the quadratic formula.