The Practice of Computing Using PYTHON

Similar documents
University of Texas at Arlington, TX, USA

Python Review IPRE

Working with Strings. Husni. "The Practice of Computing Using Python", Punch & Enbody, Copyright 2013 Pearson Education, Inc.

The Practice of Computing Using PYTHON. Chapter 4. Working with Strings. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Data Structures. Lists, Tuples, Sets, Dictionaries

LECTURE 3 Python Basics Part 2

Python Review IPRE

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

CS1 Lecture 11 Feb. 9, 2018

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

Collections. Lists, Tuples, Sets, Dictionaries

CS1 Lecture 12 Feb. 11, 2019

More Data Structures. What is a Dictionary? Dictionaries. Python Dictionary. Key Value Pairs 10/21/2010

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

CIS192 Python Programming

Topic 7: Lists, Dictionaries and Strings

Advanced Python. Executive Summary, Session 1

Sequence of Characters. Non-printing Characters. And Then There Is """ """ Subset of UTF-8. String Representation 6/5/2018.

CMPT 120 Lists and Strings. Summer 2012 Instructor: Hassan Khosravi

What is a Class? Short Answer. Responding to Messages. Everything in Python is an Object 11/8/2010

Python Intro GIS Week 1. Jake K. Carr

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

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

Python Tutorial. CS/CME/BioE/Biophys/BMI 279 Oct. 17, 2017 Rishi Bedi

CS 1301 Exam 2 Fall 2010

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

John Perry. Fall 2009

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

Python Lists, Tuples, Dictionaries, and Loops

Python for Non-programmers

1 Strings (Review) CS151: Problem Solving and Programming

CSCE 110 Programming I Basics of Python: Lists, Tuples, and Functions

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

Module 04: Lists. Topics: Lists and their methods Mutating lists Abstract list functions Readings: ThinkP 8, 10. CS116 Fall : Lists

Python: common syntax

Introduction to programming using Python

ENGR/CS 101 CS Session Lecture 12

TUPLES AND RECURSIVE LISTS 5

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

Spring 2018 Discussion 7: March 21, Introduction. 2 Primitives

Collections. John Perry. Fall 2011

Introduction to Python

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

Fall 2017 Discussion 7: October 25, 2017 Solutions. 1 Introduction. 2 Primitives

Introduction to Problem Solving and Programming in Python.

Flow Control: Branches and loops

Programming in Python

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

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

Notebook. March 30, 2019

A lot of people make repeated mistakes of not calling their functions and getting errors. Make sure you're calling your functions.

Python. Executive Summary

Lecture 4. while and for loops if else test Tuples Functions. Let us start Python Ssh (putty) to UNIX/Linux computer puccini.che.pitt.

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

The Practice of Computing Using PYTHON. Chapter 2. Control. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

DM502 Programming A. Peter Schneider-Kamp.

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

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

Introduction to Python

Chapter 1. Data types. Data types. In this chapter you will: learn about data types. learn about tuples, lists and dictionaries

Spring INF Principles of Programming for Informatics. Manipulating Lists

Python Lists. What is not a Collection. A List is a kind of Collection. friends = [ 'Joseph', 'Glenn', 'Sally' ]

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

Python. Jae-Gil Lee Based on the slides by K. Naik, M. Raju, and S. Bhatkar. December 28, Outline

CSCE 110 Programming I

MITOCW watch?v=rvrkt-jxvko

CS Introduction to Computational and Data Science. Instructor: Renzhi Cao Computer Science Department Pacific Lutheran University Spring 2017

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

Iterators & Generators

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

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015

CS 234 Python Review Part 2

def order(food): food = food.upper() print( Could I have a big + food + please? ) return fresh + food

First cut, scope. Defining scope. Find the namespace. Passing argument to parameter. A function s namespace 6/13/2017. chapter 8.

Haskell: Lists. CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Friday, February 24, Glenn G.

Using Scala in CS241

CS Summer 2013

MUTABLE LISTS AND DICTIONARIES 4

Program Planning, Data Comparisons, Strings

University of Texas at Arlington, TX, USA

DSC 201: Data Analysis & Visualization

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

Lists How lists are like strings

Babu Madhav Institute of Information Technology, UTU 2015

Slicing. Open pizza_slicer.py

Python Programming Exercises 3

ENGR 102 Engineering Lab I - Computation

The Pyth Language. Administrivia

COMP1730/COMP6730 Programming for Scientists. Strings

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

MEIN 50010: Python Data Structures

Script language: Python Data structures

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

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

Sharing, mutability, and immutability. Ruth Anderson UW CSE 160 Spring 2018

Chapter 8 Dictionaries. Dictionaries are mutable, unordered collections with elements in the form of a key:value pairs that associate keys to values.

A Function that Calls Itself. It Doesn t Do Anything! Defining a Recursive Function. 2) Base Case. 1) Divide and Conquer 11/22/2010

The Three Rules. Program. What is a Computer Program? 5/30/2018. Interpreted. Your First Program QuickStart 1. Chapter 1

Introduction to Python. Fang (Cherry) Liu Ph.D. Scien5fic Compu5ng Consultant PACE GATECH

Python Programming: Lecture 2 Data Types

Transcription:

The Practice of Computing Using PYTHON William Punch Richard Enbody Chapter 6 Lists and Tuples 1 Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Data Structures 2

Data Structures and Algorithms Part of the science in computer science is the design and use of data structures and algorithms. As you go on in CS, you will learn more and more about these two areas. 3

Data Structures Data structures are particular ways of storing data to make some operation easier or more efficient. That is, they are tuned for certain tasks. Data structures are suited to solving certain problems, and they are often associated with algorithms. 4

Kinds of Data Structures Roughly two kinds of data structures: Built-in data structures - data structures that are so common as to be provided by default. User-defined data structures - (classes in object oriented programming) designed for a particular task. 5

Python Built-in Data Structures Python comes with a general set of built-in data structures: lists tuples string dictionaries sets others... 6

Lists 7

The Python List Data Structure A list is very simple - it is just an ordered sequence of items. You have seen such a sequence before in a string. A string is just a particular kind of list. What kind? 8

Make a List Like all data structures, lists have a constructor, named the same as the data structure. It takes an iterable data structure and adds each item to the list. It also has a shortcut: the use of square brackets [ ] to indicate explicit items. 9

More List Making alist = list( abc ) alist [ a, b, c ] newlist = [1, 3.14159, a, True] 10

Similarities with Strings concatenate/+ (but only of lists) repeat/* indexing (the [ ] operator) slicing ([:]) membership (the in operator) len (the length operator) 11

Differences Between Lists and Strings Lists can contain a mixture of any python object; strings can only hold characters. 1, bill,1.2345, True Lists are mutable; their values can be changed while strings are immutable. Lists are designated with [ ], with elements separated by commas; strings use. 12

13

Indexing Can be a little confusing - what does the [ ] mean, a list or an index? [1, 2, 3][1] 2 Context solves the problem. An index always comes at the end of an expression and is preceded by something (a variable, a sequence). 14

List of Lists mylst = [ a, [1, 2, 3], z ] What is the second element (index 1) of that list? Another list: mylst[1][0] # apply left to right [1, 2, 3][0] 1 mylst[1] [1, 2, 3] 15

Operators [1, 2, 3] + [4] [1, 2, 3, 4] [1, 2, 3] * 2 [1, 2, 3, 1, 2, 3] 1 in [1, 2, 3] True [1, 2, 3] < [1, 2, 4] True Compare index to index, the first difference determines the result. 16

List Functions len(lst): Number of elements in list (top level). len([1, [1, 2], 3]) 3 min(lst): Minimum element in the list. If list of lists, looks at first element of each list. max(lst): Max element in the list. sum(lst): Sum the elements, numeric only. 17

Iteration for element in [1, [1, 2], a,true]: print element 1 [1, 2] a True 18

Mutable 19

Change an Object s Contents Strings are immutable. Once created, the object s contents cannot be changed. New objects can be created to reflect a change, but the object itself cannot be changed: mystr = abc mystr[0] = z # instead, make new str # cannot do! newstr = mystr.replace( a, z ) 20

Lists are Mutable Unlike strings, lists are mutable. You can change the object s contents! mylst = [1, 2, 3] mylst[0] = 127 print mylst [127, 2, 3] 21

List Methods Remember, a function is a small program (such as len) that takes some arguments, the stuff in the parenthesis, and returns some value. A method is called in a special way, the dot call. It is called in the context of an object (or a variable holding an object). 22

Again, Lists have Methods mylist = [ a,1,true] mylist.append( z ) arguments to the method the object that we are calling the method with the name of the method 23

Some New Methods A list is mutable and can change: mylist[0]= a #index assignment mylist.append(), mylist.extend() mylist.pop() mylist.insert(), mylist.remove() mylist.sort() mylist.reverse() 24

More about List Methods Most of these methods do not return a value. This is because lists are mutable so the methods modify the list directly; there is no need to return anything. Can be confusing. 25

Unusual Results mylst = [4, 7, 1, 2] mylst = mylst.sort() mylst None # what happened? What happened was the sort operation changed the order of the list in place (right side of assignment). Then the sort method returned None, which was assigned to the variable. The list was lost and None is now the value of the variable. 26

Range We have seen the range function before. It generates a sequence of integers. In fact, what it generates is a list with that sequence: mylst = range(1, 5) mylst [1, 2, 3, 4] 27

Split The string method split generates a sequence of characters by splitting the string at certain split-characters. It, too, returns a list: splitlst = this is a test.split() splitlst [ this, is, a, test ] 28

Sorting Only lists have a built-in sorting method. Thus you often convert your data to a list if it needs sorting: mylst = list( xyzabc ) mylst [ x, y, z, a, b, c ] mylst.sort() # convert back to a string sortstr =.join(mylst) abcxyz 29

Sorted Function The sorted function will break a sequence into elements and sort the sequence, placing the results in a list: sortlst = sorted( hi mom ) [, h, i, m, m, o ] 30

Some Examples 31

Anagram Example Anagrams are words that contain the same letters in a different order. For example: iceman and cinema. A strategy to identify anagrams is to take the letters of a word, sort those letters, then compare the sorted sequences. Anagrams should have the same sequence. 32

Code Listing 6.1 33

def areanagrams(word1, word2): """Return true, if anagrams # Sort the words. word1_sorted = sorted(word1) word2_sorted = sorted(word2) # compare lists. if word1_sorted == word2_sorted: return True else: return False 34

Code Listing 6.5 Words from Text File 35

def makewordlist(gfile): """Create a list of words from the file.""" speech = [] # list of file words for linestring in gfile: linelist = linestring.split() for word in linelist: if word!= "-- : # straggler in file speech.append(word) return speech 36

Code Listing 6.6 Unique Words 37

# requires list of words from 6.5 def makeunique(speech): """Create a list of unique words.""" unique = [] # list of unique words for word in speech # check first if word is already there if word not in unique: unique.append(word) return unique 38

More about Mutables 39

Reminder: Assignment Assignment takes an object (the final object after all operations) from the RHS and associates it with a variable on the left-hand side. When you assign one variable to another, you share the association with the same object. 40

41

Immutables Object sharing, two variables associated with the same object, is not a problem since the object cannot be changed. Any changes that occur generate a new object. 42

43

Mutability Changes an Object If two variables associate with the same object, then both reflect any change to that object. 44

45

46

Copying If we copy, does that solve the problem? mylst = [1, 2, 3] newlst = mylst[:] 47

48

The Problem is What Gets Copied What actually gets copied is the top level reference. If the list has nested lists or uses other associations, the association gets copied. This is termed a shallow copy. 49

50

51

52

Tuples 53

Tuples Tuples are easy: they are simply immutable lists. They are designated with (,): mytuple = (1, a,3.14,true) 54

The Question is, Why? The real question is, why have an immutable list, a tuple, as a separate type? An immutable list gives you a data structure with some integrity, some permanency, if you will. You know you cannot accidentally change one. 55

Lists and Tuples Everything that works with a list works with a tuple except methods that modify the tuple. Thus indexing, slicing, len, print all work as expected. However, none of the mutable methods work: append, extend, del. 56

Commas Make a Tuple For tuples, you can think of a comma as the operator that makes a tuple, where the ( ) simply acts as a grouping: mytuple = 1,2 # creates (1,2) mytuple = (1,) # creates (1) mytuple = (1) # creates 1 not (1) mytuple = 1, # creates (1) 57

Data Structures In General 58

Organization of Data We have seen strings, lists and tuples so far. Each is an organization of data that is useful for some things, not as useful for others. 59

A Good Data Structure Efficient with respect to us (some algorithms). Efficient with respect to the amount of space used. Efficient with respect to the time it takes to perform some operations. 60

EPA Example 61

List Comprehensions 62

Lists are a Big Deal! The use of lists in Python is a major part of its power. Lists are very useful and can be used to accomplish many tasks. Therefore Python provides some pretty powerful support to make common list tasks easier. 63

Constructing Lists One way is a list comprehension [n for n in range(1,5)] mark the comp with [ ] [ n for n in range(1,5)] returns [1,2,3,4] what we collect what we iterate through. Note that we iterate over a set of values and collect some (in this case all) of them 64

Modifying What We Collect [ n**2 for n in range(1,6)] Returns [1,4,9,16,25]. Note that we can only change the values we are iterating over, in this case n. 65

Multiple Collects [x+y for x in range(1,4) for y in range (1,4)] It is as if we had done the following: mylist = [ ] for x in range (1,4): for y in range (1,4): mylist.append(x+y) [2,3,4,3,4,5,4,5,6] 66

Modifying What Gets Collected [c for c in Hi There Mom if c.isupper()] The if part of the comprehensive controls which of the iterated values is collected at the end. Only those values which make the if part true will be collected: [ H, T, M ] 67