List chapter 10
Exercise 2
Create a list called myList with the following six items: 76, 92.3, “hello”, True, 4, 76. Do it with both append and with concatenation, one item at a time.
myList = []
myList.append(76)
myList.append(92.3)
myList.append("hello")
myList.append(True)
myList.append(4)
myList.append(76)
myList2 = []
myList2 += [76]
myList2 += [92.3]
myList2 += ["hello"]
myList2 += [True]
myList2 += [4]
myList2 += [76]
Exercise 3
Starting with the list in Exercise 2, write Python statements to do the following:
- Append “apple” and 76 to the list.
- Insert the value “cat” at position 3.
- Insert the value 99 at the start of the list.
- Find the index of “hello”.
- Count the number of 76s in the list.
- Remove the first occurrence of 76 from the list.
- Remove True from the list using pop and index.
myList = []
myList.append(76)
myList.append(92.3)
myList.append("hello")
myList.append(True)
myList.append(4)
myList.append(76)
myList.append(["apple", 76])
myList.insert(3, "cat")
myList.insert(0, 99)
print(myList.index("hello"))
print(myList)
myList.count(76)
myList.remove(76)
myList.pop(myList.index(True))
print(myList)
Exercise 4
Write a function to count how many odd numbers are in a list.
def count_odd(list):
index = 0
for number in list:
if number%2 != 0:
index += 1
return index
List chapter 11
Exercise 1
Create a list containing 100 random integers between 0 and 1000 (use iteration, append, and the random module). Write a function called average that will take the list as a parameter and return the average.
import random
def random_list():
list = []
for num in range(100):
list.append(random.randrange(1001))
return list
print(len(random_list()))
print(random_list())
def average_list(lst):
average = 0
for number in lst:
average += number
return average / len(lst)
print(average_list(random_list()))
Exercise 2
Write a Python function that will take a the list of 100 random integers between 0 and 1000 and return the maximum value. (Note: there is a builtin function named max but pretend you cannot use it.)
def random_list():
list = []
for num in range(100):
list.append(random.randrange(1001))
return list
def max_list(lst):
max = 0
for element in lst:
if element > max:
max = element
return max
Exercise 3
Write a function sum_of_squares(xs)
that computes the sum of the squares of the numbers in the list xs
. For example, sum_of_squares([2, 3, 4])
should return 4+9+16
which is 29
:
def sum_of_squares(lst):
sum = 0
for number in lst:
sum += number**2
return sum
print(sum_of_squares([2, 3, 4]))
Exercise 4
Sum up all the negative numbers in a list.
import random
def random_list(elements):
list = []
for num in range(elements):
list.append(random.randrange(-1000, 1000))
return list
def sum_negatives(lst):
sum = 0
for number in lst:
if number < 0:
sum += number
return sum
list = random_list(10)
print(list)
print(sum_negatives(list))
Exercise 5
Count how many words in a list have length 5.
def sum_length(list):
counter = 0
for word in list:
if len(word) == 5:
counter += 1
return counter
text ="Vel quam nam vel voluptatum. Inventore harum quas excepturi id quia vel. Nobis deserunt temporibus quasi rerum maxime. Dolores dolores saepe inventore harum doloribus in officiis."
words = text.split()
print(words)
print(sum_length(words))
Exercise 6
Count how many words occur in a list up to and including the first occurrence of the word “sam”.
def up_to_sam(lst):
counter = 0
for word in lst:
if word == "sam":
counter += 1
return counter
else:
counter +=1
return counter
text ="Vel quam nam vel voluptatum. Inventore harum quas sam excepturi id quia vel. Nobis deserunt temporibus quasi rerum maxime. Dolores dolores saepe inventore harum doloribus in officiis."
words = text.split()
print(words)
print(up_to_sam(words))
Exercise 7
Although Python provides us with many list methods, it is good practice and very instructive to think about how they are implemented. Implement a Python function that works like the following:
- count
- in
- reverse
- index
- insert
def list_count(lst, e):
counter = 0
for element in lst:
if element == e:
counter +=1
return counter
def list_in(lst, e):
for element in lst:
if element == e:
return True
return False
def list_reverse(lst):
list = []
for element in lst:
list = [element] + list
return list
def list_idx(lst, e):
for element_p in len(lst):
if lst[element_p] = e:
return element_p
return -1
def list_ins(lst, e, pos=0):
list = []
list = lst[0:pos] + [e] + lst[pos:]
return list
lst = [0, 1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9]
print(list_count(lst,1 ))
print(list_in(lst, 4))
print(list_reverse(lst))
print(list_idx(lst,2))
print(list_ins(lst, 'cat', 4))
print(list_ins(lst, 'cat'))
>>> 2
>>> True
>>> [9, 8, 7, 6, 5, 4, 3, 2, 2, 1, 1, 0]
>>> 3
>>> [0, 1, 1, 2, 'cat', 2, 3, 4, 5, 6, 7, 8, 9]
>>> ['cat', 0, 1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9]
Exercise 8
Write a function replace(s, old, new) that replaces all occurences of old with new in a string s:
test(replace('Mississippi', 'i', 'I'), 'MIssIssIppI')
s = 'I love spom! Spom is my favorite food. Spom, spom, spom, yum!'
test(replace(s, 'om', 'am'),
'I love spam! Spam is my favorite food. Spam, spam, spam, yum!')
test(replace(s, 'o', 'a'),
'I lave spam! Spam is my favarite faad. Spam, spam, spam, yum!')
Hint: use the split and join methods.
from test import testEqual
def replace(str, old, new):
list = str.split(old)
return new.join(list)
##################################
testEqual(replace('Mississippi', 'i', 'I'), 'MIssIssIppI')
s = 'I love spom! Spom is my favorite food. Spom, spom, spom, yum!'
testEqual(replace(s, 'om', 'am'),
'I love spam! Spam is my favorite food. Spam, spam, spam, yum!')
testEqual(replace(s, 'o', 'a'),
'I lave spam! Spam is my favarite faad. Spam, spam, spam, yum!')