随机密码生成
随机密码生成。编写程序,在 26 个字母大小写和 9 个数字组成的列表中随机生成 10 个 8 位密码。
参考代码
import random
if __name__ == '__main__':
str_list = [chr(i) for i in range(ord("a"), ord("z") + 1)] + [chr(i) for i in range(ord("A"), ord("Z") + 1)] + [chr(i) for i in range(ord("1"), ord("9") + 1)]
for i in range(10):
print(''.join(random.sample(str_list, 8)))
运行结果
NA1PYjoD
9LJAhf2g
M35VSEA9
Cd6DkbfJ
nDum2ea6
6Urw2s9H
boSYWNjw
6YcmSBkq
sPpjdEHD
bUl8FpE9
重复元素判定
重复元素判定。编写一个函数,接受列表作为参数,如果一个元素在列表中出现了不止一次,则返回 True,但不要改变原来列表的值。同时编写调用这个函数和测试结果的程序。
参考代码
def repeat_check(t_list):
return len(t_list) != len(set(t_list))
if __name__ == '__main__':
list1 = [1, 2, 3, 4]
list2 = [1, 2, 3, 4, 4]
print(repeat_check(list1))
print(repeat_check(list2))
运行结果
False
True
统计英文词频并生成词云
参考代码
from wordcloud import WordCloud
def getText():
txt = open("hamlet.txt", "r").read()
txt = txt.lower()
for ch in '!"#$%&()*+,-./:;<=>?@[\\]^_‘{|}~':
txt = txt.replace(ch, " ")
return txt
def get_word_cloud(frequencies):
wc = WordCloud(
background_color='white',
width=500,
height=350,
max_font_size=80,
min_font_size=10,
mode='RGBA'
)
wc.generate_from_frequencies(frequencies)
wc.to_file(r"hamlet.png")
if __name__ == '__main__':
hamletTxt = getText()
words = hamletTxt.split()
counts = {}
for word in words:
counts[word] = counts.get(word, 0) + 1
items = list(counts.items())
items.sort(key=lambda x: x[1], reverse=True)
for i in range(20):
word, count = items[i]
print("{0:<10}{1:>5}".format(word, count))
get_word_cloud(counts)
运行结果
the 1138
and 965
to 754
of 669
you 550
i 542
a 542
my 514
hamlet 462
in 436
it 416
that 391
is 340
not 314
lord 309
his 296
this 295
but 269
with 268
for 247
词云
字典相关
下面是正确的字典创建方式的是(A C D E)。
A. d={1:[1,2],3:[3,4]}
B. d={[1,2]:1,[3,4]:3}
C. d={(1,2):1,(3,4):3}
D. d={1:"张三", 3:"李四"}
E. d={"张三":1,"李四":3}
参考解答
A C D E是可以正确创建字典的,B报类型错误(TypeError: unhashable type: 'list')。
原因:Python中dict类型的key必须是不可变对象(对象内部有__hash__方法),如数字、tuple、字符串等;而list是可变序列,无法作为dict的key。除了list,还有set、dict,以及内部包含这三种类型的tuple,也不能作为字典的key。
参考了这篇博客 Python中字典的key都可以是什么?