Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

List comprehension that involves summing values

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)

>Solution :

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:]))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading