练习2

1. 随机输入一个数字判断是否为素数,参考第三课课后题代码,要求使用dict做缓存。缓存结果,避免重复计算。

2. 给你一首优美的英文诗选段
s = “”“
Have you thought about what you want people to say about you after you’re gone? Can you hear the voice saying, “He was a great man.” Or “She really will be missed.” What else do they say?
One of the strangest phenomena of life is to engage in a work that will last long after death. Isn’t that a lot like investing all your money so that future generations can bare interest on it? Perhaps, yet if you look deep in your own heart, you’ll find something drives you to make this kind of contribution---something drives every human being to find a purpose that lives on after death.
”“”

统计出其中共用到多少个字母,每个字母在字符串中出现的次数是多少,然后按照出现的频率进行排序输出。
1.        区分大小写
2.        不区分大小写

1.

#!/usr/bin/env python

#!coding:utf-8

cache = {}

while True:

num = raw_input(‘please input a num: ‘)

try:

num = float(num)

except ValueError:

print ‘Error Type‘

continue

num = int(num)

rs = cache.get(num)

if rs:

print ‘hit‘

print rs

continue

else:

print ‘miss‘

is_prime = False

for i in range(2,num):

print ‘count‘,i

if num % i == 0:

is_prime = False

break

else:

is_prime = True

msg=""

if is_prime:

msg = ‘%d is prime‘ % num

else:

msg = ‘%d is not prime‘ % num

cache[num] = msg

print msg

2.

#!/usr/bin/env python

#!coding:utf-8

#!author:liang

s = """

Have you thought about what you want people to say about you after you’re gone? Can you hear the voice saying, “He was a great man.” Or “She really will be missed.” What else do they say?

One of the strangest phenomena of life is to engage in a work that will last long after death. Isn’t that a lot like investing all your money so that future generations can bare interest on it? Perhaps, yet if you look deep in your own heart, you’ll find something drives you to make this kind of contribution---something drives every human being to find a purpose that lives on after death.

"""

import re

letters = re.findall(r‘\w‘,s)

print "区分大小写:"

dx_dict = dict([i,0] for i in letters )

for letter in letters:

dx_dict[letter] = dx_dict[letter] + 1

dx_sort = sorted(dx_dict.items(),key = lambda x:x[1],reverse = True)

dx_count = len(dx_dict.keys())

print "优美的英文诗选段共用到【%d】个字母,分别为:" % dx_count

for i in dx_sort:

print "字母【%s】,出现次数为【%d】次 " % (i[0],i[1])

print "============================================================"

print "============================================================"

print "不区分大小写:"

s_lower = s.lower()

letters_lower = re.findall(r‘\w‘,s_lower)

x_dict = dict([i,0] for i in letters_lower )

for letter_s in letters_lower:

x_dict[letter_s] = x_dict[letter_s] + 1

x_sort = sorted(x_dict.items(),key = lambda x:x[1],reverse = True)

x_count = len(x_dict.keys())

print "优美的英文诗选段共用到【%d】个字母,分别为:" % x_count

for j in x_sort:

print "字母【%s】,出现次数为【%d】次 " % (j[0],j[1])

时间: 2024-10-05 05:54:58