Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

python3 (2a) Write a function middle which takes a list L as its argument and re

ID: 3724720 • Letter: P

Question

python3

(2a) Write a function middle which takes a list L as its argument and returns the item
in the middle position of L, when L has an odd length. Otherwise, middle should
return 999999. For example, calling middle([8, 0, 100, 12, 18]) should return 100.
You should, at least, have five different lists to test in the docstring: lists of even and
odd number of numeric elements, lists of even and odd number of string elements,
and a blank list. (Hint: you may use the // integer division operator).


(2b) Write a function, mySum, with one parameter, L, a list of numbers. mySum
returns the sum of the numbers in the input list. (mySum should not use Python’s
builtin sum function.)
For example,


>>> mySum([2, 3, 2])
7


In the docstring, there should be minimally five examples of function calls including a
blank list, a single element list, and list of positive and negative numbers.

Explanation / Answer

Python3 Code:

def middle(L):

    #if odd length return middle element

    if len(L) % 2 != 0:

        return L[len(L)//2]

    return 999999 #else return 999999

def mySum(L):

    s = 0 #sum

    for val in L:

        s = s + val #add val to sum

    return s

#test cases for middle

print(middle([]))

print(middle([23, 54, 92, 12, 88, 32]))

print(middle([8, 0, 100, 12, 18]))

print(middle(["laksjdalks", "asdjioiuwew", "ahskdjhwqe"]))

print(middle(["laksjdalks", "asdjioiuwew", "ahskdjhwqe", "zxczcznxc"]))

#test cases for mySum

print(mySum([2, 3, 2]))

print(mySum([]))

print(mySum([1]))

print(mySum([34, 45, 92, 86]))

print(mySum([-12, -74, -62, -11]))