When we sort a list of items, we need a basis

Assignment Help Python Programming
Reference no: EM13168106

When we sort a list of items, we need a basis on which to compare the items to see whether one is bigger than another. If it's a list of numbers, Python just compares the numeric values; if it's a list of strings, Python compares the strings alphabetically. But what if we're sorting a list of restaurants? As we saw earlier, the sort() method uses the first field of a Restaurant object (in our case, its name) for comparison. We call the basis of comparison the sort key. Wouldn't it be convenient if we could sort lists of complex objects based on some other sort key? [Note: nothing here in part (d) requires a for-loop or an if-statement.]

(d.1) Define a function called restaurant_price that takes one argument, a Restaurant, and returns the value of the price field of that Restaurant. This is quite short and easy. But note that whenever a lab problem asks you to define a function, you also need to include in your file some calls to that function that test it, calls that demonstrate that the function works correctly. So define a list containing a few Restaurants (maybe copy the list from last week's lab) and print out the results of calling restaurant_price on those Restaurants. (You may use assert statements, which are a way of partially automating this testing process.)

This is the list from last week's work.

from collections import namedtuple
Restaurant = namedtuple('Restaurant', 'name cuisine phone dish price')
# Restaurant attributes: name, kind of food served,
 phone number, best dish, price of that dish RL = [ Restaurant("Thai Dishes", "Thai", "334-4433", "Mee Krob", 12.50), Restaurant("Nobu", "Japanese", "335-4433", "Natto Temaki", 5.50), Restaurant("Nonna", "Italian", "355-4433", "Stracotto", 25.50), Restaurant("Jitlada", "Thai", "324-4433", "Paht Woon Sen", 15.50), Restaurant("Nola", "New Orleans", "336-4433", "Jambalaya", 5.50), Restaurant("Noma", "Modern Danish", "337-4433", "Birch Sap", 35.50), Restaurant("Addis Ababa", "Ethiopian", "337-4453", "Yesiga Tibs",
 10.50) ]

(d.2) Write a sequence of statements that prints out the list of Restaurants RC in order from least expensive to most expensive (best dish). [Hint: As an argument to the sort() method, saykey=restaurant_price. Take a second to read this again, paying attention to the terminology so you know what this is telling you to write in Python. Interpreting technical terminology is an important skill; it may also help if you look at the entry for sort() in help(list). Giving key=restaurant_price as an argument to sort() tells sort() how to get the value from each Restaurant that it will compare: By default (without our saying anything), it used the first field, the name of the Restaurant; the key= argument lets us specify a function that takes a Restaurant as input and returns a value-in our example, its price field-to use instead of the name when comparing Restaurants during the sorting process. What's tricky is that we supply the name of a function after key=, but as we'll see later, functions can be useful as components of other computations.]

(d.3) Write a function called costliest that takes a list of Restaurants as its argument and returns the name of the highest-priced restaurant on that list (based on the price of the restaurant's best dish, of course). [You need to pay close attention to the wording of technical specifications like this. This function returns a string, the name of the costliest restaurant; it doesn not return the whole Restaurant object.]

To test this function, create a short list of Restaurants and print the value of calling costliest with that list as its argument.

(d.4) You may have noticed that after calling your costliest function with a list of Restaurants, two things happen: costliest returns the name of the restaurant and the list has been reordered by price. Try it out: Print the list before calling costliest and then print it again afterwards; whatever its order beforehand, it's ordered by price after the call. This is a side effect: something a function does besides compute and return a value. Sometimes side effects are a required part of solving a problem: printing, for example, or drawing on a tkinter canvas. But when we're manipulating data in our program, generally it's best if a function does its work by returning a value and leaves everything else unchanged.

Reference no: EM13168106

Questions Cloud

What is the internal data that allows the os to superwise : What is the internal data that allows the operating system to supervise and control the process? Be specific about what it includes.
Explain why is it necessary to add water after the reaction : Consult your lecture or lab text and give a complete structuer for the 'intermediate borate ester' formed in the reduction of 2-butanone with NaBH4. Why is it necessary to add water after the reaction is complete?
The total volume of the gas bags of the german dirigible : the total volume of the gas bags of the german dirigible hindenberg, was 2.0 * 10^5m^3. how many grams of H2 would be required to fill them at 20 celcius and 1.00 atm pressure? hint convert m^3>cm^3>mL>L.
Using netbeans, use repetition to display a table of values : Using Netbeans, use repetition to display a table of values showing x, the square of x and the cube of x. X is to go up to 5.
When we sort a list of items, we need a basis : When we sort a list of items, we need a basis on which to compare the items to see whether one is bigger than another. If it's a list of numbers, Python just compares the numeric values; if it's a list of strings, Python compares the strings alpha..
The heating element of a water heater in an apartment : The heating element of a water heater in an apartment building has a maximum power output of 28 kW. Four residents of the building
We can combine assignment statements : We can combine assignment statements, for-loops, and if statements to perform a wide range of tasks with lists. Suppose we have a bookstore with each book defined as follows: Book = namedtuple('Book', 'author title genre year price instock') , wher..
Write a script that simulates a casino machine : Write a script that simulates a casino machine. To play a single round on the machine user pays $ 5. Now when the user start the machine, the machine rolls a pair of dice (simulate both dice with help of random number generator) and user only wins..
A computer has a cache, main memory, and a disk : A computer has a cache, main memory, and a disk. If a referenced word is in the cache, 20 ns are required to access it. If it is in main memory but not in the cache (called cache miss)

Reviews

Write a Review

Python Programming Questions & Answers

  Python atm program to enter account number

Write a simple Python ATM program. Ask user to enter their account number, and print their initail balance. (Just make one up). Ask them if they wish to make deposit or withdrawal.

  The initial number for generating the sequences

Then, after the functions, read in the initial number for generating the sequences. Here, check that it is a positive integer. If it is not, give an error message and exit the program.

  Write python code that will execute a list

Write python code that will execute a list of functions with supplied parameters and report the observed runtime for each function run. Assume that the input file has a list of strings like so:

  Write python program which imports three dictionaries

Write a Python program called hours.py which imports three dictionaries, and uses the data in them to calculate how many hours each person has spent in the lab.

  Most popular name would be the one with the biggest number

the program will ask you to insert the year that the user is interested in, then ask the gender that the user is interested in, and print out the most popular names corresponding to the year and gender. FYI, the number on the right represents how man..

  Turn the turtle image into a .gif picture

How can you turn the turtle image into a .gif picture when using the built-in turtle for Python? If that's impossible how do you remove the line when you move the turtle around?

  Console program where you will implement

Create a console program where you will implement coding constructs and variables that are needed for this program and will implement the code within Main and any required static methods.

  Function by sum of sines

code the program using an editor (DO NOT COMMAND LINE THE PROGRAM) and show the results

  Recursion to write a python function

Use recursion to write a Python function depth(LL), where LL is a nested list of lists of lists etc. of numbers (i.e., oat and int) and strings. We want to return the depth of nesting, i.e., how often, maximally, there is a list in a list etc

  Permutation ciphers

Permutation Ciphers (a.k.a. Transposition Ciphers) are another class of simple cryptosystems. For this we use the functions apply(.,.) and inv(.) from Homework 4; copy these two functions into your le as auxiliary functions.

  Specializes in solving the equations ax=b by doolittle''s dec

Write a  program that specializes in solving the equations Ax=b by Doolittle's decomposition method, where a is the HIbber matrix of arbitrary size nxn

  Function should return a dictionary

Write a function numOccur(s), where s is a string; the function should return a dictionary whose keys are the 26 ascii letters abcdefghijklmnopqrstuvwxyz

Free Assignment Quote

Assured A++ Grade

Get guaranteed satisfaction & time on delivery in every assignment order you paid with us! We ensure premium quality solution document along with free turntin report!

All rights reserved! Copyrights ©2019-2020 ExpertsMind IT Educational Pvt Ltd