计算水仙花数——while循环
题目
通过while循环计算水仙花数
题目分析:
水仙花数是一个三位数,三位数各位的立方之和等于三位数本身。
源代码
i = 100;
r = 0 ;
s = 0 ;
t = 0 ;
while i < 1000 :
r = i//100
s = (i - r * 100) // 10
t = i - r * 100 - s * 10
if i == (r**3 + s**3 + t**3):
print("i = " + str(i))
i += 1
输出
i = 153
i = 370
i = 371
i = 407
分析
( i 取值范围 0 ~ 999)
- i//100 返回 0~9 的整数值。( 0 ~ 99 ) 返回 0 ,( 100 ~ 199 ) 返回 1,……)
- ( i - r*100 ) // 10 返回 0 ~ 9 的整数值。 ( ( i - r * 100 ) 返回 0 ~ 99 ,0 ~ 99,……)
计算遍历字典——dict函数
题目
对不同视图进行for循环遍历
源代码
s_dict = {101:'name1', 102:'name2', 103:'name3'}
for s_id in s_dict.keys():
print('学号: ' + str(s_id))
for s_name in s_dict.values():
print('学生: ' + str(s_name))
for s_id, s_name in s_dict.items():
print('学号:{0} - 学生:{1} '.format(s_id, s_name) )
输出
学号: 101
学号: 102
学号: 103
学生: name1
学生: name2
学生: name3
学号:101 - 学生:name1
学号:102 - 学生:name2
学号:103 - 学生:name3
分析
统计英文文章单词出现频率——字符串编辑、列表、字典、zip函数
题目
统计英文文章单词出现频率。
题目分析:
英文文章中的单词是通过空格分割的,当然有的单词后面还有标点符号。
源代码
# 一篇文章文本
wordstring = """
it was the best of times it was the worst of times.
it was the age of wisdom it was the age of foolishness.
"""
wordstring = wordstring.replace('.', '') # 将标点符号替换,返回新的字符串
wordlist = wordstring.split() # 分割单词,返回列表对象
wordfreq = []
for w in wordlist:
wordfreq.append(wordlist.count(w)) # wordlist.count(w)返回列表wordlist中w元素个数
d = dict(zip(wordlist, wordfreq)) # zip()将两个可迭代对象打包成元组,它们包含的元素个数相同,并且一一对应。dict()创建字典。
print(d)
输出
{'it': 4, 'was': 4, 'the': 4, 'best': 1, 'of': 4, 'times': 2, 'worst': 1, 'age': 2, 'wisdom': 1, 'foolishness': 1}
分析