CS入门学习笔记7-作业题-MIT 6.00.1x

第三周 problem set 3

Radiation Exposure
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:
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.

def f(x):
    import math
    return 10*math.e**(math.log(0.5)/5.27 * x)
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.
    '''
    area = 0.0
    for i in range(int((stop - start)/step )):
        area += step * f(start + i*step)
    return area

A Wordgame: Hangman

  1. isWordGuessed

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 and lettersGuessed are lowercase.

def isWordGuessed(secretWord, lettersGuessed):
    '''
    secretWord: string, the word the user is guessing
    lettersGuessed: list, what letters have been guessed so far
    returns: boolean, True if all the letters of secretWord are in lettersGuessed;
      False otherwise
    '''
    count = 0
    for i in secretWord:
        if i in lettersGuessed:
            count += 1
        else:
            return False
    if count == len(secretWord):
        return True
  1. getGuessedWord

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!

def getGuessedWord(secretWord, lettersGuessed):
    '''
    secretWord: string, the word the user is guessing
    lettersGuessed: list, what letters have been guessed so far
    returns: string, comprised of letters and underscores that represents
      what letters in secretWord have been guessed so far.
    '''
    ans = ''
    for i in secretWord:
         if i in lettersGuessed:
             ans = ans + i + ' '
         else:
             ans += '_ '
    return ans
  1. getAvailableLetters

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.

def getAvailableLetters(lettersGuessed):
    '''
    lettersGuessed: list, what letters have been guessed so far
    returns: string, comprised of letters that represents what letters have not
      yet been guessed.
    '''
    import string
    alphaStr = string.ascii_lowercase
    leftletters = ''
    for i in alphaStr:
         if i not in lettersGuessed:
             leftletters += i
    return leftletters
  1. hangman程序全文:
# -*- coding: utf-8 -*-
# 6.00 Problem Set 3
# 
# Hangman game
# -----------------------------------
# Helper code
# You don't need to understand this helper code,
# but you will have to know how to use the functions
# (so be sure to read the docstrings!)

import random
import string
import sys

WORDLIST_FILENAME = "C:/Users/Zoe Ding/Canopy/scripts/hangman/words.txt"

def loadWords():
    """
    Returns a list of valid words. Words are strings of lowercase letters.
    
    Depending on the size of the word list, this function may
    take a while to finish.
    """
    print "Loading word list from file..."
    # inFile: file
    inFile = open(WORDLIST_FILENAME, 'r', 0)
    # line: string
    line = inFile.readline()
    # wordlist: list of strings
    wordlist = string.split(line)
    print "  ", len(wordlist), "words loaded."
    return wordlist

def chooseWord(wordlist):
    """
    wordlist (list): list of words (strings)

    Returns a word from wordlist at random
    """
    return random.choice(wordlist)

# end of helper code
# -----------------------------------

# Load the list of words into the variable wordlist
# so that it can be accessed from anywhere in the program
wordlist = loadWords()

def isWordGuessed(secretWord, lettersGuessed):
    '''
    secretWord: string, the word the user is guessing
    lettersGuessed: list, what letters have been guessed so far
    returns: boolean, True if all the letters of secretWord are in lettersGuessed;
      False otherwise
    '''
    count = 0
    for i in secretWord:
        if i in lettersGuessed:
            count += 1
        else:
            return False
    if count == len(secretWord):
        return True

def getGuessedWord(secretWord, lettersGuessed):
    '''
    secretWord: string, the word the user is guessing
    lettersGuessed: list, what letters have been guessed so far
    returns: string, comprised of letters and underscores that represents
      what letters in secretWord have been guessed so far.
    '''
    ans = ''
    for i in secretWord:
         if i in lettersGuessed:
             ans = ans + i + ' '
         else:
             ans += '_ '
    return ans

def getAvailableLetters(lettersGuessed):
    '''
    lettersGuessed: list, what letters have been guessed so far
    returns: string, comprised of letters that represents what letters have not
      yet been guessed.
    '''
    import string
    alphaStr = string.ascii_lowercase
    leftletters = ''
    for i in alphaStr:
         if i not in lettersGuessed:
             leftletters += i
    return leftletters    

def hangman(secretWord):
    '''
    secretWord: string, the secret word to guess.

    Starts up an interactive game of Hangman.

    * At the start of the game, let the user know how many 
      letters the secretWord 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 computers 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.

    Follows the other limitations detailed in the problem write-up.
    '''
    # guess 为剩余的猜测次数,lettersGuessed为本次猜测的字母
    guess = 8
    lettersGuessed = ''
    
    print ('Welcome to the game, Hangman!')
    print ('I am thinking of a word that is ' + str(len(secretWord)) + ' letters long.') 
    while guess >= 0:
        # 此处的availableLetters 我本来是在while外定义的,但发现其值不会随着循环进行
        # 而修改,所以挪至了此处才正常。
        availableLetters = getAvailableLetters(lettersGuessed)
        print('You have ' + str(guess) + ' guesses left.')
        print('Available letters: ' + str(availableLetters))
        # 切记:总是应该考虑大小写的不同!
        guessletter = raw_input("Please guess a letter: ").lower()
        # 自己额外增加了一个退出程序的命令,前面需import sys
        if guessletter == 'exit':
            sys.exit()
        elif guessletter in lettersGuessed:
            print("Oops! You' ve already guessed that letter: " + getGuessedWord(secretWord, lettersGuessed))
        elif guessletter in secretWord: 
            lettersGuessed += guessletter
            print ('Good guess: ' + getGuessedWord(secretWord, lettersGuessed))
            # 判断游戏是否已经结束(成功)
            if isWordGuessed(secretWord, lettersGuessed) == True:
                print('Congratulations, you won!')
                break
        else:
            lettersGuessed += guessletter
            print('Oops! That letter is not in my word: ' + getGuessedWord(secretWord, lettersGuessed))
            guess -= 1
            # 判断游戏是否已经结束(失败)
            if guess == 0 and isWordGuessed(secretWord, lettersGuessed) == False:
                print('Sorry, you ran out of guesses. The word was ' + str(secretWord))
                break
    


# When you've completed your hangman function, uncomment these two lines
# and run this file to test! (hint: you might want to pick your own
# secretWord while you're testing)

secretWord = chooseWord(wordlist).lower()
hangman(secretWord)
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值