Python Problem-Solving Strategies
Python Problem-Solving Strategies
WITH PYTHON
► Course Code: UCEST105
► Course Type :Theory
► Teaching Hours/Week (L: T:P: R) 3:0:2:0
► Credits 4
► ESE Marks 60
► CIE Marks 40 Prepared by
SUMEERA K
GECK
Module-I
► PROBLEM-SOLVING STRATEGIES:- Problem-solving strategies defined,
Importance of understanding multiple problem-solving strategies, Trial and Error,
Heuristics, Means-Ends Analysis, and Backtracking (Working backward).
• A computer performs many tasks exactly in the same manner as it is told to do.
• This places responsibility on the user to instruct the computer in a correct and a
precise manner
• In order to instruct a computer correctly, the user must have a clear understanding
of the problem to be solved.
Problems can be categorized into two:
1. Well-defined Problems: That have specific goals, clear solutions and known
expected outcomes.
2. Ill-defined Problems: That lack clear goals, solution paths and expected
solutions.
Well-defined Problems Ill-defined Problems
1. Clear goals and Objectives Unclear and Vague goals and Objectives
Mathematical Equation:
■ Problem: Solve the equation 2x+3=7.
Crossword Puzzle:
■ Problem: Complete a standard crossword puzzle.
Recipe Execution:
■ Problem: Bake a chocolate cake using a provided recipe.
Ill-Defined Problems:
These problems are ambiguous, lack clear criteria for solutions, and often have multiple
possible solutions.
Writing a Novel:
■ Problem: Write a compelling novel that appeals to a broad audience.
Understanding the nature of the problem helps in choosing the right approach to
solving it
PROBLEM-SOLVING STRATEGIES
Efficiency: Some strategies are more effective for specific types of problems. Having a
repertoire of strategies can save time and resources.
•Improved Outcomes: Diverse strategies offer multiple perspectives and potential
solutions, increasing the likelihood of finding optimal solutions.
• There are several strategies you can use, each with its own method and application.
Below are some of the most common problem-solving strategies:
Heuristics: Heuristics are mental shortcuts or "rules of thumb" that simplify decision-
making and problem-solving. These strategies aim for quick, practical solutions that are
"good enough" rather than perfect.
Means-End Analysis: This strategy involves breaking down a problem into smaller,
manageable parts (means) and addressing each part to reduce the difference between the
current state and the goal state (end). It's useful for complex problems with clear goals.
Back tracking: Backtracking is used when solving problems that involve exploring multiple
options. If a chosen path doesn’t work, you backtrack to the previous step and try a different
approach, ensuring that all possibilities are considered.
1. Trial and Error
• A trial-and-error approach to problem-solving involves trying a number of
different solutions and ruling out those that do not work.
• This approach can be a good option if you have a very limited number of options
available.
• Using trial and error, one has to try different solutions until the problem is solved.
Steps :
1. In terms of a broken printer for example, one could try checking the ink levels, and
if that doesn’t work, you could check to make sure the paper tray isn’t jammed. Or
maybe the printer isn’t actually connected to a laptop.
2. say the problem is that your Wi-Fi isn’t working. You might try different things
until it starts working again, like restarting your modem or your devices until you
find or resolve the problem. When one solution isn’t successful, you try another
until you find what works.
3. If your child always stays up past their bedtime, you might try different solutions—
a visual clock to remind them of the time, a reward system, or gentle
punishments — to find a solution that works.
• Learning to Ride a Bicycle:
• Example: When learning to ride a bike, you might fall several times before figuring out
how to balance and steer properly. Each attempt helps you learn what works and what
doesn’t, leading to success.
• Solving a Puzzle:
• Example: If you’re putting together a jigsaw puzzle, you might try several pieces in a
spot before finding the one that fits. You test each piece until you find the correct one.
• Cooking Without a Recipe:
• Example: If you're cooking a dish without a recipe, you might experiment with adding
different amounts of spices or ingredients until you achieve the desired taste. You keep
adjusting based on the results of each attempt.
• Finding the Right Tool:
• Example: When assembling furniture, you might try several tools or screws to see
which one fits properly. You continue testing until you find the one that works.
Heuristics
• They are useful when a quick solution is needed, when the problem is complex, or
when full information is unavailable.
• While heuristics can lead to errors, they are often effective in everyday situations.
Characteristics of Heuristics:
•Speed: They provide quicker solutions by cutting down on the time and
effort needed.
Purpose: The goal is to find the correct solution by systematically exploring all
possibilities, while discarding paths that don’t work.
Steps in the Backtracking Method:
Identify the Problem and Constraints:
► Clearly understand the problem and any constraints (rules or limitations) that need to
be followed.
Start with an Initial Decision:
► Begin by making an initial choice or taking the first step in your solution process.
Explore Further:
► Move forward by making the next decision or taking the next step. Continue to build
your solution incrementally.
Check for Validity:
► After each step, check if the current path is valid and satisfies the problem’s
constraints. If it’s invalid, you need to backtrack.
•Backtrack if Necessary:
► If you reach a point where the current path doesn’t work, undo the last step (backtrack)
and try a different option. This might involve going back multiple steps until you find a
valid path.
•Continue Until Solution is Found:
► Repeat the process of exploring and backtracking until you either find a solution
that meets all the criteria or determine that no solution exists within the given
constraints.
When to Use the Backtracking Method
Puzzles and Games: In puzzles like Sudoku, N-Queens, or crosswords where you
need to place elements in a grid under certain constraints.
Decision-Making: In scenarios where each decision builds on the previous one, and
you need to ensure that each step is valid before proceeding.
Travel Planning: Planning a multi-city trip, backtracking to change a route if it’s not
feasible or too expensive.
MEANS-END ANALYSIS
Medical Treatment Plans: Doctors setting treatment milestones (e.g., reducing pain,
improving mobility) to achieve the final goal of full recovery.
Chess Strategy: Players determining the end goal (checkmate) and working
backward to create a sequence of moves to reach it.
Educational Goals: Students setting long-term goals (e.g., graduating) and breaking
them down into semester-wise targets and daily study plans.
Comparative Summary
Trial and Error:
Efficiency: Often inefficient due to the potentially large number of steps.
Best for: Simple problems or when no clear solution path is available.
Heuristics:
Efficiency: More efficient than Trial and Error but less reliable.
Best for: Quick decisions where perfect accuracy is not essential.
Backtracking:
Efficiency: Moderately efficient, especially in structured problems.
Best for: Problems where multiple paths can be explored and retracted, like puzzles
•Means-Ends Analysis:
• Efficiency: Generally efficient due to systematic problem breakdown.
• Best for: Complex problems that can be decomposed into smaller sub-problems with a
clear path to the goal.
Conclusion
► The efficiency of these problem-solving strategies varies based on the nature of the
problem:
Trial and Error can be the least efficient, with a potentially high number of
steps.
Heuristics are faster but may not always lead to the optimal solution.
Backtracking is efficient in structured environments where wrong paths can be
retraced.
Means-Ends Analysis is often the most efficient for complex, multi-step
problems.
► Understanding the problem type and applying the appropriate strategy will lead to
better problem-solving efficiency.
PROBLEM SOLVING PROCESS
• While this basic model works well for simple problems, more complex problems
often require multiple iterations of the input/process/output stages.
• These iterations produce intermediate results that help solve parts of the problem
before reaching the final solution.
• The essence of problem-solving lies in how we handle the "process" part of this
model. Therefore, understanding and mastering this stage is crucial.
Steps involved in problem solving
• Formulating a model
• Developing an algorithm
The first step in solving any problem is to ensure you fully understand it. This means
identifying the data provided, understanding what it represents, and knowing the
expected output.
Input: Some grades might be numerical (e.g., 85, 90) and others in letter form (e.g., A-,
C+).
Missing Data: Some students might not have grades due to absence.
Output: The result could be a number, letter grade, or graph.
To solve the problem, we must first understand the format of the grades .
The grades could be numbers ranging from 0 to 100 (e.g., 73 or 73.42), or they could be
letter grades like A to F. The format matters because different types of data (numbers vs.
letters) require different methods of calculation.
• We also need to address missing grades.
If a student doesn’t have a grade, how should we handle it?
For example, if a student was absent, do we: Include them with a grade of 0?
Exclude them from the average?
Once the problem is understood, the next step is to figure out how to process the
available data. This often involves breaking the problem into smaller, more manageable
parts and using mathematical formulas to get the desired result.
Formulating a model involves creating a formula or approach to process the input data.
This model helps us compute the result accurately. If no standard formula exists, we must
develop one.
The main point to understand this step in the problems solving process is that it is all
about figuring out how to make use of the available data to compute an answer.
s
Developing An Algorithm
● Next step is to develop a precise plan of what the computer is expected to do.
Algorithm
Step 1: Start
Step 2: Input the first number
Step 3: Input the second number
Step 4: Add the two numbers
Step 5: Display the result
Step 6: End
Pseudo code
1. Start
2. Input Number1
3. Input Number2
4. Sum=Number1 +Number2
5. Output Sum
6. End
Flowchart
Writing the Program
Once the algorithm is defined, the next step is to transform the algorithm into a set of
instructions that can be understood by the computer. Writing a program is often called
"coding" or “implementing an algorithm”.
Steps to Writing a Program
Compiling is the process of converting a program into instructions that can be understood
by the computer.
Sample Code :
print("Sum:", sum)
Testing the Program
Once a program has been written and compiled, the next critical step is to ensure that it
performs the intended task correctly.
Testing the program involves running it with various inputs to verify its accuracy and
reliability.
Running the Program: Running a program is the process of executing the compiled
code on a computer. If the program runs correctly, the expected output should be
displayed.
Testing for All Cases: It's possible that a program may work correctly for some inputs
but fail for others. Therefore, a program should be tested with a variety of input data to
cover all possible scenarios.
Handling Errors: If the output is incorrect,
it could be due to:
• The algorithm not being properly implemented in the program.
• A flaw in the algorithm itself, which does not account for certain situations.
• Bugs: : Bugs are errors in a program that cause it to produce incorrect or
undesirable results.
Debugging: Debugging is the process of finding and fixing errors (bugs) in the
program. It involves systematically testing different cases to locate the issues and
correcting them.
Evaluating The Solution
After a program produces results, it is important to evaluate those results in the context
of the original problem. This step ensures that the output is not only correct but also
meaningful and in the required format.
• Reconsider the Original Problem: Ensure the program’s output aligns with the
original problem and is in the correct format.
• Interpreting the Results: Present the results in a clear and meaningful way that aids
decision-making, using tools like charts if needed.
• Adjusting the Solution: If necessary, add more steps or data to fully solve the problem
or improve the solution’s effectiveness.
• Efficiency Considerations: Evaluate the program’s performance and make
improvements if it’s too slow or uses too many resources.
• User Responsibility: It’s up to the user or programmer to ensure the solution truly
solves the problem; further adjustments may be needed.
EXAMPLE:-The Discriminant calculator
D = b² - 4ac
3. Developing an algorithm:
STEP 1: Start
STEP 3: d = b∗b−4∗a∗c
STEP 5: Stop
4. Writing the program:
• Programming languages are used to write programs that are precise representations of
algorithms and control the behavior of a computer.
• Each language has a unique set of keywords (words that it understands) and syntax
(set of rules) to organize the program instructions.
1. Machine language:- is what the computer can understand, but it is difficult for the
programmer to understand. Machine languages consist of binary numbers only. No
translation of the program is needed and it can be executed very fast. It is machine-
dependent ie. A machine-level program written for one type of computer may not work
on another type.
• Assembly language:- falls in between machine language and high-level language. It is
similar to machine language, but easier to write code because it allows the
programmer to use symbolic names (like ADD, SUB) for operations called mnemonic
codes that are much easier to remember.
Machine languages and assembly languages are also called low level languages.
• High-level language:- is easier to understand and use for the programmer but difficult
for the computer. The programs written in high-level languages contain English-like
statements as well as programming. Eg:- C, Pascal, Java, Python etc. High level
language programs are easier to write, read, and understand. They are easily portable
from one computer to another, since they are not machine-dependent.
TRANSLATOR SOFTWARE
• The computer can understand only machine code (strings of 0’s and 1’s). Thus when
the program is written in other languages (assembly or high-level languages) has to
be converted to machine code. This conversion is called translation and is performed
by the translator software.
• The original program is called source code, and the translated code (object code) is
the target code.
• There are three types of translator software as discussed below:
1. Assembler : is a software that converts a program written in assembly language into
machine code.
2. Compiler : is a software that translates programs written in high-level language to
machine code.
3. Interpreter : The interpreter also converts the high-level language program into
machine code. However,it reads the source code line-by-line, converts it into machine
code, executes the line, and then proceeds to the next line.
Differentiate between Compiler and Interpreter.
Python: An Overview
● Data Science : Python libraries like Numpy, Pandas, and Matplotlib are used for data
analysis and visualization.
● Web Applications : Python frameworks like Django, and Pyramid, make the
development and deployment of Web Applications easy.
● Desktop GUI Applications
● Software Development
● Scientific and Numeric computations
● Business Applications
● Audio or Video based Applications.
Execution Modes
• To work in the interactive mode, we can simply type a Python statement on the >>>
prompt directly. As soon as we press enter, the interpreter executes the statement and
displays the result(s)
• Working in the interactive mode is convenient for testing a single line code for instant
execution. But in the interactive mode, we cannot save the statements for future use
and we have to retype the statements to run them again.
Script Mode
In the script mode, we can write a Python program in a file, save it and then use the
interpreter to execute it. Python scripts are saved as files where file name has extension
“.py”. By default, the Python scripts are saved in the Python installation folder. To
execute a script, we can either:
a) Type the file name along with the path at the prompt. For example, if the name of the
file is [Link], we type [Link]. We can otherwise open the program directly
from IDLE
b) While working in the script mode, after saving the file, click [Run]->[Run Module]
from the menu
Feature Interactive Mode Script Mode
Line by line, immediate Entire program executed from a
Execution
feedback file
Persistence Commands are not saved Code is saved in a file for reuse
Output for each line displayed Output displayed after entire script
Output
immediately execution
All the keywords except True, False and None are in lowercase and they must
be written as they are. The list of all the keywords is given below.
2. Identifiers
Just as identity refers to a characteristic that distinguishes a person, the same principle is a
python identifier, a token in python. In Python, an identifier is a name given to a Class,
Function, or Variable. It aids in distinguishing one entity from others.
i)Arithmetic Operators
It performs all the mathematical calculations. Here are a few of them:
•( + ) –Addition-Adds the two numeric values on either side of the operator
This operator can also be used to concatenate two strings on either side of the
operator
( – ) –Subtraction- Subtracts the operand on the right from the operand on the left
•(%)-Modulus- Divides the operand on the left by the operand on the right and returns
the remainder
•(//) Floor Division-Divides the operand on the left by the operand on the right and
returns the quotient by removing the decimal part. It is sometimes
also called integer division.
Relational operator compares the values of the operands on its either side and
determines the relationship among them.
Operator Operation Description
If the values of two operands are equal, then the condition is True,
== Equals to
otherwise it is False
If values of two operands are not equal, then condition is True,
!= Not equal to
otherwise it is False
If the value of the left-side operand is greater than the value of the
> Greater than
right side operand, then condition is True, otherwise it is False
If the value of the left-side operand is less than the value of the
< Less than
right side operand, then condition is True, otherwise it is False
If the value of the left-side operand is greater than or equal to the
Greater than
>= value of the right-side operand, then condition is True, otherwise it
or equal to
is False
Less than or If the value of the left operand is less than or equal to the value of
<=
equal to the right operand, then is True otherwise it is False
iii) Assignment Operators
Assignment operator assigns or changes the value of the variable on its left.
Operator Description
= Assigns value from right-side operand to left side operand
It adds the value of right-side operand to the left-side operand and
+= assigns the result to the left-side operand Note: x += y is same as x
=x+y
It subtracts the value of right-side operand from the left-side
-= operand and assigns the result to left-side operand Note: x -= y is
same as x = x - y
It multiplies the value of right-side operand with the value of left-
*= side operand and assigns the result to left-side operand Note: x *= y
is same as x = x * y
iv) Logical Operators
There are three logical operators supported by Python. These operators (and, or, not) are
to be written in lower case only. The logical operator evaluates to either True or
False based on the logical operands on either side. Every value is logically either
True or False.
Every value is logically either True or False. By default, all values are True except
None, False, 0 (zero), empty collections "", (), [], {}, and few other special values.
v) Membership Operators
Membership operators are used to check if a value is a member of the given sequence or
not.
Operator Description
Returns True if the variable/value is found in the specified sequence
in
and False otherwise
Returns True if the variable/value is not found in the specified
not in
sequence and False otherwise
Note:
• Parenthesis can be used to override the precedence of operators. The expression
within () is evaluated first.
• For operators with equal precedence, the expression is evaluated from left to right.
How will Python evaluate the following expression?
• 20 + 30 * 40
• 20 - 30 + 40
• (20 + 30) * 40
• 15.0 / 4 + (8 + 3.0)
4. Literals
Literals, tokens in Python, are data elements with a fixed value. Literals return a value
for an object of the specified type. Python supports a variety of literals:
•String Literals
•Numeric Literals. These are further of three types, integer, float, and complex literals.
•Boolean Literals
•Literal Collection
Lists, tuples, dictionaries, and sets are all examples of literal collections in Python.
5. Punctuators
Punctuators are tokens in python employed to put the grammar and structure of
syntax into practice. Punctuators are symbols that are used to structure programming
sentences in a computer language. Some commonly used punctuators are: ‘, ‘ ,#, \ ,( ) ,{
},[ ] ,@ ,: , =
VARIABLES
A variable in a program is uniquely identified by a name (identifier).Variables are
nothing but named reserved memory locations to store values. This means that when
you create a variable you reserve some space in memory.
• Based on the data type of a variable, the interpreter allocates memory and decides what
can be stored in the reserved memory.
• Therefore, by assigning different data types to variables, you can store integers, decimals
or characters in these variables.
Creating Variables In Python
• creating a variable is straightforward. You assign a value to a variable using the equal
sign =.
• Examples:
• age = 25
• name = "John"
• In the first line, age is a variable that stores the number 25.
• In the second line, name is a variable that stores the string "John".
• Python automatically detects the data type (number, string, etc.), so you don’t
have to declare the type.
Using Variables
For example:
print(age)
print(name)
Variables in Python are dynamic, meaning you can change their values after they are
created:
python
Copy code
age = 26
print(age)
There are some important rules to follow when naming variables in Python:
Name
Temp
my_variable
• Containing letters, numbers, and underscores (but not starting with a number):
age2 data_1
user_name
totalAmount
Illegal Variable Names
•Containing spaces:
my variable
• A data type in Python defines the type of value a variable can hold and
determines what operations can be performed on that data.
• It specifies whether the data is an integer, floating-point number, string, or
another type.
• Python is a dynamically-typed language, meaning you don't need to specify the data
type while declaring a variable; Python automatically assigns the data type
based on the value assigned
1. Number
Number data type stores numerical values only. It is further classified into three
different types: int, float and complex.
[Link] Data Type in Python
The boolean data type represents one of two values: True or False.
Boolean values are often used in conditional statements to control the flow of a
program based on whether a condition is true or false.
Boolean Values:
• True
• False
3. Sequence
A Python sequence is an ordered collection of items, where each item is indexed by
an integer. The three types of sequence data types available in Python are Strings, Lists
and Tuples.
We cannot perform numerical operations on strings, even when the string contains a
numeric value, as in str2
• Single-Line Strings: Can use single or double quotes for simple strings.
Example:
name = 'John' # String using single quotes
greeting = "Hello!" # String using double quotes
• Multi-Line Strings: Triple quotes are used for strings spanning multiple lines.
Example:
message = “““This is a
multi-line string.”””
• String Operations:
Concatenation: Joining strings together using the + operator.
full_name = "John" + " " + "Doe"
# Output: "John Doe“
Repetition: Repeating a string using the * operator.
repeated = "Hi! " * 3
# Output: "Hi! Hi! Hi! "
(B) List
List is a sequence of items separated by commas and the items are enclosed in square
brackets [ ]. Example
Tuple is a sequence of items separated by commas and items are enclosed in parenthesis
( ). This is unlike list, where values are enclosed in brackets [ ]. Once created, we
cannot change the tuple.
Example
#create a tuple
>>> tuple1 = (10, 20, "Apple", 3.4, 'a')
#print the elements of the tuple tuple1
>>> print(tuple1)
(10, 20, "Apple", 3.4, 'a')
4. Set
Set is an unordered collection of items separated by commas and the items are
enclosed in curly brackets { }. A set is similar to list, except that it cannot have
duplicate entries. Once created, elements of a set cannot be changed.
Example
#create a set
>>> set1 = {10,20,3.14,"New Delhi"}
>>> print(set1)
{10, 20, 3.14, "New Delhi"}
5. Mapping
Mapping is an unordered data type in Python. Currently, there is only one standard
mapping data type in Python called dictionary.
(A)Dictionary
Dictionary in Python holds data items in key-value pairs. Items in a dictionary are
enclosed in curly brackets { }. Dictionaries permit faster access to data. Every key is
separated from its value using a colon (:) sign. The key : value pairs of a dictionary can
be accessed using the key. The keys are usually strings and their values can be any data
type. In order to access any value in the dictionary, we have to specify its key in square
brackets [ ].
Example
#create a dictionary
>>> dict1 = {'Fruit':'Apple', 'Climate':'Cold', 'Price(kg)':120}
>>> print(dict1['Price(kg)'])
120
Type Conversion in Python (Type Casting)
Type conversion Type conversion refers to the process of converting the value of one
data type to another.
Python offers two types of type conversions
In programming, the use of function is one of the means to achieve modularity and
reusability. Function can be defined as a named group of instructions that
accomplish a specific task when it is invoked.
Types of functions
PYTHON STANDARD LIBRARY
Python has a very extensive standard library. It is a collection of many built in functions
that can be called in the program as and when required, thus saving programmer’s time
of creating those commonly used functions every time.
Built-in functions
Built-in functions are the ready-made functions in Python that are frequently used in
programs. Let us inspect the following Python program:
#Program to calculate square of a number
a = int(input("Enter a number: ")
b=a*a
print(" The square of ",a ,"is", b)
In the above program input(), int() and print() are the built-in functions. The set of
instructions to be executed for these built-in functions are already defined in the python
interpreter.
Two of the most commonly used built-in functions are the input() and print() functions
that are used for frequent input and output operations, respectively.
Python Input
To run an application, programmers often need to obtain input in Python from a user.
The simplest way to do this is to use the input() function. The function pauses program
execution to let the user type a line of information from the keyboard. When the user hits
“Enter”, the input is read and returned as a string.
EXAMPLES
>>>name = input ('What is your name?- ')
>>>print ('Hello,', name)
EXAMPLES
• >>>print(100)
100
• >>>num =65
>>>print ('The value of the number is', num)
[Link] name : math - It contains different types of mathematical functions. Most of the
functions in this module return a float value.
2. Module name : random - This module contains functions that are used for generating
random numbers.
3. Module name : statistics - This module provides functions for calculating statistics of
numeric (Real-valued) data.
VARIOUS FUNCTIONS IN MATH MODULE
[Link] the input "12345", write a Python code snippet to check if it is numeric.
[Link] college is located in a metropolitan city and you are new to that city. You would
like to go out for dinner with your friends. Explain how heuristics approach can be used to
find the best restaurant for dinner.
[Link] are asked to develop new campus management software for your college. How will
you apply Means-Ends Analysis to develop the software?
6. Given the area of a circle. Write a Python program to calculate the radius of the circle
using the math module.
[Link] the most suitable problem-solving strategies for the following use cases. Justify
your answer: i) You are solving a complex Sudoku puzzle and are unsure how to proceed
as you approach the final few cells. ii) You are tasked with planning a family trip that
involves selecting a destination, booking flights, and finding accommodation within a
budget.
9. Walk through the six problem-solving steps to calculate the area of a circle.
10. What are the basic data types in Python? Provide examples for each.
11. What is the difference between algorithms and heuristics in problem-solving? Provide
an example where heuristics lead to a faster solution than an algorithm.
12. Write a Python program to convert the time input in minutes to hours and minutes.
For example, 85 minutes is 1 hour 25 minutes.
result of the following expressions in Python