簡體   English   中英

在與輸入相同的行上打印輸出

[英]print the output on the same line as the input

我正在編寫一個程序,使用歐幾里得算法來計算兩個給定整數的最大公約數(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

如果您想逃脫詛咒,這可能會有所幫助。 每次輸入后,它都會清理屏幕,但會記住舊的輸出並重新繪制它。

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消息ValueError 該消息將顯示給用戶。

最后啟動程序:

question = 'Enter two numbers'
make_screen(question, gcd, input_converter_gcd, max_repeat=10)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM