0

我正在编写一个程序来使用欧几里得算法计算两个给定整数的最大公约数(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
4

1 回答 1

0

如果您想摆脱诅咒,这可能会有所帮助。每次输入后它都会清理屏幕,但会记住旧的输出并重新绘制它。

import functools
import platform
import subprocess
import sys

def use_full_screen(question=None, history=None):
    if platform == 'win32':
        cls_cmd = 'cls'
    else:
        cls_cmd = 'clear'
    subprocess.call(cls_cmd)
    if history:
        print history
    if question is not None:
        return raw_input(question)


def make_screen(question, func, input_converter, max_repeat=9999):
    question += ': '
    def make_history(question, args, res):
        history = question[:-1]
        for arg in args:
            history += ' {}'.format(arg)
        history += ' {}'.format(res)
        return history

    def modfiy_input_converter(input_converter):

        @functools.wraps(input_converter)
        def converter(input_string):
            if input_string.strip() in ['exit', 'quit']:
                sys.exit(0)
            try:
                args = input_converter(input_string)
            except ValueError as err:
                msg = err.message
                msg += '\nInvalid input contine y/n: '
                cont = use_full_screen(msg,  history)
                if cont.strip() and cont in ['y', 'Y', 'yes', 'Yes']:
                    return converter(use_full_screen(question, history))
                sys.exit(0)
            return args
        return converter

    input_converter = modfiy_input_converter(input_converter)
    history = None
    args = input_converter(use_full_screen(question))
    res = func(*args)
    history = make_history(question, args, res)
    args = input_converter(use_full_screen(question, history))
    for _ in xrange(max_repeat):
        res = func(*args)
        history +='\n' + make_history(question, args, res)
        args = input_converter(use_full_screen(question, history))
    use_full_screen(history=history)

这是你的功能:

def gcd (x, y):
    """Greatest Common Divisor function"""
    if x > y:
         # r = x divided by y and gives the remainder
        r = x % y
        if r == 0:
            # if the division of x and y has no remainder, return y
            # because y is the gcd.
            # This is true because no number may have a divisor greater than
            # the number itself (non-negative).
            return y
        else:
             #if a = bt+r, for integers t and r, then gcd(x,y) = gcd(b,r)
            return gcd(y, r)
    elif x < y:
         # value swapping
        x, y = y, x
        return gcd(x, y)
    else:
        return x

您需要编写转换输入的函数:

def input_converter_gcd(input_string):
    try:
        values = tuple(int(x) for x in input_string.split())
    except ValueError:
        raise ValueError("Please enter integer numbers.")
    if len(values) != 2:
        raise ValueError(
            "Exactly 2 items needed but {:d} entered.".format(len(values)))
    return values

ValueError用说话的消息提出 a 。此消息将显示给用户。

最后启动程序:

question = 'Enter two numbers'
make_screen(question, gcd, input_converter_gcd, max_repeat=10)
于 2013-06-05T13:12:04.953 回答