0%

第三周-数据表示与获取基础编程作业

MOOC链接 用python玩转数据

题一:从键盘输入整数n(1-9之间),对于1-100之间的整数删除包含n并且能被n整除的数,
例如如果n为6,则要删掉包含6的如6,16这样的数及是6的倍数的如12和18这样的数,
输出所有满足条件的数,要求每满10个数换行。

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
38
39
40
41
def Me():
num=int(input('enter a num (1-100):'))
strnum=str(num)
j=1
for i in range(1,101):
if strnum in str(i):
continue
if i%num == 0:
continue
else:
if j%10==0:
print(i)
j=1
else:
print(i,end=',')
j+=1

# if j<10:
# print(i,end=',')
# j+=1
# else:
# print(i)
# j=1

#比Teach()多一个字符

def Teach():
n = int(input("Enter the number: "))
count = 0
new_str = ''
print("The result string: ")
for i in range(101):
s = str(i)
if i % n != 0 and s.find(str(n)) == -1:
new_str = new_str + s + ','
count += 1
if count % 10 == 0:
print(new_str[:-1])
new_str = ''
if len(new_str) > 0:
print(new_str[:-1])

题二:请用随机函数产生500行1-100之间的随机整数存入文件random.txt中,
编程寻找这些整数的众数并输出,众数即为一组数中出现最多的数。

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
import random,time
def modeNum():
with open('random.txt','w+',encoding='utf-8') as f:
# num = []
for i in range(500):
num=random.randint(1,100)
f.write(str(num)+'\n')
# f.seek(0)
# text=f.read()
# lists=text.split('\n')
# print(lists[:-1]) ##变成列表
f.seek(0)
nums=f.readlines()
nums=[int(num.strip()) for num in nums]
setNums=set(nums)
lst = [0] * 101
for num in setNums:
c = nums.count(num)
lst[int(num)] = c

# 法一找众数和出现次数
index = lst.index(max(lst))
print(index, max(lst))

#法二找众数和出现次数
# for i in range(len(lst)):
# if lst[i] == max(lst):
# print(i,max(lst))

# 法三找众数和出现次数
# lst1=[0]*101
# for i in nums:
# lst1[int(i)]+=1
# index=lst1.index(max(lst1))
# print(index,max(lst1))

# modeNum()

题三:文件article.txt中存放了一篇英文文章(请自行创建并添加测试文本),
假设文章中的标点符号仅包括“,”、“.”、“!”、“?”和“…”,
编程找出其中最长的单词并输出

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import re
with open('article.txt','r+') as fp:
text=fp.readlines()
text=[str.strip() for str in text]
print(text)
list=' '.join(text)
print(list)
pattern=re.compile('\,|\.|\?|\!')
lists=re.sub(pattern,' ',list)
print(lists,type(lists))
words=lists.split(' ')
print(words)
maxlen=len(words[0])
for i,w in enumerate(words):
if len(w)>maxlen:
maxlen=len(w)
index=i
print(index,words[index],maxlen)