6-1 计算阶乘
本题要求定义一个递归函数,计算阶乘 :n! = n(n-1)!,其中,0!= 1。
函数接口定义:
fact(n)
其中 n 是用户传入的参数。 n 的值为整数,不超过int的范围。
裁判测试程序样例:
num = eval(input())
print(fact(num))
输入样例:
0
输出样例:
1
输入样例:
1
输出样例:
1
输入样例:
5
输出样例:
120
Python题解:
def fact(n):
if(n==0 or n==1):return 1
return n*fact(n-1)
7-1 统计文本中各类字符的个数
本题目要求从键盘读入一段文本,编写程序,统计并输出其中大写字母、小写字母、数字、空格和其他字符的个数。
输入格式:
键盘输入文本信息。
输出格式:
分行输出大写字母upper_num、 小写字母lower_num、数字字符numeric_num、空格字符space_num以及其他字符orthers_num的统计值。
输入样例:
123! Hello World !
输出样例:
upper_num = 2
lower_num = 8
numeric_num = 3
space_num = 3
others_num = 2
输入样例:
ABC 12三。。。def
输出样例:
upper_num = 3
lower_num = 3
numeric_num = 3
space_num = 1
others_num = 3
Python题解:
str=input()
up=0
lo=0
nu=0
sp=0
ot=0
for i in range(0,len(str)):
if(str[i]>='a' and str[i]<='z'):lo+=1
elif (str[i]>='A' and str[i]<='Z'):up+=1
elif((str[i]>='1' and str[i]<='9') or (str[i]=='一' or str[i]=='二' or str[i]=='三' or str[i]=='四' or str[i]=='五' or str[i]=='六' or str[i]=='七' or str[i]=='八' or str[i]=='九' or str[i]=='十' )):nu+=1
elif(str[i] ==' '):sp+=1
else:ot+=1
print("upper_num =",up)
print("lower_num =",lo)
print("numeric_num =",nu)
print("space_num =",sp)
print("others_num =",ot)
7-2 计算中位数
本题目计算一组输入数据的中位数。输入数据为整数。
输入格式:
键盘输入数据,回车。
输出格式:
输出计算所得这组数据的中位数。
输入样例:
4
3
5
9
8
注释:第1个整数4表示,对由4个整数组成的列表,统计其中位数。如,上述输入表示,统计中位数的列表长度为4,列表中的数据元素为3、5、9、8。
输出样例:
6.5
输入样例:
5
9
7
6
8
2
注释:第1个整数5表示,对由5个整数组成的列表,统计其中位数。如,上述输入表示,统计中位数的列表长度为5,列表中的数据元素为9、7、6、8、2。
输出样例:
7
输入样例:
1
9
注释:第1个整数1表示,对由1个整数组成的列表,统计其中位数。如,上述输入表示,统计中位数的列表长度为1,列表中的数据元素为9。
输出样例:
9
Python题解:
n=int(input())
list=[]
ans=0.0
for i in range(0,n):
t=int(input())
list.append(t)
list.sort()
if(len(list)%2==0):
ans=(list[len(list)//2]+list[len(list)//2 -1 ])/2.0
else :ans = list[len(list)//2]
print(ans)
7-3 统计词频
本题目要求键盘输入一段规范的英文文本,统计其中每个单词出现的频率,输出统计结果。
输入格式:
输入一段英文文本,单词以空格分隔。
输出格式:
以字典方式输出单词出现的频率。
输入样例:
all for one, one for all
输出样例:
{‘all’: 2, ‘for’: 2, ‘one,’: 1, ‘one’: 1}
输入样例:
Other men live to eat, while I eat to live
输出样例:
{‘Other’: 1, ‘men’: 1, ‘live’: 2, ‘to’: 2, ‘eat,’: 1, ‘while’: 1, ‘I’: 1, ‘eat’: 1}
Python题解:
str=input()
# str = str.replace(',' , '')
resoult = {} # 定义一个空字典
list = str.split(' ')
for i in list: # 遍历输入的字符串,以键值对的方式存储在字典中
if(resoult.get(i)==None):resoult[i]=0
resoult[i]+=1
print(resoult)