简体   繁体   English

Python-实现函数

[英]Python - Implementing Functions

I am creating a function to check x is greater than y, and if not it switches the two values and returns them. 我正在创建一个函数来检查x大于y,如果不是,它将切换两个值并返回它们。

def xGreater(x, y):
    if(y > x):
        x, y = y, x
    return x, y

My query is what is the best way to go about using this function within another function, my current code is the following: 我的查询是在另一个函数中使用此函数的最佳方法是什么,我当前的代码如下:

def gcd(x, y):
    x , y = xGreater(x, y)
    r = x % y
    while(r != 0):
        x, y = y, r
        r = x % y
    return y

Can I not simply call xGreater(x, y) to alter the values of x and y, without the x, y = in front? 我可以不简单地调用xGreater(x,y)来更改x和y的值,而无需在前面添加x,y =吗? Or does this only work when there is a single variable being returned. 或者这仅在返回单个变量时才起作用。 Thanks! 谢谢!

Can I not simply call xGreater(x, y) to alter the values of x and y, without the x, y = in front? 我可以不简单地调用xGreater(x,y)来更改x和y的值,而无需在前面添加x,y =吗?

I am afraid you can't, since x and y are immutable and are passed into xGreater() by value. 恐怕你做不到,因为xy是不可变的, xGreater()值传递给xGreater()

It can be done in some special cases (for example, if x and y were two lists), but not generally. 可以在某些特殊情况下完成此操作(例如,如果xy是两个列表),但通常不能这样做。

To be totally honest, I'd get rid of xGreater() and just do the swap in gcd() : 老实说,我会摆脱xGreater()而只是在gcd()进行交换:

def gcd(x, y):
    if y > x:
        x, y = y, x
    r = x % y
    ...

I personally find the code more readable this way. 我个人认为这种方式的代码更具可读性。

No, integers are immutable. 不,整数是不可变的。 But hey, you can cut down on one instance of tuple packing/unpacking: 但是,您可以减少一个元组打包/拆包的实例:

def xGreater(x, y):
    return (y, x) if y > x else (x, y)

NPE has a better solution but I'm bored and wanted to write some bit hacks NPE有一个更好的解决方案,但我很无聊,想写一些技巧

def gcd(x,y):
    minVal = y ^((x ^ y) & -(x < y))

    if ( minVal == y ):
        y = x ^ y  # Swapping values without a intermediate variable
        y = y ^ y  # This is highly inefficient to use.
        x = x ^ y  # But still kinda cool.

   return x % y

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

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