Question: In Python, Part 2: sorting apples (again) The last time we sorted apples we used two separate arrays (i.e. lists), one to hold the names,
In Python,
Part 2: sorting apples (again)
The last time we sorted apples we used two separate arrays (i.e. lists), one to hold the names, one to hold the 'sweetness' (called parallel arrays). Below is a single string that contains the same data:
apples = "McIntosh:3,Red Delicious:5,Fuji:8,Gala:6,Ambrosia:7,Honeycrisp:7.5,Granny Smith:1"
In this case, the apples are separated by commas, and each apple has two attributes (name and sweetness) separated by a colon. We will use the power of string's split method to sort this dataset.
1. define a function named apple_sort that takes a single string as an parameter, this string will be an "apple". That is it will be one of the items like 'Honeycrisp:7.5'. The function will return a numeric value that represents the sweetness of the item. This function will behave as a custom sorting function.
2. define a function named a sort_csv that takes a single string as an parameter (which represents the complete dataset). This function will split the incoming dataset into the separate items and then it will sort those items using your function you created in part 1.
So after you are done, the following code:
print(sort_csv(apples))
Should print out:
['Fuji:8', 'Honeycrisp:7.5', 'Ambrosia:7', 'Gala:6', 'Red Delicious:5', 'McIntosh:3', 'Granny Smith:1']
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
