Learn faster and stay on-track by joining this free class with other self-learners.
Register for MIT OpenCourseWare 6.00 Introduction to Computer Science and Programming now.
|
MIT OpenCourseWare 6.00 Introduction to Computer Science and ProgrammingClass length: 24 weeks. Start anytime. Creator: duallain Status: Established |
Join this class! |
|
Lesson 8: Assignment 1Homework Submissions8 total1) Are each of the following True or False:1.1. Any program that can be written using only function definitions and calls, the basic arithmetic operators, assignment, and conditionals will run in constant time. FALSE. Constant time means execution takes the same time every time. Conditionals mean it could branch and take various times to execute.
1.2. Newton's method will always converge on a correct root of a function.
FALSE. It can bogged down and bounce between two values.
1.3. In Python, dictionaries are immutable.
FALSE. Tuples are immutable. But this question seems pre-mature.
1.4. The value of "math.sqrt(2.0)*math.sqrt(2.0) == 2.0" is True. FALSE. The binary representation of sqrt of not precise enough.
1.5. One should always avoid iteration when a recursive solution is possible. FALSE
1.6. Typically, the use of functions in a program reduces the total number of lines of code. TRUE
1.7. In Python, retrieving the value associated with a dictionary key takes roughly constant time. No Idea. Wasn't covered yet. But I will guess TRUE.
2) Consider the implementations of compare1 and compare2, where a and b are floats.2.1) Do compare1 and compare2 return the same value for all possible inputs? SURE LOOKS LIKE IT. BUT I DOUBT IT.
If not, give a pair of inputs for which they return a different value.
2.2) Do compare1 and compare2 print the same thing for all possible inputs? If not, give a pair of inputs for which they print different things.
def compare1(a, b):
if a < 0:
a = -a
if b < 0:
b = -b
res = (a == b)
if res:
print a, 'and', b, 'have the same absolute value.'
else:
print a, 'and', b, 'have different absolute values.'
return res
*** Test Values:
a = 7
b = .7
------------------------------------------------------------------------
def absolute_value(n):
if n < 0:
n = -n
return n
def compare2(a, b):
res = absolute_value(a) == absolute_value(b)
if res:
print a, 'and', b, 'have the same absolute value.'
else:
print a, 'and', b, 'have different absolute values.'
return res
3) Consider the following implementation of a function f, where x is a positive integer:def f(x):
xs = str(x) # "2112"
if len(xs) == 1: # FALSE LEN(XS) = 4
return int(xs)
n = int(xs[0]) + int(xs[1]) # N = 1 + 2 = 3
if len(xs) == 2: # FALSE LEN(XS) = 4
return n
else:
return n + f(xs[2:]) # 3 + F(12); F(12) = 3
What does f(2112) return? 6
3.2. Write a specification of f."""F SUMS THE FIRST TWO DIGITS OF THE VALUE PASSED, AND THEN ADDS THEM TO THE SUM OF THE NEXT TWO DIGITS, THIS CONTINUES UNTIL ALL DIGITS HAVE BEEN SUMMED. IF THE VALUE PASSED IS AN ODD NUBMER OF DIGITS THEN THE LAST DIGIT IS ADDED DIRECTLY TO THE THE PRIOR SUM."""
4) Provide a Python implementation of a function first_N that takes a positive integer, n, as its only argument. The function should print the first n perfect squares that are not even numbers. E.g., if n were 2 it should print the perfect squares 1 and 9.## ANSWER:
def first_N(n):
"""first_N that takes a positive integer, n, as its only argument. The function should print the first n perfect squares that are not even numbers. E.g., if n were 2 it should print the perfect squares 1 and 9."""
answer = []
counter = 1
while len(answer) < n:
squared = counter * counter
if squared%2 != 0:
answer.append(squared)
counter += 1
print 'The first n perfect squares that are not even numbers are:', answer
5. Write pseudo code for an exhaustive enumeration variant of guess and check.Pick a number between 1 and 100: number
for i in range(100)
response = raw_input ("Is you number",i)
if response == yes:
break
print answer
6.) Provide a Python implementation for the function findSide specified belowdef findSide():
"""asks the user to enter the area of a rectangle and the length of one side of the rectangle. Returns a floating point number that is the length of the adjacent side."""
# l * w = a w = a / l
#
# area = 35
# length = 6
# Width = 5.8333
# get the user input
area = raw_input("What is the area of the rectangle:")
length = raw_input("What is the length of one side:")
float(area)
float(length)
width = 0.0 # initialize answer as a float
width = area / length
return width
7) Does the following function meet its specification? If not, change the program so that it is consistent with the specification.def f(L):
"""Returns a copy of the list L without modifying L."""
result = []
for e in L:
result.append(e)
return result
THIS FUNCTION DOES WORK CORRECTLY.
8) At McDonalds one can buy chicken nuggets in packages containing 6, 9 or 20 pieces. Write a Python function that accepts an integer, num, as an argument and decides whether or not it is possible to buy num nuggets at McDonalds.def even_buy(num):
"""Accepts an integer, num, as an argument and decides whether or not it is possible to buy num nuggets at McDonalds."""
# 6x + 9y + 20z = num
for x in range(num):
for y in range(num):
for z in range (num):
if 6*x + 9*y + 20*z == num:
print 'buy', x, 'six packs,', y, 'nine packs, and', z,'twenty packs.'
return (x,y,z)
return None
9) Write an appropriate specification for the function below. Assume that n is an integer.def f(n):
"""Take a number n and returns the reverse of the digits. E.g., f(239) returns 932 as a string."""
# s = 9 Result: '9'
# s = 39 Result: '9' + '3'
# s = 239 Result: '9' + '3' + '2'
s = str(n)
if len(s) <= 1:
return s
return s[-1] + f(int(s[:-1]))
Problem 11.1 False -> Correct 1.2 False -> Correct 1.3 False -> Correct 1.3 False -> Correct 1.5 False -> Correct 1.6 True -> Correct 1.7 True -> Correct Problem 22.1 Yes -> Correct 2.2 Yes -> Incorrect Problem 33.1 6 -> Correct 3.2 Returns the sum of the digits in the number x -> Correct Problem 5I don't know how to write pseudo code Problem 7 -> CorrectYes Problem 9 -> IncorrectTakes an integer and returns a string of that integer #Problem 4 -> Kind of correct
def first_N(n):
squares = []
for x in range(1,n*2,2):
squares.append(x*x)
print tuple(squares)
#Problem 6 -> Correct
def findSide():
"""asks the user to enter the area of a rectangle and the length of one side of the rectangle. Returns a floating point number that is the length of the adjacent side."""
height = 0.0
area = float(raw_input('Enter the area of a rectangle: '))
length = float(raw_input('Enter the length of one side: '))
if length == 0:
return height
else: height = area/length
return height
#Problem 8 -> Correct, but forgot to divide num by 6, 9, 20 so is inefficient.
def f(num):
a = 6
b = 9
c = 20
for x in range(0,num+1):
for y in range(0,num+1):
for z in range(0,num+1):
if a*x + b*y + c*z == num:
return True
return False
No comments. Sign up or log in to comment Quiz ##Name: Marc
##Time: ~30 Minutes
#1.1 False
#1.2 False
#1.3 False
#1.4 False
#1.5 False
#1.6 True
#1.7 True
#2.1 yes
#2.2 No, when you enter a negative number compare one prints the opposite, companre two prints the original
#3.1 6
#3.2 f adds all of the digits of the integer together
#4.
def first_N(n):
count = 0
ans = 1
for i in n:
square = ans * ans
if square % 2 != 0:
print square
count += 1
ans += 1
#5.
Def guess_and_check(criteria):
for a in range(...):
for b in range(...):
for c in range(...):
...
if satisfies_critera(a,b,c,..., criteria):
return a,b,c....
#6.
def findSide():
"""asks the user to enter the area of a rectangle and the length of one side of the rectangle. Returns a float that is the length of the adjacent side."""
area = raw_input('Enter the area of the rectangle')
side = raw_input('Enter the length of one side of the rectangle')
answer = float(area)/float(side)
print 'The length of the base is ', answer
#7. No
def f(L):
result = []
for e in L: result.append(l[e])
return result
#8.
def McNuggets(num):
for a in range(num):
for b in range(num):
for c in range(num):
answer = a*6+b*9+C*20
if answer == num
return True
return False
#9. It reverses the digits of the integer given. EX. 21118 = 81112
No comments. Sign up or log in to comment #1.1) - False - recursion can go to infinity?
#1.2) - False - as tangent gets close to zero it is not reliable
#1.3) - False - dictionaries are mutable: dict[key] = somevalue
#1.4) - False - beware of equality comparison of floats
#1.5) - False - for small values of n iteration may be faster?
#1.6) - False - not necessarily for short programs
#1.7) - True
#2.1) Yes
#2.2) ?
#3.1) 6
#3.2) """Recursive function. Input positive interger. Returns sum of int"""
#4)---------
def first_N(n):
answer = []
i = 1
while len(answer) < n:
if i**2 % 2 != 0:
answer.append(i**2)
i += 1
else:
i += 1
return answer
#5)
#def(guess,check):
# for a in range of guess(....):
# if checkfunction(a) == check
# return answer
#6)
def findSide():
side1 = float(raw_input("Enter side 1 length: "))
area = float(raw_input("Enter the area of the rectangle: "))
side2 = area / side1
return side2
#7) Yes. List is not modified
#8)
def nuggets(n):
for a in range(0, n/20 + 1):
for b in range(0, n/9 + 1):
for c in range(0, n/6 + 1):
total = 20*a + 9*b + 6*c
if total == n:
return (a, b, c)
return (None,None,None)
#9) reverses the string
No comments. Sign up or log in to comment 1) Are each of the following True or False:
1.1. Any program that can be written using only function definitions and calls, the basic arithmetic operators, assignment, and conditionals will run in constant time.
False
1.2. Newton’s method will always converge on a correct root of a function.
True
1.3. In Python, dictionaries are immutable.
False
1.4. The value of ‘math.sqrt(2.0)*math.sqrt(2.0) == 2.0’ is True.
False
1.5. One should always avoid iteration when a recursive solution is possible.
False
1.6. Typically, the use of functions in a program reduces the total number of lines of code.
True
1.7. In Python, retrieving the value associated with a dictionary key takes roughly constant time.
True
2) Consider the implementations of compare1 and compare 2, where a and b are floats.
2.1) Do compare1 and compare2 return the same value for all possible inputs? If not, give a pair of inputs for which they return a different value.
Yes
2.2) Do compare1 and compare2 print the same thing for all possible inputs? If not, give a pair of inputs for which they print different things.
No, they will print different results when provided a negative number for either a or b. compare1 modifies the actual parameter used for both comparing and printing the result, whereas compare2 keeps the original value when printing.
compare1(-1, -2)
Results in
1 and 2 have the same absolute value.
compare2(-1, -2)
Results in
-1 and -2 have the same absolute value.
3) Consider the following implementation of a function f, where x is a positive integer:
def f(x):
xs = str(x)
if len(xs) == 1:
return int(xs)
n = int(xs[0]) + int(xs[1])
if len(xs) == 2:
return n
else:
return n + f(xs[2:])
What does f(2112) return?
xs = "2112"
n = 2 + 1
n = 3
xs = "12"
n = 1 + 2
n = 3
n = 6
3.2) Write a specification of f.
Returns the sum of all individual integers
4) Provide a Python implementation of a function first_N that takes a positive integer, n, as its only argument. The function should print the first n perfect squares that are not even numbers. E.g., if n were 2 it should print the perfect squares 1 and 9.
def first_N(n):
currentRoot = 1
while n > 0:
if (currentRoot * currentRoot) % 2 != 0:
print (currentRoot * currentRoot)
n = n - 1
currentRoot = currentRoot + 1
5) Write pseudo code for an exhaustive enumeration variant of guess and check.
function guessandcheck(guess, values)
iterate through all possible combinations
if current value is same as guess, return guess
else, next combo
6) Provide a Python implementation for the function findSide specified below
def findSide():
"""asks the user to enter the area of a rectangle and the length of one side of the rectangle.
Returns a floating point number that is the length of the adjacent side."""
print "Enter area of rectangle"
area = float(raw_input())
print "Enter length of one side"
side = float(raw_input())
return (area / side)
7) Does the following function meet its specification? If not, change the program so that it is consistent with the specification.
def f(L):
"""Returns a copy of the list L without modifying L."""
result = []
for e in L:
result = result + e
return result
Yes
8) At McDonalds one can buy chicken nuggets in packages containing 6, 9 or 20 pieces. Write a Python function that accepts an integer, num, as an argument and decides whether or not it is possible to buy num nuggets at McDonalds.
def can_buy_nuggets_for_size(size):
for a in range(0, (size / 6)):
for b in range(0, (size / 9)):
for c in range(0, (size / 20)):
current_combo = (6 * a) + (9 * b) + (20 * c)
if current_combo == size:
return True
return False
9) Write an appropriate specification for the function below. Assume that n is an integer.
def f(n):
"""
Reverses the characters in n
"""
s = str(n)
if len(s) <= 1: return s
return s[-1] + f(int(s[:-1]))
No comments. Sign up or log in to comment I wanted to get feedback on my answer to question #4, as the way I coded it seems to work but seems much different from the solution provided. def first_N(n):
if n <= 0:
print 'Must enter a positive integer'
else:
for intnum in range(n*2):
intnumsq = intnum * intnum
if intnumsq%2 != 0: # if intnum is odd number
print intnumsq
Comments:Your function for #4 definitely works, and the main difference between it and the solution is when to decide when to stop searching for odd perfect squares. In the solution, they keep a count of odd perfect squares found, and once they reach N, they stop looking. Your solution looks like it uses some cool math either by design or coincidence. You only search over the space (2N)^2, but it appears that it's sufficient to contain exactly N odd perfect squares. I'm not sure if you have a proof for that, but if instead you did range(n*3), you would produce more results than needed. range(n*1.5) would produce fewer results than needed. The choice of (2N)^2 looks like it was a perfect choice, but in general, it's more fool-proof to do it the way that the solution suggests. By counting the number of results and stopping when there are N of them, it can be guaranteed to be correct. Lastly, the solution is a little more clear to an outsider reading the code. It's obvious that it will print N results. With your solution, it's not intuitive how many times it will print intnumsq. The function has to be run to see how many times it will print. No comments. Sign up or log in to comment ~~SELF-ASSESSMENT~~ As I predicted, I got 2.2 wrong. I also don't like my answer to 5 (pseudocode). I didn't udnerstand what they were asking and I still don't really like the question having seen the solution. Overall, I did well. ~~MY ANSWERS~~ 1.1) False 1.2) False 1.3) False 1.4) False 1.5) False 1.6) True 1.7) True 2.1) Same 2.2) Same (I'm probably wrong with at least one if not both of my answers to #2) 3.1) f(2112) = 3 + f(12) = 3 + 3 = 6 3.2) '''f(x) recursively adds the digits in positive integer x, returns the result''' 5) ...I don't really understand what this question is asking. My answer is therefore very generalized. assume answer is integer Input: [function] f(x), [int] solution guess: x = 0. if f(guess) == solution: return guess. else: if guess 0: guess += 1 f(guess) 7) This seems fine. 8) We basically did this for assignment 2, just need to modify the code to return the appropriate boolean if there is a solution for the input guess. Could speed up the code by adding a test to return True if the input guess is greater than 43 (the largest number of mcnuggets that cannot be bought in exact quantity). 9) '''f(n) takes an integer n and returns a string that is the reverse of n's digits.''' # Problem 4
def first_N(n):
'''Prints the first n perfect squares that are not even numbers.'''
i = 1
guess = 0
while i <= n:
guess += 1
sq = guess*guess
if sq%2 == 0:
continue
else:
print sq
i += 1
# Problem 6
def findSide():
"""asks the user to enter the area of a rectangle and the length of one side of the
rectangle. Returns a floating point number that is the length of the adjacent side."""
area = raw_input("Area: ")
side = raw_input("Side: ")
try:
area = float(area)
side = float(side)
except:
print "Input must be a number."
findSide()
length = area/side
print "The length of the other side is %.2f" % length
# Problem 8
## Here is the smallest possible program based on my results
## from assignment 2:
def CanBuyMcNuggets(guess):
possible = [6, 9, 12, 15, 18, 20, 21, 24, 26, 27, 29, 30, 32, 33, 35, 36, 38, 39, 40, 41, 42]
if guess > 43:
return True
elif guess in possible:
return True
else:
return False
No comments. Sign up or log in to comment |
No comments. Sign up or log in to comment