Checkpoint 9.12.1.
Write a program that will print out the length of each item in the list as well as the first and last characters of the item.
def count(obj, lst):
count = 0
for e in lst:
if e == obj:
count = count + 1
return count
def is_in(obj, lst): # cannot be called in() because in is a reserved keyword
for e in lst:
if e == obj:
return True
return False
def reverse(lst):
reversed = []
for i in range(len(lst)-1, -1, -1): # step through the original list backwards
reversed.append(lst[i])
return reversed
def index(obj, lst):
for i in range(len(lst)):
if lst[i] == obj:
return i
return -1
def insert(obj, index, lst):
newlst = []
for i in range(len(lst)):
if i == index:
newlst.append(obj)
newlst.append(lst[i])
return newlst
lst = [0, 1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9]
print(count(1, lst))
print(is_in(4, lst))
print(reverse(lst))
print(index(2, lst))
print(insert('cat', 4, lst))
max
but pretend you cannot use it.)import random
def max(lst):
max = 0
for e in lst:
if e > max:
max = e
return max
lst = []
for i in range(100):
lst.append(random.randint(0, 1000))
print(max(lst))
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:0 and 1000
, and write code for the function called countOdd(lst)
to count every odd
number in the listimport random
def countOdd(lst):
odd = 0
for e in lst:
if e % 2 != 0:
odd = odd + 1
return odd
# make a random list to test the function
lst = []
for i in range(100):
lst.append(random.randint(0, 1000))
print(countOdd(lst))
-1000 and 1000
, and write code for the function called sumEven(lst)
to sum up all the even
numbers in the listimport random
def sumEven(lst):
sum = 0
for e in lst:
if e % 2 == 0:
sum += e
return sum
# make a random list to test the function
lst = []
for i in range(100):
lst.append(random.randrange(-1000, 1000))
print(sumEven(lst))
-1000 and 1000
, and write code for the function called sumNegatives(lst)
to sum up all the negative
numbers in the listimport random
def sumNegatives(lst):
sum = 0
for e in lst:
if e < 0:
sum += e
return sum
lst = []
for i in range(100):
lst.append(random.randrange(-1000, 1000))
print(sumNegatives(lst))