我怎样才能重构这个for循环以遵守DRY原则?

时间:2018-03-10 06:44:23

标签: python dry

如何在不重复注释行的情况下保留下面代码的功能?

def my_round(number, place=10):
    digit_list = [digit for digit in str(number)]
    rounded_number = ''
    round_list = [10 ** i for i in range(10)]
    zeros = str(place).count('0')

    for i in round_list:
        if (place == i):
            if int(digit_list[-zeros]) >= 5:
                for x in range(-zeros, 0):                # <- These 
                    digit_list[x] = '0'                   # <-
                rounded_number = int(''.join(digit_list)) # <-
                rounded_number += i
            else:
                for x in range(-zeros, 0):                # <- Repeat...
                    digit_list[x] = '0'                   # <-
                rounded_number = int(''.join(digit_list)) # <-

    return rounded_number

print(my_round(56, 10))

我是Python和编程的新手。这也是我关于Stackoverflow的第一个问题,但是不要犹豫,告诉我在Python中提问或编码时我能做得更好!

我渴望学习!

2 个答案:

答案 0 :(得分:0)

删除重复的一般方法是定义一个函数。这甚至可以在另一个函数内完成:

def my_round(number, place=10):
    digit_list = [digit for digit in str(number)]
    rounded_number = ''
    round_list = [10 ** i for i in range(10)]
    zeros = str(place).count('0')

    def round_inner():
        for x in range(-zeros, 0):
            digit_list[x] = '0'
        return int(''.join(digit_list))

    for i in round_list:
        if (place == i):
            if int(digit_list[-zeros]) >= 5:
                rounded_number = round_inner()
                rounded_number += i
            else:
                rounded_number = round_inner()

    return rounded_number

在您的情况下,有一种更简单的方法:

def my_round(number, place=10):
    digit_list = [digit for digit in str(number)]
    rounded_number = ''
    round_list = [10 ** i for i in range(10)]
    zeros = str(place).count('0')

    for i in round_list:
        if (place == i):
            round_up = int(digit_list[-zeros]) >= 5
            for x in range(-zeros, 0):
                digit_list[x] = '0'
            rounded_number = int(''.join(digit_list))

            if round_up:
                rounded_number += i

    return rounded_number

答案 1 :(得分:0)

不确定您的示例是否故意复杂化,但如果不是,您可以将其全部替换为:

def my_round(number, place=10):
    return int(round(float(number) / place) * place)