【Python编程基础练习】 Python编程基础练习100题学习记录第二期(11~20)
2022/8/2 14:52:47
本文主要是介绍【Python编程基础练习】 Python编程基础练习100题学习记录第二期(11~20),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
1.此为GitHub项目的学习记录,记录着我的思考,代码基本都有注释。
2.可以作为Python初学者巩固基础的绝佳练习,原题有些不妥的地方我也做了一些修正。
3.建议大家进行Python编程时使用英语。
4.6~17题为level1难度,18-22题为level3难度,其余都为level1难度。
项目名称:
100+ Python challenging programming exercises for Python 3
#!usr/bin/env Python3.9 # -*- coding:UTF-8 -*- """ Question: 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. """ ''' Hints: In case of input data being supplied to the question, it should be assumed to be a console input. ''' value = [] # 创建空列表 temp = input('Please input a sequence of comma separated 4 digit binary numbers:') k = [x for x in temp.split(',')] # 将输入的4位二进制数存放进列表里面 for p in k: # for循环检查输入的4位二进制数里面有没有能被5整除的 int_p = int(p, 2) # int(x, k),k = 2, 8, 10, 16,也就是进制转换 if int_p % 5: continue value.append(p) # 将能被5整除的4位二进制数添加到已创建好的空列表里 print(','.join(value)) # print(k)
#!usr/bin/env Python3.9 # -*- coding:UTF-8 -*- """ Question: 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. """ ''' Hints: In case of input data being supplied to the question, it should be assumed to be a console input. ''' value = [] # 创建空列表 """x = int(input('Please input a number between 1000 and 3000:'))""" for x in range(999, 3001): if x % 2 == 0: # 判断数值是否为偶数 x = str(x) # 转为字符类型 value.append(x) # 加进空列表里 print(','.join(value)) # 把全部偶数以一行形式打印出来,中间用逗号分隔 # 源代码 """ 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)) """
#!usr/bin/env Python3.9 # -*- coding:UTF-8 -*- """ Question: 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 """ ''' Hints: In case of input data being supplied to the question, it should be assumed to be a console input. ''' temp = input('Please input what you want to say:') cal = {'LETTERS': 0, 'DIGITS': 0} # 创建空字典,key分别为’LETTERS‘,'DIGITS' for i in temp: if i.isalpha(): # 用isalpha( )函数判断字符串是否由字母组成 cal['LETTERS'] += 1 elif i.isdigit(): # 用isdigit( )函数判断字符串是否由数字组成 cal['DIGITS'] += 1 else: pass print('LETTERS', cal['LETTERS']) # 打印 print('DIGITS', cal['DIGITS'])
#!usr/bin/env Python3.9 # -*- coding:UTF-8 -*- """ Question: 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 """ ''' Hints: In case of input data being supplied to the question, it should be assumed to be a console input. ''' temp = input('Please input what you want to say:') cal = {'UPPER CASE': 0, 'LOWER CASE': 0} # 创建一个空字典 for i in temp: if i.isupper(): # 用isupper()函数判断字符串是否由大写字母组成 cal['UPPER CASE'] += 1 elif i.islower(): # 用islower()函数判断字符串是否由小写字母组成 cal['LOWER CASE'] += 1 else: pass print('UPPER CASE', cal['UPPER CASE']) # 输出结果 print('LOWER CASE', cal['LOWER CASE'])
#!usr/bin/env Python3.9 # -*- coding:UTF-8 -*- """ Question: 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 """ ''' In case of input data being supplied to the question, it should be assumed to be a console input. ''' x = int(input('Please input the digit:')) # 拆分成4项进行计算 a1 = x a2 = x * 10 + a1 a3 = x * 100 + a2 a4 = x * 1000 + a3 r = a1 + a2 + a3 + a4 print(r) # 源代码。更加简便,高级一些 """ a = input() n1 = int( "%s" % a ) n2 = int( "%s%s" % (a,a) ) n3 = int( "%s%s%s" % (a,a,a) ) n4 = int( "%s%s%s%s" % (a,a,a,a) ) print(n1+n2+n3+n4) """
#!usr/bin/env Python3.9 # -*- coding:UTF-8 -*- """" Question: 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 """ ''' Hints: In case of input data being supplied to the question, it should be assumed to be a console input. ''' # 方法一 temp = input('Please input your numbers,Example:1, 2, 3, 4...:') numbers = [int(x) ** 2 for x in temp.split(',') if int(x) % 2 != 0] # 使用列表推导式对每一个奇数进行平方和计算 print(numbers) # 方法二 ''' values = [] # 创建一个空列表 for i in temp.split(','): # for循环找寻输入的奇数 i = int(i) # 将i从str类型转换为int类型 if i % 2 == 0: pass elif i % 2 != 0: values.append(str(i * i)) # 将奇数平方后加到空列表里,注意需要再次转为数值类型 print(','.join(values)) # 同一行输出结果 '''
#!usr/bin/env Python3.9 # -*- coding:UTF-8 -*- """ Question: 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 """ ''' Hints: In case of input data being supplied to the question, it should be assumed to be a console input. ''' # 方法一 单个数据输出,太繁琐,不推荐 '''D = 0 W = 0 sumNum = 0 while True: Type = input("Please input log date:") if Type == "D": num = int(input("Please input the number:")) sumNum += num elif Type == "W": num = int(input("Please input the number:")) sumNum -= num else: break print("The net amount is, ", sumNum)''' # 方法2 也是按次数输入,比较麻烦 D = 0 W = 0 total = 0 c = int(input('请输入你的存取次数:')) for i in range(1, c + 1): x = input('请输入你的项目:') y = int(input('请输入你的金额:')) if x == 'D': total = total + y elif x == 'W': total = total - y else: pass print('账户净金额是:', total) # 源代码 '''net_amount = 0 while True: temp = input('Please input the transaction log.Example:D 100 W 200.:') if not temp: break log_date = temp.split(' ') operation = log_date[0] amount = int(log_date[1]) if operation == "D": net_amount += amount elif operation == "W": net_amount -= amount else: pass print(net_amount) ''' # 待解决问题:无法简便计算净储蓄金额
#!usr/bin/env Python3.9 # -*- coding:UTF-8 -*- """ 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 """ '''Hints: In case of input data being supplied to the question, it should be assumed to be a console input.''' import re # 导入正则表达式库 date = [] # 创建一个空列表 passwords = input('Please input your passwords:') for i in passwords.split(','): if len(i) < 6 or len(i) > 12: # 判定密码是否满足位数要求,满足继续进行之后的标准判定,否则从头开始下一个密码的判定 continue else: # 若满足位数要求,执行下列判定 pass if not re.search('[a-z]', i): # 判断是否满足至少有一个小写字母 continue elif not re.search('[A-Z]', i): # 判断是否至少有一个大写字母 continue elif not re.search('[0-9]', i): # 判断是否至少有一个阿拉伯数字 continue elif not re.search('[$#@]', i): # 判断是否至少有一个所给特殊字母 continue else: pass date.append(i) # 将满足条件的密码加入空列表里 print('The password is acceptable:', ','.join(date)) # 在一行里打印出符合条件的密码
#!usr/bin/env Python3.9 # -*- coding:UTF-8 -*- """ Question: You are required to write a program to sort the (name, age, height) tuples by ascending order (升序) where name is string, age and height 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')] """ ''' Hints: In case of input data being supplied to the question, it should be assumed to be a console input. We use itemgetter to enable multiple sort keys. ''' # 源代码无法实现理想效果,采用的是operator库里的itemgetter允许对多个键进行处理 '''from operator import itemgetter values = [] while True: temp = input('Please input the original date:') if not temp: break values.append(tuple(temp.split(','))) print(sorted(values, key=itemgetter(0, 1, 2)))''' temp = input('Please input the original date:') # t = [tuple(t.split(',')) for t in temp.split(' ')] # (先按空格分割,再按逗号分割)处理输入的数据并放在元组里 # t = [(i[0], int(i[1]), int(i[2])) for i in t] # 将每一组数据按既定格式存放到列表里 # sorted(t, key=lambda x: (x[0], x[1], x[2])) # lambda表达式是起到一个函数速写的作用。允许在代码内嵌入一个函数的定义。 # 此处是按照多个键进行排序,默认升序排列 # 将上述步骤合并成一行: t = sorted([(i[0], int(i[1]), int(i[2])) for i in [tuple(t.split(',')) for t in temp.split(' ')]], key=lambda x: (x[0], x[1], x[2])) print(t) # 打印结果
#!usr/bin/env Python3.9 # -*- coding:UTF-8 -*-- """ Question: Define a class with a generator which can iterate the numbers, which are divisible by 7, between a given range 0 and n. """ from audioop import reverse '''Hints: Consider use yield''' # 我的代码,采用的思想是筛选而非迭代 '''def result_num(): # 定义函数 values = [] # 创建一个空列表 n = int(input('请输入范围上限:')) for i in range(0, n): if i % 7 == 0: # 筛选能被7整除的数 values.append(str(i)) # 转换为字符型加到列表里 print(','.join(values)) # 在同一行输出结果 result_num() # 调用函数''' # 源代码 def put_numbers(n): # 定义函数 i = 0 while i < n: # 循环函数寻找能够被7整除的数字 j = i i = i + 1 if j % 7 == 0: # 判定能否被7整除 yield j # 返回值7,相当于return.也是生成器的一部分 for i in put_numbers(20): # 调用函数进行指定范围内的迭代 print(i)
“自主学习,快乐学习”
再附上Python常用标准库供大家学习使用:
Python一些常用标准库解释文章集合索引(方便翻看)
“学海无涯苦作舟”
这篇关于【Python编程基础练习】 Python编程基础练习100题学习记录第二期(11~20)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-12-20Python编程入门指南
- 2024-12-20Python编程基础与进阶
- 2024-12-19Python基础编程教程
- 2024-12-19python 文件的后缀名是什么 怎么运行一个python文件?-icode9专业技术文章分享
- 2024-12-19使用python 把docx转为pdf文件有哪些方法?-icode9专业技术文章分享
- 2024-12-19python怎么更换换pip的源镜像?-icode9专业技术文章分享
- 2024-12-19Python资料:新手入门的全面指南
- 2024-12-19Python股票自动化交易实战入门教程
- 2024-12-19Python股票自动化交易入门教程
- 2024-12-18Python量化入门教程:轻松掌握量化交易基础知识