Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

algorithm

The document outlines a course on Problem Solving using Python, covering topics such as computational thinking, data types, control flow, functions, and algorithms. It includes evaluation criteria, suggested books, and methodologies for problem-solving, including iteration and recursion. Additionally, it provides examples and exercises related to algorithm design and flowchart creation.

Uploaded by

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

algorithm

The document outlines a course on Problem Solving using Python, covering topics such as computational thinking, data types, control flow, functions, and algorithms. It includes evaluation criteria, suggested books, and methodologies for problem-solving, including iteration and recursion. Additionally, it provides examples and exercises related to algorithm design and flowchart creation.

Uploaded by

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

Problem Solving using Python

(ITFC0101)
Introduction, IDE, Program, Problem Solving
Course Outline/Curriculum & Lecture/Tutorial Count

Module
Topics
No.

Computational Thinking and Problem-Solving: Identification of Computational Problems -Algorithms,


building blocks of algorithms (statements, state, control flow, functions), notation (pseudo code, flow chart,
programming language), algorithmic problem solving, simple strategies for developing algorithms (iteration,
1 recursion).
Data Types, Expressions, and Statements: Python interpreter and interactive mode, debugging; values and
types: int, float, Boolean, string, and list; variables, expressions, statements, tuple assignment, precedence of
operators, comments.
Control Flow Functions, and Strings: Conditions - Boolean values and operators, conditional (if),
alternative (if-else), chained conditional (if-elif-else); Iteration - state, while, for, break, continue, pass;
2
Fruitful functions - return values, parameters, local and global scope, function composition, recursion; Strings
- string slices, immutability, string functions and methods, string module; Lists as arrays.
Lists, Tuples, Dictionaries: Lists - list operations, list slices, list methods, list loop, mutability, aliasing,
cloning lists, list parameters; Tuples - tuple assignment, tuple as a return value; Dictionaries - operations and
3 methods; advanced list processing, list comprehension.
Files, Modules, Packages: Files and exceptions: text files, reading and writing files, format operator;
command line arguments, errors and exceptions, handling exceptions, modules packages.
Evaluation Criteria

S.
Evaluative Components and tentative dates of examination Marks
No.
Mid Sem Examination
1 30

End Term Examination


2 50

Teachers Assessment (Quizzes): 3 Quizes, best 2 will be considered 10


3
Teachers Assessment: Assignment, Class interaction, discipline, question
10
answering, group task

Total 100
Suggested Books

1. Yashavant Kanetkar, “Let Us Python”, 6 Edition, BPB publisher, 2023


th

2. Allen B. Downey, “Think Python: How to Think like a Computer Scientist”, 2nd
Edition, O’Reilly Publishers, 2016.

3. Karl Beecher, “Computational Thinking: A Beginner's Guide to Problem-Solving and


Programming”, 1st Edition, BCS Learning & Development Limited, 2017.

4. Kenneth A. Lambert, “Fundamentals of Python: First Programs”, CENGAGE


Learning, 2012.
Some terms you will frequently encounter

• High-level language
• Low-level language
• Portable
• Python interpreter
• Python prompt
• Script
Python Prompt
Python Script

• Writing a program in a file use the interpreter to execute the contents of the file.
• Such a file is called a script.
• Scripts have the advantage that they can be saved to disk, printed, and so on.
• Using script needs text editor and interpreter.
IDE
Integrated Development environment

• For Python (and many other programming languages) there are programs that include
both a text editor and a way to interact with the interpreter.

• We call these development environments (sometimes Integrated Development


Environment or IDE).
Programming Methodology

• Problem solving
• Problem statement and analysis.
• Develop a high-level algorithm.
• Develop a low-level algorithm.
• Coding
• Choose a programming language.
• Code the program using the selected algorithm.
• Test the program and correct the errors.
Algorithm
Definition— Solution to a programming problem.

Algorithm: A combination of sequence of finite steps to solve a particular problem

• Algorithm can be written in different ways:


• Simple Statement
• Pseudo-code — English-like steps that describes the solution. (preferred)
• Flowcharts — Picture with specific blocks detailing out the logical flow of the solution
Properties of Algorithm
Definition— Solution to a programming problem.

• Input: 0 or more
• Output: 1 or more
• Finiteness: Should terminate within finite time, OR after finite iterations
• Deterministic / Definiteness: Non-ambiguous
• Task oriented steps: All steps should have meaningful task e.g. x=x //Useless
• Generic: Steps should be language independent
Example
Problem Statement: Find the average of a given list of numbers

• High level algorithm


1. Find the SUM of the given
numbers

2. Find the COUNT of the given


numbers

3. AVERAGE is SUM/COUNT
Example 7
Problem Statement: Find the average of a given list of numbers
• Low level algorithm
1. Initialize SUM as 0 and COUNT as 0.
• High level algorithm 2. If there are no more numbers remaining to be processed, then
go to step 7.
1. Find the SUM of the given 3. Set ITEM as next number in the list.
numbers
4. Add ITEM to SUM
2. Find the COUNT of the given
numbers 5. Increment COUNT by 1
6. Go back to step 2
3. AVERAGE is SUM/COUNT
7. If COUNT in equal to 0, then
1. AVERAGE is “undefined”
8. Else
Basic Building Blocks of Algorithms

• Statement
• State
• Control Flow
• Function
Basic Building Blocks of Algorithms
Statements

Statement: A single action in a computer

In a computer statements might include some of the following actions

• Input data-information given to the program


• Process data-perform operation on a given input
• Output data-processed result
Basic Building Blocks of Algorithms
State and Control Flow

State: Transition from one process to another process under specified condition with in a time is called state.

Control flow:

• The process of executing the individual statements in a given order is called control flow.
• The control can be executed in three ways
1. Sequence
2. Selection
3. Iteration
Basic Building Blocks of Algorithms
Control Flow

Sequence: All the instructions are executed one after another is called sequence execution.

Example: Addition of two numbers

Step 1: Start

Step 2: get a,b

Step 3: calculate c=a+b

Step 4: Display c

Step 5: Stop
Basic Building Blocks of Algorithms
Control Flow
Selection: Statement causes the program control to be transferred to
a specific part of the program based upon the condition.
If the conditional test is true, one part of the program will be
executed, otherwise it will execute the other part of the program.
Example: Write an algorithm to check whether he is eligible to
vote?
Step 1: Start
Step 2: Get age
Step 3: if age >= 18 print “Eligible to vote”
Step 4: else print “Not eligible to vote”
Step 6: Stop
Basic Building Blocks of Algorithms
Control Flow
Interation: In some programs, certain set of statements are executed again and again based upon conditional
test. i.e. executed more than one time. This type of execution is called looping or iteration.

Example: Write an algorithm to print all natural numbers up to n

Step 1: Start

Step 2: get n value.

Step 3: initialize i=1

Step 4: if (i<=n) go to step 5 else go to step 7

Step 5: Print i value and increment i value by 1

Step 6: go to step 4

Step 7: Stop
Basic Building Blocks of Algorithms
Function
A sub program which consists of block of code (set of instructions) that performs a particular task.
For complex problems, the problem is been divided into smaller and simpler tasks during algorithm
design.
Benefits of Using Functions

• Reduction in line of code


• Code reuse
• Better readability
• Information hiding
• Easy to debug and test
• Improved maintainability
Basic Building Blocks of Algorithms
Function
Algorithm for addition of two numbers using function

Main function()

Step 1: Start

Step 2: Call the function add()

Step 3: Stop

Sub function add()

Step 1: Function start

Step 2: Get a, b Values

Step 3: add c=a+b

Step 4: Print c

Step 5: Return
Simple Strategies of Developing Algorithms

• Iteration
• Recursion

https://www.brainkart.com/article/Simple-Strategies-For-Developing-Algorithms_35899/
Simple Strategies of Developing Algorithms
Iteration: A sequence of statements is executed until a specified condition is true.

1. for loop Example: Print n natural numbers

2. While loop BEGIN

GET n

INITIALIZE i=1
Syntax for For:
FOR (i<=n) DO
FOR( start-value to end-value) DO
PRINT i
Statement1
i=i+1
Statement2
ENDFOR
...
END
ENDFOR
Simple Strategies of Developing Algorithms
Iteration: A sequence of statements is executed until a specified condition is true.

Syntax for While: Example: Print n natural numbers


BEGIN
GET n
WHILE (condition) DO
INITIALIZE i=1
Statement 1 WHILE(i<=n) DO

Statement 2 PRINT i
i=i+1
...
ENDWHILE
ENDWHILE
END
Simple Strategies of Developing Algorithms
Iteration: A sequence of statements is executed until a specified condition is true.

Problem: Compute Factorial of a number using Iteration


Simple Strategies of Developing Algorithms
Recursion
• A function that calls itself is known as recursion.
• A Recursion is a process by which a function calls itself repeatedly until some specified
condition has been satisfied.
Properties of Recursion:

• Termination Condition (Usually first statement inside recursion)


• Recursive Steps
• Perform some task in each function call
• Parameter value change (Towards termination condition) from one function call to
another
Simple Strategies of Developing Algorithms
Recursion:
Algorithm for factorial of n numbers using
recursion:

Main function:

Step1: Start
Sub function factorial(n):
Step2: Get n
Step1: if(n==1) then fact=1 return fact
Step3: call factorial(n)
Step2: else fact=n*factorial(n-1) and return fact
Step4: print fact

Step5: Stop
Simple Strategies of Developing Algorithms
Recursion:
Pseudo Code
Sub function factorial(n):

IF(n==1) THEN
Main function:
fact=1
BEGIN
RETURN fact
GET n
ELSE
CALL factorial(n)
RETURN fact=n*factorial(n-1)
PRINT fact

END
Flowchart Building Blocks (Notations)
Example 1
Problem statement: Watch a movie at home
Start

• Algorithm
Switch on the TV
• Switch on the TV.
Change to the movie
channel
• Go to the movie channel.
Sit down watch movie
• Sit down and watch the movie.
End
Example 2
Problem Statement: Withdraw cash from ATM

• Go to the ATM
• Insert your card into the machine.
• Press in your code
• Choose “Withdraw” and enter Amount required
• Take the cash, slip and card.
Example 3
Problem statement: Calculate
the interest of a bank deposit. You are to read the
amount, years and interest rate from the keyboard and print the interest
amount.
• Algorithm
• Read Principal Amount
• Read Years
• Read Rate
• Set Interest as Amount *
Rate*Years/100
• Print Interest
Example 4
Problem Statement: Print what to do when driving to a traffic signal

• Algorithm
• Read traffic signal
• If signal is Green then set Action as GO
• Else
• Set action as STOP
• Print Action
Example 6
Problem Statement: Print Title for a person (Either Mr. or Miss. or Mrs.). You are to read the gender (and status if needed).

• Algorithm
• Read Gender
• If Gender is MALE then
• Title is Mr.
• Else
• Read status
• If status is MARRIED then
• Title is Mrs.
• Else
• Title is Miss.
Simple Strategies of Developing Algorithms
Recursion:
Flowchart: factorial of n numbers using
recursion
Arithmetical Operations – Flow Chart
Problem Statement: Simple interest (SI) is calculated by Problem Statement: Area of a SQUARE is calculated by
dividing the product of principal (P), rate of interest (R), and taking square of one side of the SQUARE. Draw the Flow
year (N) with 100. Draw the Flow Chart and write a Chart and write a program to input the side of a SQUARE
program to input P, R, and N and display the computed SI. and display the computed Area.

STAR STAR
T T
READ: P, R, READ: side
N

SI = (P * N * R ) / 100 Area = side * side

PRINT : SI PRINT : Area

STOP STOP
e.g. Input: side (10)
e.g. Input: P(1000), R (4.5), N (10)
Output: 100
Output: 450
Arithmetical Operations – Flow Chart & C Program
Problem Statement: Diameter (D), Circumference (C), Problem Statement: It is desired to exchange/swap the
and Area (A) of a circle can be computed, if Radius (R) is values of the two variables. Draw the Flow Chart and write
known. Draw the Flow Chart and write a C program to input a C program to input and swap the values and display the
R and display the computed D, C, and A. values of both variables before and after the swapping.

STAR STAR
T T
READ: V1, V2
READ: R

PRINT : V1, V2
D=2*R
C = 2 * 3.14 * R
A = 3.14 * R * R V3 = V1, V1 = V2
V2 = V1

PRINT : D, C, A
PRINT : V1, V2

STOP STOP
e.g. Input: V1 (10), V2 (20)
e.g. Input: R (20)
Output: 10 20
Output: 40 125.6 1256
20 10
Exercises
Q1. It is desired to compute the average and total marks of a student in five subjects. Draw the flow chart
and write a program to input the marks obtained in five subjects and display the average and total
marks.
Q2. Draw the flow chart and write a program to swap the values of two variables without using the third
variable
Some terms you will frequently encounter

• Python interpreter
• Python prompt
• Script
Ways to write python code

Two ways of writing python code

• Interactive mode
• Script mode
Python Prompt
Interactive Mode

• Simply type the Python statement on >>> prompt (python shell prompt)
• As we type and press enter:
• See the output in the very next line
Python Prompt
Interactive Mode

# Python program to take input from user


# Taking input from user
a = int(input())
# Taking input from user
b = int(input())
# Multiplying and storing result
c=a*b
# Printing the result
print(c)
Python Prompt
Interactive Mode

Disadvantages

• Not suitable for large programs


• Doesn’t save the statements
• Make a program it is for that time itself
• Cannot use it in the future
• For future use, retype all the code
• Editing the code is difficult
• Need to revisit all our previous commands
Python Script
Script Mode

• Writing a program in a file use the interpreter to execute the contents of the file.
• Such a file is called a script.
• Scripts have the advantage that they can be saved to disk, printed, and so on.
• Using script needs text editor and interpreter.
Python Script
Run python code in script mode

• Step 1: Make a file using a text editor. You can use any text editor of your choice (e.g.,
notepad, vscode etc.)

• Step 2: Save the file using “.py” extension


• Step 3: Open the command prompt
• Step 4: Command directory to the one where your file is stored
• Step 5: Type python “filename.py” and press enter
• Step 6: See the output on your command prompt
Python Script
Run python code in script mode
Data Types

>>> type("Hello, World!")

<class 'str’>

>>> type(17)

<class 'int’>

>>> type(3.2)

<class 'float’>

>>> type("17")

<class 'str’>
Data Types

>>> type("3.2")
<class 'str'>

>>> type('This is a string.')


<class 'str’>

>>> type("And so is this.")


<class 'str’>
Data Types
triple quoted strings

>>> type("""and this.""")

<class 'str'>

>>> type('''and even this...''')

<class 'str’>

>>> print('''"Oh no", she exclaimed, "Ben's bike is broken!"''')

"Oh no", she exclaimed, "Ben's bike is broken!"

>>>
Data Types

>>> 'This is a string.'

'This is a string.'

>>> """And so is this."""

'And so is this.
Data Types
Triple quoted strings can even span multiple lines:

>>> message = """This message will


... span several
... lines."""
>>> print(message)
This message will
span several
lines.
>>>
>>> 42000

42000

>>> 42,000

(42, 0)
Variables
Assignment Statement

>>> message = "What's up, Doc?"


>>> n = 17
>>> pi = 3.14159
The assignment token, =, should not be confused with equals, which uses the token ==
>>> 17 = n // Error Message
File "<interactive input>", line 1
SyntaxError: can't assign to literal
Variables

>>> day = "Thursday"

>>> day

'Thursday'

>>> day = "Friday"

>>> day

'Friday'

>>> day = 21

>>> day

21
Variable names and keywords
Contain both letters and digits, but they have to begin with a letter or an underscore

>>> 76trombones = "big parade"

SyntaxError: invalid syntax

>>> more$ = 1000000

SyntaxError: invalid syntax

>>> class = "Computer Science 101"

SyntaxError: invalid syntax


Python reserve keywords
Variable names and keywords

pi = 3.1415

radius = 10

area = pi * radius ** 2
Statements
Evaluating expressions
>>> 1 + 1

>>> len("hello")

5
Statements
Evaluating expressions

>>> 17
17
>>> y = 3.14
>>> x = len("hello")
>>> x
5
>>> y
3.14
Operators and operands

>>> 2 ** 3

>>> 3 ** 2

9
Operators and operands

>>> 7 / 4
1.75
>>> 7 // 4
1
>>> minutes = 645
>>> hours = minutes // 60
>>> hours
10

You might also like