# Register now to access 7 million high quality study materials (What's Course Hero?) Course Hero is the premier provider of high quality online educational resources. With millions of study documents, online tutors, digital flashcards and free courseware, Course Hero is helping students learn more efficiently and effectively. Whether you're interested in exploring new subjects or mastering key topics for your next exam, Course Hero has the tools you need to achieve your goals.

### SortingComparators

Course: CS 112, Fall 2008
School: George Mason
Rating:

Word Count: 649

#### Document Preview

and Sorting Comparators Dan Fleck Coming up: Sorting a list Sorting a list ! Sorting a list seems simple: myList = [1, 4, 3, 5] myList.sort() print myList &gt;&gt;&gt; [1, 3, 4, 5] Backwards? Not so hard really Okay, how about backwards then! ! A little harder, but we can do it myList = [1, 4, 3, 5] myList.sort() myList.reverse() print myList &gt;&gt;&gt; [5, 4, 3, 1] What about a...

Register Now

#### Unformatted Document Excerpt

Coursehero >> Virginia >> George Mason >> CS 112

Course Hero has millions of student submitted documents similar to the one
below including study guides, practice problems, reference materials, practice exams, textbook help and tutor support.

Course Hero has millions of student submitted documents similar to the one below including study guides, practice problems, reference materials, practice exams, textbook help and tutor support.
and Sorting Comparators Dan Fleck Coming up: Sorting a list Sorting a list ! Sorting a list seems simple: myList = [1, 4, 3, 5] myList.sort() print myList >>> [1, 3, 4, 5] Backwards? Not so hard really Okay, how about backwards then! ! A little harder, but we can do it myList = [1, 4, 3, 5] myList.sort() myList.reverse() print myList >>> [5, 4, 3, 1] What about a heterogeneous list? Okay, heterogeneous list? ! First, what is a heterogeneous list? ! heterogeneous - consisting of dissimilar or diverse ingredients or constituents ! homogeneous - of the same or a similar kind or nature mw.com Okay, heterogeneous list? ! First, what is a heterogeneous list? In Python then: ! heterogeneous list has elements of multiple data types (int, float, String, list) ! homogeneous list all elements are the same type So, lets sort one myList = [1, B, 4, A, [1, 2, 3], 3, 5] myList.sort() print myList >>> [1, 3, 4, 5, [1, 2, 3], 'A', 'B'] Uhhh why? The Python people had a problem how does one compare an int to a list? Ideas? Sorting heterogeneous types They didnt have a good idea either, but in a computer you MUST provide an answer, even if it isnt a good one! Python sorts alphabetically based on the name of the type. ALL ints < ALL lists < ALL strings < ALL tuples Note: Python does sort ints, floats, doubles together so that will work, but all of them will be less than lists, strings, tuples) Sorting classes What about classes? Oh still alphabetic: ALL classes < ALL ints < ALL lists < ALL strings < ALL tuples What about just a homogeneous list of classes? Sorting classes What about just a homogeneous list of classes? class MyClass: def __init__(self, x): self.x = x c1 = MyClass(1) c2 = MyClass(2) myList = [c2, c1] myList.sort() print myList [<__main__.MyClass instance at 0x70148>, <__main__.MyClass instance at 0x70120>] [<__main__.MyClass instance at 0x70120>, <__main__.MyClass instance at 0x70148>] Making classes pretty ! classes when you print a class, the default action is to print the memory location of the class. Not very helpful. ! can You override that behavior by providing a special method to be called: !def __repr__(self): Returns a string representing this class Making classes pretty class MyClass: def __init__(self, x): self.x = x def __repr__(self): Returns a string representing this class return MyClass:+str(self.x) Back to sorting c1 = MyClass(1) c2 = MyClass(2) myList = [c2, c1] myList.sort() print myList >>> [MyClass:2, MyClass:1] >>> [MyClass:1, MyClass:2] It works! Or does it? How did it do the sorting? Can you think of how it KNOWS what to sort? Neither could the Python authors! Back to sorting c2 = MyClass(2) c1 = MyClass(1) myList = [c2, c1] myList.sort() print myList >>> [MyClass:2, MyClass:1] >>> [MyClass:2, MyClass:1] Python doesnt know how to sort your class unless *YOU* tell it how! Change the order __cmp__ method ! Another special method in Python tells sort routines *HOW* do I compare two of these things? ! def __cmp__(self, other): """Return -1 if self < otherInstance Return 0 if they are equal Return +1 if self > otherInstance """ if self.x == other.x: return 0 elif self.x < other.x: return -1 else: return 1 What if I want descending order? __cmp__ method ! Frequently you want to order ...

Find millions of documents on Course Hero - Study Guides, Lecture Notes, Reference Materials, Practice Exams and more. Course Hero has millions of course specific materials providing students with the best way to expand their education.

Below is a small sample set of documents:

George Mason - CS - 112
Exception HandlingDan FleckComing up: Long ago we wrote thisLong ago we wrote thisdef addGraphicalButton(parent): # Create the PhotoImage widget im = PhotoImage(file='cake.gif') button2 = Button(root, text=&quot;Potato&quot;, image=im) button2.image = im
George Mason - CS - 112
Python Programming: An Introduction To Computer ScienceChapter 10 Defining Classes (These slides were heavily editted/ rewritten by Dan Fleck)Coming up: Objectives 1Objectives! To appreciate how defining new classes can provide structure for a c
George Mason - CS - 112
Python Programming: An Introduction to Computer ScienceChapter 1 Computers and Programs Modified by Dan FleckObjectives Introduction to the class Why we program and what that means Introduction to the Python programming languageComing up: Wha
George Mason - CS - 112
Tkinter GUIs in PythonDan Fleck CS112 George Mason UniversityNOTE: This information is not in your textbook! See references for more information!Coming up: What is it?What is it?! Tkinter is a Python interface to the Tk graphics library.!Tk i
George Mason - CS - 112
New Datatypes:Tuples and SetsDan FleckComing up: Passing a list as a parameterPassing a list as a parameterdef class FamilyTree:# This class holds a list of family members in the variable tree lots of code not shown def getTree(self): retur
George Mason - CS - 112
CS 112 Lab AssignmentInstructor: Dan Fleck Lab: Pig Latin TranslatorOverviewThis lab will familiarize you with the String class and String functions available in Python. You will be ask the user for a word and convert it into PigLatin. Pig Latin
George Mason - CS - 112
CS 112 Lab AssignmentInstructor: Dan Fleck Lab: Graphics Due Date: SPECIAL ALERT: This lab (and ONLY this lab) will be due on April 14th at midnight for EVERYONE. Just this once well have a longer due date for people because of the midterm the week
George Mason - CS - 112
CS 112 Lab AssignmentInstructor: Dan Fleck Lab: Software design and documentation Due Date: As with all labs, this lab is due one week from your lab section!OverviewThroughout the semester you have hopefully been writing pseudocode and adding goo
George Mason - CS - 112
CS 112 Lab AssignmentInstructor: Dan Fleck Lab: #1OverviewThis lab will help you familiarize yourself with Python, the computer lab and Blackboard. For this lab you will do two things: 1. Type in and run a simple Python file 2. Submit that file a
George Mason - CS - 112
CS 112 Lab AssignmentInstructor: Dan Fleck Lab: For Loops (and a little math)OverviewThis lab will help you understand how to use for loops. You will compute an estimated value for the square root of a number to a specific accuracy given from the
George Mason - CS - 112
CS 112 Project Assignment: SlidersInstructor: Dan FleckOverviewIn this project you will use Python to implement the number sliders game. This game can be seen at: http:/www.classbrain.com/artgames/publish/sliders_game.shtml You will only be imple
George Mason - CS - 540
Building SLR Parse TablesThe easiest technique for generating LR-based parse table is known as SLR (Simple LR). Understanding this technique should provide you with what you need to know to understand how LR parsers work in general; it is also the f
George Mason - CS - 367
Introduction to CAcknowledgement: These slides are adapted from lecture slides made available by Prof. Dave O Halloran (Carnegie Mellon University)Outline Overview comparison of C and Java Good evening Preprocessor Command line arguments Arr
George Mason - CS - 707
Assignment #2 - Auction ToolDue April 12IntroductionThe goal of this assignment is to introduce you to the use of a distributed object middleware such as CORBA or Java RMI to build a distributed auction tool. This tool will allow users to create
George Mason - CS - 640
SPECIALISSUEArticlesADVANCED COMPILER OPTIMIZATIONS FOR SUPERCOMPUTERSCompilers for vector or multiprocessor computers must have certain optimization features to successfully generate parallel code.DAVID A. PADUA and MICHAEL J. WOLFESuperco
George Mason - CS - 640
REGISTER ALLOCATION &amp; SPILLING VIA GRAPH COLORING G. J. Chaitin IBM Research P.O.Box 218, Yorktown Heights, NY 10598ABSTRACT In a previous paper we reported the successful use of graph coloring techniques for doing global register allocation in an
George Mason - CS - 367
Programming in C in a UNIX environmentSoftware Development LifecycleUnderstand the requirements Develop the algorithm/approach Write the code Debug the code Test the code Iterate until you get it right2Programming ToolsSeveral Integrated Deve
George Mason - CS - 640
Improvements to Graph Coloring Register AllocationPRESTON BRIGGS, KEITH D. COOPER, and LINDA TORCZON Rice UniversityWe describeopttmzstwtwo improvements to Chaitin-style graph coloring register allocators. The first, uses a stronger heuristic t
George Mason - CS - 640
CS 640 HW #1 Fall 2008 Due Sept 22 at classtime1. For the code below, what optimizations can be detected using Local Value Numbering? What about DAG construction? a = 2 b = 3 c = a + b d = a + a b = a e = a + b c = 3 f = a + c 2. In order to do supe
George Mason - CS - 640
Redundant Expression EliminationCS640 Lecture 3Redundant ExpressionstDefinitionrAn expression x op y is redundant at a point p if it has already been computed and no intervening operations redefined x or y Preserve the result of earlier comp
George Mason - CS - 640
CS640Advanced CompilersInstructor: Elizabeth Whitewhite@gmu.eduAbout the CourseInstructor: Dr. Elizabeth WhiteEmail: white@gmu.edu Office: STII 429 Office hour:Mon/Wed 2-3 By appointmentCourse web site:http:/cs.gmu.edu/~white/CS640 Check
George Mason - CS - 707
ProcessesCh. 1, 3 Tanenbaum Distributed Software Systems CS 707Software ArchitectureComponents/processesprocess = program in execution Often multi-threaded! How the processes are organized influences the overall applicationConnections between
George Mason - CS - 571
Java Thread ProgrammingThreads are built in to Java and work the same way on all platforms. Underlying implementation can vary from one platform to the next but you don't need to worry about it.GMU CS 571 - Java Thread Programming - Brian Zim
George Mason - CS - 640
Interprocedural Analysis &amp; OptimizationCS640 Lecture 12RoadmapA compiler need to perform all kinds of analysis before code transformation Controlflow analysisBasic blocks, loops, CFG (one for each procedure) Data flow analysisLocal
George Mason - CS - 707
Local Objects vs. Distributed ObjectsLocal objects are those whose methods can only be invoked by a local process, a process that runs on the same computer on which the object exists. A distributed object is one whose methods can be invoked by a rem
George Mason - CS - 707
TonightSeveral common communication mechanisms RPC RMI Sockets Next week: HTTP, CommunicationTanenbaum Ch. 4 Distributed Software Systems CS 707Middleware ProtocolsRemote Procedure Call (RPC)Figure 4-3. An adapted reference model for ne
George Mason - CS - 707
Traditional Web-Based Systems - 1Chapter 12 Distributed Web-Based SystemsFigure 12-1. The overall organization of a traditional Web site.Traditional Web-Based Systems - 2Terminology URI Uniform Resource Identifier (URL, URN) Web client (bro
George Mason - CS - 640
CS 640 HW #2 Fall 2008 Due Oct 6 at classtime1. Dataflow analysis can be used to propagate constants in a CFG. Give a dataflow algorithm for this be sure to provide details regarding the transfer functions (and how they are computed). Show how your
George Mason - CS - 640
Static Single AssignmentCS 640 Lecture 5VN Example ReviewOriginal Code ax+y bx+y a 17 cx+y With VNs a3 x1 + y2 b3 x1 + y2 a4 174 c3 x1 + y2 Rewritten a03 x01 + y02 b03 a03 a14 174 c03 a03Give each value a unique name No value is
George Mason - CS - 540
Lecture 7: Type Systems and Symbol TablesCS 540 George Mason UniversityStatic AnalysisCompilers examine code to find semantic problems. Easy: undeclared variables, tag matching Difficult: preventing execution errors Part I: Type checking Par
George Mason - CS - 540
Lecture 3: ParsingCS 540 George Mason UniversityStatic Analysis - ParsingSource languageScanner (lexical analysis)tokensParser (syntax analysis)Syntatic structureSyntatic/semantic structureSemantic Analysis (IC generator)Code Genera
George Mason - CS - 540
Lecture 5: LR ParsingCS 540 George Mason UniversityStatic Analysis - ParsingSource languageScanner (lexical analysis)tokensParser (syntax analysis)Syntatic structureSyntatic/semantic structureSemantic Analysis (IC generator)Code Gen
George Mason - CS - 540
Lecture 6: YACC and Syntax Directed TranslationCS 540 George Mason UniversityPart 1: Introduction to YACCYACC Yet Another Compiler CompilerLex spec flex lex.yy.c compiler YACC spec bison y.tab.c a.outC/C+ toolsCS 540 Spring 2009 GMU 3YACC
George Mason - CS - 540
Lecture 2: Lexical AnalysisCS 540 George Mason UniversityLexical Analysis - ScanningSource language Scanner (lexical analysis) tokens Parser (syntax analysis) Semantic Analysis (IC generator) Code GeneratorCode Optimizer Tokens described form
George Mason - CS - 540
Lecture 8: Intermediate CodeCS 540 Spring 2009Compiler ArchitectureSource languageScanner (lexical analysis)tokensParser (syntax analysis)Syntactic structureIntermediate CodeSemantic Analysis (IC generator)Code GeneratorTarget lan
George Mason - CS - 540
Lecture 4: LL ParsingCS 540 George Mason UniversityParsingSource languageScanner (lexical analysis)tokensParser (syntax analysis)Syntatic structureSyntatic/semantic structureSemantic Analysis (IC generator)Code GeneratorTarget lan
George Mason - CS - 540
CS 540 Spring 2009The Course covers: Lexical Analysis Syntax Analysis Semantic Analysis Runtime environments Code Generation Code OptimizationCS 540 Spring 2009 GMU 2Pre-requisite courses Strong programming background in C, C+ or Java CS
George Mason - CS - 540
Code GenerationCS 540 George Mason UniversityCompiler ArchitectureIntermediate Language Source language Intermediate LanguageScanner (lexical analysis)tokensParser (syntax analysis)Syntactic structureSemantic Analysis (IC generator)Co
George Mason - CS - 540
Lecture 9: Runtime EnvironmentsCS 540 George Mason UniversityRun-Time EnvironmentsStatic vs. Runtime Mapping a HL language to low-level machine environment implies generating code for allocating, maintaining and de-allocating data objects to supp
George Mason - CS - 540
ParserVal classpublic class ParserVal { public int ival; public double dval; public String sval; public Object obj; public ParserVal(int val) { ival=val; } public ParserVal(double val) { dval=val; } public ParserVal(String val) { sval=val; } public
George Mason - CS - 583
1Recurrence RelationsDr. Pearl Wang Department of Computer Sciencec 2008 P.Y. WangG EORGE M ASON U NIVERSITY2What is a Recurrence Relation? A function that is dened in terms of itself is a recurrence relation. Recurrence relations must
George Mason - CS - 583
1Linear Time SortingP.Y. Wang Department of Computer Science 4A5 George Mason University Fairfax VA 22030-4444 U.S.A.c 2008 P.Y. WangG EORGE M ASON U NIVERSITY2Lower Bound on Comparison Based Sorting All the sorting algorithms we have ex
George Mason - CS - 583
1Dynamic ProgrammingP.Y. Wang Department of Computer Science 4A5 George Mason University Fairfax VA 22030-4444 U.S.A.c 2008 P.Y. WangG EORGE M ASON U NIVERSITY2What is Dynamic Programming? Some problems can be solved using divide-and-con
George Mason - CS - 635
George Mason - CS - 635
MPI Parallel Programming1MPI Parallel Programming Part IP.Y. Wang Department of Computer Science 4A5 George Mason University Fairfax VA 22030-4444 U.S.A.c 2004 P.Y. WangG EORGE M ASON U NIVERSITYMPI Parallel Programming2ReferencesThe
George Mason - CS - 635
Intro - 21Processor Organization and Data RoutingArchitectural alternatives for communications subsystemsHigh bandwidth bussimplest (n &lt; 50 today)Multistage networks Static Networks Interconnection NetworksCrossbar networkmost complex (n
George Mason - CS - 635
Matrix Algorithms1Some Parallel Matrix AlgorithmsP.Y. Wang Department of Computer Science 4A5 George Mason University Fairfax VA 22030-4444 U.S.A.c 2004 P.Y. WangG EORGE M ASON U NIVERSITYMatrix Algorithms2Outline Data Partitioning M
George Mason - CS - 635
Data Parallel Programming and the M AS PAR1Data Parallel Programming and the M AS PARP.Y. Wang Department of Computer Science 4A5 George Mason University Fairfax VA 22030-4444 U.S.A.c 2004 P.Y. WangG EORGE M ASON U NIVERSITYData Parallel
George Mason - CS - 583
CS 583 Data Structures and Algorithm Analysis Practice Homework 31] The following problems in the textbook may be useful exercises for studying binary search trees and red-black trees: 1. Page 260, # 12.2-4 2. Page 264, # 12.3-3, 3. Page 276, all e
George Mason - CS - 635
Parallel Sorting1Parallel SortingP.Y. Wang Department of Computer Science 4A5 George Mason University Fairfax VA 22030-4444 U.S.A.c 2004 P.Y. WangG EORGE M ASON U NIVERSITYParallel Sorting2Outline Important Issues (Serial and Paralle
George Mason - CS - 635
Control Parallel Programming1MIMD/Control-Parallel Programming IssuesP.Y. Wang Department of Computer Science 4A5 George Mason University Fairfax VA 22030-4444 U.S.A.c 2004 P.Y. WangG EORGE M ASON U NIVERSITYControl Parallel Programming
George Mason - CS - 367
CS 367Bits and BytesTopics Why bits? Representing information as bits Binary/Hexadecimal Byte representations numbers characters and strings InstructionsBit-level manipulations Boolean algebra Expressing in CCS 367 F07Why Dont Com
George Mason - CS - 699
Peer-to-Peer Information RetrievalPeer-to-Peer Information Retrieval Using Self-Organizing Semantic Overlay NetworksDistributed Hash Table (DHT)CAN, Chord, Pastry, Tapestry, etc. Scalable, fault tolerant, self-organizing Only support exact key mat
George Mason - CS - 699
The Entropia Machine for Desktop GridsBrad Calder, Andrew Chien, Ju Wang, Don Yang Oct 28,2004 Presented by: Dongyu LiuGrid Introduction Grid computing, which is defined ascoordinated resource sharing and problem solving in large, multi-institut
George Mason - CS - 699
Distributed Hash Tables (DHTs) Tapestry &amp; PastryCS 699/IT 818 Sanjeev Setia1AcknowledgementsSome of the followings slides are borrowed or adapted from talks by Robert Morris (MIT) and Ben Zhao (UC, Santa Barbara)21DHTs Distributed Hash
George Mason - CS - 699
Acknowledgements Peer to Peer File Storage SystemsCS 699Some of the followings slides are borrowed from a talk by Robert Morris (MIT)12P2P File Systems File Sharing is one of the most popular P2PTarget Usesnode node Internet node node nod
George Mason - CS - 699
SplitStream: High-Bandwidth Multicast in Cooperative Environments Muhammad Abdulla10/14/20041OutlineBasic ConceptsMulticasting The SplitStream approachStructured Overlay NetworkPastry ScribeSplitStream Design Experimental Results10/14/2
George Mason - CS - 699
Acknowledgements GIA: Making Gnutella-like P2P Systems ScalableYatin Chawathe, Sylvia Ratnasamy, Lee Breslau, Scott Shenker, and Nick Lanham SIGCOMM 2003Most of the followings slides are borrowed from the talk by Yatin Chawathe (Intel)12The P
George Mason - CS - 699
Publius A Robust, Tamper Evident, Censorship Resistant WWW Based Publishing SystemBy Lorrie Cranor Avi Rubin Marc Waldman AT&amp;T Labs New York UniversityProc. 9th USENIX Security Symposium, 2000 Presented by Anyi Liu Dec. 2, 2004AcknowledgmentsSo
George Mason - CS - 699
Incentives for P2P SystemsDaniel Garrison CS 699 George Mason University November 4, 2004Incentives for P2P SystemsIncentives Build Robustness in BitTorrentBram CohenWorkshop on Economics of Peer-to-Peer Systems, 2003Incentives-Compatible Pee
George Mason - CS - 699
Scribe: A large-scale and decentralized application-level multicast infrastructurePaper by: Miguel Castro, Peter Druschel, Anne-Marie Kermarrec, Antony Rowstron, IEEE JSAC,2002. Presented by: Sankardas RoyAcknowledgement : Wang Ting and Wei Ran, u