Loading [MathJax]/extensions/tex2jax.js
显示标签为“Python”的博文。显示所有博文
显示标签为“Python”的博文。显示所有博文

MITx 6.00.1x Python Notes: Caesar Cipher

Problem

The basic idea of the Caesar cipher is that you pick an integer for a key, and shift every letter of your message by the key. For example, if your message was "happy" and your key was 3, "h" becomes "k", "a" becomes "d", and so on, because we are shifting every letter three spots to the right. Here is what the whole alphabet looks like shifted three spots to the right:

Original:  a b c d e f g h i j k l m n o p q r s t u v w x y z
 3-shift:  d e f g h i j k l m n o p q r s t u v w x y z a b c

Using the above key, we can quickly translate the message "happy" to "kdssb" (note how the 3-shifted alphabet wraps around at the end, so x -> a, y -> b, and z -> c).

This project has two phases:
  • Encryption. That is, we will encode a message based on a given key.
  • Decryption. That is, we will decode a text based on random keys and find out the exact answer.
The required p6words.txt and p6story.txt

MITx 6.00.1x Python Notes: Mid-term Quiz

Python Code

def myLog(x, b):
'''
x: a positive integer
b: a positive integer; b >= 2
returns: log_b(x), or, the logarithm of x relative to a base b.
'''
if x < b:
return 0
return myLog(x / b, b) + 1
## test
# myLog(27, 3)
# 3
# myLog(26, 3)
# 2
# myLog(4, 16)
# 0
def laceStrings(s1, s2):
"""
s1 and s2 are strings.
Returns a new str with elements of s1 and s2 interlaced,
beginning with s1. If strings are not of same length,
then the extra elements should appear at the end.
"""
s1 = list(s1)
i = 0
for j in s2:
s1.insert(i + 1, j)
i += 2
result = ''
for k in s1:
result += k
return result
## test
# laceStrings('aaaaaa', 'zzzzzz')
# 'azazazazazaz'
# laceStrings('', '')
# ''
# laceStrings('af', 'cdizxtau')
# 'acfdizxtau'
# laceStrings('mqjkxtav', 'sk')
# 'msqkjkxtav'
def laceStringsRecur(s1, s2):
"""
s1 and s2 are strings.
Returns a new str with elements of s1 and s2 interlaced,
beginning with s1. If strings are not of same length,
then the extra elements should appear at the end.
"""
def helpLaceStrings(s1, s2, out):
if s1 == '':
return out + s2
if s2 == '':
return out + s1
else:
return helpLaceStrings(s1[1:], s2[1:], out + s1[0] + s2[0])
return helpLaceStrings(s1, s2, '')
def McNuggets(n):
"""
n is an int
Returns True if some integer combination of 6, 9 and 20 equals n
Otherwise returns False.
"""
if n < 0:
return False
elif n == 0:
return True
else:
return any(McNuggets(n - x) for x in [6, 9, 20])
## test
# McNuggets(236)
# True
# McNuggets(146)
# True
# McNuggets(239)
# True
# McNuggets(16)
# False
def fixedPoint(f, epsilon):
"""
f: a function of one argument that returns a float
epsilon: a small float
returns the best guess when that guess is less than epsilon
away from f(guess) or after 100 trials, whichever comes first.
"""
guess = 1.0
for i in range(100):
if abs(f(guess) - guess) < epsilon:
return guess
else:
guess = f(guess)
return guess

MITx 6.00.1x Python Notes: A Word Game

Problem

This game is a lot like Scrabble or Words With Friends. Letters are dealt to players, who then construct one or more words out of their letters. Each valid word receives a score, based on the length of the word and the letters in that word.
The rules of the game are as follows:
Dealing
  • A player is dealt a hand of $n$ letters chosen at random (assume $n=7$ for now).
  • The player arranges the hand into as many words as they want out of the letters, using each letter at most once.
  • Some letters may remain unused (these won't be scored).
Scoring
  • The score for the hand is the sum of the scores for each word formed.
  • The score for a word is the sum of the points for letters in the word, multiplied by the length of the word, plus 50 points if all $n$ letters are used on the first word created.
  • Letters are scored as in Scrabble; A is worth 1, B is worth 3, C is worth 3, D is worth 2, E is worth 1, and so on. We have defined the dictionary SCRABBLE_LETTER_VALUES that maps each lowercase letter to its Scrabble letter value.
  • For example, 'weed' would be worth 32 points ($(4+1+1+2)$ for the four letters, then multiply by len('weed') to get $(4+1+1+2)\times4=32$). Be sure to check that the hand actually has 1 'w', 2 'e's, and 1 'd' before scoring the word!
  • As another example, if $n=7$ and you make the word 'waybill' on the first try, it would be worth 155 points (the base score for 'waybill' is $(4+1+4+3+1+1+1)\times7=105$, plus an additional 50 point bonus for using all $n$ letters).
Here is how the game output will look (human player):

MITx 6.00.1x Python Notes: Hangman Game

Problem:
Hangman is a popular word game. The rules of this problem are:
  1. The computer must select a word at random from the list of available words that was provided in words.txt.
  2. The game must be interactive; the flow of the game should go as follows:
    • At the start of the game, let the user know how many letters the computer's word contains.
    • Ask the user to supply one guess (i.e. letter) per round.
    • The user should receive feedback immediately after each guess about whether their guess appears in the computer's word.
    • After each round, you should also display to the user the partially guessed word so far, as well as letters that the user has not yet guessed.
  3. Some additional rules:
    • A user is allowed 8 guesses. Make sure to remind the user of how many guesses s/he has left after each round. Assume that players will only ever submit one character at a time (A-Z).
    • A user loses a guess only when s/he guesses incorrectly.
    • If the user guesses the same letter twice, do not take away a guess - instead, print a message letting them know they've already guessed that letter and ask them to try again.
    • The game should end when the user constructs the full word or runs out of guesses. If the player runs out of guesses (s/he "loses"), reveal the word to the user when the game ends.

Radiation Exposure (Riemann Integral) in R & Python

Problem:
In this problem, you are asked to find the amount of radiation a person is exposed to during some period of time. For instance, let's say Sarina has moved into a new apartment. Unbeknownst to her, there is a sample of Cobalt-60 inside one of the walls of the apartment. Initially that sample had 10 MBq of activity, but she moves in after the sample has been there for 5 years. She lives in the apartment for 6 years, then leaves. How much radiation was she exposed to?
We can actually figure this out using the radioactive decay curve from above. What we want to know is her total radiation exposure from year 5 to year 11.

MITx 6.00.1x Python Notes: Determining a Character in a String

Problem:
Using the idea of bisection search to determine if a character is in a string, so long as the string is sorted in alphabetical order.

Solution:First, test the middle character of a string against the character we are looking for (the "test character"). If they are the same, we are done - we've found the character we're looking for!
If they're not the same, check if the test character is "smaller" than the middle character. If so, we need only consider the lower half of the string; otherwise, we only consider the upper half of the string.

Euclidean Algorithm in R & Python

Problem:
Euclidean algorithm is a method for computing the greatest common divisor (GCD) of two (usually positive) integers. The GCD of two positive integers is the largest integer that divides both of them without leaving a remainder:

Suppose $a$ is an integer smaller than $b$.1. Then to find the greatest common factor between $a$ and $b$, divide $b$ by $a$. If the remainder is zero, then $b$ is a multiple of $a$ and we are done.
2. If not, divide the divisor $a$ by the remainder.
Continue this process, dividing the last divisor by the last remainder until the last remainder is zero. The last non-zero remainder is then the greatest common factor of the integers $a$ and $b$.

MITx 6.00.1x Python Notes: Paying Debt Off In a Year

Problem 1:
Write a program that calculates the minimum fixed monthly payment needed in order pay off a credit card balance within 12 months. By a fixed monthly payment, we mean a single number which does not change each month, but instead is a constant amount that will be paid each month.
In this problem, we will not be dealing with a minimum monthly payment rate.

The following variables contain values as described below:
balance
the outstanding balance on the credit card;
annual
annual interest rate as a decimal.
Assume that the interest is compounded monthly according to the balance at the end of the month (after the payment for that month is made). The monthly payment must be a multiple of $10 and is the same for all months. Notice that it is possible for the balance to become negative using this payment scheme, which is okay.

MITx 6.00.1x Python Notes: Paying the Minimum

Problem:
Write a program to calculate the credit card balance after one year if a person only pays the minimum monthly payment required by the credit card company each month.

The following variables contain values as described below:
balance
the outstanding balance on the credit card;
annual
annual interest rate as a decimal;
monthly
minimum monthly payment rate as a decimal.
For each month, calculate statements on the monthly payment and remaining balance, and print to screen.
Finally, print out the total amount paid that year and the remaining balance at the end of the year.

MITx 6.00.1x Python Notes: Counting Letters

Problem 1: Counting Vowels
Assume s is a string of lower case characters. Write a program that counts up the number of vowels contained in the string s. Valid vowels are: 'a', 'e', 'i', 'o', and 'u'. For example, if s = 'azcbobobegghakl', the program should print:
Number of vowels: 5
Python code
total = 0
for i in s:
if i in 'aeiou':
total += 1
print 'Number of vowels:', total
## Some results:
# s = 'aiosvumdoaiapkqeefelm'
# Number of vowels: 11
# s = 'yvyelyr'
# Number of vowels: 1
# s = 'iaieesnelhzgeiyynogcrq'
# Number of vowels: 9
view raw countvowels.py hosted with ❤ by GitHub

MITx 6.00.1x Python Notes: Gussing Secret Number

Problem
In this problem, we will create a program that guesses a secret number!
The program works as follows: the user thinks of an integer between 0 (inclusive) and 100 (not inclusive). The computer makes guesses, and you give it input - is its guess too high (input 'h') or too low (input 'l')? Using bisection search, the computer will guess the user's secret number (input 'c')!

Project Euler Problem 3 in R & Python

Project Euler Problem 3:

The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ? 

Solution:The key point is how to verify a number is a prime or not. One probable way is to divide it by every odd number which is less than its square root. For instance: we try to find the largest prime factor of 63:
1st step: divide it by 3, result is 21;
2nd step: divide 21 by 3, result is 7;
3rd step: since 7 is not divisible by 3 so move to the next odd number,
               i.e.$3+2=5$. But 5 is bigger than $\sqrt7$, so the result is 7.
The largest prime factor of 600851475143 is 6857.

Project Euler Problem 2 in R & Python

Project Euler Problem 2:

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

Project Euler Problem 1 in R & Python

Project Euler Problem 1:

If we list all the natural numbers below 10 that are multiples of 3 or 5,we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000.