繁体   English   中英

我在这条蟒蛇中缺少什么? 这是一个简单的程序来订购3个术语,最后一个订购部分不起作用

[英]What am I missing in this python? It's a simple program to order 3 terms, and the last order part doesn't work

我已经尝试直接输入 SWAP() 函数,它可以工作,但是它内部的函数不会交换变量。

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}')

当您调用SWAP函数时,它不会返回值。 并且函数 args 不会作为call-by-reference发送。

因此,您在 SWAP 函数中所做的任何更改都不会反映在调用函数中。

尝试这个 :

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}')

解释 :

SWAP 函数接受 2 个参数x,y并返回交换后的值。 你做的交换是正确的。

在调用 SWAP 时,我期望返回 2 个应该交换的变量。

例如。 ——

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.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM