当前位置:网站首页>关于交换a和b的值的四种方法
关于交换a和b的值的四种方法
2022-07-06 09:23:00 【王业强】
交换a,b的值,大家可能认为很简单,但是如果突然让你想出4种方法,可能大家一瞬间脑子里只出现了用第三变量暂存的这种最基本的方法,下面我总结了四种方法:
初始化a和b:
#关于python较换 a b 值的 方法
a = 3
b = 5
print("开始时:a = {} , b = {}".format(a,b))1.用第三变量c暂存:
def ChangeFirst(a,b): #取第三变量C暂存
c = a
a = b
b = c
print("ChangeFirst方法交换后 :a = {} , b = {}".format(a,b))2.用和与差交换(暂存):
def ChangeSecond(a,b): #用和与差
a = a+b
b = a-b
a = a-b
print("ChangeSecond方法交换后:a = {} , b = {}".format(a,b))3.用按位异或的方法:
def ChangeThird(a,b): #按位异或(按二进制位,相同为0不同为1)
a = a^b
b = a^b
a = a^b
print("ChangeThird方法交换后 :a = {} , b = {}".format(a,b))4.Python特有的方法:
def ChangeFourth(a,b): #python特有的方法
a,b = b,a
print("ChangeFourth方法交换后:a = {} , b = {}".format(a,b))代码运行:
ChangeFirst(a,b)
ChangeSecond(a,b)
ChangeThird(a,b)
ChangeFourth(a,b)代码输出:

边栏推荐
- 记一次,修改密码逻辑漏洞实战
- 《统计学》第八版贾俊平第九章分类数据分析知识点总结及课后习题答案
- Interpretation of iterator related "itertools" module usage
- 网络基础之路由详解
- Overview of LNMP architecture and construction of related services
- 《统计学》第八版贾俊平第四章总结及课后习题答案
- Database monitoring SQL execution
- 循环队列(C语言)
- [MySQL table structure and integrity constraint modification (Alter)]
- Apache APIs IX has the risk of rewriting the x-real-ip header (cve-2022-24112)
猜你喜欢

Apache APIs IX has the risk of rewriting the x-real-ip header (cve-2022-24112)

Statistics 8th Edition Jia Junping Chapter 5 probability and probability distribution

HackMyvm靶机系列(7)-Tron

SystemVerilog discusses loop loop structure and built-in loop variable I

xray与burp联动 挖掘

captcha-killer验证码识别插件

Detailed explanation of network foundation routing

Proceedingjoinpoint API use

内网渗透之内网信息收集(三)

sqqyw(淡然点图标系统)漏洞复现和74cms漏洞复现
随机推荐
记一次api接口SQL注入实战
循环队列(C语言)
Spot gold prices rose amid volatility, and the rise in U.S. prices is likely to become the key to the future
[MySQL table structure and integrity constraint modification (Alter)]
7-1 output all primes between 2 and n (PTA programming)
[MySQL database learning]
关于超星脚本出现乱码问题
Intel oneapi - opening a new era of heterogeneity
Low income from doing we media? 90% of people make mistakes in these three points
Network technology related topics
MySQL interview questions (4)
Hcip -- MPLS experiment
Detailed explanation of network foundation routing
This article explains in detail how mockmvc is used in practical work
网络层—简单的arp断网
JDBC看这篇就够了
HackMyvm靶机系列(4)-vulny
Record an API interface SQL injection practice
Experiment 7 use of common classes (correction post)
《统计学》第八版贾俊平第六章统计量及抽样分布知识点总结及课后习题答案