当前位置:网站首页>关于交换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)
代码输出:
边栏推荐
- 浙大版《C语言程序设计实验与习题指导(第3版)》题目集
- xray與burp聯動 挖掘
- Wu Enda's latest interview! Data centric reasons
- . Net6: develop modern 3D industrial software based on WPF (2)
- HackMyvm靶机系列(2)-warrior
- Hackmyvm target series (3) -visions
- Lintcode logo queries the two nearest saplings
- 内网渗透之内网信息收集(一)
- HackMyvm靶機系列(3)-visions
- Record once, modify password logic vulnerability actual combat
猜你喜欢
Harmonyos application development -- address book management system telmanagesys based on listcontainer [phonebook][api v6]
Network layer - simple ARP disconnection
Realize applet payment function with applet cloud development (including source code)
Hackmyvm Target Series (3) - vues
《統計學》第八版賈俊平第七章知識點總結及課後習題答案
WEB漏洞-文件操作之文件包含漏洞
《统计学》第八版贾俊平第五章概率与概率分布
DVWA (5th week)
Detailed explanation of network foundation
Build domain environment (win)
随机推荐
Proceedingjoinpoint API use
7-15 h0161. Find the greatest common divisor and the least common multiple (PTA program design)
MySQL interview questions (4)
Internet Management (Information Collection)
Detailed explanation of network foundation routing
《統計學》第八版賈俊平第七章知識點總結及課後習題答案
记一次api接口SQL注入实战
[paper reproduction] cyclegan (based on pytorch framework) {unfinished}
xray与burp联动 挖掘
Detailed explanation of three ways of HTTP caching
SQL注入
AQS details
《统计学》第八版贾俊平第十四章指数知识点总结及课后习题答案
On the idea of vulnerability discovery
Data mining - a discussion on sample imbalance in classification problems
XSS (cross site scripting attack) for security interview
Mathematical modeling idea of 2022 central China Cup
《统计学》第八版贾俊平第五章概率与概率分布
我的第一篇博客
SystemVerilog discusses loop loop structure and built-in loop variable I