python - 如何在 Python 中使用堆栈方法编写欧几里德算法?
问题描述
在这里寻求帮助!
有谁知道如何将欧几里得算法的递归版本(找到最大公约数 GCD)转换为使用堆栈的版本?
这是欧几里得算法的递归版本:
def euclid_gcd(a, b):
if a == 0:
return b
return gcd(b%a, a)
现在我有一个起始代码可以转换为欧几里得算法的堆栈版本:
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>
先感谢您!:)
解决方案
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)
``
推荐阅读
- javascript - 使用 JS 读取 JSON 文件中的更改
- vue.js - 无法在 vue-nativescript 上使 vue-devtools 独立应用程序正常工作
- ibm-midrange - 可以在 COBOL400 中读取 SQLView 吗?
- c++ - C++ 'std::bad_alloc' 什么():std::bad_alloc
- c# - 从 C# WPF 中的文件设置 FontFamily
- html - CSS 使用 div 作为掩码
- sql - 如何使用我的方案计算表中的总记录数
- basic - 我需要显示年份及其在该特定年份损失的价值
- sql - 选择语句中无法识别的列
- tensorflow - tf.fold vs tf.scan vs tf.map_fn