0% found this document useful (0 votes)
3 views

Module_-1[1] python ktu

The document discusses various problem-solving strategies, emphasizing the importance of understanding multiple approaches such as trial and error, heuristics, means-ends analysis, and backtracking. It outlines the problem-solving process, including defining the problem, brainstorming solutions, evaluating options, implementing solutions, and monitoring results. Additionally, it covers algorithmic problem-solving with computers, detailing the role of computers in processing data and formulating solutions.

Uploaded by

davidsicilian70
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Module_-1[1] python ktu

The document discusses various problem-solving strategies, emphasizing the importance of understanding multiple approaches such as trial and error, heuristics, means-ends analysis, and backtracking. It outlines the problem-solving process, including defining the problem, brainstorming solutions, evaluating options, implementing solutions, and monitoring results. Additionally, it covers algorithmic problem-solving with computers, detailing the role of computers in processing data and formulating solutions.

Uploaded by

davidsicilian70
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

MODULE - 01

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

THE PROBLEM-SOLVING PROCESS:- Computer as a model of computation, Understanding the problem,


Formulating a model, Developing an algorithm, Writing the program, Testing the program, and Evaluating the
solution.

ESSENTIALS OF PYTHON PROGRAMMING:- Creating and using variables in Python, Numeric and String
data types in Python, Using the math module, Using the Python Standard Library for handling basic I/O - print,
input, Python operators and their precedence.

PROBLEM

A problem is a situation or issue that presents a challenge or difficulty that needs to be resolved. It
often involves a gap between the current state and a desired state, requiring analysis, decision-making,
and action to find a solution. Problems can be simple or complex, ranging from everyday dilemmas to
significant societal issues.

PROBLEM SOLVING

Problem-solving is the process of finding solutions to challenges. These challenges can be simple or
complex, requiring us to identify the issue, brainstorm solutions, and apply the best strategy.

STEPS TO EFFECTIVE PROBLEM SOLVING

1. Define the Problem: Clearly articulate what the issue is. Identify the root cause and the impact it has. This
step often involves gathering information and understanding the context.
2. Brainstorm Possible Solutions: Generate a variety of ideas without judgment. Encourage creative thinking
and consider all potential solutions, no matter how unconventional.
3. Evaluate the Solutions: Assess the feasibility, pros, and cons of each option. Consider factors like resources,
time, and potential outcomes to determine the most viable solutions.
4. Implement the Solution: Put the chosen solution into action. Develop a plan, assign responsibilities, and
communicate effectively with all stakeholders involved.
5. Monitor & Adjust: After implementation, track the results to see if the problem is resolved. Be prepared to
make adjustments as necessary based on feedback and outcomes.
PROBLEM SOLVING STRATEGIES

Problem-solving strategies are plans of action to find solutions. There are various strategies, each with
its own method and application.

1. Trial and Error: This involves trying multiple solutions until the problem is resolved.
2. Heuristics :These are mental shortcuts that simplify decision-making and problem-solving.
3. Means-Ends Analysis ;This strategy involves breaking down a problem into smaller, more
manageable sub-problems.
4. Backtracking : This strategy involves starting with the desired outcome and working backward to
the current state

1. Trial And Error Problem-Solving Strategy


ü The trial-and-error problem-solving strategy involves attempting different solutions and learning
from mistakes until a successful outcome is achieved.
ü It is a fundamental method that relies on experimentation and iteration, rather than systematic
or analytical approaches.

ü Consider the situation where you have forgotten the password to your online account, and there
is no password recovery option available.
ü You decide to use trial and error to regain access:
1. Initial Attempts: You start by trying passwords you commonly use. For instance, you might
first try ”password123,” ”Qwerty2024,” or ”MyDog-Tommy.”
2. Learning from Mistakes: None of these initial attempts work. You then recall that you
sometimes use a combination of personal information. You try variations incorporating your
birthdate, pet’s name, or favorite sports team.
3. Refinement: After several failed attempts, you remember you recently started using a new
format for your passwords, combining a favorite quote with special characters. You attempted
various combinations, such as”ToBeOrNotToBe!”, ”NeeNeeyaayirikkuka#,” and other
combinations.
4. Success: Eventually, through persistent trial and error, you hit upon the correct password:
”NeeNeeyaayirikkuka#2024.”
In this scenario, trial and error involved systematically trying different potential passwords, learning
from each failed attempt, and refining the approach based on what you remember about your password
habits. This method is practical when there is no clear pathway to the solution and allows for
discovering the correct answer through persistence and adaptability.

2. Heuristic Problem-Solving Strategy


ü A heuristic is a practical approach to problem-solving based on experience and intuition.
ü It does not guarantee a perfect solution but provides a good enough solution quickly, often
through rules of thumb or educated guesses.
ü When driving in a city with frequent traffic congestion, you might use a heuristic approach to
find the fastest route to your destination:
1. Rule of Thumb: You know from experience that certain streets are typically less congested during
rush hour.
2. Current Conditions: You use a traffic app to check current traffic conditions, looking for red or
yellow indicators on major roads.
3. Alternative Routes: You consider side streets and shortcuts you have used before that tend to be
less busy.
4. Decision: Based on the app and your knowledge, you decide to avoid the main highway (which
shows heavy congestion) and take a series of back roads that usually have lighter traffic.

While this heuristic approach does not guarantee that you will find the absolute fastest route, it
combines your experience and real-time data to make an informed, efficient decision, likely saving
you time compared to blindly following the main routes.
3. Means-Ends Analysis Problem-Solving Strategy
Means-ends analysis is a strategy that involves breaking down a problem into smaller, manageable
parts (means) and addressing each part to achieve the final goal (ends). It involves identifying the
current state, the desired end state, and the steps needed to bridge the gap between the two. Imagine
you want to plan a road trip from Trivandrum to Kashmir. Here is how you might use means-ends
analysis.
o Define the Goal: Your ultimate goal is to drive from Trivandrum to Kashmir.
o Analyze the Current State: You start in Trivandrum with your car ready to go.
o Identify the Differences: The primary difference is the distance between Trivandrum and
Kashmir, which is approximately 3,700 kilometers.
o Set Sub-Goals (Means):
• Fuel and Rest Stops: Determine where you will need to stop for fuel and rest.
• Daily Driving Targets: Break the trip into daily segments, such as driving 500-600
kilometers per day.
• Route Planning: Choose the most efficient and scenic route, considering highways,
weather conditions, and places you want to visit.
o Implement the Plan:
§ Day 1: Drive from Trivandrum to Bangalore, Karnataka (approx.720 km). Refuel in Madurai,
Tamil Nadu. Overnight stay in Bangalore.
§ Day 2: Drive from Bangalore to Hyderabad, Telangana (approx.570 km). Refuel in Anantapur,
Andhra Pradesh. Overnight stay inHyderabad.
§ Day 3: Drive from Hyderabad to Nagpur, Maharashtra (approx. 500km). Refuel in Adilabad,
Telangana. Overnight stay in Nagpur.
§ Day 4: Drive from Nagpur to Jhansi, Uttar Pradesh (approx. 580km). Refuel in Sagar, Madhya
Pradesh. Overnight stay in Jhansi.
§ Day 5: Drive from Jhansi to Agra, Uttar Pradesh (approx. 290 km).Refuel in Gwalior, Madhya
Pradesh. Overnight stay in Agra. Visit the Taj Mahal.
§ Day 6: Drive from Agra to Chandigarh (approx. 450 km). Refuel in Karnal, Haryana. Overnight
stay in Chandigarh.
§ Day 7: Drive from Chandigarh to Jammu (approx. 350 km). Refuel in Pathankot, Punjab.
Overnight stay in Jammu.
§ Day 8: Drive from Jammu to Srinagar, Kashmir (approx. 270 km).
o Adjust as Needed:
Throughout the trip, you may need to make adjustments based on traffic, road conditions, or personal
preferences. By breaking down the long journey into smaller, achievable segments and ad-dressing
each part systematically, you can effectively plan and complete the road trip. This method ensures
that you stay on track and make steady progress to-ward your final destination, despite the
complexity and distance of the trip.
Importance of Understanding Multiple Problem-Solving Strategies
ü Adaptability: Different problems require different approaches. Under-standing multiple strategies
allows for flexibility and adaptability in problem-solving.
ü 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.
ü Skill Development: Exposure to various strategies enhances cognitive
skills, critical thinking, and creativity.

Problem decomposition
In the previous example of traveling from Trivandrum to Kashmir, breaking down the journey into
smaller segments helped you come up with an effective plan for the completion of the trip. This is the
key to solving complex problems. When the problem to be solved is too complex to manage, break it
into manageable parts known as sub-problems. This process is known as problem decomposition. Here
are the steps in solving a problem using the decomposition approach:
1. Understand the problem: Develop a thorough understanding of the problem.
2. Identify the sub-problems: Decompose the problems into smaller parts.
3. Solving the sub-problems: Once decomposition is done, you proceed to solve the individual sub-
problems. You may have to decide upon the order in which the various sub-problems are to be
solved.
4. Combine the solution: Once all the sub-problems have been solved, you should combine all those
solutions to form the solution for the original problem.
5. Test the combined solution: Finally you ensure that the combined solution indeed solves the
problem effectively.
Other Problem-solving Strategies
Here are some examples of problem-solving strategies that may equally be adopted to see which works
best for you in different situations:
i. Brainstorming
Brainstorming involves generating a wide range of ideas and solutions to a problem without
immediately judging or analyzing them. The goal is to encourage creative thinking and explore various
possibilities. In a team meeting to improve customer satisfaction, everyone contributes different ideas,
such as enhancing product quality, improving customer service training, offering loyalty programs, and
using customer feedback to make improvements. These ideas are later evaluated and the best ones are
implemented.

ii. Lateral Thinking


Lateral thinking is about looking at problems from new and unconventional angles. It involves thinking
outside the box and challenging established patterns and assumptions.A company facing declining sales
of a product might use lateral thinking to identify new uses for the product or new markets to target,
rather than just trying to improve the existing product or marketing strategy.

iii.Root Cause Analysis


Root cause analysis involves identifying the fundamental cause of a problem rather than just addressing
its symptoms. The goal is to prevent the problem from recurring by solving its underlying issues. If a
factory’s production line frequently breaks down, rather than just repairing the machinery each time,
the team conducts a root cause analysis and discovers that poor maintenance scheduling is the
underlying issue. By implementing a better maintenance plan, they reduce the breakdowns.

iv. Mind Mapping


Mind mapping is a visual tool for organizing information. It helps in brainstorming, understanding, and
solving problems by visually connecting ideas and concepts. When planning a large event, an organizer
creates a mind map with the event at the center, branching out into categories like venue, catering,
entertainment, invitations, and logistics. Each category further branches into specific tasks and
considerations.

v. SWOT Analysis
SWOT analysis involves evaluating the Strengths, Weaknesses, Opportunities, and Threats related to a
particular problem or decision. It helps in understanding both internal and external factors that impact
the situation.
A business firm considering a new product launch performs a SWOT analysis. They identify their
strengths (strong brand, good distribution network), weaknesses (limited R&D budget), opportunities
(market demand, potential partnerships), and threats (competition, economic downturn).
This analysis guides their decision-making process.
vi. Decision Matrix
A decision matrix, also known as a decision grid or Pugh matrix, helps in evaluating and prioritizing a
list of options. It involves listing options and criteria, assigning weights to each criterion, and scoring
each option based on the criteria. A family deciding on a new car creates a decision matrix with criteria
such as cost, fuel efficiency, safety features, and brand reputation. They rate each car option against
these criteria and calculate a total score to make an informed choice.

vii. Simulation
Simulation involves creating a model of a real-world system and experimenting with it to understand
how the system behaves under different conditions. It helps in predicting outcomes and identifying the
best course of action. Urban planners use traffic simulation software to model the impact of new road
constructions on traffic flow. By testing different scenarios, they can design the most effective road
network to reduce congestion.

Algorithmic problem solving with computers


In today’s digital era, the computer has become an indispensable part of our life. Down from performing
simple arithmetic right up to accurately determining the position for a soft lunar landing, we rely heavily
on computers and allied digital devices. Computers are potent tools for solving problems across diverse
disciplines. Problem-solving is a systematic way to arrive at solutions for a given problem.
Computer as a model of computation
A computer is an electronic device that processes data according to programmed instructions. It
performs essential functions such as input (receiving data), processing (calculating and manipulating
data), storage (saving information temporarily or permanently), and output (producing results).
Ranging from simple calculators to powerful servers, computers are vital tools in various fields,
enabling tasks like data analysis, communication, and automation.
1. Input/Output (I/O)
• Input: Devices that allow users to enter data into the computer. Examples include:
o Keyboard: For typing text and commands.
o Mouse: For navigating and selecting items on the screen.
o Scanner: For digitizing physical documents.
• Output: Devices that present processed data to users. Examples include:
o Monitor: Displays visual output, such as images and text.
o Printer: Produces physical copies of documents.
o Speakers: Output audio signals.
2. CPU (Central Processing Unit)
• The CPU is the brain of the computer, responsible for executing instructions and processing
data. It consists of:
• ALU (Arithmetic Logic Unit): Performs arithmetic operations (like addition and
subtraction) and logical operations (like comparisons). For example, the ALU can calculate
the sum of two numbers or determine if one number is greater than another.
• CU (Control Unit): Directs the operation of the CPU and coordinates how data moves
between the CPU, memory, and I/O devices. For example, it fetches instructions from
memory, decodes them, and executes them.
• Registers: Small, fast storage locations within the CPU that temporarily hold data and
instructions. For example, a register might hold the result of a calculation before it's sent to
main memory.
3. Main Memory (RAM)
• Random Access Memory (RAM): A type of volatile memory that temporarily stores data
and instructions currently being used by the CPU. For example, when you open a program,
it is loaded into RAM for quick access. If the computer is turned off, the data in RAM is
lost.
4. Secondary Memory
• Secondary Memory: Non-volatile storage that retains data even when the computer is
powered off. It is used for long-term storage of data and programs. Examples include:
o Hard Disk Drive (HDD): A traditional spinning disk used for storing large amounts
of data.
o Solid State Drive (SSD): A faster, more reliable storage option that uses flash
memory.
o USB Flash Drive: A portable storage device that allows easy data transfer between
computers.
The Problem solving process
Let us now explore how computers can be put to solving problems:
1. Understand the problem: Effective problem-solving demands a thorough knowledge of the
problem domain. Once you have identified the problem, its exact nature must be sought and defined.
The problem context, objectives, and constraints if any are to be understood properly.
Several techniques can be used to gather information about a problem. Some of these include
conducting interviews and sending questionnaires to the stakeholders (people who are concerned with
the problem). Segmenting a big problem into simple manageable ones often helps you to
develop a clear picture of the problem.

2. Formulate a model for the solution: After the problem is thoroughly understood, the next step is
to devise a solution. You should now identify.the various ways to solve the problem. Brainstorming is
one of the mostcommonly used techniques for generating a large number of ideas within a short time.
Brainwriting and Mind mapping are two alternative techniques
that you can employ here. The generated ideas are then transformed into a conceptual model that can
be easily converted to a solution. Mathematical modeling and simulation modeling are two popular
modeling techniques that you could adopt. Whatever the modeling technique is, ensure the defined
model accurately reflects the conceived ideas.

3. Develop an algorithm: Once a list of possible solutions is determined, they have to be translated
into formal representations – algorithms. Obviously, you do not implement all the solutions. So the
next step is to assess the pros and cons of each algorithm to select the best one for the problem. The
assessment is based on considering various factors such as
memory, time, and lines of code.
4. Code the algorithm: The interesting part of the process! Coding! After the best algorithm is
determined, you implement it as an executable program. The program or the code is a set of instructions
that is more or less, a concrete representation of the algorithm in some programming language. While
coding, always follow the incremental paradigm – start
with the essential functionalities and gradually add more and more to it.

5. Test the program: Nobody is perfect! Once you are done with the coding, you have to inspect your
code to verify its correctness. This is formally called testing. During testing, the program is evaluated
as to whether it produces the desired output. Any unexpected output is an
error. The program should be executed with different sets of inputs to detect errors. It is impossible to
test the program with all possible inputs. Instead, a smaller set of representative inputs called test suite
is identified
and if the program runs correctly on the test suite, then it is concluded that the program will probably
be correct for all inputs. You can get the help of automated testing tools to generate a test suite for your
code. Closely associated with testing is the process of debugging which involves fixing or resolving
the errors (technically called bugs) identified during testing. Testing and debugging should be repeated
until all errors are fixed.

6. Evaluate the solution: This final step is crucial to ensure that the program effectively addresses the
problem and attains the desired objectives. You have to first define the evaluation criteria. These could
include metrics like efficiency, feasibility, and scalability, a few to mention. The potential risks that
could arise with the program’s deployment are also to
be assessed. Collect quantitative and qualitative feedback from the stake- holders. Based on the
feedback, you have to work on making necessary improvements to the program. Nevertheless, the
refined code should also be subject to rigorous testing.

A case study - The Discriminant calculator

Real problem at hand – determining the discriminant of a quadratic equation.

1. Understand the problem: Here we formally define the problem by specifying the inputs and
output.

Input: The three coefficients a, b and c of the quadratic equation

Output: The discriminant value D for the quadratic equation


2. Formulate a model for the solution: Develop a mathematical model for the solution, that is
identify the mathematical expression for the quadratic equation discriminant D:

D = b2 − 4ac

3. Develop an algorithm: A possible algorithm (actually, a pseudocode)

for our discriminant problem is given below:

1. Start
2. Read(a, b, c)
3. d=b∗b−4∗a∗c
4. Print(d)
5. Stop

You will learn more about pseudocodes in Chapter 2.

4. Code the algorithm: The Python program to calculate the discriminant is as follows:

#Input the coefficients

a = int(input("Enter the value of first coefficient"))

b = int(input("Enter the value of second coefficient"))

c = int(input("Enter the value of third coefficient")) #Find the discriminant

d = (b**2) - (4*a*c) #Print the discriminant

print(d)

5. Test the program: You create a test suite similar to the one shown in the below Table. Each row
denotes a set of inputs (a, b, and c) and the expected output (d) with which the actual output is to be
compared.
ESSENTIALS OF PYTHON PROGRAMMING

Python

• High-Level Language: Python abstracts complex details, making it easier to write and read code.
• Interpreted: Code is executed line-by-line, which facilitates debugging and testing.
• Clear Syntax: Emphasizes readability and simplicity, reducing the learning curve for beginners.
• Multi-Paradigm: Supports procedural, object-oriented, and functional programming styles.
• Extensive Standard Library: Comes with a rich set of built-in modules and functions for various
tasks.
• Vibrant Ecosystem: Boasts a vast array of third-party packages and libraries for diverse
applications.
• Popular Applications: Widely used in web development, data analysis, artificial intelligence,
scientific computing, and automation.

Python Interpreter

Fig :Steps in interpreting a Python program

The interpreter performs a sequence of steps to execute your script:

i. The interpreter first reads a Python expression or a statement and verifies that it is valid with
regard to the rules, or syntax, of the language. Any invalid statement is called a syntax error.
When the interpreter encounters such an error, it halts with an error message.
ii. If the expression is well formed, the interpreter then translates it to an executable form called
byte code. The Syntax checker and Translator component of the interpreter is responsible
for verifying the syntax of the statements and translating valid statements to byte code.
iii. Then, the byte code is sent to another interpreter component called the Python Virtual
Machine (PVM) for execution. If any error occurs during execution, the process is halted with
a runtime error message. Otherwise, the execution runs to completion and the output is
produced.

Steps in learning Python

1. Character set
ü The set of characters supported by a programming language is called character set.
ü A character can be an alphabet, a digit, or a special symbol.
ü Python supports the following characters:
a. upper case alphabets (A–Z)
b. lower case alphabets (a–z)
c. digits (0–9)
d. special symbols like @,#,%,$ etc.

Python maps each valid character to an integer value called ASCII value. (ASCII is the abbreviation of
American Standard Code for Information Inter- change.) For example, the ASCII value of character 'A'
is 65.

2. Constants, variables, and keywords

Constants

A ‘constant’ is an entity whose value doesn’t change.

Definition: A constant is a value that does not change during the execution of a program.

Example: PI = 3.14

Variables

§ The data on which programs operate are stored in various memory locations. To simplify the
retrieval and use of data values, these memory locations are given names. Since the value
stored in each location may change occasionally, the names given to these locations are
called ‘variable names’ or simply ‘variables’.
§ Thus, a variable is a name that refers to a value.
§ ‘_’ is a valid variable name.

You might also like