0%

第四周-字典练习题

题一:用字典创建一个平台的用户信息(包含用户名和密码)管理系统,新用户可以用与现有系统帐号不冲突的用户名创建帐号,已存在的老用户则可以用用户名和密码登陆重返系统。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
userdict = {'chendong': '1234', 'chenjuan': '5678'}


def newusers():
name = input('enter your name: ')
if name in userdict.keys():
newusers()
else:
psw = input('enter your password: ')
userdict[name] = psw


def oldusers():
uinfo = input('enter your name and password: ')
print(uinfo)
user=uinfo.split(',')
name,password=user
print(name,password)
if password in userdict.values():
print(name, 'welcome back ')
else:
print('login incorrect')


def login():
option = input('enter a option(N or O or E): ')
if option == 'N':
newusers()
if option == 'O':
oldusers()
if option == 'E':
exit()


if __name__ == '__main__':
login()
print(userdict)

题二:统计词频:输入一个长句子,句子只含,|.|?|”|’这几种标点,统计每个单词出现的频率。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import re

with open('sentense.txt', 'r+') as f:
txt = f.read()
txt = txt.lower()
pattern = re.compile("\,|\.|\"|\'|\!")
sentense = re.sub(pattern, ' ', txt)
# print(sentense)
words = sentense.split(' ')
##清洗words,去掉'',
clswords = []
# print(words)
for word in words:
if word == '':
continue
else:
clswords.append(word)
setwords = set(clswords)
listwords = list(setwords)
wordfreq = [0] * len(listwords)
for i in range(len(listwords)):
wordfreq[i] = clswords.count(listwords[i])
worddiction = dict(zip(listwords, wordfreq))
print(worddiction, len(worddiction))
print(sum(worddiction.values()))

sentence.txt:hi,boy. Don’t worry,have good night ! tomorrow must be a sunny day. “emmm….”,sounds like pretty. ok, I will go to bed. “see you tomorrow,have a good night”.a,a,a,a,a,a,a,a,a.

题三:给定一个整数数组 nums 和一个目标值 target,
请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标
若存在,只要返回一组,且其中一个数字尽量小。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
def townum_sum(n,lst):
d={}
for i in range(len(lst)):
d[lst[i]]=i
for i in range(len(lst)):
if n-lst[i] in d.keys():
return i,d[n-lst[i]]
return -1

if __name__== '__main__':
target=int(input('enter a num: '))
nums=[1,4,5,6,7,8,9,10,11,12,13,15,18,19,20,21,29,34,54,65]
result=townum_sum(target,nums)
if result == -1:
print('not find')
else:
print(result)