python 练习题(1-15)
1、给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。
2、生成双色球
3、逻辑运算(运算符优先级)
4、输入一个整数,判断这个数是几位数
5、用while循环计算 1-2+3-4...-99 中除了88以外的所有数的总和
6、不通过引用三方变量,交换a、b的值
7、找出字符串中的整数
8、判断一个数是否是水仙花数, 水仙花数是一个三位数, 三位数的每一位的三次方的和还等于这个数.
9、税务部门征收所得税
10、循环读文件,并将每一行转成列表+字典的形式
11、将循环列表转成字典
12、写函数,用户传入修改的文件名,与要修改的内容,执行函数,完成整个文件的批量修改操作
13、写函数,接收一个参数(此参数类型必须是可迭代对象),将可迭代对象的每个元素以’_’相连接,形成新的字符串,并返回.
14、写函数,传入一个参数n,返回n的阶乘。例如:cal(7) 计算7*6*5*4*3*2*1
15、九九乘法表
1、给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。
你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。
比如:给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
lis = [1,3,3,4,5,6,8]
def getIndex(li, target):
new = [] #所有等于target的元组
for index_i,i in enumerate(li): #index_i = 0
for index_j,j in enumerate(li[index_i + 1:]): #li[1:]少重复
if i + j == target:
new.append([index_i, index_i + 1 + index_j]) #此时j的位置
return new print(getIndex(lis,9))
2、生成双色球
#红球 1-33 选6个,一注中的红球不能重复
#蓝球 1-16 选一个
#不足2位的补零
#写文件
#循环num次,num注球不能重复
import random
def ranNum(): #生成随机数
red = [] #红球列表
while len(red) != 6: #用while,使得取的红球6个号不重复,循环直到取到不同的6个数
num = random.randint(1,33) #从1,33随机取一个数
num = str(num).zfill(2) #把num转成str,不足2位的补零
if num not in red: #如果num不在红球列表中
red.append(num) #添加
red_str = ' '.join(red) #把红球列表拼接到一起
blue = str(random.randint(1,16)).zfill(2) #生成蓝球1个
res = '红球是:%s 蓝球是:%s\n' % (red_str,blue) #函数返回一个str(换行)
return res def op_file(filename,content): #写入文件
f = open(filename,'w',encoding='utf-8')
if content:
f.writelines(content) #f.writelines()将文件循环写入
print('写入文件成功')
f.close() def main():
all_tickets = [] #红+蓝列表
num = input('请输入需要生成的双色球条数:').strip()
if num.isdigit() and num !='':
num = int(num)
while len(all_tickets) != num: #while循环,直到取num组不同的条数
data = ranNum()
print(data)
all_tickets.append(data)
else:
print('输入的条数必须是正整数')
op_file('tick.txt',all_tickets)
# ranNum()
main()
3、逻辑运算
#Python运算符优先级:() > not > and > or,同一级别从左往右计算
# x or y:x是True的,取左边的x;否则取y(and与or相反,可只记住or)
print(1 > 1 or 3 < 4 or 4 > 5 and 2 > 1 and 9 > 8 or 7 < 6)
# 1 > 1 or 3 < 4 or False or 7 < 6 ===>True print(not 2 > 1 and 3 < 4 or 4 > 5 and 2 > 1 and 9 > 8 or 7 < 6)
# True and 3 < 4 or 4 > 5 and 2 > 1 and 9 > 8 or 7 < 6
# False or False or 7 < 6 ===>False print(8 or 3 and 4 or 2 and 0 or 9 and 7)
# 8 or 4 or 0 or 7 ==>8
print(0 or 2 and 3 and 4 or 6 and 0 or 3)
# 0 or 4 or 0 or 3 ==>4 print(6 or 2 > 1) #
print(3 or 2 > 1) #
print(0 or 5 < 4) #False
print(5 < 4 or 3) #
print(2 > 1 or 6) #True
print(3 and 2 > 1) #True--
print(0 and 3 > 1) #
print(2 > 1 and 3) #
print(3 > 1 and 0) #
print(3 > 1 and 2 or 2 < 3 and 3 and 4 or 3 > 2) #
4、输入一个整数,判断这个数是几位数
num = input("请输入一个数:").strip() #'88'
if num.isdigit():
num = int(num)
count = 0
while num > 0: #88>0
num = num // 10 #取整:返回商的整数部分 8 0
count += 1 #
print("这个数是%s位数" % (count))
else:
print('输入的不是整数')
5、用while循环计算 1-2+3-4...-99 中除了88以外的所有数的总和
sum = 0
i = 1
while i< 100:
if i==88:
i += 1 # 记得+1
continue
elif i%2==1:
sum += i
else:
sum -= i
i += 1 print(sum)
sum = 0
i = 1
j = -1 #引入符号位
while i< 100:
j = -j
if i==88:
i += 1 # 记得+1
continue
else:
sum += i*j
i += 1 print(sum)
6、直接交换两个变量的值:
b, a = a, b #交换两个变量的值
通过引入三方变量来交换a、b的值:
a = 1
b = 2
c = None c = b
b = a
a = c
print(a,b)
不通过引用三方变量,交换a、b的值:
a = 1
b = 2
a = a + b #a=3
b = a - b #b=3-2=1
a = a - b #a=3-1=2
print(a,b)
7、找出字符串中的整数
s = 'fhdkladh123jk12dsfjsh3'
for i in s:
if i.isalpha():
s = s.replace(i,' ') #将字母替换成空格
print(s) # 123 12 3
print(s.split()) #['123', '12', '3']
import re #导入正则模块
s = 'fhdkladh123jk12dsfjsh3'
print(re.findall('\d+',s)) #匹配所有数字 >>>['123', '12', '3']
print(re.findall('\D+',s)) #匹配所有非数字 >>>['fhdkladh', 'jk', 'dsfjsh']
8、判断一个数是否是水仙花数, 水仙花数是一个三位数, 三位数的每一位的三次方
的和还等于这个数. 那这个数就是一个水仙花数, 例如: 153 = 1**3 + 5**3 + 3**3
num = input('请输入一个三位数:').strip()
if num.isdigit() and int(num)>99 and int(num)<1000:
num = int(num)
ones = num % 10 #个位
tens = int(num / 10 % 10) #十位
hund = int(num / 100) #百位
print(ones,tens,hund)
if ones**3 + tens**3 + hund**3==num:
print('这是水仙花数')
else:
print('这不是水仙花数')
else:
print('输入不正确')
9、税务部门征收所得税. 规定如下:
1). 收入在2000以下的. 免征.
2). 收入在2000-4000的, 超过2000部分要征收3%的税.
3). 收入在4000-6000的, 超过4000部分要征收5%的税.
4). 收入在6000-10000的, 超过6000部分要征收8%的税.
4). 收入在10000以上的, 超过部分征收20%的税.
注, 如果一个人的收入是8000, 那么他要交2000到4000的税加上4000到6000的税加上6000到8000的税.
收入 = 8000-(4000-2000)*3%-(6000-4000)*4%-(8000-6000)*8%
让用户输入它的工资, 计算最终用户拿到手是多少。
money = input('输入金额:').strip()
money = float(money)
# count = money
tax = 0
while count>0:
if 0<count<=2000:
single = 0
tax += single
count = count - 2000
elif 2000<count<=4000:
single = (count - 2000) * 0.03 #8000 2000*0.03 60
tax += single
count = count - (count - 2000)
elif 4000<count<=6000: #2000*0.05 100
single = (count - 4000) * 0.05
tax += single
count = count - (count - 4000)
elif 6000<count<=10000: #2000 *0.08 =160
single = (count - 6000) * 0.08
tax += single
count = count - (count - 6000)
elif count>10000:
single = (count - 10000) * 0.2
tax += single
count = count - (count - 10000)
print('应缴税额:%.2f' %tax)
print('实际结算:%.2f' %(money - tax))
10、文件a1.txt的内容: 序号 部门 人数 平均年龄 备注
1 python 30 26 单身狗
2 Linux 26 30 没对象
3 运营部 20 24 女生多
.......
通过代码,将其构建成这种数据类型:
[{'序号':'1','部门':Python,'人数':30,'平均年龄':26,'备注':'单身狗'},...... ]
data = [] #总的列表
with open('copy.txt','r',encoding='utf-8') as f:
title = f.readline().strip().split() #第一行key
# print(title) # ['序号', '部门', '人数', '平均年龄', '备注']
dic = {} #**每次循环line,dic都会被新行的值覆盖
for line in f: #循环读文件
line_list = line.strip().split() #分割成list['1', 'python', '30', '26', '单身狗']
if line_list: #**过滤掉是空的行,否则结果不准确
for i in range(len(line_list)): #**有多少非空的行就循环多少次
dic[title[i]] = line_list[i] #title和line_list相对应的值加入字典
print(dic)
data.append(dic) #每一行合成的字典加入总的列表
print(data)
11、
list3 = [
{"name": "alex", "hobby": "抽烟"},
{"name": "alex", "hobby": "喝酒"},
{"name": "alex", "hobby": "烫头"},
{"name": "alex", "hobby": "Massage"},
{"name": "wusir", "hobby": "喊麦"},
{"name": "wusir", "hobby": "街舞"},]
# 如何把上面的列表转换成下方的列表?
list4 = [
{"name": "alex", "hobby_list": ["抽烟", "喝酒", "烫头", "Massage"]},
{"name": "wusir", "hobby_list": ["喊麦", "街舞"]}]
#方法一:把名字作为字典的key
dic = {}
for i in list3:
if i['name'] not in dic: #'alex'这个key不存在
dic[ i['name'] ] = {'name':i['name'], 'hobby_list':[i['hobby']]} #加入一个小字典
else:
dic[i['name']]['hobby_list'].append(i['hobby']) #list加元素 print(dic) #{'alex': {'name': 'alex', 'hobby_list': ['抽烟', '喝酒', '烫头', 'Massage']},}
print(list(dic.values())) #[{'name': 'alex', 'hobby_list': ['抽烟', '喝酒', '烫头', 'Massage']},} #dic.values转成list
#方法二
list4 = [] #[{"name": "alex", "hobby_list": ["抽烟", ]} , ]
for i in list3: #i={"name": "alex", "hobby": "烫头"}
for j in list4: #j={"name": "alex", "hobby_list": ["抽烟", ] }
if i['name']==j['name']:
j['hobby_list'].append(i['name'])
break #退出j循环
else:
list4.append( {'name':i['name'],'hobby_list':[i['hobby']]} ) #'hobby_list':[] print(list4)
12、写函数,用户传入修改的文件名,与要修改的内容,执行函数,完成整个文件的批量修改操作
import os
def file_update(filename,old=None,new=None):
bak_file = filename +'.bak' #新文件
with open(filename,encoding='utf-8') as f,\
open(bak_file,'w',encoding='utf-8') as fw:
if old and new: #新旧内容不为空
for line in f: #一行一行读
if old in line:
line = line.replace(old,new) #替换
fw.write(line) #写入新文件
else: #如果不需要修改
res = f.read() #直接读取原文件
return res
os.remove(filename) #remove必须写在with open的外面,文件正在使用中不能删除
os.rename(bak_file, filename) #重命名 res = file_update('student_msg','xiaoxue','本科')
print(res)
13、写函数,接收一个参数(此参数类型必须是可迭代对象),将可迭代对象的每个元素以’_’相连接,形成新的字符串,并返回.
def func(li):
s = ''
for i in li:
i = str(i)
s =s + i + '-'
return s.strip('-') #去掉末尾的'-' print(func('abc'))
print(func([1,'张三','李四']))
14、写函数,传入一个参数n,返回n的阶乘。例如:cal(7) 计算7*6*5*4*3*2*1
#方法一:
def calc(n):
if str(n).isdigit():
if n==1 or n==0: #0!=1
return 1
else:
return n * calc(n-1)
else:
print('负数没有阶乘') print(calc(5)) #方法二:
def calc(n):
sum = 1
if n==1 or n==0:
return 1
else:
while n>0:
sum = sum * n
n -= 1
return sum
print(calc(5))
15、九九乘法表
def func(n):
for i in range(1,n+1):
for j in range(1,i+1):
print('%s * %s = %s'%(i,j,i*j),end=' ') #中间的空格
print(' ') #每行末尾都是空格
func(9)
python 练习题(1-15)的更多相关文章
- Python练习题-1.使用匿名函数对1~1000求和,代码力求简洁。
Python 练习 标签(空格分隔): Python Python练习题 Python知识点 一.使用匿名函数对1~1000求和,代码力求简洁. 答案: In [1]: from functools ...
- Python练习题 028:求3*3矩阵对角线数字之和
[Python练习题 028] 求一个3*3矩阵对角线元素之和 ----------------------------------------------------- 这题解倒是解出来了,但总觉得 ...
- Python练习题 027:对10个数字进行排序
[Python练习题 027] 对10个数字进行排序 --------------------------------------------- 这题没什么好说的,用 str.split(' ') 获 ...
- Python练习题 026:求100以内的素数
[Python练习题 026] 求100以内的素数. ------------------------------------------------- 奇怪,求解素数的题,之前不是做过了吗?难道是想 ...
- Python练习题 025:判断回文数
[Python练习题 025] 一个5位数,判断它是不是回文数.即12321是回文数,个位与万位相同,十位与千位相同. ---------------------------------------- ...
- Python练习题 024:求位数及逆序打印
[Python练习题 024] 给一个不多于5位的正整数,要求:一.求它是几位数,二.逆序打印出各位数字. ---------------------------------------------- ...
- Python练习题 004:判断某日期是该年的第几天
[Python练习题 004]输入某年某月某日,判断这一天是这一年的第几天? ---------------------------------------------- 这题竟然写了 28 行代码! ...
- Python天天美味(15) - Python正则表达式操作指南(re使用)(转)
http://www.cnblogs.com/coderzh/archive/2008/05/06/1185755.html 简介 Python 自1.5版本起增加了re 模块,它提供 Perl 风格 ...
- PYTHON练习题 二. 使用random中的randint函数随机生成一个1~100之间的预设整数让用户键盘输入所猜的数。
Python 练习 标签: Python Python练习题 Python知识点 二. 使用random中的randint函数随机生成一个1~100之间的预设整数让用户键盘输入所猜的数,如果大于预设的 ...
- 《Think Python》第15章学习笔记
目录 <Think Python>第15章学习笔记 15.1 程序员定义的类型(Programmer-defined types) 15.2 属性(Attributes) 15.3 矩形( ...
随机推荐
- Python——PyQt GUI编程(python programming)
import sys from math import * from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidg ...
- [转]TopShelf 用法
static void Main(string[] args) { { x.Service<SyncData>(s => { s.ConstructUsing(name => ...
- Selenium之动作链(ActionChains)
用selenium做自动化,有时候会遇到需要模拟鼠标操作才能进行的情况,比如单击.双击.点击鼠标右键.拖拽等等.而selenium给我们提供了一个类来处理这类事件——ActionChains se ...
- 在socket的server端处理client端发来的数据
一.楔子 最近做了一个需求遇到一个坑,归结成一个小问题,其实就是在socket的server端处理client端发来的数据的问题,现将这个问题总结一下,本文将数据在server端以字典的形式存储. 另 ...
- 各平台操作系统查询主机WWPN
查询主机WWPN 目录 3.4.3.8.2.3 查询主机WWPN 3.4.3.8.2.3.1 查看主机HBA相应端口的WWPN(Windows) 3.4.3.8.2.3.2 查看主机HBA相应端口的W ...
- 棒槌的工作第八天-----------------------早会-------三次握手四次挥手(转载https://www.cnblogs.com/zmlctt/p/3690998.html)尚待了解,下班补充
TCP三次握手 所谓三次握手(Three-way Handshake),是指建立一个TCP连接时,需要客户端和服务器总共发送3个包. 三次握手的目的是连接服务器指定端口,建立TCP连接,并同步连接双方 ...
- vue新建移动端项目模板
vue移动端模板 tip: 1.ui我们使用的是vux,庆幸的是,解决了打包过大的问题, 2.这里使用的是rem布局,移动端还是要使用ipad和不同尺寸的手机 3.版本:webpack:3.6.0 ...
- c语言函数参数类似继承的传递
函数的参数如果是一个父结构的指针, 这个结构包含在另一个子结构中, typedef struct test_node_one test_node_one_t; typedef struct test_ ...
- Python爬虫的步骤和工具
#四个步骤 1.查看crawl内容的源码格式 crawl的内容可以是 url(链接),文字,图片,视频 2.请求网页源码 (可能要设置)代理,限速,cookie 3.匹配 用正则表达 ...
- 关于Unsupported major.minor version 52.0解决方案的补充
参考:https://blog.csdn.net/jingtianyiyi/article/details/80455916 补充: 这个设置比较容易忽略: 在eclipse中新建tomcat或在原有 ...