Lecture no

Similar documents
Advanced Algorithms and Computational Models (module A)

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

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

CSC148 Fall 2017 Ramp Up Session Reference

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals:

Loops and Conditionals. HORT Lecture 11 Instructor: Kranthi Varala

1 Lexical Considerations

Here n is a variable name. The value of that variable is 176.

Lexical Considerations

And Parallelism. Parallelism in Prolog. OR Parallelism

The Arithmetic Operators. Unary Operators. Relational Operators. Examples of use of ++ and

The Arithmetic Operators

Princeton University COS 333: Advanced Programming Techniques A Subset of Python 2.7

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

Programming. We will be introducing various new elements of Python and using them to solve increasingly interesting and complex problems.

egrapher Language Reference Manual

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

Beyond Blocks: Python Session #1

PRG PROGRAMMING ESSENTIALS. Lecture 2 Program flow, Conditionals, Loops

Flow Language Reference Manual

cs1114 REVIEW of details test closed laptop period

Question 1. Part (a) Part (b) December 2013 Final Examination Marking Scheme CSC 108 H1F. [13 marks] [4 marks] Consider this program:

Conditionals and Recursion. Python Part 4

CSC A20H3 S 2011 Test 1 Duration 90 minutes Aids allowed: none. Student Number:

Chapter 4: Making Decisions. Copyright 2012 Pearson Education, Inc. Sunday, September 7, 14

Fundamentals of Programming (Python) Getting Started with Programming

The SPL Programming Language Reference Manual

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

TUPLES AND RECURSIVE LISTS 5

Sketchpad Graphics Language Reference Manual. Zhongyu Wang, zw2259 Yichen Liu, yl2904 Yan Peng, yp2321

PLEASE HAND IN UNIVERSITY OF TORONTO Faculty of Arts and Science

L-System Fractal Generator: Language Reference Manual

Operators. Java operators are classified into three categories:

lambda forms map(), reduce(), filter(), eval(), and apply() estimating π with list comprehensions

Introduction to Python

Lexical Considerations

Pace University. Fundamental Concepts of CS121 1

61A Lecture 3. Friday, September 5

Python Evaluation Rules

Part IV. More on Python. Tobias Neckel: Scripting with Bash and Python Compact Max-Planck, February 16-26,

Contents. Jairo Pava COMS W4115 June 28, 2013 LEARN: Language Reference Manual

CS 115 Lecture 8. Selection: the if statement. Neil Moore

Sequence types. str and bytes are sequence types Sequence types have several operations defined for them. Sequence Types. Python

Python I. Some material adapted from Upenn cmpe391 slides and other sources

Programming in Python 3

Chapter 4: Making Decisions

Ruby: Introduction, Basics

Flow Control. CSC215 Lecture

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

Java Methods. Lecture 8 COP 3252 Summer May 23, 2017

Chapter 4: Making Decisions

The PCAT Programming Language Reference Manual

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Introduction to Python, Cplex and Gurobi

The float type and more on variables FEB 6 TH 2012

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

Introduction. Following are the types of operators: Unary requires a single operand Binary requires two operands Ternary requires three operands

LECTURE 3 Python Basics Part 2

Reasoning About Programs Panagiotis Manolios

XQ: An XML Query Language Language Reference Manual

age = 23 age = age + 1 data types Integers Floating-point numbers Strings Booleans loosely typed age = In my 20s

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming

Conditionals & Control Flow

COMP322 - Introduction to C++ Lecture 02 - Basics of C++

Selection Statement ( if )

Flow Control: Branches and loops

Preface Introduction... 23

Chapter 8 Statement-Level Control Structures

Java is an objet-oriented programming language providing features that support

CS1 Lecture 5 Jan. 25, 2019

Chapter 8. Statement-Level Control Structures

GBL Language Reference Manual

Getting Started with Python

Table of Contents. Preface... xxi

PYTHON FOR KIDS A Pl ayfu l I ntrodu ctio n to Prog r am m i ng J a s o n R. B r i g g s

Advanced Python. Executive Summary, Session 1

University of Washington CSE 140 Introduction to Data Programming Winter Midterm exam. February 6, 2013

Recap. ANSI C Reserved Words C++ Multimedia Programming Lecture 2. Erwin M. Bakker Joachim Rijsdam

Objects CHAPTER 6. FIGURE 1. Concrete syntax for the P 3 subset of Python. (In addition to that of P 2.)

CS1 Lecture 5 Jan. 26, 2018

PLEASE HAND IN UNIVERSITY OF TORONTO Faculty of Arts and Science

Python. Executive Summary

Chapter 8. Statement-Level Control Structures

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

Fundamental of Programming (C)

Chapter 8. Statement-Level Control Structures ISBN

Introduction to Python (All the Basic Stuff)

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

Scheme Quick Reference

CSC 108H1 F 2009 Test 1 Duration 35 minutes Aids allowed: none. Student Number:

LECTURE 04 MAKING DECISIONS

Variable and Data Type I

Lecture 5 Tao Wang 1

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

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

Basic operators, Arithmetic, Relational, Bitwise, Logical, Assignment, Conditional operators. JAVA Standard Edition

Babu Madhav Institute of Information Technology, UTU 2015

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

LECTURE 18. Control Flow

PYTHON- AN INNOVATION

Transcription:

Advanced Algorithms and Computational Models (module A) Lecture no. 3 29-09-2014 Giacomo Fiumara giacomo.fiumara@unime.it 2014-2015 1 / 28

Expressions, Operators and Precedence Sequence Operators The following operations are supported by sequence types: Operation s == t s!= t s < t s <= t s > t s >= t Description equivalent (element by element) not equivalent lexicographically less than lexicographically less than or equal to lexicographically greater than lexicographically greater than or equal to 2 / 28

Expressions, Operators and Precedence Operators for Sets and Dictionaries Sets and frozensets support the following operators: Operator key in s key not in s s1 == s2 s1!= s2 s1 <= s2 s1 < s2 s1 >= s2 s1 > s2 s1 s2 s1 & s2 s1 - s2 s1ˆs2 Description containment check non-containment check s1 is equivalent to s2 s1 is not equivalent to s2 s1 is subset of s2 s1 is proper subset of s2 s1 is superset of s2 s1 is proper superset of s2 the union of s1 and s2 the intersection of s1 and s2 the set of elements in s1 but not in s2 the set of elements in precisely one of s1 or s2 3 / 28

Expressions, Operators and Precedence Operators for Sets and Dictionaries Sets do not guarantee a particular order of their elements, so the comparison operators (such as <) are not lexicographic; rather, they are based on the mathematical notion of subset The consequence is that the comparison operators define a partial order Dictionaries, like sets, do not maintain a well-defined order on their elements The concept of subset is not particularly meaningful for dictionaries, so the dict class does not support operators such as < Dictionaries support the notion of equivalence, with d1 == d2 if the two dictionaries contain the same set of key-value pairs 4 / 28

Expressions, Operators and Precedence Operators for Sets and Dictionaries The most widely used behavior of dictionaries is accessing a value associated with a particular key k with the indexing syntax, d[k]. The supported operators are the following: Operator d[key] d[key] = value del d[key] key in d key not in d d1 == d2 d1!= d2 Description value associated with the given key set (or reset) the value associated with given key remove key and its associated value from dictionary containment check non-containment check d1 is equivalent to d2 d1 is not equivalent to d2 5 / 28

Expressions, Operators and Precedence Compound Expressions and Operator Precedence Type Symbols 1 member access expr.member 2 function/method calls expr(...) 3 exponentiation 4 unary operators +expr, -expr 5 multiplication, division *, /, //, % 6 addition, subtraction +, - 7 bitwise shifting «,» 8 bitwise and & 9 bitwise xor ˆ 10 bitwise or 11 comparisons (containment) is, is not, ==,!=, <, <=, >, >=, in not in 12 logical not not expr 13 logical and and 14 logical or or 15 conditional val1 if cond else val2 16 assignments =, +=, -=, *=, etc. 6 / 28

Control flow Conditionals Conditional constructs provide a way to execute a chosen block of code based on the run-time evaluation of one or more Boolean expressions if first_condition: first_body elif second_condition: second_body elif third_condition: third_body else: fourth_body 7 / 28

Control flow Conditionals Each condition is a Boolean expression, and each body contains one or more commands that are executed conditionally There may be any number of elif clauses; the final else clause is optional Nonboolean types may be evaluated as Boolean with intuitive meanings, for example if response: is equivalent to: if response!= : 8 / 28

Control flow Conditionals For example: if door_is_closed: if door_is_locked: unlock_door() open_door() advance() The final command, advance(), is not indented and therefore not part of the conditional body. It will be executed unconditionally 9 / 28

Control flow Loops: while loops The syntax for a while loop in Python is as follows: while condition: body condition can be an arbitrary Boolean expression body can be an arbitrary block of code (including nested control structures) 10 / 28

Control flow Loops: while loops The execution of a while loop begins with a test of the Boolean condition: if that condition evaluates to True, the body of the loop is performed After each iteration of the body, the loop condition is retested, and if it evaluates to True, another iteration of the body is performed When the test condition evaluates to False (if ever), the loop is exited and the flow of control continues just beyond the body of the loop 11 / 28

Control flow Loops: while loops An example: j = 0 while j < len(data) and data[j]!= X : j += 1 The correctness of this loop relies on the behavior of the and operator In this code fragment, first is tested j < len(data) to ensure that j is a valid index and only after the relative element of data is accessed If the compound condition was written in the opposite order, the evaluation of data[j] would eventually raise an IndexError when X is not found. 12 / 28

Control flow Loops: for loops The syntax for a for-loop in Python is as follows: for element in iterable: body The for-loop syntax can be used on any type of iterable structure, such as list, set, dict or file An example: biggest = data[0] for val in data: if val > biggest: biggest = val 13 / 28

Control flow Loops: for loops In some applications is needed the index of an element within the sequence, for example the index of the biggest element in a list In this case it is possible to loop over the all possible indices of the list To this purpose, Python provides a built-in class named range that generates integer sequences. The syntax range(n) generates the series of n values from 0 to n 1 For example: bigindex = 0 for j in range(len(data)): if data[j] > data[bigindex]: bigindex = j 14 / 28

Control flow Loops: for loops Python supports a break statement that immediately terminates a while or for loop when executed within its body For example: found = False for item in data: if item == target: found = True break Python also supports a continue statement that causes the current iteration of a loop body to stop, but with subsequently passes of the loop proceeding as expected 15 / 28

Functions Python supports both functions and methods The term function refers to a traditional, stateless function that is invoked without the context of a particular class or an instance of that class, such as sorted(data) The term method is used to describe a member function that is invoked upon a specific object using an object-oriented message passing syntax, such as data.sort() 16 / 28

Functions def count(data, target): n = 0 for item in data: if item == target: n += 1 return n The first line, beginning with the keyword def serves as the function s signature, which establishes a new identifier as the name of the function and the number of parameters that it expects Each time a function is called, Python creates a dedicated activation record that stores information relevant to the current call The activation record includes the namespace, to manage all the identifiers having a local scope within the current call 17 / 28

Functions Return Statement A return statement is used within the body of a function to indicate that the function should immediately cease execution, and that an expressed value should be return to the caller If a return statement is executed without an explicit argument, the None value is automatically returned Often, a return statement is the final command within the body of the function However, multiple return statements are admitted in the same function, with conditional logic controlling which command will be executed def contains(data, target): for item in data: if item == target: return True return False 18 / 28

Functions Information Passing The identifiers used to describe the expected parameters are known as formal parameters, and the objects sent by the caller when invoking the functions are knwon as actual parameters Parameter passing in Python follows the semantics of the standard assignement statement: when a function is invoked, each identifier (formal parameter) is assigned, in the function s local scope, to the respective actual parameter provided by the caller of the function 19 / 28

Functions Information Passing For example: def count(data, target):... prizes = count(grades, A ) 20 / 28

Functions Information Passing Just before the function body is executed, the actual parameter, grades and A, are implicitly assigned to the formal parameter data and target The communication of a return value from the function back to the caller is similarly implemented as an assignment An advantage to Python s mechanism for passing information to and from a function is that objects are not copied As a consequence, the invocation of a function is efficient, even in the case where a parameter or return value is a complex object 21 / 28

Functions Default Parameter Values Python provides means for functions to support more than one possible calling signature (polimorphism) Most notably, functions can declare one or more default values for parameters, thereby allowing the caller to invoke a function with varying numbers of actual parameters Suppose a function is declared with signature def foo(a, b=15, c=27) There are three parameters, two of which offer default values A caller can send three actual parameters, e.g. foo(5, 20, 25), in which case the default values are not used If the caller sends one parameter, foo(4), the function will execute with parameter values a = 4, b = 15, c = 27 22 / 28

Functions Python s Built-in Functions Calling Syntax abs all(iterable) any(iterable) chr(integer) divmod(x, y) hash(obj) Description Return the absolute value of a number Return True if bool(e) is True for each element e Return True if bool(e) is True for at least one element e Return a one-character string with the given Unicode code point Return (x//y, x%y) as tuple, if x and y are integers Return an integer hash value for the object 23 / 28

Functions Python s Built-in Functions Calling Syntax id(obj) input(prompt) isinstance(obj, cls) iter(iterable) len(iterable) Description Return the unique integer serving as an identity for the object Return a string from stdin; the prompt is optional Determine if obj is an instance of the class Return a new iterator object for the parameter Return the number of elements in the given iteration 24 / 28

Functions Python s Built-in Functions Calling Syntax Description map(f, iter1, iter2,...) Return an iterator yelding the result of function calls f(e1, e2,...) for respective elements e1 iter 1, e2 iter2,... max(iterable) Return the largest element of the given iteration max(a, b, c,...) Return the largest of the arguments min(a, b, c,...) Return the smallest of the arguments next(iterator) Return the next element reported by the iterator 25 / 28

Functions Python s Built-in Functions Calling Syntax Description open(filename, mode) Open a file with the given name and access mode ord(char) Return the Unicode code point of the given character pow(x, y) Return the value x y (as an integer if x and y are integers) pow(x, y, z) Return the value x y mod z as an integer print(obj1, obj2,...) Print the arguments, with separating spaces and trailing newline 26 / 28

Functions Python s Built-in Functions Calling Syntax Description range(stop) Construct an iteration of values 0, 1,..., stop 1 range(start, stop) Construct an iteration of values start, start + 1,..., stop 1 range(start, stop, step) Construct an iteration of values start + step, start + 2 step,... reversed(sequence) Return an iteration of the sequence in reverse round(x) Return the nearest int value round(x, k) Return the value rounded to the nearest 10 k sorted(iterable) Return a list containing elements of the iterable in sorted order 27 / 28

Functions Python s Built-in Functions Calling Syntax sum(iterable) type(obj) Description Return the sum of the elements in the iterable (must be numeric) Return the class to which the instance obj belongs 28 / 28