Lecture 18: Lists II. CS1068+ Introductory Programming in Python. Dr Kieran T. Herley 2018/19. Department of Computer Science University College Cork

Similar documents
Lecture 11: while loops CS1068+ Introductory Programming in Python. for loop revisited. while loop. Summary. Dr Kieran T. Herley

Lecture 8: Simple Calculator Application

Lecture 15: Dictionaries

Lecture 10: Strings. CS1068+ Introductory Programming in Python. Dr Kieran T. Herley 2018/19. Department of Computer Science University College Cork

CS205: Scalable Software Systems

Lecture 2: Writing Your Own Class Definition

Lecture 4: Simple Input-Calculate-Output Programs

Lecture 2: Python Arithmetic

Introduction to programming using Python

EXTERNAL SORTING. CS 564- Spring ACKs: Dan Suciu, Jignesh Patel, AnHai Doan

CS1 Lecture 12 Feb. 11, 2019

Lecture 7: Functions. CS1068+ Introductory Programming in Python. Dr Kieran T. Herley 2018/19. Department of Computer Science University College Cork

Lecture 10: Boolean Expressions

CSc 372 Comparative Programming Languages

CSc 372 Comparative Programming Languages

Lecture 5: Regular Expression and Finite Automata

CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees. CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees 1

Alastair Burt Andreas Eisele Christian Federmann Torsten Marek Ulrich Schäfer. October 6th, Universität des Saarlandes. Introduction to Python

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

CSI33 Data Structures

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

Lists CS 1111 Introduction to Programming Fall 2018

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

CS 1110: Introduction to Computing Using Python Loop Invariants

Working with Lists 4

Lecture 4: Stack Applications CS2504/CS4092 Algorithms and Linear Data Structures. Parentheses and Mathematical Expressions

Random Numbers; Object-Oriented Programming 11/14/2017

Arrays. Friday, November 9, Department of Computer Science Wellesley College

CSCE 314 TAMU Fall CSCE 314: Programming Languages Dr. Flemming Andersen. Haskell Functions

The Practice of Computing Using PYTHON

Lecture 11. Lecture 11: External Sorting

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

Lecture 4: Basic I/O

Lecture 2: SQL Basics CS1106/CS5021/CS6503 Introduction to Relational Databases. Brief Note on Naming Conventions. Our Running Example.

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

CSC148H Week 3. Sadia Sharmin. May 24, /20

Simple Lexical Analyzer

CS F-11 B-Trees 1

Lists, loops and decisions

Python Lists and for Loops. Learning Outcomes. What s a List 9/19/2012

MUTABLE LISTS AND DICTIONARIES 4

Lecture 2: SQL Basics

University of Washington CSE 140 Data Programming Winter Final exam. March 11, 2013

CS150 - Sample Final

Announcements. Project 5 is on the street. Second part is essay questions for CoS teaming requirements.

Programming in Python

CS 206 Introduction to Computer Science II

Department of Computer Science & Engineering Indian Institute of Technology Kharagpur. Practice Sheet #04

Topic 7: Lists, Dictionaries and Strings

CIS192 Python Programming

Module 08: Searching and Sorting Algorithms

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

Lecture 1: Relational Databases

CSC236H Lecture 5. October 17, 2018

CS 323 Lecture 1. Design and Analysis of Algorithms. Hoeteck Wee

Programming Languages ML Programming Project Due 9/28/2001, 5:00 p.m.

CS1 Lecture 11 Feb. 9, 2018

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

Data Structures and Algorithms

CMPSCI 105: Lecture #12 Searching, Sorting, Joins, and Indexing PART #1: SEARCHING AND SORTING. Linear Search. Binary Search.

Introduction to Computer Programming for Non-Majors

List Processing Patterns and List Comprehension

Lecture 3: More SQL Basics CS1106/CS5021/CS6503 Introduction to Relational Databases. Single-Criterion WHERE Conditions. SQL Conditions.

Introduction to Python

CS Lecture 19: Loop invariants

CS264: Homework #1. Due by midnight on Thursday, January 19, 2017

CS150 Sample Final. Name: Section: A / B

TUPLES AND RECURSIVE LISTS 5

Download the forcomp.zip handout archive file and extract it somewhere on your machine.

Sequence Types FEB

F28PL1 Programming Languages. Lecture 14: Standard ML 4

CS112 Spring 2012 Dr. Kinga Dobolyi. Exam 2. Do not open this exam until you are told. Read these instructions:

Shell CSCE 314 TAMU. Haskell Functions

CS 11 python track: lecture 3. n Today: Useful coding idioms

Decorate, sort, undecorate pattern

CS205: Scalable Software Systems

List Processing Patterns and List Comprehension

Lecture 3: More SQL Basics

Lecture I: Shortest Path Algorithms

Introduction to Computer Programming for Non-Majors

Lecture 2: Getting Started

Lecture 8: Context Free Grammars

Practice Question. Omar Khan / Atif Alvi. October 10, 2016

Name CPTR246 Spring '17 (100 total points) Exam 3

DM502 Programming A. Peter Schneider-Kamp.

Lecture 4: SQL Data Manipulation Basics

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

CS-141 Final Exam Review December 8, 2017 Presented by the RIT Computer Science Community

CSI33 Data Structures

Programming. We will be introducing various new elements of Python and using them to solve increasingly interesting and complex problems.

Python Lists, Tuples, Dictionaries, and Loops

Lab 9: More Sorting Algorithms 12:00 PM, Mar 21, 2018

Math236 Discrete Maths with Applications

Module 8: Binary trees

Working with recursion. From definition to template. Readings: HtDP, sections 11, 12, 13 (Intermezzo 2).

CS 307 Final Fall 2009

Working with recursion

CS-141 Final Exam Review May 16, 2015 Presented by the RIT Computer Science Community

University of Texas at Arlington, TX, USA

15110 Principles of Computing, Carnegie Mellon University - CORTINA. Binary Search. Required: List L of n unique elements.

Transcription:

Lecture 18: Lists II CS1068+ Introductory Programming in Python Dr Kieran T. Herley 2018/19 Department of Computer Science University College Cork

Summary More on Python s lists. Sorting and reversing. List comprehensions. 1

Some useful list functions lst.sort() lst.reverse() Rearrange elements within s in increasing order. Reverse the order of the elements within s. [4, 2, 1, 3].sort() ==> [1, 2, 3, 4] [2, 2, 1, 2].sort() ==> [1, 2, 2, 2] [1, 2, 3, 4].reverse() ==> [4, 3, 2, 1] NB: Both re-arrange elements of lst in place. 2

sort vs sorted Suppose x = [3, 6, 2, 1, 5, 4] sort Rearranges elements in place; returns None sorted leaves original untouched; returns copy of x in increasing order Syntax x after val. returned x.sort() [1, 2, 3, 4, 5, 6] None sorted(x) [3, 6, 2, 1, 5, 4] [1, 2, 3, 4, 5, 6] For back-to-front copy of list x, list(reversed(x)) 3

Palindromes def is list palindrome ( lst ): # Return True if list ' lst ' reads the same # left to right as it does right to left. mirror = lst.copy() mirror. reverse () return lst == mirror Note: function copy makes a (shallow) copy of a list 4

Palindromes cont d def is palindrome ( text ): # Return True if string ' text ' is a palindrome.q lst = list (text) return is list palindrome ( lst ) Note: function list transform string into list of its constituent characters. For example list("python") ==> ["P", "y", "t", "h", "o", "n"] 5

Some more list functions lst.insert(i, x) Insert new element with value x at index i. lst.pop(i) Remove the ithe element and return its value lst.remove(x) Remove the first (from left) occurrence of value x within s. [2, 3, 5, 7].insert(0, 20) ==> [20, 2, 3, 5, 7] [2, 3, 5, 7].insert(2, 30) ==> [2, 3, 30, 5, 7] [2, 3, 5, 7].pop(1) ==> [2, 5, 7] (returns 3) [2, 3, 5, 7].pop(3) ==> [2, 3, 5] (returns 7) [3, 1, 4, 1, 5, 9].remove(1) ==> [3, 4, 1, 5, 9] 6

Example: anagrams Write a Python function that checks whether two words are anagrams of each other (same number of each letter occurring) Example: "silent", "listen" "monty", "python" ==> True ==> False 7

Example: anagrams Write a Python function that checks whether two words are anagrams of each other (same number of each letter occurring) Example: "silent", "listen" "monty", "python" ==> True ==> False def are anagrams(word1, word2): # Return True if 'word1' and 'word2' are anagrams i.e # contain the same letters in the same multiplicity. lst1 = list (word1.upper()) lst2 = list (word2.upper()) lst1. sort () lst2. sort () return lst1 == lst2 7

List comprehensions

List comprehensions Create a list of the squares of the first few integers Doing it the straightforward way: squares = [] for n in range(10): squares.append(n 2) 8

List comprehensions Create a list of the squares of the first few integers Doing it the straightforward way: squares = [] for n in range(10): squares.append(n 2) Using a list comprehension: squares = [n 2 for n in range(10)] 8

List comprehensions with filters Create a list of the odd squares of the first few integers: odd squares = [n 2 for n in range(10) if n % 2 == 1] This is equivalent to odd squares = [] for n in range(10): if n % 2 == 1: odd squares.append(n 2) 9

Example: acronyms Write a Python function that generates an acronym for a phrase by taking the first letter of each word Example: "Random access memory" ==> "RAM" 10

Example: acronyms Write a Python function that generates an acronym for a phrase by taking the first letter of each word Example: "Random access memory" ==> "RAM" def get acronym(phrase): # Return a acronym for 'phrase' words = phrase. split () initials = [w[0].upper() for w in words] return. join ( initials ) 10

Calculating most common value in a list def most common(lst): # Return the most commonly occurring value in list ' lst ' # ( ties broken arbitrarily ). List must be non empty. multiplicities = [ lst. count(elem) for elem in lst ] largest = max( multiplicities ) return lst [ multiplicities. index( largest )] 11

Calculating most common value in a list lst: [1, 2, 3, 1, 4, 1] Count multiplicity (number of appearances) of each element in list multiplicities = [ lst. count(elem) for elem in lst ] Determine the largest multiplicity largest = max( multiplicities ) Return the corresponding list element return lst [ multiplicities. index( largest )] multiplicities: [3, 1, 1, 3, 1, 3] largest: 3 index is 0 lst[...] ==> 1 12

What does this do? print(,. join (reversed([n for n in input(). split ()]))) 13

What does this do? print(,. join (reversed([n for n in input(). split ()]))) Admittedly a bit cryptic, but demonstrates Python s power. 13

Dictionary comprehensions 14

Back Material

Notes and Acknowledgements Reading Code Acknowledgements 15