我是编程的新手。在那里直接射击那一个。现在我要列出三个代码模块:
def GCD(x,y):
#gives the Greatest Common Divisor of two values.
while y != 0:
r = x
while r >= y: #these two lines are used to
r -= y #calculate remainder of x/y
x = y
y = r
print x
这是我写的原始程序,基于欧几里德算法的GCD。它功能正常。我现在想要删除上面的两个注释行,并用调用我做的另一个模块替换它,它计算余数:
剩余计算器
def xy(x, y):
#Gives the remainder of the division of x by y. Outputs as r.
while x >= y:
x -= y
r = x
此程序也可正常运行。 我想在我编辑的程序中使用名称'r'的值。我试图在下面这样做,但它会导致问题:
def GCD(x,y):
import remainder
#gives the Greatest Common Divisor of two values.
while y != 0:
remainder.xy(x,y)
from remainder import r #here is the problem. This line is my attempt at
#importing the value of r from the remainder calculating
#module into this module. This line is incorrect.
x = y
y = r #Python cannot find 'r'. I want to use the value for 'r' from the execution
#of the remainder calculating module. Attempts to find how have been
#unsuccessful.
print x
我需要了解如何在我的第二个GCD模块中使用我的xy模块中的'r'计算值。我尝试过使用
global r
在我的模块中,虽然我没有成功。我不确定我是否正确地解释了'全球'的功能。
感谢您的帮助。
Jet Holt
答案 0 :(得分:0)
如果我理解正确的话:
from remainder import xy
def GCD(x,y):
#gives the Greatest Common Divisor of two values.
while y != 0:
r = xy(x,y)
x = y
y = r
print x
和
def xy(x, y):
#Gives the remainder of the division of x by y. Outputs as r.
while x >= y:
x -= y
return x