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

Similar documents
Programming in Python

18.1. CS 102 Unit 18. Python. Mark Redekopp

Collections. Lists, Tuples, Sets, Dictionaries

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

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

MUTABLE LISTS AND DICTIONARIES 4

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

Overview of List Syntax

Python. Karin Lagesen.

Lecture Agenda. Objects. But First... Immutable Types and Nesting. Immutable Types and Nesting

COMP1730/COMP6730 Programming for Scientists. Strings

Advanced Python. Executive Summary, Session 1

Lecture 7: Python s Built-in. in Types and Basic Statements

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

Topic 7: Lists, Dictionaries and Strings

Script language: Python Data structures

Introduction to Python

Python - Variable Types. John R. Woodward

Data Handing in Python

Lab 6: Data Types, Mutability, Sorting. Ling 1330/2330: Computational Linguistics Na-Rae Han

Advanced Algorithms and Computational Models (module A)

Python Tutorial. Day 1

Variable and Data Type 2

The Pyth Language. Administrivia

Sequences and iteration in Python

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

Python. Executive Summary

Beyond Blocks: Python Session #1

Play with Python: An intro to Data Science

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

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

Dictionaries. By- Neha Tyagi PGT CS KV 5 Jaipur II Shift Jaipur Region. Based on CBSE Curriculum Class -11. Neha Tyagi, KV 5 Jaipur II Shift

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

CSCE 110 Programming I

Data Structures. Lists, Tuples, Sets, Dictionaries

6. Data Types and Dynamic Typing (Cont.)

Introduction to Python

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

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

Introduction to Python: Data types. HORT Lecture 8 Instructor: Kranthi Varala

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

EE 355 Unit 17. Python. Mark Redekopp

Python Tutorial. CSE 3461: Computer Networking

Lecture 21. Chapter 12 More Python Containers

Introduction to Problem Solving and Programming in Python.

ECE 364 Software Engineering Tools Laboratory. Lecture 4 Python: Collections I

STSCI Python Introduction. Class URL

CS 33. Introduction to C. Part 5. CS33 Intro to Computer Systems V 1 Copyright 2017 Thomas W. Doeppner. All rights reserved.

cosmos_python_ Python as calculator May 31, 2018

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

Algorithmic Thinking: Computing with Lists

COMP10001 Foundations of Computing Functions

Types, lists & functions

COLLEGE OF ENGINEERING, NASHIK-4

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

Lists, loops and decisions

Introduction to Python

Lists How lists are like strings

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

COMP1730/COMP6730 Programming for Scientists. Sequence types, part 2

List of squares. Program to generate a list containing squares of n integers starting from 0. list. Example. n = 12

Python Basics. 1 of 7 9/5/2018, 8:51 AM. txt1 = "ada lovelace, english mathematician and writer" print(txt1)

University of Washington CSE 140 Introduction to Data Programming Winter Midterm exam. February 6, 2013

Python Programming Language

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

Python The way of a program. Srinidhi H Asst Professor Dept of CSE, MSRIT

Dictionaries. Looking up English words in the dictionary. Python sequences and collections. Properties of sequences and collections

CMSC 201 Fall 2015 Lab 12 Tuples and Dictionaries

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

Compound Data Types 1

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

1. BASICS OF PYTHON. JHU Physics & Astronomy Python Workshop Lecturer: Mubdi Rahman

COMP1730/COMP6730 Programming for Scientists. Dictionaries and sets

A Brief Introduction to Python for those who know Java. (Last extensive revision: Daniel Moroz, fall 2015)

The Practice of Computing Using PYTHON

Python for Non-programmers

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

AI Programming CS S-02 Python

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

Collections. Michael Ernst CSE 190p University of Washington

Scripting Languages. Python basics

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

John Perry. Fall 2009

The current topic: Python. Announcements. Python. Python

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

MEIN 50010: Python Data Structures

Lists, Tuples and Dictionaries. HORT Lecture 10 Instructor: Kranthi Varala


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

Download Python from Any version will do for this class

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

COMP 364: Functions II

Review 4. Lists and Sequences

Collections. John Perry. Fall 2011

CSC326 Python Sequences i. CSC326 Python Sequences

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

CS 2316 Exam 1 Spring 2014

University of Texas at Arlington, TX, USA

Programming to Python

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

Transcription:

Day 3: Collections Suggested reading: Learning Python (3rd Ed.) Chapter 8: Lists and Dictionaries Chapter 9: Tuples, Files, and Everything Else Chapter 13: while and for Loops 1

Turn In Homework 2

Homework Review Will not be posted online 3

Write code. At least a little. Every day. Play around! 4

5

Single-Value Objects So far: int, float, str, bool Objects of these types hold exactly one value x int 42 6

How can we have a collection of (related) values? 7

Collection Examples All even numbers from 40 100 Outdoor temperatures by date/time List of data files to read Weights associated with test items Frequency counts of a set of tokens Set of all observations from an instrument 8

Lists 9

List Ordered Variable length Arbitrary objects and types Access via integer position ( index ) Mutable x list 0 1 2 3 42 3.141 Tim Hello int float str 42 3.141 Tim str Hello 10

Creating a List [item0, item1,..., item-2, item-1] names = ['Tim', 'Scot', 'Alan'] empty = [] mixed = [42, 3.14159, 'hello', True] long = [925, 161, 164, 529, 168, 208, 896, 531, 747, 932] some_ints = range(2, 100, 2) 11

Using a List list[index] courses 0 1 2 CS 302 CS 367 CS 368 courses = ['CS 302', 'CS 367', 'CS 368'] print courses courses[0] = 'CS 302 - Intro to Progr.' courses[1] += ' - Data Structures' print 'What is %s?' % (courses[2]) 12

x = [42, 't', 1.3] Other List Operations length len(x) 2 concatenate [1, 2] + x [1, 2, 42, 't', 1.3] membership 42 in x True slice x[0:2] [42, 't'] append x.append(3) x: [42, 't', 1.3, 3] extend x += [3, 1] x: [42, 't', 1.3, 3, 1] insert x.insert(1, 'a') x: [42, 'a', 't', 1.3] delete del x[1] x: [42, 1.3] remove x.pop(1) 't' x: [42, 1.3] 13

List Bounds valid index: int from 0 to (length 1) lists can grow and shrink (append, insert, ) limited only by memory going out of bounds is run-time error: >>> x = ['a', 'b', 'c'] >>> x[3] Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: list index out of range 14

Perplexing Python 15

Mutable vs. Immutable Mutable types allow changes to objects in memory Examples: list, dict Immutable types do not Examples: int, float, str, bool >>> x = 42 >>> y = x >>> x += 1 >>> print x 43 >>> print y #?? >>> x = [] >>> y = x >>> x += [1] >>> print x [1] >>> print y #?? 16

Back to Collections 17

Tuples (item0, item1,..., item-2, item-1) tuple[n] Immutable lists List operators work, methods do not t = (1, 2) t += (3, 4) # wait, what?!? if 3 in t: print t[1:3] 18

Dictionaries 19

Dictionary Unordered Variable length Arbitrary objects and types Access via arbitrary, unique immutable object ( key ) Mutable x 'en' 'fr' 'de' 'es' 'English' 'French' 'German' 'Spanish' dict 'en' 'fr' 'de' 'es' str str 'English' 'French' 'German' Spanish' str str 20

Creating a Dictionary {keya: valuea, keyb: valueb,...} languages = {'en': 'English', 'fr': 'French', 'de': 'German', 'es': 'Spanish'} # print languages # {'fr': 'French', 'en': 'English',...} readings = {'TI3a': 43.23, 'TF3a': 47.09, 'TI3b': 38.22, 'TF3b': 42.96, 'TI4a': 42.98, 'TF4a': 47.00,...} 21

dictionary[key] Using a Dictionary languages = {'en': 'English',...} print languages['de'] languages['es'] = 'Espanol' languages['de'] = 'Deutsche' languages['de'] += ' (German)' print "'es' => '%s'" % (languages['es']) len(languages) # 4 languages['ja'] = 'Japanese' # new entry len(languages) # 5 22

Other Dictionary Operations c = {'a': 5, 'the': 7, 'an': 2} length len(c) 3 membership 'an' in c True safe lookup c.get('an') c.get('no') 2 None keys c.keys() ['the', 'an', 'a'] items c.items() [('the', 7), ('an', 2) ] delete del c['the'] c: {'an': 2, 'a': 5} remove c.pop('the') 7 c: {'an': 2, 'a': 5} 23

Sets models mathematical concept of a set unordered, variable-length, mutable collection somewhat between a list and a dictionary a = set([1, 2, 3]) b = set([2, 3, 4]) 1 in a # True 1 in b # False a & b # set([2, 3]) a b # set([1, 2, 3, 4]) a b # set([1]) 24

Collections and Loops 25

Sequences and Loops for item in seq: print item # list, tuple, set, str sum = 0 for n in xrange(1, 11): sum += n print sum s = 'Hello, world!' print 'Char ASCII' print '---- -----' for char in s: print '%4s %5s' % (char, ord(char)) 26

Dictionaries and Loops for key in dict.keys(): print '%s => %s' % (key, dict[key]) for pair in dict.items(): print '%s => %s' % pair for key, value in dict.items(): print '%s => %s' % (key, value) valid_tests = [] for key, value in readings.items(): if value > 0: valid_tests.append(key) 27

Phew! 28

Other Scripting Languages All have arrays and associative arrays Check for different or additional: Terminology (list, array; hash, map, dictionary, ) Syntax ([] vs. {}, len(array) vs. array.length) Operations (sort, unique elements, flatten, shuffle) Collections (e.g., set) 29

Homework Implement a simple data analysis tool Collect data observations Display the items and their count, sum, mean(, ) BE SURE TO LABEL YOUR PRINTOUT!!! #!/usr/bin/env python """Homework for CS 368-4 () Assigned on Day 03, 2012-10-29 Written by <Your Name> """ 30