Skip to content

Instantly share code, notes, and snippets.

@LizaPiya
Last active November 25, 2023 06:59
Show Gist options
  • Save LizaPiya/a22e1b76ea7a5fd46be4acd8ea21262c to your computer and use it in GitHub Desktop.
Save LizaPiya/a22e1b76ea7a5fd46be4acd8ea21262c to your computer and use it in GitHub Desktop.
Week 5
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])))
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
## 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)
## 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)
##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)
## 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)
## 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)
## 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]
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:])
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])
## 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]))
##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)
## 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])
L2 = ["Cherry", "Apple", "Blueberry"]
print(sorted(L2, reverse=True))
## 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)
## 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)
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))
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
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]))
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))
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
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']))
@Rajat-Pathak
Copy link

ex_lst = ['hi', 'how are you', 'bye', 'apple', 'zebra', 'dance']
def second_let(x):

s=[]
for wrd in [x]:
    s.append(wrd[1])

return s

sorted_by_second_let=sorted(ex_lst, key=second_let)

@hadrocodium
Copy link

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)

@mingyuan9
Copy link

Final Assessment Problem 8

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)

@boby132
Copy link

boby132 commented Nov 25, 2023

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)

@boby132
Copy link

boby132 commented Nov 25, 2023

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