【发布时间】:2013-05-31 16:03:36
【问题描述】:
我正在编写一个程序来使用欧几里得算法计算两个给定整数的最大公约数 (GCD)。输入包含两个正整数 x 和 y,由空格分隔。当输入 0 0 时,程序终止。我刚接触 Python,我绝对是编程的菜鸟,所以我的编码实践可能有点粗糙。我试图将计算出的 GCD 打印在与输入相同的行上。如何将该计算值打印到我输入两个整数的同一行?
输入完成后看起来像这样:
输入:
210 45 15
这就是我所能做的:
输入:
210 45
15
到目前为止,我有此代码用于 python 2.7:
def gcd (x, y): # Greatest Common Divisor function
if x > y:
r = x%y # r = x divided by y and gives the remainder
if r == 0: # if the division of x and y has no remainder, return y because y is the gcd.
return y #This is true because no number may have a divisor greater than the number itself (non-negative).
else:
return gcd(y, r) #if a = bt+r, for integers t and r, then gcd(x,y) = gcd(b,r)
if x < y:
x, y = y, x # value swapping
return gcd(x, y)
getinput = True
while(getinput):
#list created for storing user entered values
ssplit = []
s = raw_input('Input: \n ') # read a string of data, no evaluation by python
ssplit = s.split(' ') # read values between whitespace
x = int(ssplit[0]) # place value from raw_input() into list
y = int(ssplit[1])
if( x != 0 and y != 0 ): #tests to see if gcd needs to be evaluated
print (gcd (x, y))
else:
getinput = False # input was 0 0
【问题讨论】:
-
看来你忘了问问题 :)
-
没有一些极端的输出处理是不可能的。从docs.python.org/2/library/curses.html开始
-
也许我得重做这个。此外,我需要接受多行整数对。我可以继续手动将变量对添加到列表中,然后当输入 0 0 时,程序停止接收整数对并计算并打印存储在列表和 gcd 中的整数。
-
为了记录,这很难的原因是当你输入输入时,你用换行符终止了它。该换行符将您的光标向下移动到您的 终端 内,python 对此一无所知。你能在同一行打印输入然后输出吗?
-
如果你想要比 ncurses 更充实的东西,你可以看看 excess.org/urwid,这是一个很棒的模块,它提供了很好的 MVC ncurses 驱动的小部件。
标签: python python-2.7