Algorithms and Data Structures

Similar documents
Algorithms and Data Structures

Algorithms and Data Structures

Selection Statement ( if )

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

Algorithms and Data Structures

Control Flow: Loop Statements

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

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

Condition Controlled Loops. Introduction to Programming - Python

Test #2 October 8, 2015

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

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

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?

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

SBT 645 Introduction to Scientific Computing in Sports Science #3

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

Condition Controlled Loops. Introduction to Programming - Python

Loops / Repetition Statements

Programming for Experimental Research. Flow Control

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

Text Input and Conditionals

CS 112: Intro to Comp Prog

CONDITION CONTROLLED LOOPS. Introduction to Programming - Python

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

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

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

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

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

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

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

Flow Control: Branches and loops

Python lab session 1

Introduction to Python (All the Basic Stuff)

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

Python Boot Camp. Day 3

Common Loop Algorithms 9/21/16 42

Example: Monte Carlo Simulation 1

CS1110 Lab 6 (Mar 17-18, 2015)

Chapter 2: Functions and Control Structures

Control structure: Repetition - Part 2

ECE 122. Engineering Problem Solving with Java

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

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

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

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

Coding Tutorial. Derrick Hasterok. February 1, 2005

Fundamentals of Programming (Python) Getting Started with Programming

Control Structures 1 / 17

Theory of control structures

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

18.1. CS 102 Unit 18. Python. Mark Redekopp

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

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

Introduction to Python

REPETITION CONTROL STRUCTURE LOGO

Introduction to Computational Models Using Python

[CHAPTER] 1 INTRODUCTION 1

Control flow statements

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

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

LOOPS. Repetition using the while statement

GE PROBLEM SOVING AND PYTHON PROGRAMMING. Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING

Python - Loops and Iteration

6. Control Statements II

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

Loops and Conditionals. HORT Lecture 11 Instructor: Kranthi Varala

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

COGS 119/219 MATLAB for Experimental Research. Fall 2016 Week 1 Built-in array functions, Data types.m files, begin Flow Control

An Introduction to Python

ENGR 101 Engineering Design Workshop

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

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

Lecture no

Chapter 4 Introduction to Control Statements

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

Selection Control Structure CSC128: FUNDAMENTALS OF COMPUTER PROBLEM SOLVING

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

CSCI 1101B. While Loops

FORM 2 (Please put your name and form # on the scantron!!!!)

More on control structures

CSC 1052 Algorithms & Data Structures II: Recursion


Module 3: New types of data

ECE15: Introduction to Computer Programming Using the C Language. Lecture Unit 4: Flow of Control

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

Introduction to Scientific Python, CME 193 Jan. 9, web.stanford.edu/~ermartin/teaching/cme193-winter15

61A LECTURE 10 MUTABLE DATA. Steven Tang and Eric Tzeng July 10, 2013

Computer Programming I - Unit 5 Lecture page 1 of 14

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

CPTS 111, Fall 2011, Sections 6&7 Exam 3 Review

Functions and Recursion

Getting Started with Python

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

CSCI 131, Midterm Exam 1 Review Questions This sheet is intended to help you prepare for the first exam in this course. The following topics have

3 The L oop Control Structure

Dept. of CSE, IIT KGP

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15

Problem Solving and 'C' Programming

Downloaded from Chapter 2. Functions

Introduction to Internet of Things Prof. Sudip Misra Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur

Transcription:

Algorithms and Data Structures 4. Łódź 2012

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

for Loops - The for loop is used to repeat the calculadons in cases one knows ahead of Dme how many Dmes 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]. >>> for x in [12, - 3, 5, 0.5]: >>> print ( x, x**2) - What is the body of the above loop? How many Dmes a body is executed in the general case? 3

range FuncDon - This is a built- in funcdon 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. >>> range(9) >>> range(- 2, 12) >>> x = 5 >>> range(3, x+7) >>> range(3, x- 2) >>> range(3, x- 1) >>> range(5, 2, - 1) 4

AccumulaDon Loops - Script harmonic.py contains an accumulator variable total which gradually accumulates some quanddes 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 - AccumulaDon loops may accumulate also through other operadons, e.g. subtracdon, muldplicadon and division (x - = v, x *= v, x /= v) rather than addidon. Do not use sum as an accumulator variable name, because it is a built- in Python funcdon. >>> x = range(6) >>> print ( sum ( x ) ) - For many repeddons, the program may run much too long. To break the loop, use CNTRL- C or restart Pylab or Python shell. 5

Body Mass Index Revisited - Make the script using Notepad++, save as bmi_evaluahon.py and run in Pylab. 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 operahons that return boolean values: x == y Equal. x!= y Not equal. x < y Less than. x > y Greater than. x <= y Less than or equal. x >= y Greater than or equal. Avoid using == or!= to compare floats! >>> x = 3 >>> y = 2 >>> P = x == y #P is a Boolean variable >>> print (P) 7

Boolean (Logic) Expressions - Boolean expressions may be combined with this boolean operahons: 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. >>> x = 3 >>> y = 2 >>> P = not ((x == y) or (y == 2)) >>> print (P) >>> P = True >>> Q = False >>> R = P and Q >>> print R 8

if Statement Perhaps all programming languages have some form of if statement. In Python, it has essendally 3 forms. if <boolean> : <body> if <boolean> : <body1> else: <body2> >>> YourGender = Female >>> if YourGender == Male : >>> print ( Good day, Mister! ) >>> else: >>> 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 calculadons without necessarily knowing in advance how many Dmes the loop will run. Syntax: while <boolean> : <body> - The <boolean> expression is evaluated, and if it is True, then the <body> is executed. Ajer that, the <boolean> is checked again and if it is sdll True, the <body> executes again. This is repeated undl the boolean expression is False. (a) Print all posidve integers up to n (b) Print even numbers up to n >>> n = 5 >>> n = 10 >>> i = 1 >>> i = 1 >>> while i < n+1: >>> while i < n+2: >>> print i >>> if i%2 == 0: print i >>> i += 1 >>> 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- C to break calculadons of an infinite loop. >>> i = 0 >>> while True: >>> print(i) >>> 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 >>> i = 2 >>> while i<num and num%i!= 0: >>> 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 termina7on: 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 (n = 5), run the harmonic.py program and enter 3 when asked for a posidve 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() funcdon from the math module. 14

Exercises 4.5. Write a mymax.py funcdon that returns the largest of x, y and z. 4.6. Write a median3.py funcdon that returns the middle value among the x, y and z. 4.7. Write a myabs.py funcdon 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

Summary 1) The for loop is used when one knows in advance how many Dmes calculadons 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 bolean data type can have any of two values: True or False. 4) Boolean values are returned by comparison operahons. 5) The funcdon range() produces a list of integers. 6) The if statement allows doing different parts of a program provided some condidons are sadsfied. 7) The while loop is used to program repeddve computadons without knowing the number of repeddons in advance. 8) Loops can somedmes be infinite. 16

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