Advanced Algorithms and Computational Models (module A)

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

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

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

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

Data Handing in Python

Operators and Expressions

CS4120/4121/5120/5121 Spring 2016 Xi Language Specification Cornell University Version of May 11, 2016

Operators. Java operators are classified into three categories:

Language Reference Manual simplicity

Operators in C. Staff Incharge: S.Sasirekha

1 CS580W-01 Quiz 1 Solution

Python Class-Lesson1 Instructor: Yao

Lecture no

Babu Madhav Institute of Information Technology, UTU 2015

Visual C# Instructor s Manual Table of Contents

Script language: Python Data structures

COMP Primitive and Class Types. Yi Hong May 14, 2015

L-System Fractal Generator: Language Reference Manual

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

Variables, Constants, and Data Types

Overview of C. Basic Data Types Constants Variables Identifiers Keywords Basic I/O

Full file at

Python memento TI-Smart Grids

DaMPL. Language Reference Manual. Henrique Grando

egrapher Language Reference Manual

Java Primer 1: Types, Classes and Operators

UNIVERSITÀ DI PADOVA. < 2014 March >

Python - Variable Types. John R. Woodward

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

COMP519 Web Programming Lecture 17: Python (Part 1) Handouts

GO - OPERATORS. This tutorial will explain the arithmetic, relational, logical, bitwise, assignment and other operators one by one.

Chapter 2 Working with Data Types and Operators

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

GraphQuil Language Reference Manual COMS W4115

CS109A ML Notes for the Week of 1/16/96. Using ML. ML can be used as an interactive language. We. shall use a version running under UNIX, called

Operators and Expressions in C & C++ Mahesh Jangid Assistant Professor Manipal University, Jaipur

Learning Language. Reference Manual. George Liao (gkl2104) Joseanibal Colon Ramos (jc2373) Stephen Robinson (sar2120) Huabiao Xu(hx2104)

JAVA OPERATORS GENERAL

FRAC: Language Reference Manual

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

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

Operators in java Operator operands.

Number System. Introduction. Decimal Numbers

Chapter 4 : Informatics Practices. Data Handling. Class XI ( As per CBSE Board) Visit : python.mykvs.in for regular updates

CS313D: ADVANCED PROGRAMMING LANGUAGE

XC Specification. 1 Lexical Conventions. 1.1 Tokens. The specification given in this document describes version 1.0 of XC.

CS113: Lecture 3. Topics: Variables. Data types. Arithmetic and Bitwise Operators. Order of Evaluation

Java enum, casts, and others (Select portions of Chapters 4 & 5)

CIS192: Python Programming

4. Inputting data or messages to a function is called passing data to the function.

CS 115 Lecture 4. More Python; testing software. Neil Moore

Full file at

Chapter 3: Operators, Expressions and Type Conversion

Lexical Considerations

PYTHON- AN INNOVATION

Objects and Types. COMS W1007 Introduction to Computer Science. Christopher Conway 29 May 2003

A Java program contains at least one class definition.

CS 115 Data Types and Arithmetic; Testing. Taken from notes by Dr. Neil Moore

Lecture 3 Tao Wang 1

Unit-2 (Operators) ANAND KR.SRIVASTAVA

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

Expression and Operator

CMPT 125: Lecture 3 Data and Expressions

Collections. Lists, Tuples, Sets, Dictionaries

1 Lexical Considerations

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

Module 2 - Part 2 DATA TYPES AND EXPRESSIONS 1/15/19 CSE 1321 MODULE 2 1

Chapter 6 Primitive types

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

Introduction to Programming Using Java (98-388)

SECTION II: LANGUAGE BASICS

2 nd Week Lecture Notes

Chapter 2: Using Data

9/5/2018. Overview. The C Programming Language. Transitioning to C from Python. Why C? Hello, world! Programming in C

CSC Web Programming. Introduction to JavaScript

Declaration and Memory

The C Programming Language. (with material from Dr. Bin Ren, William & Mary Computer Science)

4 Programming Fundamentals. Introduction to Programming 1 1

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

THIS CHAPTER DESCRIBES PYTHON S BUILT-IN OPERATORS as well as the precedence

Lecture 3. More About C

Programming Lecture 3

Lecture Set 2: Starting Java

Reserved Words and Identifiers

Le L c e t c ur u e e 2 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Variables Operators

Chapter 3 : Computer Science. Class XI ( As per CBSE Board) Data Handling. Visit : python.mykvs.in for regular updates

Lecture Set 2: Starting Java

CIS 110: Introduction to Computer Programming

COMP1730/COMP6730 Programming for Scientists. Data: Values, types and expressions.

JAVA Programming Fundamentals

The SPL Programming Language Reference Manual

Java Basic Datatypees

Department of Computer Science

Introduction to Python

WEEK 4 OPERATORS, EXPRESSIONS AND STATEMENTS

Outline. Data and Operations. Data Types. Integral Types

Algorithmic "imperative" language

Language Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */

Unit-II Programming and Problem Solving (BE1/4 CSE-2)

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

Transcription:

Advanced Algorithms and Computational Models (module A) Giacomo Fiumara giacomo.fiumara@unime.it 2014-2015 1 / 34

Python's built-in classes A class is immutable if each object of that class has a xed value upon instantiation that cannot subsequently be changed For example, the class float is immutable, since once an instance has been created, its value cannot be changed Class Description Immutable bool Boolean value y int integer y float oating-point number y list mutable sequence of objects n tuple immutable sequence of objects y str character string y set unordered set of distinct objects n frozenset immutable form of set class y dict associative mapping (aka dictionary) n 2 / 34

The bool class The bool class is used to manipulate Boolean values The two only instances of the class are expressed as the literals False and True The default constructor, bool() returns False goofy = bool() pluto = False Python allows the creation of a Boolean value from a non-boolean type using the syntax bool(huey) for value huey The interpretation depends upon the type of the parameter numbers evaluate to False if zero, and True if nonzero Strings and lists evalutate to False if empty, and True if nonempty 3 / 34

The int class The int class is designed to represent integer values with arbitrary magnitude Unlike Java and C++ which support dierent integer types with dierent precision, Python automatically chooses the internal representation for an integer based upon the magnitude of its value In some contexts may be useful to express an integral value using binary, octal or hexadecimal. For example: 0b110101 0o755 0x9ab 4 / 34

The int class 5 / 34

The int class The constructor int() returns value 0 by default However, it can be used only to construct an integer value starting from an existing value of another type For example 6 / 34

The int class If goofy represents a oating-point value, int(goofy) produces the truncated value of goofy The constructor can be used to parse a string which is presumed to represent an integral value: int( 150 ) produces the integer value 150 By default, the string must use base 10 If conversion from another base is desired, that base can be indicated as a second optional parameter, for example: int( 7f, 16) evaluates to the integer 127 7 / 34

The float class The float class is the sole oating-point type in Python with a xed-precision Literal forms are 98.6 and 10e3 The constructor form of float() returns 0.0. When given a parameter, the constructor attempts to return the equivalent oating-point value For example, the call float(2) returns 2.0 If the parameter to the constructor is a string (float( 14.3 )), it attempts to parse the string as a oating-point value 8 / 34

The list class A list instance stores a sequence of objects A list is a referential structure, as it technically stores a sequence of references to its elements Lists are array-based sequenced and are zero-indexed (a list of length n has elements indexed from 0 to n 1 inclusive) Lists are probably the most used container types in Python, thay have many valuable behaviors, including the ability to dynamically expand and contract their capacities as needed 9 / 34

The list class Python uses the characters [ and ] as delimiters for a list literal, with [] being en empty list. For example: [ one, two, three ] If identiers a, b, c have been established, the following syntax is correct: [a, b, c] 10 / 34

The list class 11 / 34

The list class The list() constructor produces an empty list by default However, the constructor will accept any parameter that is of iterable type (e.g., strings, lists, tuples, sets, dictionaries) For example: 12 / 34

The tuple class The tuple class provides an immutable version of a sequence Python uses the characters ( and ) to delimit a tuple, with () being an empty tuple To express a tuple of length one as a literal, a comma must be placed after the element (within the parentheses). For example: 13 / 34

The str class The str class is designed to represent an immutable sequence of characters based upon the Unicode international character set Strings have a more compact internal representation than lists and tuples 14 / 34

The str class Strings can be enclosed in single quotes, as in ciao or double quotes, as in ciao The second choice is conveniente, in particular when using another of the quotation characters as in L attimo Alternatively, the quote delimiter can be designated using a backslash (the so-called escape character) as in L attimo Of course, even the backslash must itself be escaped (if necessary) Python also supports the delimiter or The main advantage of these delimiters is that strings naturally contain newlines 15 / 34

The set and frozenset classes The set class represents the mathematical notion of a set, namely a collection of distinct elements without an inherent order The major advantage of using a set is that it has a highly optimized method for checking whether a specic element is contained in the set Two main restrictions: The set does not maintain the elements in any particular order Only instances of immutable elements can be added to a Python set (integers, oating-point numbers, character strings) Python uses { and } as delimiters for a set, for example {1, 4, 2, 9} or aa, b, ciao There is an important exception: {} represents an empty dictionary (not a set). To represent an empty set the constructor set() must be invoked 16 / 34

The set and frozenset classes 17 / 34

The dict class The dict class represents a dictionary, from a set of distinct keys to associated values For example, a dictionary might map from unique student ID numbers, to larger student records (name, address, course grades) The literal form {} represents an empty dictionary, while a nonempty dictionary is expressed using a comma-separated series of key: value pairs For example: phone = { john : 4040, joe : 4041, kate : 4042} 18 / 34

Expressions, Operators and Precedence Logical Operators Python supports the following keyword operators for Boolean values: Operator not and or Description Unary negation Conditional and Conditional or The and and or operators short-circuit, in that they do not evaluate the second operand if the result can be determined based on the value of the rst operand 19 / 34

Expressions, Operators and Precedence Equality Operators Python supports the following operators to test two notions of equality: Operator Description is same identity is not dierent identity == equivalent!= not equivalent 20 / 34

Expressions, Operators and Precedence Equality Operators The expression a is b evaluated to True precisely when identiers a and b are aliases for the same object The expression a == b tests a more general notion of equivalence: If identiers a and b refer to the same object, then a == b evaluates to True If identiers refer to dierent objects that are equivalent, then a == b evaluates to True The precise notion of equivalence depends on the data type: two strings are considered equivalent if they match character for character, while two sets are equivalent if they have the same content, irrispective of order In general, use of is and is not should be reserved for situations in which it is necessary to detect true aliasing 21 / 34

Expressions, Operators and Precedence Comparison Operators Data types may dene a natural order via the following operators Operator Description < less than <= less than or equal to > greater than >= greater than or equal to These operators have expected behavior for numeric types They are dened lexicographically, and case sensitively, for strings An exception is raised if operands have incomparable types 22 / 34

Expressions, Operators and Precedence Comparison Operators 23 / 34

Expressions, Operators and Precedence Comparison Operators 24 / 34

Expressions, Operators and Precedence Arithmetic Operators Python supports the following arithmetic operators: Operator Description + addition subtraction multiplication / true division // integer division % modulo operator 25 / 34

Expressions, Operators and Precedence Arithmetic Operators The use of addition, subtraction and multiplication is straightforward (if both operands have type int, then the result is int as well; if one or both operands have type float, the result will be float) In Python, / denotes the so-called true division, returning the oating-point result of the computation, while // is used to perform the integral calculation and % returns the remainder of the integer division 26 / 34

Expressions, Operators and Precedence Arithmetic Operators Where: Python extends the semantics of // and % to cases where one or both operands are negative Let's assume that n, is the dividend m, is the divisor n = q m + r q, is the quotient (q = n//m) r, is the remainder (r = n%m) 27 / 34

Expressions, Operators and Precedence Arithmetic Operators n = q m + r When the divisor is positive, Python guarantees that 0 r < m As a consequence, we have that 27//4 = 7 and 27%4 = 1 We have indeed that 7 4 + 1 = 27 When the divisor is negative, Python guarantees that m < r 0 As a consequence, we have that 27//( 4) = 7 and 27% 4 = 1 We have indeed that 7 ( 4) 1 = 27 28 / 34

Expressions, Operators and Precedence Bitwise Operators Python supports the following bitwise operators for integers: Operator Description bitwise complement (prex unary operator) & bitwise and bitwise or ˆ bitwise exclusive-or << shift bits left, lling in with zeros >> shift bits right, lling in with sign bit 29 / 34

Expressions, Operators and Precedence Sequence Operators Each of Python's built-in sequence types (str, tuple, list) support the following operator syntaxes: Operator Description s[j] element at index j s[start : stop] slice including indices [start, stop] s[start : stop : step] slice including indices start, start+step, start +2 step,... up to but not equalling or stop s + t concatenation of sequences k s shorthand for s + s + s +... (k times) val in s containment check val not in s non-containment check 30 / 34

Expressions, Operators and Precedence Sequence Operators Python relies on zero-indexing of sequences (a sequence has n elements indexed from 0 to n 1 inclusive) It is supported the use of negative indices, which denote a distance from the end of the sequence: index 1 denotes the last element, index 2 the second to last and so on Python uses a slicing notation to describe subsequences of a sequence Slices are described as half-open intervals, with a start index (included) and a stop index (excluded) An optional step index, possibly negative, can be indicated as a third parameter of a slice If a start or stop index is omitted in the slicing notation, it is presumed to designate the extreme of the original sequence 31 / 34

Expressions, Operators and Precedence Sequence Operators 32 / 34

Expressions, Operators and Precedence Sequence Operators Lists are mutable, therefore the following syntax is used to replace an element at a given index s[j] = val Lists also support a syntax to remove the designated element from the list: del s[j] Slice notation can also be used to replace or delete a sublist 33 / 34

Expressions, Operators and Precedence Sequence Operators The notation val in s can be used for any of the sequences to see if there is an element equivalent to val in the sequence All sequences dene comparison operators based on lexicographic order, performing an element by element comparison until the rst dierence is found. For example: 34 / 34