CHAPTER 4 AND 5 Section06: Sequences. General Description "Normal" variables x = 19  The name "x" is associated with a single value Sequence variables:

Slides:



Advertisements
Similar presentations
ThinkPython Ch. 10 CS104 Students o CS104 n Prof. Norman.
Advertisements

Course A201: Introduction to Programming 10/28/2010.
Container Types in Python
Chapter 6 Lists and Dictionaries CSC1310 Fall 2009.
Python Mini-Course University of Oklahoma Department of Psychology Day 4 – Lesson 15 Tuples 5/02/09 Python Mini-Course: Day 4 – Lesson 15 1.
Dictionaries: Keeping track of pairs
String and Lists Dr. Benito Mendoza. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list List.
I210 review Fall 2011, IUB. Python is High-level programming –High-level versus machine language Interpreted Language –Interpreted versus compiled 2.
Lists Introduction to Computing Science and Programming I.
CSCI/CMPE 4341 Topic: Programming in Python Chapter 6: Lists, Tuples, and Dictionaries – Exercises Xiang Lian The University of Texas – Pan American Edinburg,
JaySummet IPRE Python Review 2. 2 Outline Compound Data Types: Strings, Tuples, Lists & Dictionaries Immutable types: Strings Tuples Accessing.
CMPT 120 Lists and Strings Summer 2012 Instructor: Hassan Khosravi.
Guide to Programming with Python
Python Programming Chapter 10: Dictionaries Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
Python Programming Chapter 8: Lists Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
October 4, 2005ICP: Chapter 4: For Loops, Strings, and Tuples 1 Introduction to Computer Programming Chapter 4: For Loops, Strings, and Tuples Michael.
Lists in Python.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 9 More About Strings.
Handling Lists F. Duveau 16/12/11 Chapter 9.2. Objectives of the session: Tools: Everything will be done with the Python interpreter in the Terminal Learning.
Python Lists and Such CS 4320, SPRING List Functions len(s) is the length of list s s + t is the concatenation of lists s and t s.append(x) adds.
Collecting Things Together - Lists 1. We’ve seen that Python can store things in memory and retrieve, using names. Sometime we want to store a bunch of.
Built-in Data Structures in Python An Introduction.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 8 Working.
Introducing Python CS 4320, SPRING Resources We will be following the Python tutorialPython tutorial These notes will cover the following sections.
Data Collections: Lists CSC 161: The Art of Programming Prof. Henry Kautz 11/2/2009.
10. Python - Lists The list is a most versatile datatype available in Python, which can be written as a list of comma-separated values (items) between.
Lists. The list is a most versatile datatype available in Python which can be written as a list of comma-separated values (items) between square brackets.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 8 Lists and Tuples.
By Austin Laudenslager AN INTRODUCTION TO PYTHON.
More Sequences. Review: String Sequences  Strings are sequences of characters so we can: Use an index to refer to an individual character: Use slices.
Guide to Programming with Python Chapter Five Lists and dictionaries (data structure); The Hangman Game.
LISTS and TUPLES. Topics Sequences Introduction to Lists List Slicing Finding Items in Lists with the in Operator List Methods and Useful Built-in Functions.
7. Lists 1 Let’s Learn Saenthong School, January – February 2016 Teacher: Aj. Andrew Davison, CoE, PSU Hat Yai Campus
Python Files and Lists. Files  Chapter 9 actually introduces you to opening up files for reading  Chapter 14 has more on file I/O  Python can read.
Dictionaries. The compound types you have learned about - - strings, lists, and tuples – use integers as indices. If you try to use any other type as.
String and Lists Dr. José M. Reyes Álamo. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list.
PYTHON PROGRAMMING. WHAT IS PYTHON?  Python is a high-level language.  Interpreted  Object oriented (use of classes and objects)  Standard library.
Guide to Programming with Python Chapter Four Strings, and Tuples; for Loops: The Word Jumble Game.
Unit 4 – Chapter 4 Strings and Tuples. len() Function You can pass any sequence you want to the len() function and it will return the length of the sequence.
Section06: Sequences Chapter 4 and 5. General Description "Normal" variables x = 19 – The name "x" is associated with a single value Sequence variables:
String and Lists Dr. José M. Reyes Álamo.
Section06: Sequences Chapter 4 and 5.
Python – May 18 Quiz Relatives of the list: Tuple Dictionary Set
Python - Lists.
Containers and Lists CIS 40 – Introduction to Programming in Python
From Think Python How to Think Like a Computer Scientist
Section 6: Sequences Chapter 4 and 5.
Lists Part 1 Taken from notes by Dr. Neil Moore & Dr. Debby Keen
CISC101 Reminders Quiz 2 this week.
Introduction to Strings
Bryan Burlingame 03 October 2018
Bryan Burlingame Halloween 2018
CHAPTER THREE Sequences.
Guide to Programming with Python
6. Lists Let's Learn Python and Pygame
8 – Lists and tuples John R. Woodward.
Lists A list is an ordered set of values, where each value is identified by an index. The values that make up a list are called its elements. Lists are.
String and Lists Dr. José M. Reyes Álamo.
Topics Sequences Introduction to Lists List Slicing
Lists Part 1 Taken from notes by Dr. Neil Moore
15-110: Principles of Computing
CISC101 Reminders Assignment 2 due today.
CHAPTER 4: Lists, Tuples and Dictionaries
Bryan Burlingame Halloween 2018
Topics Sequences Introduction to Lists List Slicing
And now for something completely different . . .
Python Review
For loop Using lists.
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Introduction to Computer Science
Presentation transcript:

CHAPTER 4 AND 5 Section06: Sequences

General Description "Normal" variables x = 19  The name "x" is associated with a single value Sequence variables: L = (5, 17, 19, -1)  A name which is associated with a group of values.

Python sequences Immutable types (Ch. 4)  Strings: a group of characters  Tuples: a group of other python objects Mutables types (Ch. 5)  Lists: a group of other python objects  Dictionaries: a group of key-value pairs (the value is a python object), indentified by key.

Length of sequences Returns the number of "things" in the sequence. S = "ABCDEF" T = (1, 2, 3) U = (4, 5, (6, 7, 8), 9) len(S) # 6 len(T) # 3 len(U) # 4

Indexing Sequences (except Dictionaries) Index number identifies a position. s = "Oranges" Examples: >>> s[0] # 'O' >>> s[2]# 'a' >>> s[-1] # 's' >>> s[-2] # 'e' The indexed value can be used anywhere a "normal" variable / constant would Oranges

Slicing Sequences Returns a section of a sequence  Doesn't work for Dictionaries. >>> s = "Apples-Oranges" >>> s[1:4] # "ppl" >>> s[5:9] # "s-Or" >>> s[-6:-1] # "range" >>> s[-5:-7] # "" >>> s[10:] # "nges" >>> s[:6] # "Apples" >>> s[1:10:2] # "plsOa" >>> s[12:8:-1] # "egna" >>> s[-1::-1] # "segnarO-selppA" (backward) Apples-Oranges

for loops A type of repetition, but tied to a sequence. Syntax: for var in seq: # for-loop block The number of items in seq controls the number of iterations. var is a variable, created / updated by python  A reference to the "current" item in the sequence. Equivalent to: i = 0 while i < len(seq): var = seq[i] i += 1 # for-loop block

for loop example s = "ABCDE" for c in s: print(c) Outputs: A B C D E # Doing the same thing with a while loop i = 0 while i < len(s): c = s[i] print(c) i += 1

range objects range([start,] end [, step]) Treated as a sequence (sort of) Useful when used with for loops Example: for i in range(1, 6,2): # prints 1, 3, then 5 print(i) s = "ABCDE" for i in range(len(s)): # prints 0,1,2,3, then 4 print(i, s[i])

a new random function random.choice(sequence) Returns a random element of sequence. s = "ABCDEFG" print(random.choice(s)) Here's how we could do this ourself: Indx = random.randint(0,len(s)-1) X = s[Indx] # Same as x = random.choice(s)

Concatenation Combining two sequences into a new one. s1 = "ABCDEF" s2 = "GHI" s3 = s1 + s2

count method All sequences have this method. Returns the # of times that value appears S = "ABCDEFGBH" S.count("B") # returns 2 S.count("AB") # returns 1 S.count("I") # returns 0

in operator val in seq Returns True or False if the given value appears in the sequence. Examples: S = "ABCD" "B" in S # True "X" in S # False "AB" in S # True

Review A few "quiz-ish" problems:  Write a function which takes a string as an argument and returns true if this string is a palindrome.  Write another function which also takes a string as an argument and returns the odd characters, in reverse sequence.  Example: func2("ABCDEFGHI") would return "HFDB"

Tuples A (possibly) heterogenous group of python objects. Deliminted by parentheses (when creating) Examples: T1 = (1, 2, 3, 4, 5) T2 = ("ABC", "DEF", "GHI") T2[1] # "DEF" T2[1][0] # "D" T3 = (1.7, "XYZ", 19) T4 = () # Empty tuple T5 = (5,) # Tuple with only 1 elem. T6 = (10, 11, (12, 13), 14) # Nested T7 = (screen, marioSurf, luigiSurf)

Tuples, cont. All the previous operations, work with tuples [Try it!] Where have we seen tuples already?  Colors (pygame.draw.xxx, screen.fill)  Positions (pygame.draw.xxx)  Window Dimensions (pygame.display.set_mode)  Point-lists (pygame.draw.polygon)  Rectangles (pygame.draw.rect)  Multiple return values from functions

2D Tuples A common name for a tuple with tuple (sub-)elements Example: T = ((15,8,7), (3,2,9), (1,-2,10)) T[0] # (15,8,7) T[0][1] # 8 T[0:2] # ((15,8,7), (3,2,9)) T[0][1:]# (8,7) T[1] + T[2] # (3,2,9,1,-2,10) T[1] + T[1] # (3,2,9,3,2,9) T[1][1] + T[2][-1] # 12

Tuple un-packing Another way to extract values from a sequence. T = (1, 2, 3) x,y,z = T # x is 1, y is 2, z is 3 One catch: #variables on left must be == len(T) Look familiar?  We've seen this with functions returning multiple values def foo(): x = random.randint(1,10) y = random.randint(1,10) return x, y # Equivalent to return (x, y) a, b = foo() # or… t = foo() a = t[0] b = t[1]

Review Write a function which takes a tuple of numbers as an arugment and returns the average of this tuple:  e.g. print(avg((3, 5, 15, 9))) would print 8.0  Make sure it will work with tuples of any size Use a for loop to "traverse" a tuple of this form: example = (("A", 5), ("joe", 3), ("!", 4)) and produce this output (make it work with tuples of any size): AAAAA joejoejoe !!!!

Lists Like a tuple, but they are mutable.  You can add elements  You can remove elements  You can change elements  You can share references to the same thing. Delimited by square brackets.  Note: All sequences use square brackets for slicing / indexing.  The delimiters are only relevant when creating.

Lists Adding an element: L = [4, 5] G = [1.0, 2.0, 3.0] H = L + G # H is now [4, 5, 1.0, 2.0, 3.0] G.append(9.0) # G is now [1.0, 2.0, 3.0, 9.0] G.insert(0, 11.0) # G is [11.0,1.0,2.0,3.0,9.0] G.insert(2, 0.0) # G is [11.0,1.0,0.0,2.0,3.0,9.0] Note: these are both methods of all list objects.

Lists, cont. Removing an element L = [1.3, 9.2, 5.8, 1.7, 1.3, 2.1]  Using the remove method L.remove(9.2) # L is [1.3,5.8,1.7,1.3,2.1] L.remove(1.3) # L is [5.8, 1.7, 1.3, 2.1] L.remove(L[0]) # L is [1.7, 1.3, 2.1] L.remove(2.2) # ERROR!  Using the del operator del L[0]  Note: del can be used to "un-define" any variable, not just mutable seq. variables.

Lists, cont. Changing elements L = [1.1, 2.2, 3.3, 4.4, 5.5] L[0] = 9.9 # L is [9.9, 2.2, 3.3, 4.4, 5.5] L[1:3] = [10.1, 11.11, 12.12] print(L) # [9.9, 10.1, 11.1, 12.12, 4.4, 5.5] You can only do this to mutable objects. Even though tuples allow indexing, they don't allow changing.  A work around: T = (1.1, 2.2, 3.3, 4.4, 5.5) T = (9.9,) + T[1:] T = (T[0],) + (10.1, 11.1, 12.12) + T[3:] Note: has the same effect for lists, but we're re-creating the tuple (could be slow for large tuples)

Lists & Mutability, cont. Mutability also means a variable of a mutable type is a reference (or pointer) to the memory location. AddressValue This is L …… …… This is the actual list data (4 bytes per float) …… …… …… L = [1.2, 3.7, 5.0, 9.9, 10.3]

Lists & Mutability, cont. This is important because assigning a new variable = to the mutable object simply copies the reference. AddressValue This is L …… …… This is the actual list data (4 bytes per float) …… >>> L = [1.2, 3.7, 5.0, 9.9, 10.3] >>> K = L This is K …… >>> K[2] = 1000 AddressValue This is L …… …… This is the actual list data (4 bytes per float) …… >>> print(K) [1.2, 3.7, 1000, 9.9, 10.3] >>> print(L) [1.2, 3.7, 1000, 9.9, 10.3]

Mutable objects as function parameters Recall: when you have a function call, the argument is copied to the parameter. This is still true, but with mutable objects (e.g. Lists), you're copying the reference. This means that when we change elements of the list in the function those changes are also reflected in the argument (in the caller). We'll take advantage of this…a lot.

Mutable objects as parameters Example: def func(a): """ a is a list of integers """ for i in range(len(a)): a[i] -= 1 L = [3.1, 2.9, 7.6, 4.0, 1.3, 10.4] H = [0.0, 12.3, 6.5] func(L) func(H) print(L) # Prints [2.1, 1.9, 6.6, 3.0, 0.3, 9.4] Print(H) # Prints [-1.0, 11.3, 5.5]

Lists & Mutability We’ll see other mutable objects in python:  Dictionaries  Objects (from Object-Oriented Programming)

A bigger example Lame space-invaders clone  Bullets  Enemies moving in a group Data Structures  A list holding player data [x-pos, bullets]  A list of invaders [[x1,y1], [x2,y2], [x3,y3], …] Functions  drawInvaders(surf, L)  drawPlayer(surf, P)  handleCollisions(L, P) ...