15-112: Introduction to Programming and Computer Science, Fall 2013

advertisement
15-112 Homework 2
Page 1 of 6
15-112: Introduction to Programming and Computer Science, Fall
2013
Homework 2 Programming: Functions, Conditionals, and Loops
Due: Tuesday, September 10, 2013 by 23:59
This programming homework is designed to get you more practise with functions, conditionals, and loops.
Your submission will be made through the web interface of Autolab. In this homework,
you will be writing six functions. Write all functions in the same file and call that file
YourAndrewIDhw2.py. You should not have any test code in this file besides the six function
definition plus any other helper functions you want to write. You should not have any main
code that is executed. Your functions should be named according to the specifications given
in the questions below. Again, if you want to write helper functions within the same file to
help you organize your code, you are more than welcome to do so and you can name them
whatever you want. You should submit this python file under lab2 option at:
https://autolab.cs.cmu.edu/15112q-f13
1
Error Checking
We have seen in some lecture notes that if we want to read a float from the user, we use
the function raw_input() to read a string from the user and then use the function float()
to convert that string to a float number. We also learned that if the user enters an invalid
number, our program will crash. Now we don’t like programs that crash. So, we would like
to check if a string can be a float before we attempt to convert it to a float. This way, if the
string is not float, we can print an error message and exit gracefully instead of crashing the
program. If would be nice to have a function called isFloat that takes an input of string and
returns back True if the input is a valid float and False if it is not. We can use this function
in our programs as given below:
inp = raw_input("Enter your QPA: ")
if( not isFloat(inp)):
print "You entered a value that is not a valid QPA. Exiting gracefully :)"
exit()
else:
# we can safely decode the float now
qpa = float(inp)
Task 1 (5 pts) Your task is to write the isFloat function that checks the string passed to it
for validity of being a float number. If the input is a valid float number, it should return True,
15-112 Homework 2
Page 2 of 6
otherwise, it should return False. I will be calling the function as shown in the above example,
so make sure the return values, function name, and input parameters are appropriate.
2
Monte Carlo Simulation
“Any method which solves a problem by generating suitable random numbers and observing
that fraction of the numbers obeying some property or properties. The method is useful for
obtaining numerical solutions to problems which are too complicated to solve analytically”
(source - Wolfram mathworld).
Let’s take a simple example. If I flip a coin, what are the chances that I will get heads
or tails. We know from simple probability that the chances of each side is exactly 0.5. We
can prove this experimentally by flipping a coin 1,000,000 times and dividing the number
of times I get a head by 1,000,000. We can simulate that using python code by choosing a
random number a million times. If the number is 1 we assume it means heads and if it is
2 we assume that means tails. We count the number of 1s we get out of a million tries and
the ratio should be around 0.5.
In order to do this, we should be able to generate random numbers. There is a library
in python that allows you to do that. The library is called “random” and the function that
generates random number is called randint. randint takes two values as input (lets call them
a and b) and returns a random number (lets call the return value n) such that a <= n <=
b. Based on that, the following code will generate a random number between 1 and 2.
import random
randomvalue = random.randint(1, 2)
We can write out simulation for flipping of a coin as:
import random
#initialize number of times we got a head to 0
countheads = 0
#generate a million random numbers between 1 and 2
for i in range(0,1000000):
r = random.randint(1,2)
# if this coin flip result in 1 then count it
if r == 1:
countheads = countheads + 1
# now count how many times we got head
print countheads/1000000.0
If you run the above code several times, each time you will get a value that is close to
0.5. I ran the above code 10 times and got the following values:
15-112 Homework 2
Page 3 of 6
0.499828
0.499661
0.499429
0.499762
0.50036
0.499664
0.499573
0.499489
0.500282
0.499692
We can use the same technique to estimate the value of PI. We can estimate the value of
PI using Monte Carlo Simulation. Imagine you have a square that is 100 meters wide and
you place a circle of radius 50 inside this square centered at the center of the square. The
following figure shows this picture.
50 meters
1
0
0
1
100 meters
If you pick a random point inside the square, the probability that this point is inside the
square is of course 1 but the probability that this point is inside the circle depends on the
area of the circle as compared to the area of the square. So we can say that probability of
the point being inside the circle is given by:
P =
πr2
10000
Where P is the probability that the point is inside the circle and r is the radius of the
circle which is equal to 50 and square of that is equal to 2500. Hence the equation becomes:
P =
π∗2500
10000
=
pi
4
Now our goal is to find the value of π and there are two unknowns in the above equation,
P and π. We can estimate P using montecarlo simulation. If we pick a random point inside
15-112 Homework 2
Page 4 of 6
the square and check if the point is also inside the circle. We repeat this process a large
number (Lets call this number n) of times and count how many times the point falls inside
the circle (Let’s call this number c). We can find the experimental value of P by using the
equation:
P = c/n
Task 2 (6 pts) Your task is to write a function called estimatePI that will use the above
technique to estimate the value of π. Your function should take as input an integer n that
determines how many times you will run the simulation. The function should return the
estimated value of PI.
3
Narcissistic Numbers
Narcissistic numbers are the numbers such that if you find the sum of its digits, each raised
to the power of its number of digits, you get the same number back. For example:
370 = 33 + 73 + 03 – (From Wikipedia)
In the above example, 370 has 3 digits, so we take each digit and raise it to the power of
3 and find the sum. The result is 370 which is the same number we started with (Try this
out using the above example). Similarly, 1634 and 54748 are also narcissistic numbers.
Task 3 (6 pts) Write a function called isNarcissistic that takes any integer, and returns
True if the number passed in is narcissistic, otherwise the function should return False.
4
Factorial
I suppose we all know what a factorial number is, a non-negative number that is a product
of all positive integers less than or equal to its value.
Task 4 (6 pts) Create a function called deFactorial that takes an integer x as input parameter, and returns the position of this number in factorial sequence if it is a factorial number.
If the number is not a factorial, return the position of the largest factorial that is less than
x. For example: If the value of x is 120, your function should return 5 since factorial of 5 is
120. If the value of x is 130, your functions should return 5 since 120 is the largest factorial
less than 130.
5
Collatz Conjecture
Collatz Conjecture is a conjecture in mathematics named after Lothar Collatz, it is also
known as the 3n + 1 conjecture. The conjecture uses a function f(n) defined as:
f (n) =
n/2
3n + 1
if n is even
if n is odd
15-112 Homework 2
Page 5 of 6
The conjecture suggests that if you take any positive integer n, and repeatedly apply f(n)
to it, the result will eventually become 1. Collatz Conjecture is still unproven but no one is
able to come up with a number that counters the argument (that is, a number that will not
reduce to 1).
Task 5 (6 pts) Write a function collatz that takes a positive integer as an argument and
returns the number of times f(n) needs to be applied on it to reach 1. If the argument passed
in is negative or zero, return -1.
6
Squareception
For the next task of the homework we will refer to an "operation" as using 4 points (representing the given square) to get coordinates for a new square whose corners are exactly
at the center of each edge in the given square. With that being said, the coordinates for
the resulting square are acquired by getting the midpoint between each 2 consecutive points
from the given square. Notice that your algorithm should work for every quad and not only
for squares. The following figure shows starting this operation with a square represented by
four points - (0,0), (5,0), (5,5), (0,5). We apply the operation N = 2 times and we get two
more squares with the last square at points - (3.75,1.25), (3.75,3.75), (1.25, 3.75), (1.25,1.25).
Task 6 (6 pts) Write a function called squareception that takes 8 input arguments to represent x and y coordinates of four points and a 9th argument that represents the number of
times your function should apply the operation explained above. Your function should apply
the operation described above n times on the given points. Each time a new operation is
applied, it should use the new coordinates (results of the previous operation). The function
15-112 Homework 2
Page 6 of 6
should then print the coordinates of the final square. For example, the output for the above
square with n = 2 should be:
Square at n = 2 is : (3.75,1.25), (3.75,3.75), (1.25, 3.75), (1.25,1.25)
Download