# lecture 3.2 problem set 3

xiaoxiao2021-02-28  7

"Radioactive decay" is the process by which an unstable atom loses energy and emits ionizing particles - what is commonly refered to as radiation. Exposure to radiation can be dangerous and is very important to measure to ensure that one is not exposed to too terribly much of it.辐射衰变是不稳定原子失去能量并释放电离子的过程-这通常被称为辐射。接触辐射（暴露于辐射）可能是危险的，同时检测并确保人们不暴露于过量辐射（的环境）中变得重要。

The radioactivity of a material decreases over time, as the material decays. A radioactive decay curve describes this decay. The x-axis measures time, and the y-axis measures the amount of activity produced by the radioactive sample. 'Activity' is defined as the rate at which the nuclei within the sample undergo transititions - put simply, this measures how much radiation is emitted at any one point in time. The measurement of activity is called the Becquerel (Bq). Here is a sample radioactive decay curve:物质的辐射活性随着时间的流逝而减少，因为辐射物质在衰减。辐射衰减曲线用于描述这样的衰减过程。x轴表示时间，y轴表示辐射物质样品产生的辐射活性量。辐射的活性量定义为处于物质迁变的核的比率，它给出某一时刻所释放的辐射量。活性的度量称为Bq(理解为度量的单位即量纲)。如下是一个辐射衰减曲线的样例：

(Click on the pictures to view full-sized images)

Now here's the problem we'd like to solve. 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.

Total radiation exposure corresponds to the area between the two green lines at time = 5 and time = 11, and under the blue radioactive decay curve. This should make intuitive sense - if the x axis measures time, and the y axis measures activity, then the area under the curve measures (time * activity) = MBq*years, or, approximately the total number of MBq Sarina was exposed to in her time in the radioactive apartment (technically, this result is the combination of gamma rays and beta particles she was exposed to, but this gets a bit complicated, so we'll ignore it. Sorry, physicists!).

So far, so good. But, how do we calculate this? Unlike a simple shape - say a square, or a circle - we have no easy way to tell what the area under this curve is.

However, we have learned a technique that can help us here - approximation. Let's use an approximation algorithm to estimate the area under this curve! We'll do so by first splitting up the area into equally-sized rectangles (in this case, six of them, one rectangle per year):

Once we've done that, we can figure out the area of each rectangle pretty easily. Recall that the area of a rectangle is found by multiplying the height of the rectangle by its width. The height of this rectangle:

is the value of the curve at 5.0. If the curve is described by a function, f, we can obtain the value of the curve by asking for f(5.0).

f(5.0) = 5.181

The width of the rectangle is 1.0. So the area of this single rectangle is 1.0*5.181 = 5.181. To approximate how much radiation Sarina was exposed to, we next calculate the area of each successive rectangle and then sum up the areas of each rectangle to get the total. When we do this, we find that Sarina was exposed to nearly 23 MBq of radiation (technically, her apartment was bombarded by 23e6 * 3.154e6 = 7.25e13 neutrons, for those interested...).

Whether or not this will kill Sarina depends exactly on the type of radiation she was exposed to (see this link which discusses more about the ways of measuring radiation). Either way, she should probably ask her landlord for a substantial refund.

In this problem, you are asked to find the amount of radiation a person is exposed to during some period of time by completing the following function:

def radiationExposure(start, stop, step): ''' Computes and returns the amount of radiation exposed to between the start and stop times. Calls the function f (defined for you in the grading script) to obtain the value of the function at any point. start: integer, the time at which exposure begins stop: integer, the time at which exposure ends step: float, the width of each rectangle. You can assume that the step size will always partition the space evenly. returns: float, the amount of radiation exposed to between start and stop times. '''

To complete this function you'll need to know what the value of the radioactive decay curve is at various points. There is a function f that will be defined for you that you can call from within your function that describes the radioactive decay curve for the problem.

You should implement this function on your own machine. Open a new Canopy Python file and title it "radiationExposure.py". Complete your work inside this file. Test your code well in Canopy, and when you are convinced it is correct, cut and paste your definition into this tutor window.

def radiationExposure(start, stop, step): s = 0 while(start < stop): s += f(start) * step start += step return s

2

## IS THE WORD GUESSED?

(5/5 分数)

Please read the Hangman Introduction before starting this problem. The helper functions you will be creating in the next three exercises are simply suggestions, but you DO have to implement them if you want to get points for this Hangman Problem Set. If you'd prefer to structure your Hangman program in a different way, feel free to redo this Problem Set in a different way. However, if you're new to programming, or at a loss of how to construct this program, we strongly suggest that you implement the next three helper functions before continuing on to Hangman Part 2.

We'll start by writing 3 simple functions that will help us easily code the Hangman problem. First, implement the function isWordGuessed that takes in two parameters - a string, secretWord, and a list of letters, lettersGuessed. This function returns a boolean - True if secretWord has been guessed (ie, all the letters of secretWord are in lettersGuessed) and False otherwise.

Example Usage:

>>> secretWord = 'apple' >>> lettersGuessed = ['e', 'i', 'k', 'p', 'r', 's'] >>> print isWordGuessed(secretWord, lettersGuessed) False

For this function, you may assume that all the letters in secretWord andlettersGuessed are lowercase.

def isWordGuessed(secretWord, lettersGuessed): flag = 1 for c in secretWord: if c in lettersGuessed: flag = 1 else: flag = 0 break if flag: return True else: return False

3

## PRINTING OUT THE USER'S GUESS

(5/5 分数)

Next, implement the function getGuessedWord that takes in two parameters - a string,secretWord, and a list of letters, lettersGuessed. This function returns a string that is comprised of letters and underscores, based on what letters in lettersGuessed are in secretWord. This shouldn't be too different from isWordGuessed!

Example Usage:

>>> secretWord = 'apple' >>> lettersGuessed = ['e', 'i', 'k', 'p', 'r', 's'] >>> print getGuessedWord(secretWord, lettersGuessed) '_ pp_ e'

When inserting underscores into your string, it's a good idea to add at least a space after each one, so it's clear to the user how many unguessed letters are left in the string (compare the readability of ____ with _ _ _ _ ). This is called usability - it's very important, when programming, to consider the usability of your program. If users find your program difficult to understand or operate, they won't use it!

For this problem, you are free to use spacing in any way you wish - our grader will only check that the letters and underscores are in the proper order; it will not look at spacing. We do encourage you to think about usability when designing.

For this function, you may assume that all the letters in secretWord andlettersGuessed are lowercase.

def getGuessedWord(secretWord, lettersGuessed): s = '' for c in secretWord: if c in lettersGuessed: s += c else: s += '_' return s

4

## PRINTING OUT ALL AVAILABLE LETTERS

(5/5 分数)

Next, implement the function getAvailableLetters that takes in one parameter - a list of letters, lettersGuessed. This function returns a string that is comprised of lowercase English letters - all lowercase English letters that are not in lettersGuessed.

Example Usage:

>>> lettersGuessed = ['e', 'i', 'k', 'p', 'r', 's'] >>> print getAvailableLetters(lettersGuessed) abcdfghjlmnoqtuvwxyz

Note that this function should return the letters in alphabetical order, as in the example above.注意返回的字符串要按字母顺序，如上所示。

For this function, you may assume that all the letters in lettersGuessed are lowercase.这里你可以假设lettersGuessed中的字母都是小写的。

Hint: You might consider using string.ascii_lowercase, which is a string comprised of all lowercase letters:提示: 你可以考虑使用 string.ascii_lowercase,来获得所有小写字母:

>>> import string >>> print string.ascii_lowercase abcdefghijklmnopqrstuvwxyz

def getAvailableLetters(lettersGuessed): import string s = string.ascii_lowercase for e in lettersGuessed: if e in s: s = s.replace(e, '') return s

5

## THE GAME

(15/15 分数)

Now you will implement the function hangman, which takes one parameter - the secretWord the user is to guess. This starts up an interactive game of Hangman between the user and the computer. Be sure you take advantage of the three helper functions, isWordGuessed, getGuessedWord, and getAvailableLetters, that you've defined in the previous part.

#### Hints 提示:

You should start by noticing where we're using the provided functions (at the top of ps3_hangman.py) to load the words and pick a random one. Note that the functions loadWords and chooseWord should only be used on your local machine, not in the tutor. When you enter in your solution in the tutor, you only need to give your hangman function.

Consider using lower() to convert user input to lower case. For example:考虑用函数 lower() 来将用户的输入转换为小写。

guess = 'A' guessInLowerCase = guess.lower()

Consider writing additional helper functions if you need them!如果你需要，你可以考虑编写额外的辅助函数

There are four important pieces of information you may wish to store:4个重要的信息你可能需要考虑保存

secretWord: The word to guess.猜测的目标单词.lettersGuessed: The letters that have been guessed so far.追踪用户猜测过的字母mistakesMade: The number of incorrect guesses made so far.记录用户猜测错误的次数availableLetters: The letters that may still be guessed. Every time a player guesses a letter, the guessed letter must be removed from availableLetters (and if they guess a letter that is not in availableLetters, you should print a message telling them they've already guessed that - so try again!).还可以用来被猜测的字母，用户猜测过的字母需要从availableLetters移除，用户重复猜了的字母，你需要告知用户你已经猜过这个字母。

### Sample Output 输出样例

The output of a winning game should look like this... And the output of a losing game should look like this...

Note that if you choose to use the helper functions isWordGuessed, getGuessedWord, or getAvailableLetters, you do not need to paste your definitions in the box. We have supplied our implementations of these functions for your use in this part of the problem. If you use additional helper functions, you will need to paste those definitions here.

Your function should include calls to raw_input to get the user's guess.你的函数需要用 raw_input 来获得用户的每次猜测.

def hangman(secretWord): print 'Welcome to the game, Hangman!' print 'I am thinking of a word that is %s letters long ' % len(secretWord) num = 8 l=[] while num > 0: print '------------' print 'You have %s guesses left ' % num print 'Available letters:', getAvailableLetters(l) guesse = raw_input('Please guess a letter: ').lower() if guesse not in l: l.append(guesse) if guesse in secretWord: print 'Good guess: ', getGuessedWord(secretWord, l) else: num -= 1 print 'Oops! That letter is not in my word: ', getGuessedWord(secretWord, l) else: print 'Oops! You\'ve already guessed that letter: ', getGuessedWord(secretWord, l) if isWordGuessed(secretWord, l): break print '------------' if isWordGuessed(secretWord, l): print 'Congratulations, you won!' else: print 'Sorry, you ran out of guesses. The word was ', secretWord