Sorting Ruth Anderson UW CSE 140 Winter 2014 1. Sorting hamlet = "to be or not to be that is the question whether tis nobler in the mind to suffer".split()

Slides:



Advertisements
Similar presentations
List comprehensions UW CSE 140 Winter Ways to express a list 1.Explicitly write the whole thing: squares = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81,
Advertisements

Lists Ruth Anderson CSE 140 University of Washington 1.
Container Types in Python
Recursion Genome 559: Introduction to Statistical and Computational Genomics Elhanan Borenstein.
CHAPTER 4 AND 5 Section06: Sequences. General Description "Normal" variables x = 19  The name "x" is associated with a single value Sequence variables:
UW CSE 190p Section 7/12, Summer 2012 Dun-Yu Hsiao.
Andean South America.
Chemistry II Atomic Theory History Tutorial. Time Periods 500 BC – 1600 AD: The Alchemical Era 1600 AD – 1800 AD: The Transitional Time Period 1800 AD.
Computer Science 111 Fundamentals of Programming I Search Algorithms.
Lists and More About Strings CS303E: Elements of Computers and Programming.
DECOMPOSITION. KEY TERMS  Structured programming  Functionality  Structure Charts  Stepwise refinement  Modularity.
What is Science and Technology?. What is Science? Science is the knowing or the explaining of events in the real world. Science Science explains these.
UW CSE 190p Section 8/2, Summer 2012 Dun-Yu Hsiao.
I can make observations of science notebooks so I am able to understand the purpose of notebooking in science.
Lists CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 8 Working.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 8 Lists and Tuples.
Lists CS303E: Elements of Computers and Programming.
AP Computer Science edition Review 1 ArrayListsWhile loopsString MethodsMethodsErrors
Pre-Reading: 1.Do you know the names of some famous scientists? 2. What are they famous for?
Giants of the Past Scientists Project. Overview “If I have seen further, it is by standing on the shoulders of giants.” – Sir Isaac Newton It is important.
Sorting Ruth Anderson UW CSE 160 Spring sorted vs. sort hamlet = "to be or not to be that is the question whether tis nobler in the mind to suffer".split()
Collections Michael Ernst CSE 190p University of Washington.
Compsci 101.2, Fall Plan for WBTB l APT Quiz 3 – due tonight l Solving problems in the wild  How can you change how things are sorted Other.
COP 2510 Chapter 6 - Functions. Random function (randint) #import the desired function import random #integer random number in the range of 1 through.
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.
AO3 help This guide is to help you ensure that you have everything that you need for a PASS/MERIT If you would like a distinction, please see me.
Lists Ruth Anderson University of Washington CSE 160 Winter
Computer Science 101 Python Lists. Literals, Assignment, Comparisons, Concatenation Similar to the behavior of strings so far a = [1, 2, 3] b = range(1,
OCR Computing GCSE © Hodder Education 2013 Slide 1 OCR GCSE Computing Python programming 3: Built-in functions.
Quiz 3 Topics Functions – using and writing. Lists: –operators used with lists. –keywords used with lists. –BIF’s used with lists. –list methods. Loops.
性別平等教育 尊重彼此的不同 學會善解別人 瑞田國小. 你喜歡看那一種卡通? 小妹妹一定是背著洋娃娃嗎?
Functions with Arguments and Return Values, Oh My! CS303E: Elements of Computers and Programming.
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Assignment 5 is posted. Exercise 8 is very similar to what you will be doing with assignment 5. Exam.
Compsci 6/101, Spring Why is sorting data important? l Guess a number in [1,100] --- I'll tell you yes or no  How many guesses needed worst-case?
Dictionaries Ruth Anderson UW CSE 160 Winter
Copyright © 2013 by John Wiley & Sons. All rights reserved. SETS AND DICTIONARIES CHAPTER Slides by James Tam Department of Computer Science, University.
Indentations makes the scope/block Function definition def print_message (): print “hello” Function usages print_message () hubo.move ()// hubo is a class.
More on Lists.
Department of Computer Science,
Famous Scientists.
Sharing, mutability, and immutability
Lists Part 1 Taken from notes by Dr. Neil Moore & Dr. Debby Keen
Ruth Anderson UW CSE 160 Winter 2017
Lists Part 1 Taken from notes by Dr. Neil Moore
Ruth Anderson UW CSE 160 Spring 2015
Lists in Python.
Manipulating Arrays.
Sharing, mutability, and immutability
Isaac Newton ( ) February 19, 2018.
Natural Forces Quiz By Andrew 1.
CISC101 Reminders Assn 3 due tomorrow, 7pm.
Strings and Lists – the split method
Ruth Anderson UW CSE 160 Spring 2018
Sharing, mutability, and immutability
Ruth Anderson UW CSE 160 Winter 2017
Michael Ernst UW CSE 140 Winter 2013
Writing Functions( ) (Part 4)
Topics Sequences Introduction to Lists List Slicing
Writing Functions( ) (Part 4)
Lists Part 1 Taken from notes by Dr. Neil Moore
Basic String Operations
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Module 8 – Searching & Sorting Algorithms
Topics Sequences Introduction to Lists List Slicing
Ruth Anderson UW CSE 160 Spring 2018
CSE 231 Lab 8.
CISC101 Reminders Assignment 3 due today.
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Ruth Anderson UW CSE 160 Winter 2016
Presentation transcript:

Sorting Ruth Anderson UW CSE 140 Winter

Sorting hamlet = "to be or not to be that is the question whether tis nobler in the mind to suffer".split() print "hamlet:", hamlet print "sorted(hamlet):", sorted(hamlet) print "hamlet:", hamlet print "hamlet.sort():", hamlet.sort() print "hamlet:", hamlet Lists are mutable – they can be changed – including by functions 2

Customizing the sort order Goal: sort a list of names by last name names = ["Isaac Newton", "Albert Einstein", "Niels Bohr", "Marie Curie", "Charles Darwin", "Louis Pasteur", "Galileo Galilei", "Margaret Mead"] print "names:", names This does not work: print "sorted(names):", sorted(names) When sorting, how should we compare these names? "Niels Bohr" "Charles Darwin" 3

Sort key A sort key is a different value that you use to sort a list, instead of the actual values in the list def last_name(str): return str.split(" ")[1] print 'last_name("Isaac Newton"):', last_name("Isaac Newton") Two ways to use a sort key: 1.Create a new list containing the sort key, and then sort it 2.Pass a key function to the sorted function 4

1. Use a sort key to create a new list Create a different list that contains the sort key, sort it, then extract the relevant part: names = ["Isaac Newton", "Fred Newton", "Niels Bohr"] # keyed_names is a list of [lastname, fullname] lists keyed_names = [] for name in names: keyed_names.append([last_name(name), name]) Take a look at the list you created, it can now be sorted: print "keyed_names:", keyed_names print "sorted(keyed_names):", sorted(keyed_names) print "sorted(keyed_names, reverse = True):" print sorted(keyed_names, reverse = True) (This works because Python compares two elements that are lists elementwise.) sorted_keyed_names = sorted(keyed_names, reverse = True) sorted_names = [] for keyed_name in sorted_keyed_names: sorted_names.append(keyed_name[1]) print "sorted_names:", sorted_names 5 1) Create the new list. 2) Sort the list new list. 3) Extract the relevant part.

Digression: Lexicographic Order Aaron Andrew Angie with withhold withholding [1, 9, 9] [2, 1] [3] [1] [1,1] [1,1,1] Able Charlie baker delta 6

2. Use a sort key as the key argument Supply the key argument to the sorted function or the sort function def last_name(str): return str.split(" ")[1] names = ["Isaac Newton", "Fred Newton", "Niels Bohr"] print "sorted(names, key = last_name):" print sorted(names, key = last_name) print "sorted(names, key = last_name, reverse = True):" print sorted(names, key = last_name, reverse = True) print sorted(names, key = len) def last_name_len(name): return len(last_name(name)) print sorted(names, key = last_name_len) 7

itemgetter is a function that returns a function import operator operator.itemgetter(2, 7, 9, 10) operator.itemgetter(2, 7, 9, 10)("dumbstricken") operator.itemgetter(2, 5, 7, 9)("homesickness") operator.itemgetter(2, 7, 9, 10)("pumpernickel") operator.itemgetter(2, 3, 6, 7)("seminaked") operator.itemgetter(1, 2, 4, 5)("smirker") operator.itemgetter(9, 7, 6, 1)("beatnikism") operator.itemgetter(14, 13, 5, 1)("Gedankenexperiment") operator.itemgetter(12, 10, 9, 5)("mountebankism") 8

Using itemgetter from operator import itemgetter student_score = ('Robert', 8) itemgetter(0)(student_score)  “Robert” itemgetter(1)(student_score)  8 student_scores = [('Robert', 8), ('Alice', 9), ('Tina', 7)] Sort the list by name: sorted(student_scores, key=itemgetter(0) ) Sort the list by score sorted(student_scores, key=itemgetter(1) ) 9

Two ways to Import itemgetter from operator import itemgetter student_score = ('Robert', 8) itemgetter(0)(student_score)  “Robert” itemgetter(1)(student_score)  8 Or import operator student_score = ('Robert', 8) operator.itemgetter(0)(student_score)  “Robert” operator.itemgetter(1)(student_score)  8 10

Sorting based on two criteria Two approaches: Approach #1: Use an itemgetter with two arguments Approach #2: Sort twice (most important sort last) student_scores = [('Robert', 8), ('Alice', 9), ('Tina', 10), ('James', 8)] Goal: sort based on score; if there is a tie within score, sort by name Approach #1: sorted(student_scores, key=itemgetter(1,0) ) Approach #2: sorted_by_name = sorted(student_scores, key=itemgetter(0) ) sorted_by_score = sorted(sorted_by_name, key=itemgetter(1) ) 11

Sort on most important criteria LAST Sorted by score (ascending), when there is a tie on score, sort using name from operator import itemgetter student_scores = [('Robert', 8), ('Alice', 9), ('Tina', 10), ('James', 8)] sorted_by_name = sorted(student_scores, key=itemgetter(0) ) >>> sorted_by_name [('Alice', 9), ('James', 8), ('Robert', 8), ('Tina', 10)] sorted_by_score = sorted(sorted_by_name, key=itemgetter(1) ) >>> sorted_by_score [('James', 8), ('Robert', 8), ('Alice', 9), ('Tina', 10)] 12

More sorting based on two criteria If you want to sort different criteria in different directions, you must use multiple calls to sort or sorted student_scores = [('Robert', 8), ('Alice', 9), ('Tina', 10), ('James', 8)] Goal: sort score from highest to lowest; if there is a tie within score, sort by name alphabetically (= lowest to highest) sorted_by_name = sorted(student_scores, key=itemgetter(0) ) sorted_by_hi_score = sorted(sorted_by_name, key=itemgetter(1), reverse=True) 13

Sorting: strings vs. numbers Sorting the powers of 5: >>> sorted([125, 5, 3125, 625, 25]) [5, 25, 125, 625, 3125] >>> sorted(["125", "5", "3125", "625", "25"]) ['125', '25', '3125', '5', '625'] 14