Python 7 Levels, L4, Unit 32, Common Algorithms for List

Powered By EmbedPress

Exercise 1:

list1 = [34,56,2,67,99,50]
list1_max = list1[0]
for i in list1:
    if i > list1_max:
        list1_max = i
print(list1_max)

Exercise 2:

number = int(input("Please input how many students: "))
score_list = []
score_h60 = []
score_l60 = []
for i in range(number):
    score = int(input("Please input score of student "+str(i+1)+" :"))
    score_list.append(score)
for i in score_list:
    if i >= 60:
        score_h60.append(i)
    else:
        score_l60.append(i)

print("Scores more than 60 are: ",end = "")
for i in score_h60:
    print(i,end = "\t")
print() #new line
print("Scores less than 60 are:",end = "")
for i in score_l60:
    print(i,end = "\t")

Exercise 3:

name_list = ["David Smith","Aaron Williams","Mark Steward","Peter Pan"]
name = input("Please input the name you are searching:")
for i in name_list:
	if i == name:
		print(name+"'s index is",name_list.index(name))
		break
else:
	print(name," does not exist.")

Exercise 4:

number = int(input("Please input how many students:"))
name_list = []
for i in range(number):
    name = input("Please input the name of student "+str(i+1)+":")
    name_list.append(name)
while True:
    name = input("Please input student's name to search:(Q/q to quit)")
    if name == "Q" or name == "q":
        print("Abort system.")
        break
    else:
        for i in name_list:
            if i == name:
                print(name+"'s index is:",name_list.index(name)+1)
                break
        else:
            print(name,"does not exist.")

Homework:

a = [6,12,34,56,73,75,88,99]
new = int(input("Please input number to be inserted: "))
a.append(new)
for i in range(len(a)-1,0,-1):
    if a[i] < a[i-1]: #swap 2 items to make an ordered list
        n = a[i]
        a[i] = a[i-1]
        a[i-1] = n
    else: #the list has been ordered
        break
for i in a:
    print(i)

dahan1999

1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts