Here, we want to build up a list, and then sort it. We'll use the sorted function
def get_10_ints():
'''Take in 10 integers from input, store them in a list, and return the list
'''
ints = [] #empty initially
for i in range(10):
new_int = int(input("Give me an integer: "))
ints.append(new_int)
return ints
ints = get_10_ints()
print(sorted(ints))
def get_N_ints(N):
'''Take in N integers from input, and then sort them
'''
ints = []
for i in range(3):
new_int = int(input("Give me an integer: "))
ints.append(new_int)
return ints
ints = get_N_ints(3)
for i in range(len(ints)):
ints[i] *= 2 #the same as ints[i] = ints[i] * 2
print(ints)
sort()
or sorted()
. Then, write the program while avoiding sort()
and sorted()
¶M = [10, 2, 20, 3]
print(sorted(M)[-2:]) #Done!
M = [10, 2, 20, 3]
M.sort()
print(M[-2:])
Now, let's try to not use sort
/sorted
. The idea is to keep track of the largest and the second-largest measurement that we saw so far.
M = [10, 2, 20, 3]
#First, let's set up the initial values. The idea is to use the first two.
if M[0] > M[1]:
largest, second_largest = M[0], M[1]
else:
largest, second_largest = M[1], M[0]
#Now, we just go through the entire list
for i in range(2, len(M)):
#Three cases:
#1. M[i] is the new largest number
#2. M[i] is the new second-largest number
#3. M[i] is neither
if M[i] > largest:
largest, second_largest = M[i], largest
elif M[i] > second_largest:
second_largest = M[i]
print(second_largest, largest)
OPTIONAL The easiest thing to do is to use str.split together with list.index. That requires knowing about index. Let's use a bit of acrobatics to do this in one line
def what_is_runny(sympt):
words = sympt.lower().split()
return "Your " + words[words.index("runny") + 1] + " is runny"
what_is_runny("Doctor, I have a runny foot")
Now, let's do this in a way that's helpful for the next exercise. We'll find the index where "runny" starts using str.find, and then we'll find the the index where the next word ends. In order to facilitate that, we'll replace all punctuation with spaces.
def what_is_runny2(sympt):
sympt = sympt.lower()
for punc in "!.,;:?":
sympy = sympy.replace(punc, " ") #replace every puncutation sign with a space
ind_runny = sympy.find("runny")
#Now, we know that whatever is runny will start at index sympt[ind_runny+len("runny")+1] (the + 1 is for the space)
ind_bodypart = ind_runny + len("runny") + 1
ind_bodypart_end = sympy.find(" ", ind_bodypart) #find the space that follows the name of the body part. There's
#definitely a space, since we got rid of all
#punctuation
return "Your " + sympt[ind_bodypart:int_bodypart_end] + " is runny"
what_is_runny("Doctor, I have a runny foot")