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

边栏推荐
- XSS (cross site scripting attack) for security interview
- Sqqyw (indifferent dot icon system) vulnerability recurrence and 74cms vulnerability recurrence
- 7-7 7003 combination lock (PTA program design)
- Hackmyvm target series (5) -warez
- 《统计学》第八版贾俊平第十章方差分析知识点总结及课后习题答案
- 内网渗透之内网信息收集(四)
- 内网渗透之内网信息收集(三)
- A complete collection of papers on text recognition
- Markdown font color editing teaching
- JDBC看这篇就够了
猜你喜欢

循环队列(C语言)

Résumé des points de connaissance et des réponses aux exercices après la classe du chapitre 7 de Jia junping dans la huitième édition des statistiques

JDBC看这篇就够了

Build domain environment (win)

Statistics 8th Edition Jia Junping Chapter 14 summary of index knowledge points and answers to exercises after class
![Harmonyos application development -- address book management system telmanagesys based on listcontainer [phonebook][api v6]](/img/0b/ddbee0b8a34627e13bff5598bbaed8.jpg)
Harmonyos application development -- address book management system telmanagesys based on listcontainer [phonebook][api v6]

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

Wu Enda's latest interview! Data centric reasons

JDBC事务、批处理以及连接池(超详细)

Attack and defense world misc practice area (GIF lift table ext3)
随机推荐
我的第一篇博客
Hackmyvm target series (2) -warrior
HackMyvm靶机系列(1)-webmaster
Internet Management (Information Collection)
7-7 7003 combination lock (PTA program design)
攻防世界MISC练习区(SimpleRAR、base64stego、功夫再高也怕菜刀)
Hackmyvm Target Series (3) - vues
Interpretation of iterator related "itertools" module usage
Which is more advantageous in short-term or long-term spot gold investment?
New version of postman flows [introductory teaching chapter 01 send request]
JDBC transactions, batch processing, and connection pooling (super detailed)
内网渗透之内网信息收集(四)
Based on authorized access, cross host, and permission allocation under sqlserver
Captcha killer verification code identification plug-in
Intel oneapi - opening a new era of heterogeneity
攻防世界MISC练习区(gif 掀桌子 ext3 )
Only 40% of the articles are original? Here comes the modification method
[insert, modify and delete data in the headsong educator data table]
网络基础之路由详解
The difference between layer 3 switch and router