Professional Documents
Culture Documents
CSC 102 Introduction To Problem Solving PDF
CSC 102 Introduction To Problem Solving PDF
This lecture material is prepared to introduce and acquaint students with the basic knowledge of
problem solving alongside the tools. In addition, the fundamentals of python programming language
are also highlighted. Importantly, the materials are gathered from Books, Journals and Web
resources.
Lecture 1
Problem Solving Methods
Objectives:
After going through this topic, students would be able to:
➢ Understand meaning of problem
➢ Understand the concept of Problem-Solving Method
➢ Analyse the process of Problem-Solving Method
Overview
Problem-solving (PS) skills are needed in all areas of life, including classroom problem
solving activities. The capacity to decisively analyse a problem, and set up an effective
solution is one of the most valuable skills one can acquire in life, in school, work or in social
circle. Training in this regard promotes cognitive, social development, and can prepare
students with the skills needed to address and solve problems all the way through the rest of
their lives. In reality, whatever activity human being or machine do to achieve a specified
objective comes under problem solving.
1. Problem - Meaning
A problem is a task. Generally, problem is a kind of barrier to achieve something and
problem solving is a process to get that barrier removed by performing some sequence of
activities. Thus, PS is an act of defining a problem; determining the cause of the problem;
identifying, prioritizing and selecting alternatives for a solution; and implementing the
solution.
Learning in a problem-solving method is by working on problems. Students learn new
knowledge by solving problems. This is done through observation, understanding, analysing,
interpreting to find solutions, and performing applications that would give insight to a holistic
understanding of the concepts. Overall, PS is a process - ability to work from known and
discover unknown. Examples of PS:
Example 1: A simple example on input/process/output. Calculate the average grade for all
students in a class.
Input: get all the grades … perhaps by typing them in via the keyboard or by reading them
from a USB flash drive or hard disk.
Process: add them all up and compute the average grade.
Output: output the answer to either the monitor, to the printer, to the USB flash drive or hard
disk … or a combination of any of these devices. To solve the problem, understand the
problem. Thus, these questions???????
▪ What input data/information is available?
▪ What does it represent?
▪ What format is it in?
▪ Is anything missing?
▪ Do I have everything that I need?
▪ What output information am I trying to produce?
▪ What do I want the result to look like … text, a picture, a graph … ?
▪ What am I going to have to compute?
In the example,
➢ the input is a bunch of grades
➢ we need to understand the format of the grades
➢ each grade might be a number from 0 to 100
➢ it may be a letter grade from A+ to F
➢ If it is a number, the grade might be a whole integer like 73 or it may be a real number
like 73.42
➢ need to consider missing grades, if we do not have the grade for every student (e.g.,
some were away during the test) ????
➢ understand what the output should be (output a whole or real number or a letter grade
??????)
➢ display results using charts
The need to understand the processing part of the problem. Break the problem into smaller
problems that require some kind of simple mathematical computations in order to process the
data since we are going to compute the average. So, what is the model (or formula) for
computing the average of a bunch of numbers????? If there is no such “formula”, then, need
to develop one. Sometimes, we can look up certain formulas in a book or online if we get
stuck.
To come up with a model, we need to fully understand the information available to us.
Assuming that the input data is a bunch of integers or real numbers x1,x2,…,xn representing
a grade percentage, we can use the following computational model:
Average1 = (x1 + x2 + x3 + … + xn) / n
Assuming the input number is from 0 to 100.
Conversely, the approach will not work if the input data is a set of letter grades like B-, C,
A+, F, D-, etc.. because we cannot perform addition and division on the letters. Then,
thinking is required.
Assuming, we may decide to assign an integer number to the incoming letters
as follows:
A+ = 12 B+ = 9 C+ = 6 D+ = 3 F = 0
A = 11 B=8 C=5 D=2
A- = 10 B- = 7 C- = 4 D- = 1
If we assume that these newly assigned grade numbers are y1,y2,…,yn, then we can use the
following computational model:
Average2 = (y1 + y2 + y3 + … + yn) / n
where the result will be a number from 0 to 12. The next is formulating an algorithm.
Example 2: On school resumption day, a student is ready to go to school but yet he/she has
not picked up those books and copies which are required as per timetable. As a result, picking
up books and copies according to timetable is a kind of problem solving.
Example 3: Some students in a class plan to host an event and decide to share the expenses
among them. So, making up plans including budgets, noting all activities, risks, alternatives,
etc. is also a kind of problem solving.
The problems that we want to solve can come from any real-world problem or perhaps even
from the abstract world. We need to have a standard systematic approach to solving
problems. The three basic purposes include:
1. Seeking information
2. Generating new knowledge
3. Making decisions
Objectives
After completing this chapter, students will be able to:
• Know role of algorithm in PS
• Understand what is algorithm
• Understand concept and properties of algorithm
• Know common elements of algorithm
• Understand types of algorithms
• Implement/express algorithm
2. Introduction
Students have a challenge! They need to thank the school management for providing well
equipped computer lab including public address system for them. How do they appreciate
these? They could send thank you note via mail. They could call the Head of Department
(HoD) on phone. They could send email message. They could send representatives to HoD
office. In fact, there are many ways to solve this problem; however, that is not the point.
What is important is that they must decide how to solve the problem and as well, use
appropriate tool to implement their plan.
Assuming representatives are sent to HoD office to deliver them thank you. So, the
representatives are the tool but need to take instruction from the whole students. They have
their mandate on what to say, the time to go, and the message to be delivered. A computer
program is similar to the instruction given to the representatives. The student story is a useful
view concerning computers and computer programs. Every problem solution starts with a
plan. That plan is called an algorithm.
2.2 Algorithm
Algorithm is the set of step-by-step measures or rules followed to complete a given task or
solve a particular problem. It is “a process that performs some sequence of operations in
order to solve a given problem”. The set of rules must be unambiguous and have a clear
stopping point. Note that there might be other ways to solve a problem; as a result, there may
be more than one algorithm for a problem.
Algorithms are used for calculation, data processing, and many other fields. They are
essential because, algorithms provide the organized procedures that computers require. A
good algorithm is similar to using the exact tool in a workshop. Jobs are done effortlessly.
Using the erroneous algorithm or one that is not plainly defined is like trying to cut a piece of
plywood with a pair of scissors: though it may get done, but how effective could it be in
completing it. So, when solving a problem, the key to arriving at the best solution is often
choosing the right approach.
Example of Algorithm
Problem to solve: Write an algorithm to read two numbers and find their sum.
Inputs to the algorithm (accept two inputs):
• First num1
• Second num2
Expected output:
• Sum of the two numbers
Algorithm:
• Step1: Start
• Step2: input the first num1.
• Step3: input the second num2.
• Step4: Sum = num1+num2
• Step5: Print Sum
• Step6: End
Flowchart
Objectives
At the end of this chapter, students will be able to:
• Understand flowchart
• Understand flowchart symbols
• Know general rules of flowcharting
• Comprehend types of flowchart
Flowcharting uses symbols that have been in use for a number of years to represent the type
of operations and/or processes being performed. The standardised format provides a common
method for people to visualise problems together in the same manner. The use of
standardised symbols makes the flow charts easier to interpret; however, standardizing
symbols is not as important as the sequence of activities that make up the process.
Examples of Flowcharts
To comprehend flowchart techniques, let’s consider these examples.
The figure shows basic flowchart process. Recall what circle shape stands for “connector”.
Here, it connects and extends processes from start to end.
Example1: Consider finding the largest number between A and B
Algorithm for the above problem is as follows:
Read A, B
If A is less than B
BIG=B
SMALL = A
Else
BIG=A
SMALL = B
Display BIG, SMALL
Flowchart for the above algorithm will look like:
Example 2: Find the area of a circle of radius r.
3.3 Types of Flowcharts:
High-Level Flowchart:
A high-level (also known as first-level or top-down) flowchart illustrates the major steps in a
process. It can also include the intermediate outputs of each step (the product or service
produced), and the sub-steps involved.
This type of flowchart presents fundamental picture of the process and identifies the changes
taking place within the process. It is very handy for identifying appropriate team members
(those who are involved in the process) and for developing indicators for checking the
process because of its focus on intermediate outputs.
Most processes can be effectively presented in four or five boxes that symbolize the major
steps or activities of the process
Detailed Flowchart:
It provides a detailed picture of a process by mapping all of the steps and activities that occur
in the process. This type of flowchart indicates the steps or activities of a process and
includes such things as decision points, waiting periods, tasks that frequently must be redone
(rework), and feedback loops. This type of flowchart is useful for examining areas of the
process in detail and for looking for problems or areas of inefficiency.
Given below is the Detailed Flowchart of an Order Filling Process which shows the sub-steps
involved in the process and also reveals the delays that occur when the materials required are
not available in the inventory.
Detailed flowchart.
3.5 Software
Any drawing program can be used to create flowchart diagrams. Some tools offer special
support for flowchart drawing. Currently, many software packages exist that can create
flowcharts automatically, either directly from source code, or from a flowchart description
language. On-line Web-based versions of such programs are available.
4. What is Pseudocode?
Literally, pseudo code means “fake code”. It is an artificial and informal approach to writing
sequence of actions and instructions (algorithms) in the form that humans can understand
with ease. In other word, it is a means of describing computer algorithms using a combination
of natural language and programming language. This aids programmers concentrate on the
organization and sequence of a computer algorithm without the need for actually following
the exact coding syntax.
In pseudocode, you don't have to think about semi-colons, curly braces, and the syntax for
arrow functions, how to define promises, DOM methods and other core language principles.
You just have to be able to explain what you are thinking and doing. You make the rules. It
does not matter what language you use to write your pseudocode. All that matters is
comprehension.
Once the problem is broken down to the work package, it helps to represent these problem
solving steps in the clearest and most easily understandable way. It is an intermittent step
towards developing the real code. So, programming is the expression of logic. A program is a
set of instructions that defines how software behaves. Thus, coding is how it is implemented
in the computer system.
Flowchart:
Pseudocode:
Enter Limit
Set Number = 0.
Set Sum = 0.
Repeat the following:
a. If Sum > Limit, terminate the repetition, otherwise.
b. Increment Number by one.
c. Add Number to Sum and set equal to Sum.
Print Number and Sum.
Lecture 5: Programming Languages
Objectives
At the end of the lecture, students should be able to:
• Understand computer program
• Know programming language and its types
• Understand computer programming
I. Machine language (Low-level language): This is a binary code of 0’s and 1’s which
the language understand by the computer. It is a collection of binary digits or bits that
the computer reads and interprets. Machine languages are the only languages
understood by computers, while easily understood by computers, machine languages
are almost impossible for humans to use because they consist entirely of numbers.
II. Assembly language (Low-level language): This work between the machine language
and high-level language. It uses mnemonics codes, Low-level languages are closer to
the language used by a computer. A program written in assembly language consists of
a series of instructions mnemonics that correspond to a stream of executable
instructions, when translated by an assembler that can be loaded into memory and
executed. Assembly languages use keywords and symbols, much like English, to
form a programming language but at the same time introduce a new problem. The
problem is that the computer doesn't understand the assembly code, so we need a way
to convert it to machine code, which the computer does understand. Assembly
language programs are translated into machine language by a program called an
assembler.
III. High-level language: High-level languages are closer to human languages. High-level
languages allow us to write computer code using instructions resembling everyday
spoken language (for example: print, if, while) which are then translated into machine
language to be executed. The term programming language usually refers to high-level
languages, which is the language man mostly understand.
A program written in any programming language need to be converted into machine language
so that the computer can understand it. There are two ways to do this:
Objectives:
After going through this topic, students would be able to:
➢ Understand Object-oriented programming
➢ Know what is an object, message, and method
➢ Understand Object-oriented problem-solving approach
When a program is executed, the objects interact by sending messages to one another. For
example, consider “student status” as an object can tell average grade point, year in school, or list of
registered courses, etc. An object asks another object to perform an action by sending it a message.
The requesting (sending) object is referred to as sender and the receiving object is referred to
as receiver. Control is given to the receiving object until it completes the command; control then
returns to the sending object. For example, a School object asks the Student object for its name by
sending it a message asking for its name. The receiving Student object returns the name back to the
sending object.
More example, if ‘customer’ and ‘account’ are two objects in a program, then the customer
object may send message to account object requesting for a bank balance. Each object
contains data and code to manipulate data. Objects can interact without having to know
details of each other’s data or code. It is sufficient to know the type of message accepted and
the type of response returned by the objects.
A message can also contain information the sending objects needs to pass to the receiving
object, called the argument in the message. A receiving object always returns a value back to
the sending object. This returned value may or may not be useful to the sending object. For
example, the School object now wants to change the student's name. It does this by sending
the Student object a message to set its name to a new name. The new address is passed as an
argument in the message. In this case, the School object does not care about the return value
from the message.
The message can trigger other messages to be delivered to it or to other objects in order to
complete its task. This is known as sequential operation. A message has code that associated
with it. When an object receives a message, code is executed. As mentioned, messages
determine an object's behaviour and the code determines how the object carries out each
message. The code that is associated with each message is called a method. The message
name is also called the method name due to its close association with the method. When an
object receives a message, it determines what method is being requested and passes control to
the method. An object has as many methods as it takes to perform its designed actions.
Methods that operate on specific objects are instance methods and messages that invoke
instance methods are called instance message. Methods that operate on specific classes
are class methods
➢ Problem Identification: Compute the sum of two numbers and print out the result.
➢ Objects Identification: Identify objects needed to solve the problem.
a. First number (object)
b. Second number (object)
c. Result of the addition (Sum)(object)
➢ Message Identification: Message needed to send to objects. This is the message sent
to the receiver object. The result of this message is the value (a numeric object) of the
total sum of the receiver object. It also includes a message that displays the value of
the receiver object, in this case; print.
➢ Object-message sequences: This sequence to solve the problem is;
The message + with parameter Second_num (an object), is sent to the object
First_num. The result is an object (First_num + Second_num), then, the
message print is sent. The parentheses are included to avoid any ambiguity as
to which message should be activated first.
Note: The sequence of evaluation is from left to right unless is specified by parentheses ( ).
For example:
2 + 3 * 4 = 20
2 +(3 * 4) = 14
Lecture 7
Basic Introduction to Python Programming Language
Learning Objectives
The objectives of this course are to get you started with the basic introduction to Python as
the programming language and give you a taste of how to start working with data in Python.
In this course you will learn about:
• What Python is and why is it useful
• The application of Python
• How to define variables
• Data types in python
• Python collection (data structures)
Introduction
This topic teaches the basics of Python and begins by exploring what and why python along
with some of the different data types such as integers, real numbers, and strings. Continue
with brief introduction to different python data structures.
7.6 IDLE
IDE stands for integrated development environment (IDE). It is a software tool that a
programmer uses to write and test the program and software. Thus, IDE is a software
environment which usually consists of a software development package containing code
editor and build automation. Other features include syntax highlighting, auto completion, and
smart indent. It also has a debugger with stepping and breakpoints features. This makes
debugging easier. The integrated development and learning environment (IDLE) is the IDE
for python. It is a program that allows users to type programs and run them. There are other
IDEs for Python (PyCharm, Visual studio code, Eclipse, etc.).
To exit python command line, type the following to quit the python command line interface:
exit()
It can also be done by creating a python file on the server, using the .py file extension, and
running it in the Command Line
C:\Users\Your Name>python myfile.py
7.7.3 Python Indentation
Indentation refers to the spaces at the beginning of a code line. Python uses indentation to
indicate a block of code.
Example
if 5 > 2:
print("Five is greater than two!")
Python will give you an error if you skip the indentation:
Example Syntax Error:
if 5 > 2:
print("Five is greater than two!")
Example Floats:
x = float(1) # x will be 1.0
y = float(2.8) # y will be 2.8
z = float("3") # z will be 3.0
w = float("4.2") # w will be 4.2
Example Strings:
x = str("s1") # x will be 's1'
y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'
7.7.8 Case-Sensitive
Variable names are case-sensitive.
Example
This will create two variables:
a=4
A = "Sally"
#A will not overwrite a
Camel Case
Each word, except the first, starts with a capital letter:
myVariableName = "John"
Pascal Case
Each word starts with a capital letter:
MyVariableName = "John"
Snake Case
Each word is separated by an underscore character:
my_variable_name = "John"
7.7.11 Comments
For documentation purposes, Python offers commenting capability.
Comments start with#, and Python will render the rest of the line as a comment:
Example
#This is a comment.
print("Hello, World!")
Comments can be placed at the end of a line, and Python will ignore the rest of the line
Example
7.9.1 Int
Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length.
Example Integers:
x=1
y = 35656222554887711
z = -3255522
print(type(x))
print(type(y))
print(type(z))
7.9.2 Float
Float, or "floating point number" is a number, positive or negative, containing one or more
decimals.
Example Floats:
x = 1.10
y = 1.0
z = -35.59
print(type(x))
print(type(y))
print(type(z))
Float can also be scientific numbers with an "e" to indicate the power of 10.
Example Floats:
x = 35e3
y = 12E4
z = -87.7e100
print(type(x))
print(type(y))
print(type(z))
Type Conversion
You can convert from one type to another with the int(), float(), and complex() methods:
Example Convert from one type to another:
x = 1 # int
y = 2.8 # float
z = 1j # complex
#convert from int to float:
a = float(x)
#convert from float to int:
b = int(y)
#convert from int to complex:
c = complex(x)
print(a)
print(b)
print(c)
print(type(a))
print(type(b))
print(type(c))
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
7.12.1 List
Lists are used to store multiple items in a single variable. Lists are one of 4 built-in data types
in Python used to store collections of data; the other 3 are Tuple, Set, and Dictionary all with
different qualities and usage.
Example
Create a List:
thislist = ["apple", "banana", "cherry"]
print(thislist)
List Items
List items are ordered, changeable, and allow duplicate values. List items are indexed, the
first item has index [0], the second item has index [1] etc.
When it is said that lists are ordered, it means that the items have a defined order, and that
order will not change. If new items are added to a list, the new items will be placed at the end
of the list.
Note: There are some list methods that will change the order, but in general: the order of the
items will not change.
The list is changeable, meaning that it is possible to change, add, and remove items in a list
after it has been created. Since lists are indexed, lists can have items with the same value:
Example Lists allow duplicate values:
thislist = ["apple", "banana", "cherry", "apple", "cherry"]
print(thislist)
List Length
To determine how many items a list has, use the len() function:
Example Print the number of items in the list:
thislist = ["apple", "banana", "cherry"]
print(len(thislist))
In many respect, lists are like tuples. One key difference is they are mutable. Lists can
contain strings, floats, integers. It can nest other lists. This is also applicable to data structure
(nesting).
7.12.2 Tuple
Tuples are an ordered sequence. Tuples are expressed as comma separated elements within
parentheses. The elements are immutable which means they cannot be changed.
Ratings = (10, 9, 5, 8, 7, 4, 9, 6)
These are values inside the parentheses. In Python, there are different types: strings, integer,
and float. They can all be contained in a tuple but the type of the variable is tuple. Each
element of a tuple can be accessed via an indexing, slicing. The first element can be accessed
by the name of the tuple followed by a square bracket with the index number, in this case
zero.
7.12.3 Dictionaries
Dictionaries are a type of collection in Python. A dictionary has key/value pair. The key is
analogous to the index. They are like addresses, but they don't have to be integers. They are
usually characters. The values are similar to the element in a list and contain information. To
create a dictionary, we use curly brackets. The keys are the first elements.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
Dictionary items are ordered, changeable, and does not allow duplicates. Dictionary items are
presented in key: value pairs, and can be referred to by using the key name.
Example: Implementing Algorithm on PS
Example: Problem: Read two numbers and find the sum as discussed earlier.
• Read question
• Understand it
• Analyse
o Need input (accept 2 numbers)
o Process
o Output (result – sum of 2 numbers)
• Evaluate solution
Algorithm
Start
Input First_num
Input Second_num
Sum = First_num + Second_num
Print Sum
End
Implement in Python
# Program to find the sum of two numbers. It accepts input and process to give sum.
First_num = float(input(“Enter first number “))
Second_num = float(input(“Enter second number “))
Sum = First_num + Second_num
print(Sum)
References
An Introduction to Computer Science and Problem Solving. COMP1405/1005.
Bodner, G. M. (1987). The role of algorithms in problem solving. Journal of Chemical Education .
https://www.owlnet.rice.edu/~ceng303/manuals/fortran/FOR3_3.html
https://www.freecodecamp.org/news/what-is-pseudocode-in-programming/
https://www.brainkart.com/article/Algorithm,-Pseudocode-and-Flowchart_6945/
http://esug.org/data/Old/ibm/tutorial/OOP.HTML