python题库刷题训练软件_Python基础练习100题 ( 11~ 20)
刷题继续
上一期和大家分享了前10道题,今天继续来刷11~20
Question 11:
Write a program which accepts a sequence of comma separated 4 digit binary numbers as its input and then check whether they are divisible by 5 or not. The numbers that are divisible by 5 are to be printed in a comma separated sequence.
Example:
0100,0011,1010,1001
Then the output should be:
1010
Notes: Assume the data is input by console.
解法一
def check(x): # check function returns true if divisible by 5
return int(x,2)%5 == 0 # int(x,b) takes x as string and b as base from which
# it will be converted to decimal
data = input().split(',')
data = list(filter(check,data)) # in filter(func,object) function, elements are picked from 'data' if found True by 'check' function
print(",".join(data))
解法二
value = []
items=[int(x) for x in input().split(',')]
result = " ".join(str(x) for x in items if x %5==0 )
print(",".join(result))
解法三
data = input().split(',')
data = list(filter(lambda i:int(i,2)%5==0,data))
print(",".join(data))
Question 12:
Write a program, which will find all such numbers between 1000 and 3000 (both included) such that each digit of the number is an even number.The numbers obtained should be printed in a comma-separated sequence on a single line.
解法一
values = []
for i in range(1000, 3001):
s = str(i)
if (int(s[0])%2==0) and (int(s[1])%2==0) and (int(s[2])%2==0) and (int(s[3])%2==0):
values.append(s)
print (",".join(values))
解法二
lst = []
for i in range(1000,3001):
flag = 1
for j in str(i): # every integer number i is converted into string
if ord(j)%2 != 0: # ord returns ASCII value and j is every digit of i
flag = 0 # flag becomes zero if any odd digit found
if flag == 1:
lst.append(str(i)) # i is stored in list as string
print(",".join(lst))
解法三
def check(element):
return all(ord(i)%2 == 0 for i in element) # all returns True if all digits i is even in element
lst = [str(i) for i in range(1000,3001)] # creates list of all given numbers with string data type
lst = list(filter(check,lst)) # filter removes element from list if check condition fails
print(",".join(lst))
解法四
lst = [str(i) for i in range(1000,3001)]
lst = list(filter(lambda i:all(ord(j)%2 == 0 for j in i),lst )) # using lambda to define function inside filter function
print(",".join(lst))
Question 13:
Write a program that accepts a sentence and calculate the number of letters and digits.
Suppose the following input is supplied to the program:
hello world! 123
Then, the output should be:
LETTERS 10
DIGITS 3
解法一
text_input = input()
d={"DIGITS":0, "LETTERS":0,'SPACE':0}
d['DIGITS']= sum(c.isdigit() for c in text_input)
d['LETTERS']= sum(c.isalpha() for c in text_input)
d['SPACE'] = sum(c.isspace() for c in text_input)
for k,v in d.items():
print(k,v)
解法二
word = input()
letter,digit = 0,0
for i in word:
if ('a'<=i and i<='z') or ('A'<=i and i<='Z'):
letter+=1
if '0'<=i and i<='9':
digit+=1
print("LETTERS {0}\nDIGITS {1}".format(letter,digit))
解法三
word = input()
letter,digit = 0,0
for i in word:
letter+=i.isalpha() # returns True if alphabet
digit+=i.isnumeric() # returns True if numeric
print("LETTERS %d\nDIGITS %d"%(letter,digit)) # two different types of formating method is shown in both solution
Question 14:
Write a program that accepts a sentence and calculate the number of upper case letters and lower case letters.
Suppose the following input is supplied to the program:
Hello world!
Then, the output should be:
UPPER CASE 1
LOWER CASE 9
解法一
word = input()
upper,lower = 0,0
for i in word:
if 'a'<=i and i<='z' :
lower+=1
if 'A'<=i and i<='Z':
upper+=1
print("UPPER CASE {0}\nLOWER CASE {1}".format(upper,lower))
解法二
text_input = input()
d={"UPPER CASE":0, "LOWER CASE":0}
for c in text_input:
if c.isupper():
d["UPPER CASE"]+=1
elif c.islower():
d["LOWER CASE"]+=1
else:
pass
print ("UPPER CASE", d["UPPER CASE"])
print ("LOWER CASE", d["LOWER CASE"])
解法三
word = input()
upper = sum(1 for i in word if i.isupper())
lower = sum(1 for i in word if i.islower())
print("UPPER CASE {0}\nLOWER CASE {1}".format(upper,lower))
Question 15:
Write a program that computes the value of a+aa+aaa+aaaa with a given digit as the value of a.
Suppose the following input is supplied to the program:
9
Then, the output should be:
11106
解法一
a = input()
total,tmp = 0,str() # initialing an integer and empty string
for i in range(4):
tmp+=a # concatenating 'a' to 'tmp'
total+=int(tmp) # converting string type to integer type
print(total)
解法二
a = input()
total = int(a) + int(2*a) + int(3*a) + int(4*a) # N*a=Na, for example a="23", 2*a="2323",3*a="232323"
print(total)
Question 16:
Use a list comprehension to square each odd number in a list. The list is input by a sequence of comma-separated numbers.
Suppose the following input is supplied to the program:
1,2,3,4,5,6,7,8,9
Then, the output should be:
1,3,5,7,9
解法一
values = input()
numbers = [x for x in values.split(",") if int(x)%2!=0]
print (",".join(numbers))
Question 17:
Write a program that computes the net amount of a bank account based a transaction log from console input. The transaction log format is shown as following:
D 100
W 200
D means deposit while W means withdrawal.
Suppose the following input is supplied to the program:
D 300
D 300
W 200
D 100
Then, the output should be:
500
解法一
netAmount = 0
while True:
s = input()
if not s:
break
values = s.split(" ")
operation = values[0]
amount = int(values[1])
if operation=="D":
netAmount+=amount
elif operation=="W":
netAmount-=amount
else:
pass
print(netAmount)
解法二
total = 0
while True:
s = input().split()
if not s: # break if the string is empty
break
cm,num = map(str,s)
if cm=='D':
total+=int(num)
if cm=='W':
total-=int(num)
print(total)
Question 18:
A website requires the users to input username and password to register. Write a program to check the validity of password input by users.
Following are the criteria for checking the password:
At least 1 letter between [a-z]
At least 1 number between [0-9]
At least 1 letter between [A-Z]
At least 1 character from [$#@]
Minimum length of transaction password: 6
Maximum length of transaction password: 12
Your program should accept a sequence of comma separated passwords and will check them according to the above criteria. Passwords that match the criteria are to be printed, each separated by a comma.
Example
If the following passwords are given as input to the program:
ABd1234@1,a F1#,2w3E*,2We3345
Then, the output of the program should be:
ABd1234@1
解法一
import re
value = []
items=[x for x in input().split(',')]
for p in items:
if (len(p)<6 or len(p)>12):
break
elif not re.search("[a-z]",p):
break
elif not re.search("[0-9]",p):
break
elif not re.search("[A-Z]",p):
break
elif not re.search("[$#@]",p):
break
elif re.search("\s",p):
break
else:
value.append(p)
break
print (",".join(value))
解法二
def is_low(x): # Returns True if the string has a lowercase
for i in x:
if 'a'<=i and i<='z':
return True
return False
def is_up(x): # Returns True if the string has a uppercase
for i in x:
if 'A'<= i and i<='Z':
return True
return False
def is_num(x): # Returns True if the string has a numeric digit
for i in x:
if '0'<=i and i<='9':
return True
return False
def is_other(x): # Returns True if the string has any "$#@"
for i in x:
if i=='$' or i=='#' or i=='@':
return True
return False
s = input().split(',')
lst = []
for i in s:
length = len(i)
if 6 <= length and length <= 12 and is_low(i) and is_up(i) and is_num(i) and is_other(i): #Checks if all the requirments are fulfilled
lst.append(i)
print(",".join(lst))
解法三
def check(x):
cnt = (6<=len(x) and len(x)<=12)
for i in x:
if i.isupper():
cnt+=1
break
for i in x:
if i.islower():
cnt+=1
break
for i in x:
if i.isnumeric():
cnt+=1
break
for i in x:
if i=='@' or i=='#'or i=='$':
cnt+=1
break
return cnt == 5 # counting if total 5 all conditions are fulfilled then returns True
s = input().split(',')
lst = filter(check,s) # Filter function pick the words from s, those returns True by check() function
print(",".join(lst))
解法四
import re
s = input().split(',')
lst = []
for i in s:
cnt = 0
cnt+=(6<=len(i) and len(i)<=12)
cnt+=bool(re.search("[a-z]",i)) # here re module includes a function re.search() which returns the object information
cnt+=bool(re.search("[A-Z]",i)) # of where the pattern string i is matched with any of the [a-z]/[A-z]/[0=9]/[@#$] characters
cnt+=bool(re.search("[0-9]",i)) # if not a single match found then returns NONE which converts to False in boolean
cnt+=bool(re.search("[@#$]",i)) # expression otherwise True if found any.
if cnt == 5:
lst.append(i)
print(",".join(lst))
Question 19:
You are required to write a program to sort the (name, age, score) tuples by ascending order where name is string, age and score are numbers. The tuples are input by console. The sort criteria is:
1: Sort based on name
2: Then sort based on age
3: Then sort by score
The priority is that name > age > score.
If the following tuples are given as input to the program:
Tom,19,80
John,20,90
Jony,17,91
Jony,17,93
Json,21,85
Then, the output of the program should be:
[('John', '20', '90'), ('Jony', '17', '91'), ('Jony', '17', '93'), ('Json', '21', '85'), ('Tom', '19', '80')]
解法一
lst = []
while True:
s = input().split(',')
if not s[0]: # breaks for blank input
break
lst.append(tuple(s))
lst.sort(key= lambda x:(x[0],x[1],x[2]))
print(lst)
Question 20:
Define a class with a generator which can iterate the numbers, which are divisible by 7, between a given range 0 and n.
解法一
class Test:
def generator(self,n):
return [i for i in range(n) if i%7==0]
n = int(input())
num = Test()
lst = num.generator(n)
print(lst)
源代码下载
这十道题的代码在我的github上,如果大家想看一下每道题的输出结果,可以点击以下链接下载:
我的运行环境Python 3.6+,如果你用的是Python 2.7版本,绝大多数不同就体现在以下3点:
raw_input()在Python3中是input()
print需要加括号
fstring可以换成.format(),或者%s,%d
谢谢大家,我们下期见!希望各位朋友不要吝啬,把每道题的更高效的解法写在评论里,我们一起进步!!!
python题库刷题训练软件_Python基础练习100题 ( 11~ 20)相关推荐
- 计算机二级题库python题库有几套_2019计算机二级备考资料+题库(含Python)
释放双眼,带上耳机,听听看~! 2019年全国计算机等级考试(NCRE)将举办四次考试,时间分别为3月30日至4月1日(第54次).6月1日(第55次).9月21日至23日(第56次)及12月7日(第 ...
- 大学计算机基础-题库刷题-精选
题库刷题: 写在前面: 这个是我准备应对学校转专业考试而刷的题库, 也是大学计算机的题库,同样适用于大学计算机这门课的期末考试. 精选了一些重要的题目. 目录 题库刷题: 写在前面: 题目1:(接下来 ...
- 1000道Python题库系列分享15(1道代码改写题)
考虑到前面分享题库的时候,要等下一期才给出答案,不方便大家及时核对和学习.以后改为每期在文末直接给出答案,不明白的地方可以文末留言交流,提高学习效率. ================= 问题描述: ...
- 1000道Python题库系列分享14(1道代码阅读题)
上期题目链接:1000道Python题库系列分享13(22道填空题) 上期题目答案: 本期题目:阅读下面的代码,分析其功能,并指出可能存在的错误及其原因,最好能够给出解决方案. 留言给出完整答案的朋友 ...
- 大学c语言作业用什么搜题比较好,快速查找题库_什么手机软件可以把题库输入进去然后输入关键字可以查找点道题_淘题吧...
❶ 什么手机软件可以把题库输入进去.然后输入关键字可以查找点道题 用试题通啊,这款软件可以的,题库录入过后搜索关键字就能看到答案和题目了. ❷ 如何快速寻找题库中的答案我有份题库,答题时如何快速的找到 ...
- 北邮oj题库刷题计划(更新ing)
北邮oj题库刷题计划(更新ing) 83. A + B Problem 84 Single Number 85. Three Points On A Line 120 日期 121 最值问题 122 ...
- 计算机考试随机出题,打乱题库_有什么软件可以自己导入题库然后可以随机抽题做有没有这种软件啊_淘题吧...
㈠ 全国计算机等级考试三级网络技术,系统在题库抽题时,是抽一整套试卷还是打乱抽的 随机抽选!一道概念性的题,它可能会用几种方式来提出问题,然后在几个问题中随机抽选一道题,以此类推.一个概念性的题不会重 ...
- 基于科目分类的题库刷题小程序系统
基于科目分类的题库刷题小程序系统 使用场景 在线答题,是一种在线练习.考试.测评的智能答题系统,适用于企业培训.学生练习.评测考核.知识竞赛.模拟考试等场景. 简介 考研刷题小程序云开发实战.题库小程 ...
- 长春理工大学c语言实验题库,长春理工大学首届趣味心理知识竞赛初赛题库.doc...
长春理工大学首届趣味心理知识竞赛初赛题库 长春理工大学首届趣味心理知识竞赛初赛题库 心理知识简述 1.心理学概念 心理学是研究人的心理活动及其发生.发展规律的科学.人的心理是以不同的形式能动地反映客观 ...
最新文章
- 常见浏览器User-Agent大全
- 2016政策与市场协同发力大数据,小公司如何搏杀BAT?
- PHP设计模式-单例模式
- 4.Hibernate O/R 映射
- 【Linux】一步一步学Linux——ipcalc命令(191)
- Eclipse快捷键(自用)
- Dapper操作MySQL数据库获取JSON数据中文乱码
- linux 下搭建postfix服务器
- 微软将于今年秋天停用Azure区块链服务
- 网络工程师职业规划(三)
- webAppbuilder微件使用教程3 地理处理微件
- 信息技术专项习题汇总
- 统计矩形中的正方形和长方形
- ps抠图 淘宝抠图
- Kryo+Netty传输序列化对象
- 群体结构分析:用 phylip 构建进化树
- 中国牛奶市场竞争态势分析及未来发展前景预测报告2022-2028年版
- surfer-地形图渲染
- 蓝桥杯——BASIC-3——基础练习 字母图形
- Kubectl 常用命令大全(*)