I already tried inputting the SWAP() function directly, and it works, but with the function inside it doesn't swap the variables.
def SWAP(x,y):
w = x
x = y
y = w
del w
def ORDER(x,y,z):
if x > z:
SWAP(x,z)
if x > y:
SWAP(x,y)
if y > z:
SWAP(y,z)
print(f'{x}<{y}<{z}')
When you are calling SWAP
function it is not returning the values. And function args are not sent as call-by-reference
.
So what ever changes you do in SWAP function does not get reflected in the calling function.
Try this :
def SWAP(x,y):
w = x
x = y
y = w
return x,y
def ORDER(x,y,z):
if x > z:
x,z=SWAP(x,z)
if x > y:
x,y=SWAP(x,y)
if y > z:
y,z=SWAP(y,z)
print(f'{x}<{y}<{z}')
Explanation :
SWAP function takes 2 args x,y
and returns the swapped value. Swapping done by you was correct.
While calling SWAP I am expecting a return of 2 variable which should be swapped.
Eg. -
a = 5
b = 8
a,b = SWAP(a,b)
Here I am calling SWAP with `a,b` who have values `5,8` currently,
Now SWAP returns `8,5`as response. I am storing `8,5` into `a,b`.
So Now a becomes 8 and b becomes 5.
All the other logic is same as you wrote for comparing.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.