University of Texas at Arlington, TX, USA

Similar documents
The Practice of Computing Using PYTHON

University of Texas at Arlington, TX, USA

CS1 Lecture 11 Feb. 9, 2018

Python Review IPRE

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

University of Texas at Arlington, TX, USA

CS1 Lecture 12 Feb. 11, 2019

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

Collections. Lists, Tuples, Sets, Dictionaries

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

Python Review IPRE

Data Structures. Lists, Tuples, Sets, Dictionaries

Advanced Python. Executive Summary, Session 1

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

LECTURE 3 Python Basics Part 2

Introduction to Python

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

ENGR/CS 101 CS Session Lecture 12

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

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

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

Introduction to Problem Solving and Programming in Python.

CIS192 Python Programming

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

Python Intro GIS Week 1. Jake K. Carr

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

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

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

Python for Non-programmers

Programming in Python

Spring INF Principles of Programming for Informatics. Manipulating Lists

Python: common syntax

Introduction to programming using Python

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

Python Programming Exercises 3

CS 1301 Exam 2 Fall 2010

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

1 Strings (Review) CS151: Problem Solving and Programming

Topic 7: Lists, Dictionaries and Strings

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

Programming in Python

Flow Control: Branches and loops

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

Python. Executive Summary

Introduction to Python

John Perry. Fall 2009

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

Slicing. Open pizza_slicer.py

CSCE 110 Programming I

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

Notebook. March 30, 2019

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

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

CSc 120. Introduc/on to Computer Programing II. 01- b: Python review. Adapted from slides by Dr. Saumya Debray

Lists in Python CS 8: Introduction to Computer Science, Winter 2018 Lecture #10

TUPLES AND RECURSIVE LISTS 5

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

CS Summer 2013

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

Using Scala in CS241

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

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

Python Lists, Tuples, Dictionaries, and Loops

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

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

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

Impera've Programming

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

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

Babu Madhav Institute of Information Technology, UTU 2015

University of Texas at Arlington, TX, USA

Lists How lists are like strings

Teach A level Compu/ng: Algorithms and Data Structures

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

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

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

Introduction to Python! Lecture 2

CS S-02 Python 1. Most python references use examples involving spam, parrots (deceased), silly walks, and the like

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

Control, Quick Overview. Selection. Selection 7/6/2017. Chapter 2. Control

MITOCW watch?v=rvrkt-jxvko

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

DM502 Programming A. Peter Schneider-Kamp.

Implementing an Algorithm for Boomerang Fraction Sequences in Python

Chapter 8 SETS AND DICTIONARIES

About the Final. Saturday, 7-10pm in Science Center 101. Closed book, closed notes. Not on the final: graphics, file I/O, vim, unix

Python debugging and beautification

A list a **mutable** collection of ordered items, that can be of mixed type - created using square brackets.

Lecture #12: Immutable and Mutable Data. Last modified: Mon Feb 22 16:33: CS61A: Lecture #12 1

Python List built-in methods, accessing elements, selection, slicing, recursive functions, list comprehension

6. Data Types and Dynamic Typing (Cont.)

CS 234 Python Review Part 2

Script language: Python Data structures

Try and Error. Python debugging and beautification

CS 349 / SE 382 Scripting. Professor Michael Terry March 18, 2009

ENGR 102 Engineering Lab I - Computation

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

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

MEIN 50010: Python Data Structures

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

Transcription:

Dept. of Computer Science and Engineering University of Texas at Arlington, TX, USA

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.

Data structures are par?cular ways of storing data to make some opera?on easier or more efficient. That is, they are tuned for certain tasks. Data structures are suited to solving certain problems, and they are oden associated with algorithms.

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 par?cular task.

Python comes with a general set of built in data structures: lists tuples string dic?onaries sets others...

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 par?cular kind of list. What kind?

Like all data structures, lists have a constructor, named the same as the data structure (list). It takes an iterable data structure and adds each item to the list. alist = list( abc ) alist [ a, b, c ]

It also has a shortcut: the use of square brackets [ ] to indicate explicit items. newlist = [1, 3.14159, a, True]

Concatenate + (but only of lists) Repeat * indexing (the [ ] operator) slicing ([:]) membership (the in operator) len (the length operator)

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.

Can be a li_le 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).

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 mylst[1] [1, 2, 3] [1, 2, 3][0] 1

[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.

len(lst): Number of elements in list (top level). len([1, [1, 2], 3]) 3 min(lst): Minimum element in the list max(lst): Max element in the list sum(lst): Sum the elements, numeric only.

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

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 )

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

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 mylist will contain [ a,1, True, z ]

A list is mutable and can change: mylist[0]= a #index assignment mylist.append(x) #appends element x at the end of mylist mylist.extend(c) #appends list C to end of mylist mylist.pop() #removes last element of list mylist.insert(e,p) #inserts element e in posi?on p mylist.remove(x) #removes first element with value x mylist.sort() #sort elements of mylist mylist.reverse() #reverses elements of mylist

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 why?

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

We have seen the range func?on before. It generates a sequence of integers. In fact, range generates a list with that sequence: mylst = range(1, 5) mylst [1, 2, 3, 4]

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

Only lists have a built in sor?ng method. Sugges?on: convert your data to a list if it needs sor?ng: mylst = list( xyzabc ) mylst [ x, y, z, a, b, c ] mylst.sort() # convert back to a string sortstr =.join(mylst) abcxyz

The sorted func?on 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 ]

Anagrams are words that contain the same le_ers in a different order. For example: iceman and cinema. How can you iden?fy anagrams? A strategy to iden?fy anagrams is to take the le_ers of a word, sort those le_ers, then compare the sorted sequences. Anagrams : should have the same sequence.

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

myint = 27 Assignment takes an object from the RHS and associates it with variable on the LHS yourint = myint When you assign one variable to another, you share the associa/on with the same object.

Any changes that occur Does not change exis?ng objects but generates a new object

Mutable objects (e.g., lists) are handled differently!

So then: >>> list1 [1, 2, 3, 27] >>> list2 [1, 2, 3, 27]

Does copying (with slice) solve the problem?

What actually gets copied is the top level reference. If the list has nested lists or uses other associa?ons, the associa?on gets copied. This is termed a shallow copy.

Tuples are easy: they are simply immutable lists. They are designated with (,): mytuple = (1, a,3.14,true) Note that the comma generates a tuple, not the parenthesis!

The real ques?on 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.

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.

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)