当前位置:网站首页>关于交换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)
代码输出:
边栏推荐
- 攻防世界MISC练习区(gif 掀桌子 ext3 )
- JDBC事务、批处理以及连接池(超详细)
- Solutions to common problems in database development such as MySQL
- 7-8 7104 Joseph problem (PTA program design)
- Sentinel overall workflow
- Attack and defense world misc practice area (GIF lift table ext3)
- 《统计学》第八版贾俊平第七章知识点总结及课后习题答案
- Interpretation of iterator related "itertools" module usage
- xray與burp聯動 挖掘
- Hackmyvm Target Series (3) - vues
猜你喜欢
Data mining - a discussion on sample imbalance in classification problems
《统计学》第八版贾俊平第十章方差分析知识点总结及课后习题答案
Applet Web Capture -fiddler
Realize applet payment function with applet cloud development (including source code)
"Gold, silver and four" job hopping needs to be cautious. Can an article solve the interview?
Middleware vulnerability recurrence Apache
Database monitoring SQL execution
Network layer - simple ARP disconnection
Intranet information collection of Intranet penetration (I)
《统计学》第八版贾俊平第五章概率与概率分布
随机推荐
Realize applet payment function with applet cloud development (including source code)
7-14 error ticket (PTA program design)
7-9 make house number 3.0 (PTA program design)
《统计学》第八版贾俊平第二章课后习题及答案总结
Force deduction 152 question multiplier maximum subarray
Experiment 9 input and output stream (excerpt)
Harmonyos JS demo application development
Lintcode logo queries the two nearest saplings
攻防世界MISC练习区(SimpleRAR、base64stego、功夫再高也怕菜刀)
Sword finger offer 23 - print binary tree from top to bottom
Chain team implementation (C language)
Build domain environment (win)
Markdown font color editing teaching
内网渗透之内网信息收集(四)
《统计学》第八版贾俊平第十三章时间序列分析和预测知识点总结及课后习题答案
《英特尔 oneAPI—打开异构新纪元》
Xray and Burp linked Mining
Low income from doing we media? 90% of people make mistakes in these three points
How to turn wechat applet into uniapp
JDBC事务、批处理以及连接池(超详细)