Home > Net >  List comprehension that involves summing values
List comprehension that involves summing values

Time:09-09

I was presented with a problem where I had to create an algorithm that takes any given input integer of even length and, based on the input, determines whether the sum of the first n digits is equal to the sum of the last n digits, where each n is the equal to the length of the number divided by two (e.g. 2130 returns True, 3304 returns False).

My solution, which works but is rather unwieldy, was as follows:

def ticket(num):
    list_num = [int(x) for x in str(num)] 
    half_length = int(len(list_num)/2)
    for i in range(half_length*2):
        first_half = list_num[0:half_length]
        second_half = list_num[half_length::]
    if sum(first_half) == sum(second_half):
        return True
    else:
        return False

In an effort to improve my understanding of list comprehensions, I've tried to look at ways that I can make this more efficient but am struggling to do so. Any guidance would be much appreciated.

EDIT:

Thank you to jarmod: Reorganised as so:

def ticket(num):
    list_num = [int(x) for x in str(num)] 
    half_length = int(len(list_num)/2)
    return sum(list_num[0:half_length]) == sum(list_num[half_length::])

ticket(1230)

CodePudding user response:

You can remove the unnecessary assignment and loops to create a shorter, more pythonic solution:

def ticket(num):
    half_length = int(len(list_num)/2)
    first_half = sum(list(num[:half_length]))
    second_half = sum(list(num[half_length:]))
    return first_half == second_half

It can be further shortened though, which isn't as readable:

def ticket(num):
    return sum(list(num[:len(num)//2])) == sum(list(num[len(num)//2:]))
  • Related