简体   繁体   English

如何在Python中使用堆栈方法编写欧几里得算法?

[英]How to write Euclid's Algorithm using a stack method in Python?

looking for help here!在这里寻求帮助!

Does anyone know how to convert the recursive version of Euclid's algorithm (to find the greatest common divisor GCD) into a version that uses STACK?有谁知道如何将欧几里得算法的递归版本(找到最大公约数 GCD)转换为使用堆栈的版本?

Here is the recursive version of Euclid's algorithm:这是欧几里得算法的递归版本:

def euclid_gcd(a, b):
    if a == 0:
        return b
    return gcd(b%a, a)

Right now I have a starting code to convert to a STACK version of Euclid's algorithm:现在我有一个起始代码可以转换为欧几里得算法的堆栈版本:

def euclid_gcd_stack(a, b):
    s = Stack()
    s.push(a)
    s.push(b)

    while s.count() > 0:
        b = s.pop()
        a = s.pop()

 <code to be continued here>

Thank you in advance: :)先感谢您: :)

def euclid_gcd_stack(a, b):
    s = Stack()
    s.push(a)
    s.push(b)

    while s.count() > 0:
        b = s.pop()
        a = s.pop()

        if a > b:
            a, b = b, a
        if a == 0:
            return b
        else:
            s.push(a)
            s.push(b - a)
``

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

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