How to think like a Computer Scientist: 课后习题第十九、二十章

本文介绍了如何解答《如何像计算机科学家一样思考》一书的第十九章和第二十章的课后习题,重点涉及使用Python语言和字典数据结构。通过分析alice_words.txt文件,探讨了在Alice in Wonderland文本中处理和分析数据的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#-------------------------------------------------------------------------------
# Name:        module1
# Purpose:
#
# Author:      penglaixy
#
# Created:     19/09/2013
# Copyright:   (c) penglaixy 2013
# Licence:     <your licence>
#-------------------------------------------------------------------------------
import string
import sys

def test(did_pass):
    '''print the result of a test '''
    linenum=sys._getframe(1).f_lineno
    if did_pass:
        msg = "Test at line{0} ok".format(linenum)
    else:
        msg = "Test at line{0} failed".format(linenum)
    print msg

def readposint():
    '''
    prompt the user for a positive integer
    '''
    try:
        value_get = int(raw_input("Enter a  postive value:"))
        if value_get < 0:
            raise ValueError("{0} is not a valid value.".format(value_get))
    except:
        print "I am not going to crash, value is invalid"

def letter_counts():
    letter_tab = {}
    str = raw_input("Please input a string with letters: a-zA-Z:")

    for al in str:
        if al not in string.letters:
            continue

        al = string.lower(al)

        letter_tab[al] = letter_tab.get(al, 0) + 1

    al_keys = list(letter_tab.keys())
    al_keys.sort()

    for al in al_keys:
        print al, "  ", letter_tab[al]

    return

def add_fruit(inventory, fruit, quantity = 0):
    inventory[fruit] = inventory.get(fruit, 0) + quantity
    return

def text_to_words(the_text):
    '''
    return a list of words with all punctuation removed,
    and all in lowercase.
    '''
    my_substitutions = string.maketrans(
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!\"#$%&()*+,-./:;<=>?@[]^_'{|}~'",
    "abcdefghijklmnopqrstuvwxyz                                         ")

    cleaned_text = the_text.translate(my_substitutions)
    wds = cleaned_text.split()
    return wds

def get_words_in_book(filename):
    '''
    Read a book from filename, and return a list of its words.
    '''
    f = open(filename,'r')
    content = f.read()
    f.close()

    wds = text_to_words(content)
    wds.sort()
    return wds

def alice_words():
    wds_table = {}
    idx = None
    wds_list = get_words_in_book("alice_in_wonderland.txt")
    for wds in wds_list:
        wds_table[wds] = wds_table.get(wds, 0) + 1

    al_list = list(wds_table.keys())
    al_list.sort()

    f = open("alice_words.txt","w")
    f.write("Word              Count\n")
    f.write("=======================\n")
    for al in al_list:
        str_get = "{0:<18}{1:<5}\n".format(al, wds_table[al])
        f.write(str_get)
    f.close()

    for (ix,al) in enumerate(al_list):
        if idx == None:
            idx = ix
        else:
            if len(al_list[ix]) > len(al_list[idx]):
                idx = ix
    print "The longest word in Alice in Wonderland is {0}, and it has {1} charactors".\
format(al_list[idx], len(al_list[idx]))

    return


def main():
    readposint()
    letter_counts()
    new_inventory = {}
    add_fruit(new_inventory, "strawberries", 10)
    test("strawberries" in new_inventory)
    test(new_inventory["strawberries"] == 10)
    add_fruit(new_inventory, "strawberries", 25)
    test(new_inventory["strawberries"] == 35)
    alice_words()

if __name__ == '__main__':
    main()


输出结果 alice_words.txt的下载地址 :http://download.youkuaiyun.com/detail/penglaixy/6290293

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值