Search code examples
pythonfunctionif-statementrepeatcode-readability

How to simplify a repetitive function


Is there a way anyone can think of to simplify this function? I find much of this quite repetitive but having a hard time thinking of a way to make it more pythonic or cleaner. Relatively new to python, so I'd appreciate any recommendations.

def colorize(n):
    if n in range(0, 10):
        return selection[-1]
    elif n in range(10, 20):
        return selection[-2]
    elif n in range(20, 30):
        return selection[-3]
    elif n in range(30, 40):
        return selection[-4]
    elif n in range(40, 50):
        return selection[-5]
    elif n in range(50, 60):
        return selection[-6]
    elif n in range(60, 70):
        return selection[-7]
    elif n in range(70, 80):
        return selection[-8]
    elif n in range(80, 90):
        return selection[-9]
    elif n in range(90, 100):
        return selection[-10]
    else:
        return None

Solution

  • To get 1 for the range 0 to 10 and 2 for the range 10 to 20 you can use Python 3's floored integer division.

    x = n // 10 + 1
    

    You can then negate this and use this for your indexing

    def colorize(n):
        if 0 <= n < 100:
            return selection[-(n // 10 + 1)]
    

    If you do not return anything from a function it returns None, you do not explicitly have to return it