当前位置:网站首页>关于交换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)代码输出:

边栏推荐
- xray与burp联动 挖掘
- SQL injection
- 7-8 7104 Joseph problem (PTA program design)
- WEB漏洞-文件操作之文件包含漏洞
- [paper reproduction] cyclegan (based on pytorch framework) {unfinished}
- [VMware abnormal problems] problem analysis & Solutions
- Experiment 7 use of common classes
- 《统计学》第八版贾俊平第十一章一元线性回归知识点总结及课后习题答案
- 小程序web抓包-fiddler
- Fire! One day transferred to go engineer, not fire handstand sing Conquest (in serial)
猜你喜欢
随机推荐
Record an edu, SQL injection practice
Database monitoring SQL execution
内网渗透之内网信息收集(五)
Record once, modify password logic vulnerability actual combat
循环队列(C语言)
JVM memory model concept
Based on authorized access, cross host, and permission allocation under sqlserver
Interpretation of iterator related "itertools" module usage
"Gold, silver and four" job hopping needs to be cautious. Can an article solve the interview?
Wei Shen of Peking University revealed the current situation: his class is not very good, and there are only 5 or 6 middle-term students left after leaving class
Attack and defense world misc practice area (simplerar, base64stego, no matter how high your Kung Fu is, you are afraid of kitchen knives)
Sword finger offer 23 - print binary tree from top to bottom
[three paradigms of database] you can understand it at a glance
C language file operation
《统计学》第八版贾俊平第一章课后习题及答案总结
Hackmyvm target series (1) -webmaster
This article explains in detail how mockmvc is used in practical work
Harmonyos application development -- address book management system telmanagesys based on listcontainer [phonebook][api v6]
Apache APIs IX has the risk of rewriting the x-real-ip header (cve-2022-24112)
Chain team implementation (C language)









