CS 125
Lecture 12

Compute the sum of numbers in a list.

def mysum(a : list):
    sum = 0
    for x in a:
        sum += x
    return sum
>>> mysum([3,5,1,2,6,4])
21

Compute the product of numbers in a list.

def myproduct(a : list):
    product = 1
    for x in a:
        product *= x
    return product
>>> myproduct([3,5,1,2,6,4])
720

Find the maximum of the numbers in a list.

def mymax(a : list):
    guess = a[0]
    for x in a[1:]:
        if x > guess:
            guess = x
    return guess
>>> mymax([3,5,1,2,6,4])
6

Find the minimum of the numbers in a list.

def mymin(a : list):
    guess = a[0]
    for x in a[1:]:
        if x < guess:
            guess = x
    return guess
>>> mymin([3,5,1,2,6,4])
1

Print a Square

def square(width : int, height : int, c : str):
    for i in range(height):
        print(c * width)
>>> square(5, 3, '*')
*****
*****
*****
>>> square(8, 4, '#')
########
########
########
########

Print a Hollow Square

def hollow_square(width : int, height : int, c : str):
    if height == 1:
        print(c * width)
    elif width == 1:
        for i in range(height):
            print(c)
    elif height > 1 and width > 1:
        print(c * width)
        for i in range(height - 2):
             print(c + " " * (width - 2) + c)
        print(c * width)
>>> hollow_square(1, 1, '$')
$
>>> hollow_square(1, 5, '$')
$
$
$
$
$
>>> hollow_square(5, 1, '$')
$$$$$
>>> hollow_square(3, 5, 'x')
xxx
x x
x x
x x
xxx
>>> hollow_square(2, 2, 'x')
xx
xx
>>> hollow_square(0, 2, 'x')
>>> hollow_square(2, 0, 'x')
>>> 

Print a Triangle

def triangle(size : int, c : str):
    for i in range(size):
        print(c * (i + 1))
>>> triangle(1, '#')
#
>>> triangle(2, '#')
#
##
>>> triangle(5, '#')
#
##
###
####
#####
>>> triangle(0, '#')
>>>

Print a Hollow Triangle

def hollow_triangle(size : int, c : str):
    if size == 1:
        print(c)
    elif size >= 2:
        print(c)
        for i in range(size - 2):
            print(c + " " * i + c)
        print(c * size)
>>> hollow_triangle(0, '#')
>>> hollow_triangle(1, '#')
#
>>> hollow_triangle(2, '#')
#
##
>>> hollow_triangle(3, '#')
#
##
###
>>> hollow_triangle(4, '#')
#
##
# #
####
>>> hollow_triangle(5, '#')
#
##
# #
#  #
#####
>>> hollow_triangle(8, '#')
#
##
# #
#  #
#   #
#    #
#     #
########
>>> 

Testing

Print a String in a Box

def box(message, c):
    print(c * (len(message) + 4))
    print(c + " " + message + " " + c)
    print(c * (len(message) + 4))
>>> box("This is a message!", "#")
######################
# This is a message! #
######################