C Homework 6 - due 04/20

check out the files in this directory

C Homework 5 - due 04/11

check out the files in this directory

C Homework 4 - due 04/04

check out the files in this directory

C Homework 3 - due 03/21

check out the files in this directory

pdf-format / doc-format

C Homework 2 - due 03/14

rubric + solutions

pdf-format / pdf-format

C Homework 1 - due 02/28

rubric + solutions

pdf-format / doc-format

C Homework 0 - complete by 02/21

Python Homework Guidelines

  1. Each problem is to be submitted as its own .py file in the format hw<hw-number>_p<problem-number>.py. For instance, submit the file called hw2_p1.py for homework 2 problem 1.
  2. Each file is to start with a header comment formatted like:
    # Name:           <your full name>
    # Class:          COP 3223 Section 1 Spring 2013
    # Assignment:     hw  <hw-number> problem< problem-number>
    # Date completed: <date>
    #
    # Description of what the code does
  3. Code should contain comments for each section of code. For instance:
    # add values
    x = x + y
    y = x + 2
    # subtract values
    x = x -y
  4. Each program is to have a main method that is executed with all the other code being called by main. Note: if main is defined but not called, then no credit will be given for the assignment as no code is actually executed.
  5. The python file must be able to be executed directly. Do not copy any output from the shell into the file.
  6. Structure code using functions def. Avoid duplicating code.
  7. If using mathematical constants, import them from the math library. For instance, use math.pi instead of 3.14.

The solutions for all homeworks are available below.

Python Homework 4

due: 02/06

out: 01/31

Solution Problem 1

# Name:           TA Solution (by James Cary, edited by Matt Hyman)
# Class:          COP 3223 Section 1 Spring 2014
# Assignment:     hw 4 problem 1

# Define a function, reverse_list, that 
# takes an arbitrary list as input
# and returns a new list in which all the 
# elements appear in reverse order

# Make sure that you DO NOT MUTATE the input list!!!

# You are not allowed to use the Python built-in method reverse()

# For instance:
# a = [1,2,3]
# b = reverse_list(a)
# print(a) 
# should print out [1,2,3], 
# meaning that the list a was NOT MUTATED
# print(b)
# should print out the new list [3,2,1], 
# which is the reversed version of a

def reverse_list(input_list):
    
    output_list = []

    #get length of list
    in_len = len(input_list) - 1

    #loop through list in reverse order to make a new list
    while in_len >= 0:
        output_list += [input_list[in_len]]
        in_len -= 1

    #return new list
    return output_list 

# to test your implementation of reverse_list, 
# you have to use/include the following code below

def main():
    test_lists = [[1,2,3],['Python', 'is', 'fun'], ["I'm","getting","better","at","programming"], [1, ["nested", "list"]]]
    for test_list in test_lists:
        print('original list: ', test_list, 'and its reversed version:', reverse_list(test_list))

main()

Problem 1

# Define a function, reverse_list, that 
# takes an arbitrary list as input
# and returns a new list in which all the 
# elements appear in reverse order

# Make sure that you DO NOT MUTATE the input list!!!

# You are not allowed to use the Python built-in method reverse()

# For instance:
# a = [1,2,3]
# b = reverse_list(a)
# print(a) 
# should print out [1,2,3], 
# meaning that the list a was NOT MUTATED
# print(b)
# should print out the new list [3,2,1], 
# which is the reversed version of a

def reverse_list(input_list):
# fill in the missing code
    return output_list 

# to test your implementation of reverse_list, 
# you have to use/include the following code below

def main()
    test_lists = [[1,2,3],['Python', 'is', 'fun'], ["I'm","getting","better","at","programming"], [1, ["nested", "list"]]]
    for test_list in test_lists:
        print('original list: ', test_list, 'and its reversed version:', reverse_list(test_list))

main()

Solution Problem 2

# Name:           TA Solution (by James Cary, edited by Matt Hyman)
# Class:          COP 3223 Section 1 Spring 2014
# Assignment:     hw 4 problem 2

# Define a function, find_most_frequent_keyword, that
# takes a pre-built index (see week 4/5 lecture notes)
# as input and returns the keyword that appears most often in web pages

# for instance, assume that the index has been built as follows:

# index = [['ucf', ['http://ucf.edu']],
#          ['quantum', ['http://www.eecs.ucf.edu/~wocjan', 'http://www.quantum.com']]]

# we can explain this index as a list of lists, each containing
# a keyword and another list of website URLs in which this keyword appears

# find_most_frequent_keyword(index)

# should return 'quantum' because its accompanying URL list has 2 elements,
# where 'ucf' has only 1 (in this example)

# print(find_most_frequent_keyword(index))

# should print 'quantum' because its accompanying URL list has 2 elements,
# where 'ucf' has only 1 (in this example)

# Hint: Don't think about it too hard, most of the work is done for you
# in the main function. You want to find the keyword that has the largest
# number of accompanying URLs.


def find_most_frequent_keyword(index):

    #number of websites that contain the highest index
    max = 0
    #the highest index
    highest_index = ''

    #loop trhough each index to find the index that is in the most websites
    for i in index:

        #get the name of the index from the nested list 
        keyword = i[0]

        #use the length of the list of websites to see if this is
        #the most fequent index found so far, if so store its name and length
        if len(i[1]) > max:
            max = len(i[1])
            highest_index = keyword

    #return the name of the highest index
    return highest_index

# to test your implementation of find_most_frequent_keyword,
# you have to use/include the following code below

def main():
    keyword_num = 0
    index = []
    print("Entering the empty string as keyword stops the index building process.")
    while True:
        keyword = str(input("Enter keyword #" + str(keyword_num) + ": "))
        if keyword == "":
            break

        print("  Enter now all URLs that contain the keyword '" + keyword + "'.")
        print("  Entering the empty string as URL stops this process.")
        url_num = 0
        url_list = []

        while True:
            url = str(input("  Enter url #" + str(url_num) + ": "))
            if url == "":
                break
            url_list.append(url)
            url_num = url_num + 1

        index.append([keyword,url_list])
        keyword_num = keyword_num + 1

    print("You have manually created the index:")
    print(index)

    print("The most frequent keyword is", find_most_frequent_keyword(index))

main()

Problem 2

# Define a function, find_most_frequent_keyword, that
# takes a pre-built index (see week 4/5 lecture notes)
# as input and returns the keyword that appears most often in web pages

# for instance, assume that the index has been built as follows:

# index = [['ucf', ['http://ucf.edu']],
#          ['quantum', ['http://www.eecs.ucf.edu/~wocjan', 'www.quantum.com']]]

# we can explain this index as a list of lists, each containing
# a keyword and another list of website URLs in which this keyword appears

# find_most_frequent_keyword(index)

# should return 'quantum' because its accompanying URL list has 2 elements,
# where 'ucf' has only 1 (in this example)

# print(find_most_frequent_keyword(index))

# should print 'quantum' because its accompanying URL list has 2 elements,
# where 'ucf' has only 1 (in this example)

# Hint: Don't think about it too hard, most of the work is done for you
# in the main function. You want to find the keyword that has the largest
# number of accompanying URLs.


def find_most_frequent_keyword(index):
# fill in the missing code

# to test your implementation of find_most_frequent_keyword,
# you have to use/include the following code below

def main():
    keyword_num = 0
    index = []
    print("Entering the empty string as keyword stops the index building process.")
    while True:
        keyword = str(input("Enter keyword #" + str(keyword_num) + ": "))
        if keyword == "":
            break

        print("  Enter now all URLs that contain the keyword '" + keyword + "'.")
        print("  Entering the empty string as URL stops this process.")
        url_num = 0
        url_list = []

        while True:
            url = str(input("  Enter url #" + str(url_num) + ": "))
            if url == "":
                break
            url_list.append(url)
            url_num = url_num + 1

        index.append([keyword,url_list])
        keyword_num = keyword_num + 1

    print("You have manually created the index:")
    print(index)

    print("The most frequent keyword is", find_most_frequent_keyword(index))

main()

Python Homework 3

due: 01/31

out: 01/24

Solution to Problem 1

# Name:           TA Solution (by Matt Hyman)
# Class:          COP 3223 Section 1 Spring 2014
# Assignment:     hw 3 problem 1

# mystery code
# someone forgot to comment the code
# so you have to figure out what it does

def proc0(a):
    ref = a
    ref[1] = a[0]

def proc1(b):
    b = b + ["crazy stuff going on!"]

def proc2(p):
    q = p
    p.append(3)
    q.pop()

def main(c):
    if len(c) < 2:
        print("too short")
    else:
        proc0(c)
        proc1(c)
        proc2(c)
        if c[0] != c[1]:
            print("weird")
        else:
            print("strange")

# assume that you call main and pass to it
# an ARBITRARY list (it could even be a nested list)

# Indicate which of the following statements is false / true:
# 1 - always prints weird: FALSE
# 2 - always prints strange: FALSE
# 3 - never prints weird: TRUE
# 4 - never prints strange: FALSE
# 5 - sometimes prints too short: TRUE

Problem 1

# mystery code
# someone forgot to comment the code
# so you have to figure out what it does

def proc0(a):
    ref = a
    ref[1] = a[0]

def proc1(b):
    b = b + ["crazy stuff going on!"]

def proc2(p):
    q = p
    p.append(3)
    q.pop()

def main(c):
    if len(c) < 2:
        print("too short")
    else:
        proc0(c)
        proc1(c)
        proc2(c)
        if c[0] != c[1]:
            print("weird")
        else:
            print("strange")

# assume that you call main and pass to it
# an ARBITRARY list (it could even be a nested list)

# Indicate which of the following statements is false / true:
# 1 - always prints weird
# 2 - always prints strange
# 3 - never prints weird
# 4 - never prints strange
# 5 - sometimes prints too short

Note that you do not need to submit any python code for this problem. You have to upload a text file, in which you indicate which of the above statements are true and which ones are false.

Solution to Problem 2

# Name:           TA Solution (by Matt Hyman)
# Class:          COP 3223 Section 1 Spring 2014
# Assignment:     hw 3 problem 2

# Define a procedure, concat_list,
# takes as input a list of strings,
# and returns a string that is
# the concatenation all
# those strings together.

def concat_list(p):
    string = ""
    #loop through each string in list p 
    for word in p:
        #concat each word to string 
        string+= word

    #return string 
    return string 

# you have to use the main function below in your code

def main():
    list = []
    i = 1
    print('Entering the empty string stops the input process.')
    while True:
        str_input = str(input('Enter string #' + str(i) + ': '))
        if str_input == '':    # empty string -> stop input process
            if i > 1:
                list.pop()     # remove the last element ' ' from list
            break
        i = i + 1
        list.append(str_input)
        list.append(' ')       # we want the user's input strings to be interspersed with ' '
                               # for instance: ['Python', ' ', 'is', 'so', ' ', 'cool']
    
    print(concat_list(list))   # <===== updated this on line Thu 01/30

main()

# The above problem could be solved easily by using the join method. For instance,
# ' '.join(['Python','is','so','cool']) directly yields the string
# 'Python is so cool'

# You are not allowed to use join.

Problem 2

# Define a procedure, concat_list,
# takes as input a list of strings,
# and returns a string that is
# the concatenation all
# those strings together.

def concat_list(p):
# fill in the missing code

# you have to use the main function below in your code

def main():
    list = []
    i = 1
    print('Entering the empty string stops the input process.')
    while True:
        str_input = str(input('Enter string #' + str(i) + ': '))
        if str_input == '':    # empty string -> stop input process
            if i > 1:
                list.pop()     # remove the last element ' ' from list
            break
        i = i + 1
        list.append(str_input)
        list.append(' ')       # we want the user's input strings to be interspersed with ' '
                               # for instance: ['Python', ' ', 'is', 'so', ' ', 'cool']
    
    print(concat_list(list))   # <===== updated this on line Thu 01/30

main()

# The above problem could be solved easily by using the join method. For instance,
# ' '.join(['Python','is','so','cool']) directly yields the string
# 'Python is so cool'

# You are not allowed to use join.

Solution to Problem 3

# Name:          TA Solution (by Matt Hyman)
# Class:          COP 3223 Section 1 Spring 2014
# Assignment:     hw  3 problem 3

# Define a procedure, greatest,
# that takes as input a list
# of positive numbers, and
# returns the greatest number
# in that list. If the input
# list is empty, the output
# should be 0.

def greatest(p):

    #if p is an empty list return 0
    if not p:
        return 0

    #let maxVal start as the first value in the list
    maxVal = p[0]

    #loop through each item in the list
    for num in p:
        #if the current item is larger then maxVal then set maxVal equal to it
        if num > maxVal:
            maxVal = num

    #return the maximum value that we have found 
    return maxVal 

# you have to use the main function below in your code

def main():
    list = []
    while True:
      n = int(input('Enter either 0 to stop input process or a positive number to add to list: '))
      if n == 0:
        break
      list.append(n)
    print('The greatest number in the list', list, 'is', greatest(list))

main()

# The above problem could be solved easily by using the max command. For instance,
# max([1,2,3,2,1]) yields the integer 3, which is the greatest number of the list.

# You are not allowed to use max.

Problem 3

# Define a procedure, greatest,
# that takes as input a list
# of positive numbers, and
# returns the greatest number
# in that list. If the input
# list is empty, the output
# should be 0.

def greatest(p):
# fill in the missing code

# you have to use the main function below in your code

def main():
    list = []
    while True:
      n = int(input('Enter either 0 to stop input process or a positive number to add to list: '))
      if n == 0:
        break
      list.append(n)
    print('The greatest number in the list', list, 'is', greatest(list))

main()

# The above problem could be solved easily by using the max command. For instance,
# max([1,2,3,2,1]) yields the integer 3, which is the greatest number of the list.

# You are not allowed to use max.

Python Homework 2

due: 01/24

out: 01/17

Problem 1

You must use a while loop.

# Define a procedure, countdown, that takes a positive whole
# number as its input, and prints out a countdown from 
# that number to 0, followed by the string "Problem 1 done!".

# Your program has to read-in an input number from the user and call countdown 
# with the read-in value.

# For instance, if the user enters 4 as input, then countdown(4) should print out:
# 4
# 3
# 2
# 1
# 0
# Problem 1 done!

To emphasize: the string "Problem 1 done!" has to be printed out after the numbers.

Solution to Problem 1

# Name:           TA Solution (by James Cary, edited by Matt Hyman)
# Class:          COP 3223 Section 1 Spring 2013
# Assignment:     hw 2 problem 1

#
# Defines and calls a procedure, countdown, that takes a positive whole
# number as its input, and prints out a countdown from 
# that number to 0, followed by the string "Problem 1 done!".


#see explanation above 
def countdown(n):
        #iterate through eave value of n until n is a negative number 
  while n >= 0:
                #print out the value of n
    print (n)
    #decrement the value of n
    n=n-1

  #once the loop is done print out that the problem is done
  print ("Problem 1 done!")

#main contains the actual logic of the program
#in this case the logic is reading in an integer and calling countdown with it
def main():
        value = int(input("Please enter a positive number to countdown from. "))
        countdown(value)

#call main to run program 
main()

Problem 2

You must use nested while loops.

# Define a procedure, print_addition_table, 
# that takes as input a positive whole number,
# and prints out an addition table showing
# all the whole number additions up to 
# and including the input number.

# Your program has to read-in an input number from the user and call print_addition_table 
# with the read-in value.

# For instance, if the user enters 3, then print_addition_table(3) should print out:
# 1 + 1 = 2
# 1 + 2 = 3
# 1 + 3 = 4
# 2 + 1 = 3
# 2 + 2 = 4
# 2 + 3 = 5
# 3 + 1 = 4
# 3 + 2 = 5
# 3 + 3 = 6

Solution to Problem 2

# Name:           TA Solution (by James Cary, edited by Matt Hyman)
# Class:          COP 3223 Section 1 Spring 2013
# Assignment:     hw 2 problem 2

# Define a procedure, print_addition_table, 
# that takes as input a positive whole number,
# and prints out an addition table showing
# all the whole number additions up to 
# and including the input number.

# Your program has to read-in an input number from the user and call print_addition_table 
# with the read-in value.


def print_addition_table(n):
    x = 1
    y = 1
    #for each value of x until it is greater than n execute the below code
    while x <= n:
        
        #reset the value of y for each iteration of the outer loop
        y = 1
        #for each value of y until it is greater than n print the sum of x and y
        while y <= n:
            print(x, "+", y, "=", (x+y))
            #increment the y counter 
            y = y + 1
        #increment the x counter 
        x = x + 1
  

#main contains the actual logic of the program
#in this case the logic is reading in an integer and calling print_addition_table with it
def main():
    value = int(input("Please enter a positive number to countdown from. "))
    print_addition_table(value)

#call main to run program 
main()

Problem 3

You must use if statements to determine the median. Using sort is not allowed!

# Define a procedure, median, that takes three
# numbers as its inputs, and returns the median
# of the three numbers.

# Your program has to read-in three input numbers from the user and call median 
# with the read-in values.

# For instance, if the user enters the three numbers 1, 2, and 3 (in this order), then
# median(1,2,3) should be called.

# To test your code, for instance, you could try enering 
# the 6 different triples consisting of 1, 2, 3.

Solution to Problem 3

# Name:           TA Solution (by James Cary, edited by Matt Hyman)
# Class:          COP 3223 Section 1 Spring 2013
# Assignment:     hw 2 problem 3

# Define a procedure, median, that takes three
# numbers as its inputs, and returns the median
# of the three numbers.

def median(a, b, c):
  if a <= b <= c or c <= b <= a:
    print (b)
    return b
  elif b <= a <= c or c <= a <= b:
    return (a)
  else:
    return (c)

#main contains the actual logic of the program
#in this case the logic is reading in 3 integers,
#using them to call median, and print the resulting value
def main():
        a = int(input("Please enter a number. "))
        b = int(input("Please enter a number. "))
        c = int(input("Please enter a number. "))
        print("The median is:", median(a,b,c))

#call main to run program 
main()

Python Homework 1

due: 01/17

out: 01/10

Make sure the first line of the files you upload is a comment containing your full name.

Problem 1

Download and install Python on your computer. Follow the instructions at http://www.python.org/download/

Problem 2

Using the program below as a blueprint, write python code that computes the area of a circle. The radius should be entered by the user on the keyboard.

# rectangle_area.py 
# This program lets the user enter the width and
# the height of a rectange using the keyboard and
# prints out its area

print("I compute the area of a rectangle")

# reading in the user input
width  = float(input("enter the width: "))
height = float(input("enter the height: "))
      
# computing the area of the rectangle
area   = width * height
print("the area of this rectangle is", area) 

Solution to Problem 2

# circle.py
import math

def circle():
    radius = float(input("Enter the radius of the circle: "))
    area = math.pi * math.pow(radius, 2)
    print("Area of the circle is:", area)

def main():
    circle()

main()

Problem 3

Write python code that prints out the first two URLs that appear in the string variable page. You may assume that page contains at least two URLs. To do this, extend the code below.

# The first part of the Python code extracts the HTML code of the website
# http://www.cs.ucf.edu/courses/cop3223/spr2014/section1/simple.html'
# and stores it in the variable page

import urllib.request

def get_html(url):
    response = urllib.request.urlopen(url)
    html = response.read().decode("utf-8")
    return html

page = get_html('http://www.cs.ucf.edu/courses/cop3223/spr2014/section1/simple.html')

# This second part of the Python code prints out the first URL
# that appears in a link tag in the string 
# stored in the variable page

start_link = page.find('<a href=')
start_quote = page.find('"', start_link)
end_quote = page.find('"', start_quote + 1)
url = page[start_quote + 1 : end_quote]
print('The first URL is', url)

# Extend this code so it also prints out the second URL
# inside page.

Solution to Problem 3

# url.py
import urllib.request


def get_html(url):
    response = urllib.request.urlopen(url)
    html = response.read().decode("utf-8")
    return html


def url():
    url = 'http://www.cs.ucf.edu/courses/cop3223/spr2014/section1/simple.html'
    page = get_html(url)

    # This second part of the Python code prints out the first URL
    # that appears in a link tag in the string
    # stored in the variable page

    start_link = page.find('<a href=')
    start_quote = page.find('"', start_link)
    end_quote = page.find('"', start_quote + 1)
    url1 = page[start_quote + 1:end_quote]

    page = page[end_quote:]

    # Extend this code so it also prints out the second URL
    # inside page.

    start_link = page.find('<a href=')
    start_quote = page.find('"', start_link)
    end_quote = page.find('"', start_quote + 1)
    url2 = page[start_quote + 1:end_quote]

    print('The first URL is:', url1)
    print('The second URL is:', url2)


def main():
    url()

main()