Last active
November 25, 2023 06:59
-
-
Save LizaPiya/a22e1b76ea7a5fd46be4acd8ea21262c to your computer and use it in GitHub Desktop.
Week 5
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Exercise 1 | |
states = {"Minnesota": ["St. Paul", "Minneapolis", "Saint Cloud", "Stillwater"], | |
"Michigan": ["Ann Arbor", "Traverse City", "Lansing", "Kalamazoo"], | |
"Washington": ["Seattle", "Tacoma", "Olympia", "Vancouver"]} | |
print(sorted(states, key=lambda state: len(states[state][0]))) | |
-------------------------------------------------------------------------- | |
Exercise 2 | |
def s_cities_count(city_list): | |
ct = 0 | |
for city in city_list: | |
if city[0] == "S": | |
ct += 1 | |
return ct | |
states = {"Minnesota": ["St. Paul", "Minneapolis", "Saint Cloud", "Stillwater"], | |
"Michigan": ["Ann Arbor", "Traverse City", "Lansing", "Kalamazoo"], | |
"Washington": ["Seattle", "Tacoma", "Olympia", "Vancouver"]} | |
print(sorted(states, key=lambda state: s_cities_count(states[state]))) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
L1 = [1, 7, 4, -2, 3] | |
def absolute(x): | |
if x >= 0: | |
return x | |
else: | |
return -x | |
print(absolute(3)) | |
print(absolute(-119)) | |
for y in L1: | |
print(absolute(y)) | |
------------------- | |
output: | |
3 | |
119 | |
1 | |
7 | |
4 | |
2 | |
3 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## Below, we have provided a list of strings called nums. Write a function called last_char that takes a string as input, and returns only its last character. Use this function to sort the list nums by the last digit of each number, from highest to lowest, and save this as a new list called nums_sorted. | |
nums = ['1450', '33', '871', '19', '14378', '32', '1005', '44', '8907', '16'] | |
def last_char(str): | |
return str[-1] | |
nums_sorted =sorted(nums,reverse=True,key=last_char) | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## Below, we have provided the dictionary groceries, whose keys are grocery items, and values are the number of each item that you need to buy at the store. Sort the dictionary’s keys into alphabetical order, and save them as a list called grocery_keys_sorted. | |
groceries = {'apples': 5, 'pasta': 3, 'carrots': 12, 'orange juice': 2, 'bananas': 8, 'popcorn': 1, 'salsa': 3, 'cereal': 4, 'coffee': 5, 'granola bars': 15, 'onions': 7, 'rice': 1, 'peanut butter': 2, 'spinach': 9} | |
grocery_keys_sorted=sorted(groceries) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
##Sort the following string alphabetically, from z to a, and assign it to the variable sorted_letters. | |
letters = "alwnfiwaksuezlaeiajsdl" | |
sorted_letters=sorted(letters,reverse=True) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## Sort the list below, animals, into alphabetical order, a-z. Save the new list as animals_sorted. | |
animals = ['elephant', 'cat', 'moose', 'antelope', 'elk', 'rabbit', 'zebra', 'yak', 'salamander', 'deer', 'otter', 'minx', 'giraffe', 'goat', 'cow', 'tiger', 'bear'] | |
animals_sorted=sorted(animals) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## The dictionary, medals, shows the medal count for six countries during the Rio Olympics. Sort the country names so they appear alphabetically. Save this list to the variable alphabetical. | |
medals = {'Japan':41, 'Russia':56, 'South Korea':21, 'United States':121, 'Germany':42, 'China':70} | |
alphabetical=sorted(medals) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## Given the same dictionary, medals, now sort by the medal count. Save the three countries with the highest medal count to the list, top_three. | |
medals = {'Japan':41, 'Russia':56, 'South Korea':21, 'United States':121, 'Germany':42, 'China':70} | |
list=sorted(medals,key=lambda medal:medals[medal],reverse=True) | |
top_three=list[:3] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sort the list ids by the last four digits of each id. Do this using lambda and not using a defined function. Save this sorted list in the variable sorted_id. | |
ids = [17573005, 17572342, 17579000, 17570002, 17572345, 17579329] | |
#ids=[str(items) for items in ids] | |
#print (ids) | |
sorted_id=sorted(ids,key=lambda N: str(N)[-4:]) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sort the following list by each element’s second letter a to z. Do so by using lambda. Assign the resulting value to the variable lambda_sort. | |
ex_lst = ['hi', 'how are you', 'bye', 'apple', 'zebra', 'dance'] | |
lambda_sort=sorted(ex_lst,key=lambda k:k[1]) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## We have provided the dictionary groceries. You should return a list of its keys, but they should be sorted by their values, from highest to lowest. Save the new list as most_needed. | |
groceries = {'apples': 5, 'pasta': 3, 'carrots': 12, 'orange juice': 2, 'bananas': 8, 'popcorn': 1, 'salsa': 3, 'cereal': 4, 'coffee': 5, 'granola bars': 15, 'onions': 7, 'rice': 1, 'peanut butter': 2, 'spinach': 9} | |
most_needed=sorted(groceries,key=lambda fruit:groceries[fruit],reverse=True) | |
for fruit in most_needed: | |
print ("Quantity of {} are/is {}".format(fruit,groceries[fruit])) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
##Create a function called last_four that takes in an ID number and returns the last four digits. For example, the number 17573005 should return 3005. Then, use this function to sort the list of ids stored in the variable, ids, from lowest to highest. Save this sorted list in the variable, sorted_ids. Hint: Remember that only strings can be indexed, so conversions may be needed. | |
ids = [17573005, 17572342, 17579000, 17570002, 17572345, 17579329] | |
ids=[str(items) for items in ids] | |
print (ids) | |
def last_four(x): | |
new_list=[] | |
for idx in ids: | |
new_list.append(str(idx[-4:])) | |
return new_list | |
sorted_ids=sorted(ids,key=last_four) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## Once again, sort the list nums based on the last digit of each number from highest to lowest. However, now you should do so by writing a lambda function. Save the new list as nums_sorted_lambda. | |
nums = ['1450', '33', '871', '19', '14378', '32', '1005', '44', '8907', '16'] | |
def last_char(str): | |
return str[-1] | |
nums_sorted_lambda =sorted(nums,reverse=True,key=lambda str:str[-1]) | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
L2 = ["Cherry", "Apple", "Blueberry"] | |
print(sorted(L2, reverse=True)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## Sort the following dictionary based on the keys so that they are sorted a to z. Assign the resulting value to the variable sorted_keys. | |
dictionary = {"Flowers": 10, 'Trees': 20, 'Chairs': 6, "Firepit": 1, 'Grill': 2, 'Lights': 14} | |
sorted_keys=sorted(dictionary) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## Sort the following dictionary’s keys based on the value from highest to lowest. Assign the resulting value to the variable sorted_values. | |
dictionary = {"Flowers": 10, 'Trees': 20, 'Chairs': 6, "Firepit": 1, 'Grill': 2, 'Lights': 14} | |
sorted_values=sorted(dictionary,key=lambda k:dictionary[k],reverse=True) | |
for k in sorted_values: | |
print ("{} appears {} times".format(k,dictionary[k])) | |
print (sorted_values) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sort the list, lst from largest to smallest. Save this new list to the variable lst_sorted. | |
lst = [3, 5, 1, 6, 7, 2, 9, -2, 5] | |
lst_sorted=(sorted(lst,reverse=True)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
L = ['E', 'F', 'B', 'A', 'D', 'I', 'I', 'C', 'B', 'A', 'D', 'D', 'E', 'D'] | |
d = {} | |
for x in L: | |
if x in d: | |
d[x] = d[x] + 1 | |
else: | |
d[x] = 1 | |
y = sorted(d.keys()) | |
for k in y: | |
print("{} appears {} times".format(k, d[k])) | |
------------------------------------------------------- | |
Output: | |
A appears 2 times | |
B appears 2 times | |
C appears 1 times | |
D appears 4 times | |
E appears 2 times | |
F appears 1 times | |
I appears 2 times | |
---------------------------------------------------------------------------------------------------------------------------------- | |
L = ['E', 'F', 'B', 'A', 'D', 'I', 'I', 'C', 'B', 'A', 'D', 'D', 'E', 'D'] | |
d = {} | |
for x in L: | |
if x in d: | |
d[x] = d[x] + 1 | |
else: | |
d[x] = 1 | |
y = sorted(d.keys(), key=lambda k: d[k], reverse=True) | |
for k in y: | |
print("{} appears {} times".format(k, d[k])) | |
----------------------------- | |
Output: | |
D appears 4 times | |
I appears 2 times | |
A appears 2 times | |
B appears 2 times | |
E appears 2 times | |
C appears 1 times | |
F appears 1 times |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
L = ['E', 'F', 'B', 'A', 'D', 'I', 'I', 'C', 'B', 'A', 'D', 'D', 'E', 'D'] | |
d = {} | |
for x in L: | |
if x in d: | |
d[x] = d[x] + 1 | |
else: | |
d[x] = 1 | |
def g(k): | |
return d[k] | |
y =(sorted(d.keys(), key=g, reverse=True)) | |
# now loop through the keys | |
for k in y: | |
print("{} appears {} times".format(k, d[k])) | |
----------------------------------------------------------------------- | |
Improvised way: | |
L = ['E', 'F', 'B', 'A', 'D', 'I', 'I', 'C', 'B', 'A', 'D', 'D', 'E', 'D'] | |
d = {} | |
for x in L: | |
if x in d: | |
d[x] = d[x] + 1 | |
else: | |
d[x] = 1 | |
# now loop through the sorted keys | |
for k in sorted(d, key=lambda k: d[k], reverse=True): | |
print("{} appears {} times".format(k, d[k])) | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
L1 = [1, 7, 4, -2, 3] | |
def absolute(x): | |
if x >= 0: | |
return x | |
else: | |
return -x | |
L2 = sorted(L1, key=absolute) | |
print(L2) | |
#or in reverse order | |
print(sorted(L1, reverse=True, key=absolute)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
L1 = [1, 7, 4, -2, 3] | |
L2 = ["Cherry", "Apple", "Blueberry"] | |
L1.sort() | |
print(L1) | |
L2.sort() | |
print(L2) | |
output: | |
[-2, 1, 3, 4, 7] | |
['Apple', 'Blueberry', 'Cherry'] | |
--------------------------- | |
L2 = ["Cherry", "Apple", "Blueberry"] | |
L3 = sorted(L2) | |
print(L3) | |
print(sorted(L2)) | |
print(L2) # unchanged | |
print("----") | |
L2.sort() | |
print(L2) | |
print(L2.sort()) #return value is None | |
output: | |
['Apple', 'Blueberry', 'Cherry'] | |
['Apple', 'Blueberry', 'Cherry'] | |
['Cherry', 'Apple', 'Blueberry'] | |
---- | |
['Apple', 'Blueberry', 'Cherry'] | |
None |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Example 1: | |
tups = [('A', 3, 2), | |
('C', 1, 4), | |
('B', 3, 1), | |
('A', 2, 4), | |
('C', 1, 2)] | |
for tup in sorted(tups): | |
print(tup) | |
Example 2: | |
fruits = ['peach', 'kiwi', 'apple', 'blueberry', 'papaya', 'mango', 'pear'] | |
new_order = sorted(fruits, key=lambda fruit_name: (len(fruit_name), fruit_name), reverse=True) | |
for fruit in new_order: | |
print(fruit) | |
Example 3: | |
weather = {'Reykjavik': {'temp':60, 'condition': 'rainy'}, | |
'Buenos Aires': {'temp': 55, 'condition': 'cloudy'}, | |
'Cairo': {'temp': 96, 'condition': 'sunny'}, | |
'Berlin': {'temp': 89, 'condition': 'sunny'}, | |
'Caloocan': {'temp': 78, 'condition': 'sunny'}} | |
sorted_weather = sorted(weather, key=lambda w: (w, weather[w]['temp'])) | |
for w in sorted_weather: | |
print ("{} {}".format(w, weather[w]['temp'])) | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ex_lst = ['hi', 'how are you', 'bye', 'apple', 'zebra', 'dance'] | |
def second_let(str): | |
return str[1] #returning the second letter on any string | |
sorted_by_second_let=sorted(ex_lst,key=second_let) | |
print (sorted_by_second_let) |
Final Assessment- Problem 6
"""
Create a function called last_four that takes in an ID number and returns the
last four digits. For example, the number 17573005 should return 3005. Then,
use this function to sort the list of ids stored in the variable, ids, from
lowest to highest. Save this sorted list in the variable, sorted_ids.
Hint:Remember that only strings can be indexed, so conversions may be needed.
"""
def last_four(x):
return (str(x)[-4:])
ids = [17573005, 17572342, 17579000, 17570002, 17572345, 17579329]
#print(ids)
sorted_ids = sorted(ids, key=last_four)
#print(sorted_ids)
The answer above is not right since it's said not allowed to use lambda function.
Correct answer are written below:
ex_lst = ['hi', 'how are you', 'bye', 'apple', 'zebra', 'dance']
def second_let(x): # x can be a list
for wrd in [x]:
return wrd[1]
sorted_by_second_let = sorted(ex_lst, key=second_let)
print(sorted_by_second_let)
ex_lst = ['hi', 'how are you', 'bye', 'apple', 'zebra', 'dance']
def second_let(elem):
for i in ex_lst:
return elem[1]
sorted_by_second_let = sorted(ex_lst, key=second_let)
print(sorted_by_second_let)
nums = ['1450', '33', '871', '19', '14378', '32', '1005', '44', '8907', '16']
def last_char(s):
for i in nums:
return s[-1]
nums_sorted = sorted(nums, key = last_char, reverse= True)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ex_lst = ['hi', 'how are you', 'bye', 'apple', 'zebra', 'dance']
def second_let(x):
sorted_by_second_let=sorted(ex_lst, key=second_let)