Sorting Ruth Anderson UW CSE 160 Spring 2015 1. sorted vs. sort 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.
Class Scope class Student { private: string id; string firstName, lastName; float gpa; public: void Read() { cin >> id >> firstName >> lastName >> gpa;
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.
1 Working with References. 2 References Every object variable is a reference to an object Also true when an object is passed as an argument When the object.
UW CSE 190p Section 7/12, Summer 2012 Dun-Yu Hsiao.
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.
Sorting. Simple Sorting As you are probably aware, there are many different sorting algorithms: selection sort, insertion sort, bubble sort, heap sort,
Ruby (on Rails) CSE 190M, Spring 2009 Week 2. Arrays Similar to PHP, Ruby arrays… – Are indexed by zero-based integer values – Store an assortment of.
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.
1 By: Nour Hilal. Microsoft Access is a database software where data is stored in one or more Tables. A Database is a group of related Tables. Access.
Arrays The concept of arrays Using arrays Arrays as arguments Processing an arrays data Multidimensional arrays Sorting data in an array Searching with.
I can make observations of science notebooks so I am able to understand the purpose of notebooking in science.
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()
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 8 Working.
Data Collections: Lists CSC 161: The Art of Programming Prof. Henry Kautz 11/2/2009.
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
CSCI 51 Introduction to Programming March 12, 2009.
Pre-Reading: 1.Do you know the names of some famous scientists? 2. What are they famous for?
C++ String Class nalhareqi©2012. string u The string is any sequence of characters u To use strings, you need to include the header u The string is one.
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.
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.
Lists Victor Norman CS104. Reading Quiz Lists Our second collection data type – elements are in order (like strings) – indexed from 0 to n – 1 (like.
Lists Ruth Anderson University of Washington CSE 160 Winter
OCR Computing GCSE © Hodder Education 2013 Slide 1 OCR GCSE Computing Python programming 3: Built-in functions.
性別平等教育 尊重彼此的不同 學會善解別人 瑞田國小. 你喜歡看那一種卡通? 小妹妹一定是背著洋娃娃嗎?
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?
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.
1 ORACLE I 3 – SQL 1 Salim Phone: YM: talim_bansal.
String and Lists Dr. José M. Reyes Álamo.
COMP 103 Comperator and Comparable Thomas Kuehne 2015-T2 Lecture 9
Fundamentals of Programming I Sort Algorithms
More on Lists.
Ruth Anderson University of Washington CSE 160 Spring 2015
Famous Scientists.
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
Structs And Arrays.
Ruth Anderson University of Washington CSE 160 Spring 2018
Sharing, mutability, and immutability
Natural Forces Quiz By Andrew 1.
Ruth Anderson UW CSE 160 Spring 2018
Chapter 8 Data Structures: Cell Arrays and Structures
Sharing, mutability, and immutability
String and Lists Dr. José M. Reyes Álamo.
Ruth Anderson UW CSE 160 Winter 2017
Michael Ernst UW CSE 140 Winter 2013
Fundamentals of Programming I Sort Algorithms
Writing Functions( ) (Part 4)
Topics Sequences Introduction to Lists List Slicing
Lists Part 1 Taken from notes by Dr. Neil Moore
Basic String Operations
Algorithmic complexity: Speed of algorithms
Module 8 – Searching & Sorting Algorithms
Topics Sequences Introduction to Lists List Slicing
Ruth Anderson UW CSE 160 Spring 2018
Chapter 8 Data Structures: Cell Arrays and Structures, Sorting
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Ruth Anderson UW CSE 160 Winter 2016
Presentation transcript:

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() 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 Modifies the list in place, returns None Returns a new sorted list (does not modify the original list)

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 function that can be called on each list element to extract/create a value that will be used to make comparisons. We can use this to sort on a value (e.g. “last_name”) other than the actual list element (e.g. “first_name last_name”). We could use the following sort key so help us sort by last names: 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", "Fig 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]) sorted_keyed_names = sorted(keyed_names) 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. If there is a tie in last names, sort by next item in list: fullname 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 [1, 1] [1, 1, 2] [1, 2]

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", "Fig Newton", "Niels Bohr"] print sorted(names, key = last_name) print sorted(names, key = len) def last_name_len(name): return len(last_name(name)) print sorted(names, key = last_name_len) 7 If there is a tie in last names, preserves original order of values.

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 Returns a function

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 Another way to import, allows you to can call itemgetter directly.

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 Goal: sort based on score; if there is a tie within score, sort by name 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)] 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 Remember: Sort on most important criteria LAST

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