Script language: Python Data structures

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

Advanced Algorithms and Computational Models (module A)

Lists. Lists Element Types. Creating Lists. CS 112 Lists Part II 2/22/09. Dan Fleck Spring 2009 George Mason University

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

Python Tutorial. Day 1

Babu Madhav Institute of Information Technology, UTU 2015

egrapher Language Reference Manual

COLLEGE OF ENGINEERING, NASHIK-4

Data Handing in Python

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

Topic 7: Lists, Dictionaries and Strings

Sequences and iteration in Python

LECTURE 1. Getting Started with Python

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

LECTURE 3 Python Basics Part 2

Python Lists: Example 1: >>> items=["apple", "orange",100,25.5] >>> items[0] 'apple' >>> 3*items[:2]

Introduction to Python

Python Evaluation Rules

Declaration and Memory

Primitive Data Types: Intro

CS2304: Python for Java Programmers. CS2304: Sequences and Collections

CIS192: Python Programming Data Types & Comprehensions Harry Smith University of Pennsylvania September 6, 2017 Harry Smith (University of Pennsylvani

CPD for GCSE Computing: Practical Sheet 6 February 14

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

Variable and Data Type 2

Programming to Python

Visual C# Instructor s Manual Table of Contents

Ceng 111 Fall 2015 Week 7a

Basic Scripting, Syntax, and Data Types in Python. Mteor 227 Fall 2017

Python - Variable Types. John R. Woodward

Chapter 10: Creating and Modifying Text Lists Modules

MULTIPLE CHOICE. Chapter Seven

ECS15, Lecture 13. Midterm solutions posted. Topic 4: Programming in Python, cont. Staying up to speed with Python RESOURCES. More Python Resources

The Pyth Language. Administrivia

UNIVERSITÀ DI PADOVA. < 2014 March >

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

Index. object lifetimes, and ownership, use after change by an alias errors, use after drop errors, BTreeMap, 309

Worksheet 6: Basic Methods Methods The Format Method Formatting Floats Formatting Different Types Formatting Keywords

Play with Python: An intro to Data Science

Introduction to Python! Lecture 2

Overview of List Syntax

XQ: An XML Query Language Language Reference Manual

COMP284 Scripting Languages Lecture 15: JavaScript (Part 2) Handouts

Python. Karin Lagesen.

Data Structures. Dictionaries - stores a series of unsorted key/value pairs that are indexed using the keys and return the value.

Python: Short Overview and Recap

Computer Sciences 368 Scripting for CHTC Day 3: Collections Suggested reading: Learning Python

Lesson 4: Type Conversion, Mutability, Sequence Indexing. Fundamentals of Text Processing for Linguists Na-Rae Han

STSCI Python Introduction. Class URL

Booleans, Logical Expressions, and Predicates

Strings. Upsorn Praphamontripong. Note: for reference when we practice loop. We ll discuss Strings in detail after Spring break

MATVEC: MATRIX-VECTOR COMPUTATION LANGUAGE REFERENCE MANUAL. John C. Murphy jcm2105 Programming Languages and Translators Professor Stephen Edwards

CIS192 Python Programming

Chapter 2: Using Data

6. Data Types and Dynamic Typing (Cont.)

PYTHON MOCK TEST PYTHON MOCK TEST III

Primitive Types. Four integer types: Two floating-point types: One character type: One boolean type: byte short int (most common) long

Part 4 CLASSES AS ABSTRACT DATA TYPES AND INTERFACE IMPLEMENTATION. Data Structures and Algorithms 31632

Java+- Language Reference Manual

Module 3: Strings and Input/Output

Python allows variables to hold string values, just like any other type (Boolean, int, float). So, the following assignment statements are valid:

Built-in Types of Data

Python and Bioinformatics. Pierre Parutto

Lecture 1. Types, Expressions, & Variables

Introduction to Python for Plone developers

Java Fall 2018 Margaret Reid-Miller

Lecture 1. Getting Started with Python

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes

LISTS WITH PYTHON. José M. Garrido Department of Computer Science. May College of Computing and Software Engineering Kennesaw State University

Haske k ll An introduction to Functional functional programming using Haskell Purely Lazy Example: QuickSort in Java Example: QuickSort in Haskell

CMPT 125: Lecture 3 Data and Expressions

Chapter 6: List. 6.1 Definition. What we will learn: What you need to know before: Data types Assignments

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

Outline. Data and Operations. Data Types. Integral Types

Operators. Java operators are classified into three categories:

CSCE 110 Programming I

Introduction to Bioinformatics

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

CS61A Lecture 16. Amir Kamil UC Berkeley February 27, 2013

Programming in Python

An introduction introduction to functional functional programming programming using usin Haskell

COMP1730/COMP6730 Programming for Scientists. Strings

Python for ArcGIS. Lab 1.

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

Computing with Numbers

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

Introduction to Computer Programming CSCI-UA 2. Review Midterm Exam 1

Collections. Lists, Tuples, Sets, Dictionaries

BEGINNING PROBLEM-SOLVING CONCEPTS FOR THE COMPUTER. Chapter 2

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Beyond Blocks: Python Session #1

Data type built into Python. Dictionaries are sometimes found in other languages as associative memories or associative arrays.

RTL Reference 1. JVM. 2. Lexical Conventions

Python Programming: Lecture 2 Data Types

Introduction to: Computers & Programming: Strings and Other Sequences

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

Basic data types. Building blocks of computation

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

All programs can be represented in terms of sequence, selection and iteration.

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

Transcription:

Script language: Python Data structures Cédric Saule Technische Fakultät Universität Bielefeld 3. Februar 2015

Immutable vs. Mutable Previously known types: int and string. Both are Immutable but what does that mean? The numbers are fix and cannot be modified. New allocation by: number = number + 1 When assigning, a new object is created with the desired value. So what are Immutable for? Mutable (variable data types) use Immutable for addressing. Be referred to as hashable. Same Immutable reference (in part) to optimize memory on the same memory address. 2 of 38

Data types in Python. There is different built-in (immutable, mutable) data type: Logical values bool Numbers int, (long), float, complex Sequential data string, tuple, list Mapping dict Sets set, frozenset Special cases: None. Worth nothing Meets in: Java null Perl undef 3 of 38

Python Logical Boolean, Truth tests, equality operators. 4 of 38

What are the logical values in Python? Logical values are clearly defined by bool. True. False. In addition, each truth test results are an object True. 5 of 38

What are the logical values in Python? The following statements are considered as False: None False 0, 0L, 0.0, 0j the number 0,, (), [] Empty sequential data type {} Empty mapping. Special case for some classes which implement one of the following methods and would provide this as a return value: False or 0. nonzero () len () 6 of 38

Boolean operators The following operators replace the usual shortcuts, && respectively!, sorted by order of priority. In addition, they are special functions which are their own input value and have the following outputs: X or Y logical OR, as a function: If X == False, then Y, otherwise X X and Y logical AND, as a function: If X == True, then Y, otherwise X not X logical negation, (no!; Negate the statement fowarded by the command line.) 7 of 38

Comparison operators can be concatenated: X < Y <= Z will be X<Y and Y<=Z, where the last expression is evaluated only if the first is evaluated as True. All objects can be compared. Objects of different types cannot be equal but they are always sorted in the same order so, in a heterogeneous array, they will be sorted on the same order. Objects must be of the same type to implement cmp (), to be evaluated as equal. 8 of 38

Comparison operators < smaller than > greater than == equal is objects identity <= smaller or equal >= greater or equal!= different is not object not of the same identity <, <=, > and >= throw atypeerror when we compare complex numbers. With sequential data types, it exists two other comparison operators. 9 of 38 in is included. not in is not included.

Python Numbers Integer, Float, Complex 10 of 38

Numbers There is four different types of numbers in Python 2.X. Integer/Long Integers 100 # Integer 100 L # Long sys. maxint # Maximal size of integers, # until it is automatically # converted into long. Float Floating point numbers, 1. or -55.3 Complex Complex numbers, 1.5+2j 11 of 38

Numbers Special & Operations Since the Python 2.6 and 3, the Integers and the Longs have been merged. When the range of a number is too large for an Integer, it is automatically converted in Long. int <OPERAND> int = int and float <OPERAND> int = float +, -, *, /... ll // Integer portion of the division. % Modulo Y**Z -X Opposite of X +X Unchanged X Y Z Shorthand: x <OPERAND>= y x = x <OPERAND> y 12 of 38

Numbers Important functions abs() Absolute value long() Output as long complex(r, i) Complex number, (r)real part, (i)imaginary part divmod(x,y) (x // y, x % y) int() Output as int float() Output as float c.conjugate() Compute the conjugate of a complex number math.* See math-module 13 of 38

Exercises Precedence of the operators Compute the following operations. What is the precedence of the operators? > 4 * 3 + 6 > 4 + 3 * 6 > 100 / 5 % 3 > 5 * 6 ** 7 > res = 7. > n = 5 > res //= -n 14 of 38

Python Sequential data types. String, Tuple, List 15 of 38

Sequential data types Sequential data types can generally be seen as a container for sequences of objects and their references. For Strings, Lists and Tuples apply the same standard access operators. > s = " Hello you!" 0123456789 > s [2:7] > s [0] llo y H > list = [s, 54, World ] 0 1 2 > list [1] > list [2][0:2] 54 Wo 16 of 38

Sequential data types Operations & Functions x in s True, if x is in s, otherwise False. s*n, n*s Concatenates n copies of s. s[i] Object in the i th position. s[i:j] Slice from i to j. len(s) Size of s. s.index(i) First occurrence of i in s x not in s False, if x is in s, otherwise True. s+t Concatenation of s and t. s[i:j:k] Slice from i to j with an increase of k. min(s) Smallest element in s. max(s) Greatest element in s. s.count(i) Number of all i in s. 17 of 38

String String of any length. String are instanciated between " " or String indices begin with 0 and the last index is: len(string)-1. Immutable Changes of form s[0] = "a" not allowed. Escape character: \. Only ASCII characters can be processed easily into 2.x. String!= Unicode In Python 3.x, both the type were merged for the first time. s = "I am a string of size 24" 18 of 38

String Important methods str(<input>) INPUT as string. count(sub[, start[, end]]) Number of non-overlapping substrings sub. endswith(suffix[, start[, end]]) True, if the string finish with suffix, then False; Can also be a String with a tuple. find(sub[, start[, end]]) Index Position of the first occurence of sub, returns -1 otherwise. r/lstrip([chars]) Remove the string chars from left or right, no parameters or None space. If you want to stripped on both sides, use strip([chars]). Specify optional start and end in slice notation. 19 of 38

String Important methods partition(sep) The string is split at sep; Returns a 3-uple: (prefix, sep, suffix), if sep is not found, we will have (string,, ). split([sep[, maxsplit]]) Split the String after each sep if it is given, otherwise after each white space. maxsplit specify the maximal number of plit parts. capitalize() The first letter is in capital, the others are in small. swapcase() Small letters become capital and vice versa. join(<iterable>) starts all elements from ITERABLE to the String. 20 of 38

Exercise String and numbers A first small exercise on the theme of types, conversions and modifications: 1. Create the number z with the value 4353,3. 2. Convert it as string and split it by the point and save the result in your own variable l. 3. Add 1 to the integer part and save it again as string in l. 4. Overwrite z, now it should be in the front of the decimal point and the modified integer value of l should be behind the point. z and l and their contents should always be of the same type! 21 of 38

Tuple No changeable list Immutable. Any length. Elements can be of different types. Notation: Content is between parentheses (...). Listed objects will be comma-separated. > s1 = (u" are ",1) > suffix = " tuple " > _tuple = (s1, 1337, suffix ) > _tuple ((u" are ", 1), 1337, " tuple ") 22 of 38

List Changeable list Mutable. Any length. Elements can be of different types. Notation: Content is between square brackets [...]. Listed objects will be comma-separated. > s1 = (u" are ",1) > suffix = " tuple " > _list = [s1, 1337, suffix ] > _list [2] = " list " > _list [(u" are ", 1), 1337, " list "] 23 of 38

Exercise (Im)mutable 1. Create a variable tuple as seen on the tuple slides. 2. Instanciate a variable of type list with the content of the _tuple. Modify the list so that its content be the same as _list. 3. Convert back the first list in tuple and set the content once again in a new variable of tuple. Uses the functions list() as well as tuple(). 24 of 38

Operations on sequential mutable data types. Replace and remove references: s[i] = x Reallocation. s[i:j] = t Slice replacement with iterable t. s[i:j:k] = t Interval increased with k with the elements of t. s.insert(i, x) x an index i slide s[i:i] = [x]. del s[i(:j(:k))] Drop elements, j and k are optional. 25 of 38

Operations on sequential mutable data types. Find references, change data structures: s.index(x[,i[,j ]]) Index of the elements x s[k] == x and i <= k < j. s.remove(x) x deleted from s del s[s.index(x)]. s.extend(x) Add all element of x to s. 26 of 38

Exercises Lists Create a List with these elements: 1, 2, 3, 4, 5, 6, 7, 8, 9 Remove the first element. Remove the first element and add it again to the list. Remove the second and third element. Replace the forth element with the size of the list. Append the list with the elements [10, 11, 12] at the end of the list. Append the list with the elements [10, 11, 12] between the elements 7 and 8. Give each step from the list. 27 of 38

Operations on sequential mutable data types. List as Queue: s.append(x) Add x to s s[len(s):len(s)] = [x]. s.pop([i]) Delete the last elements of the list and return them x = s[i]; del s[i]; return x. > list = [] > store = list. append > store ( apple ) > store ( math.pi) > list [ apple, 3.141592653589793] 28 of 38

Operations on sequential mutable data types. Change order of objects: s.reverse() Reverse elements order. s.sort([cmp[, key[, reversep]]])... Both methods change the sequential data structure directly No returned value. Memory efficient. Particularity of sort(...): Details for cmp-function in Advanced data structures. 29 of 38

Exercises Reverse strings considered you a short script that reverses a given string. So Here I am! would become!ma I ereh. 30 of 38

Python Mapping data types. Dict[ionary] (Hashmap) 31 of 38

Mapping data types. dict Until now, dict is the only mapping data type in Python. This data type is mutable. It consists of unordered pairs of key : value. key must be hashable immutable!!! value can be of any type. Caution when used in numbers as key. Equivalent point to the same value: 1 == 1. float very inappropriate (floating point number!!11elf.) Standard notation: dict1 = {key0: value0, key1: value1, key2: value2} Specified in standard notation or on dict s constructor. 32 of 38

Dictionary creation dictionaries can be instanciated by the standard notation or will be instanciated through the call of the following constructor. class dict (** kwarg ) class dict ( mapping, ** kwarg ) class dict ( iterable, ** kwarg ) Example: > a = dict ( one =1, two =2) > b = { one : 1, two : 2} > c = dict ( zip ([ one, two ], [1, 2])) > d = dict ([( two, 2), ( one, 1)]) > e = dict ({ one : 1, two : 2}) > a == b == c == d == e True 33 of 38

Read and modify a dictionnary. values can be directly accessed by key (Read, Modification, Addition of new mappings): > b = {1: on, 2: two } > b [1] on > b [1] = one > b [1] one > b [3] = three > b [2; two, 3: three, 1: one } 34 of 38

Python Set Data types Mix Set, Frozenset 35 of 38

Set, Frozenset Mix set and frozenset are containers for unique element. Mathematically, they can be viewed as sets. Each object (element) must be immutable. There is some methods to specific mixing: union(), intersetion(), issubset(),issuperset(),isdisjoint(),... We give two different implementations for mixing: set Variable mix frozenset Non-variable mix immutable 36 of 38

Set, Frozenset Example of code > s = set ( abc ) > s { a, b, c } > s. update ( x, [8]) > s {8, a, b, c, x } > s. intersection ( ac8 ) { a, c } 37 of 38

Set, Frozenset Constructors: class set([iterable]), class frozenset([iterable]). Short hands-instantiation without constructor: lem1, elem2,..., elemnelem1, elem2,..., elemn. In sets of sets the referenced set type must be frozenset. Other methods and explanations: Python 2.7-Documentation 38 of 38