簡體   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