Algorithms and Data Structures

Similar documents
Algorithms and Data Structures

Algorithms and Data Structures

Outline. 1 If Statement. 2 While Statement. 3 For Statement. 4 Nesting. 5 Applications. 6 Other Conditional and Loop Constructs 2 / 19

Control Flow: Loop Statements

Flow Control: Branches and loops

Condition Controlled Loops. Introduction to Programming - Python

Selection Statement ( if )

While Loops CHAPTER 5: LOOP STRUCTURES. While Loops. While Loops 2/7/2013

Number System. Introduction. Natural Numbers (N) Whole Numbers (W) Integers (Z) Prime Numbers (P) Face Value. Place Value

1 Truth. 2 Conditional Statements. Expressions That Can Evaluate to Boolean Values. Williams College Lecture 4 Brent Heeringa, Bill Jannen

Text Input and Conditionals

SBT 645 Introduction to Scientific Computing in Sports Science #3

06/11/2014. Subjects. CS Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / ) Beginning with Python

CONDITION CONTROLLED LOOPS. Introduction to Programming - Python

Lecture 11: while loops CS1068+ Introductory Programming in Python. for loop revisited. while loop. Summary. Dr Kieran T. Herley

Loops / Repetition Statements

Algorithms and Data Structures

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

Test #2 October 8, 2015

Control, Quick Overview. Selection. Selection 7/6/2017. Chapter 2. Control

7 Control Structures, Logical Statements

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #16 Loops: Matrix Using Nested for Loop

CS 105 Lab As a review of what we did last week a. What are two ways in which the Python shell is useful to us?

Session 1: Introduction to Python from the Matlab perspective. October 9th, 2017 Sandra Diaz

Loops and Conditionals. HORT Lecture 11 Instructor: Kranthi Varala

Lab1. Introduction to Python. Lab 4: Selection Statement. Eng. Mai Z. Alyazji

Matlab- Command Window Operations, Scalars and Arrays

Lecture 3 (02/06, 02/08): Condition Statements Decision, Operations & Information Technologies Robert H. Smith School of Business Spring, 2017

Condition Controlled Loops. Introduction to Programming - Python

Textbook. Topic 5: Repetition. Types of Loops. Repetition

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

Repetition Structures Chapter 9

While Loops A while loop executes a statement as long as a condition is true while condition: statement(s) Statement may be simple or compound Typical

Python review. 1 Python basics. References. CS 234 Naomi Nishimura

Chapter 5 : Informatics practices. Conditional & Looping Constructs. Class XI ( As per CBSE Board)

Introduction to Python

LOOPS. Repetition using the while statement

Control structure: Repetition - Part 2

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Control Structures 1 / 17

Introduction to Computational Models Using Python

Module 06. Topics: Iterative structure in Python Readings: ThinkP 7. CS116 Spring : Iteration

function [s p] = sumprod (f, g)

Individual research task. You should all have completed the research task set last week. Please make sure you hand it in today.

Statements 2. a operator= b a = a operator b

Chapter 2: Functions and Control Structures

REPETITION CONTROL STRUCTURE LOGO

C PROGRAMMING LANGUAGE. POINTERS, ARRAYS, OPERATORS AND LOOP. CAAM 519, CHAPTER5

Theory of control structures

Example: Monte Carlo Simulation 1

JME Language Reference Manual

Loops and Files. Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz

n Group of statements that are executed repeatedly while some condition remains true

Python lab session 1

Q1 Q2 Q3 Q4 Q5 Total 1 * 7 1 * 5 20 * * Final marks Marks First Question

Introduction to Matlab. By: Hossein Hamooni Fall 2014

Control flow statements

Selection Control Structure CSC128: FUNDAMENTALS OF COMPUTER PROBLEM SOLVING

Algorithm Discovery and Design. Why are Algorithms Important? Representing Algorithms. Chapter 2 Topics: What language to use?

9. Elementary Algebraic and Transcendental Scalar Functions

Computer Programming I - Unit 5 Lecture page 1 of 14

Chapter 5 Conditional and Iterative Statements (Part-II) To carry out repetitive task, python provides following iterative/looping statements:

Coding Tutorial. Derrick Hasterok. February 1, 2005

MATH LEVEL 2 LESSON PLAN 1 NUMBER TO INTEGER Copyright Vinay Agarwala, Checked: 06/02/18

Computer Programming ECIV 2303 Chapter 6 Programming in MATLAB Instructor: Dr. Talal Skaik Islamic University of Gaza Faculty of Engineering

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. The Increment and Decrement Operators

Programming with Python

Chapter 5 Conditional and Iterative Statements. Statement are the instructions given to the computer to perform any kind of action.

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Decision structures. A more complex decision structure is an if-else-statement: if <condition>: <body1> else: <body2>

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Announcements. Lab Friday, 1-2:30 and 3-4:30 in Boot your laptop and start Forte, if you brought your laptop

CHAPTER 2.2 CONTROL STRUCTURES (ITERATION) Dr. Shady Yehia Elmashad

Downloaded from Chapter 2. Functions

CS 112: Intro to Comp Prog

VLC : Language Reference Manual

Iteration: Intro. Two types of loops: 1. Pretest Condition precedes body Iterates 0+ times. 2. Posttest Condition follows body Iterates 1+ times

CME 193: Introduction to Scientific Python Lecture 1: Introduction

Lecture. Loops && Booleans. Richard E Sarkis CSC 161: The Art of Programming

(Python) Chapter 3: Repetition

Getting Started. Office Hours. CSE 231, Rich Enbody. After class By appointment send an . Michigan State University CSE 231, Fall 2013

Lab 5 - Repetition. September 26, 2018

ENGR 101 Engineering Design Workshop

Introduction to Python Practical 1

ENGR 1181 MATLAB 4: Array Operations

Conditional Expressions and Decision Statements

Conditionals & Loops /

Lists, loops and decisions

MEIN 50010: Python Flow Control

An Introduction to Python

Introduction to Python Part 1. Brian Gregor Research Computing Services Information Services & Technology

Math 171 Proficiency Packet on Integers

Emil Sekerinski, McMaster University, Winter Term 16/17 COMP SCI 1MD3 Introduction to Programming

18.1. CS 102 Unit 18. Python. Mark Redekopp

Fundamentals of Programming (Python) Getting Started with Programming

Control and Environments Fall 2017 Discussion 1: August 30, 2017 Solutions. 1 Control. If statements. Boolean Operators

Ch.5. Loops. (a.k.a. repetition or iteration)

Introduction to Python (All the Basic Stuff)

Transcription:

Algorithms and Data Structures 4. Łódź 2018

Exercise Harmonic Sum - Type in the program code - Save it as harmonic.py - Run the script using IPython Wikipedia - This program uses the for loop, the range() function and += operator. 2

for Loops - The for loop is used to repeat the calculations in cases one knows ahead of time how many times the loop needs to run. Syntax: for <variable> in <sequence>: <body> - For each item in the <sequence>, the <variable> is assigned the value of that item and the the <body> is executed. - A sequence in Python is an ordered set of elements. An example is the list whose elements are listed in square brackets, e.g. [12, -3, 5, 0.5]. In[1]: for x in [12, -3, 5, 0.5]: In[2]: print ( x, x**2) - What is the body of the above loop? How many times a body is executed in the general case? 3

range Function - This is a built-in function that creates a sequence of integers. Syntax: range(stop) Begin at 0. Take steps of 1. End just before stop. range(start, stop) Begin at start. Take steps of 1. End just before stop. range(start, stop, step) Begin at start. Take steps of step. End just before stop. - The variables start, stop and step are integers. In[1]: range(9) In[2]: range(-2, 12) In[3]: x = 5 In[4]: range(3, x+7) In[5]: range(3, x-2) In[6]: range(3, x-1) In[7]: range(5, 2, -1) 4

Accumulation Loops - Script harmonic.py contains an accumulator variable total which gradually accumulates some quantities as the loop runs. Syntax: <accumulator> = <starting value> loop: <accumulator> += <value to add> - The x += v is a shorthand assignment equivalent to x = x + v -Accumulation loops may accumulate also through other operations, e.g. subtraction, multiplication and division (x -= v, x *= v, x /= v) rather than addition. Do not use sum as an accumulator variable name, because sum() is a built-in Python function. In[1]: x = range(6) In[1]: print ( sum ( x ) ) - For many repetitions, the program may run much too long. To break the loop, use CTRL-D or restart IPython shell. 5

Body Mass Index Revisited - Make the script using Kate, save as bmi_evaluation.py and run in IPython. Wikipedia 6

Boolean (Logic) Expressions - Another type of data in Python is boolean. Variables that hold this type have only 2 possible values: True or False. - Python has the following comparison operations that return boolean values: x == y x!= y x < y x > y x <= y x >= y Avoid using == or!= to compare floats! In[1]: x = 3 In[2]: y = 2 In[3]: P = x == y #P is a Boolean variable In[4]: print (P) Equal. Not equal. Less than. Greater than. Less than or equal. Greater than or equal. 7

Boolean (Logic) Expressions - Boolean expressions may be combined with this boolean operations: P and Q P or Q not P True if both P and Q are True; otherwise False. True if either P or Q are True; otherwise False. True if P is False; otherwise False. In[1]: x = 3 In[2]: y = 2 In[3]: P = not ((x == y) or (y == 2)) In[4]: print (P) In[5]: P = True In[6]: Q = False In[7]: R = P and Q In[8]: print R P P P and Q P or Q Q Q 8

if Statement Perhaps all programming languages have some form of if statement. In Python, it has essentially 3 forms. Indent if <boolean> : <body> Colon if <boolean> : <body1> else: <body2> In[1]: YourGender = Female In[2]: if YourGender == Male : In[3]: print ( Good day, Mister! ) In[4]: else: In[5]: print( Nice to see you, Madame! ) if <boolean1> : <body1> elif <boolean2> : <body2> elif <boolean3> : <body3> else : <bodyn> 9

while Loops - The while loops allow program to repeat the calculations without knowing in advance how many times the loop will run. Syntax: while <boolean> : <body> -The <boolean> expression is evaluated, and if it is True, then the <body> is executed. After that, the <boolean> is checked again and if it is still True, the <body> executes again. This is repeated until the boolean expression is False. (a) Print all positive integers up to n (b) Print even numbers up to n In[1]: n = 5 In[1]: n = 10 In[2]: i = 1 In[2]: i = 1 In[3]: while i < n+1: In[3]: while i < n+2: In[4]: print i In[4]: if i%2 == 0: print i In[5]: i += 1 In[5]: i += 1 10

Temperature Converter - In the following temp.py program the while loop repeats when user enters an invalid temperature value. - Unlike the for loop, it is possible for a while loop to be infinite. Press CTRL-D to break calculations of an infinite loop. In[1]: i = 0 In[2]: while True: In[3]: print(i) In[4]: i += 1 11

Prime numbers - In the following prime.py program, the while loop is used to find out whether an entered number is prime or not. 12

Prime numbers tracing the code In[1]: i = 2 In[1]: while i<num and num%i!= 0: In[1]: i += 1 Loop terminated num = 9: num = 5: i i<num num%i Boolean expression 2 T 1 T 3 T 0 F - - - - - - - - i i<num num%i Boolean expression 2 T 1 T 3 T 2 T 4 T 1 T 5 F - F On termination: i = 3 i = 5 i<num not prime i==num prime 13

Exercises 4.1. Explain the use of n+1 instead of n in harmonic.py. Conjecture what happens to the harmonic sum for very large n. 4.2. Assign the value of 10 to a variable n, run the harmonic.py program and enter 3 when asked for a positive integer that is assigned to the variable n in the program. Then print the value of n and explain the result. List all the local variables and describe the scope of each. 4.3. Determine a range expression to iterate over each of these sequences (a) 0, 1, 2, 3 (b) 3, 2, 1, 0 (c) 1, 3, 5, 7, 9, 11 (d) 10, 27, 44, 61,, 197 (e) 100, 90,, 10 (f) 2, 4, 6, 8,, 200 4.4. Write a program myfactorial.py that returns the product 1*2*3* n. Use an accumulator; do not use the factorial() function from the math module. 14

Exercises 4.5. Write a mymax.py function that returns the largest of x, y and z. 4.6. Write a median3.py function that returns the middle value among the x, y and z. 4.7. Write a myabs.py function that returns the absolute value of x. 4.8. Find the smallest number in the list. 4.9. Find the largest number in the list. 4.10. Write a Python code example of a nested loop. 4.11. Write an infinite loop. 15

Exercises 4.12. Write a Python program to construct the following pattern (use a nested loop) * ** *** **** ***** **** *** ** * 4.13. Write a Python program that prints each item and its corresponding type from the following list (use type() function): datalist = [1452, 11.23, 1+2j, True, 'w3resource', (0, -1), [5, 12], {"class":'v', "section":'a }] 4.14. Write a Python program to calculate the sum of the elements in: - a vector, - a 2D matrix, - each row of a 2D matrix, - each column of a 2D matrix. 16

Exercises 4.15. Write a Python program to calculate the average of the elements in: - a vector, - a 2D matrix, - each row of a 2D matrix, - each column of a 2D matrix. 4.16. Write a program to add: - scalar to a vector, - two vectors to each other, - scalar to a matrix, - two matrices to each other. 4.17. Write a program to multiply two matrices. (https://en.wikipedia.org/wiki/matrix_multiplication) 17

Summary 1) The for loop is used when one knows in advance how many times calculations are to be repeated. 2) Python list stores an ordered sequence of items. The items (list elements) can be of any type, e.g. a_list = [10, False, Hi mate!, 3.14159]. 3) Python boolean data type can have any of two values: True or False. 4) Boolean values are returned by comparison operations. 5) The function range() produces a list of integers. 6) The if statement allows doing different parts of a program provided some conditions are satisfied. 7) The while loop is used to program repetitive computations without knowing the number of repetitions in advance. 8) Loops can sometimes be infinite. 18

Literature Brian Heinold, Introduction to Programming Using Python, Mount St. Mary s University, 2012 (http://faculty.msmary.edu/heinold/python.html). Brad Dayley, Python Phrasebook: Essential Code and Commands, SAMS Publishing, 2007 (dostępne też tłumaczenie: B. Dayley, Python. Rozmówki, Helion, 2007). Mark J. Johnson, A Concise Introduction to Programming in Python, CRC Press, 2012. 19