Home > front end >  How does one sum 3 numbers in a list of 6 elements?
How does one sum 3 numbers in a list of 6 elements?

Time:09-24

For example, we have a 6-digit number, and we have to make a sum of 2 halves of it (say, 123456, we get 1 2 3 and 4 5 6). Here's the program I tried to write it for :

ticket = int(input("Input your ticket : ")) #ticket input
ticket_list = [int(i) for i in str(ticket)] #make a list
length = len(ticket_list)
mid = length//2
half1 = ticket_list[:mid] 
half2 = ticket_list[mid:] #split the list in two halves
def sum3digits1(mysum): #sum of 1st half
  mysum=0
  for i in range(half1):
    mysum =int(i)
  return mysum
def sum3digits2(suma): #sum of 2nd half
  suma=0
  for i in range(half2):
    suma =int(i)
  return suma
a = sum3digits1(ticket_list) 
b = sum3digits2(ticket_list)
print(a, b)

However, it shows my program got an error, but I really dunno what's the fix supposed to be. I tried using range() for sum of 3 elements, but it didn't work out quite well. Any help will be appreciated!

CodePudding user response:

Since you already got examples that should work i'll just add an explanation: range() is going to give you all numbers between two numbers. (take a look at https://www.w3schools.com/python/ref_func_range.asp) if you give it just one argument its going to start with 0 and try to give you every number (in a standard interval of one, unless you specify otherwise) up to the number you gave it (not it though). But you gave it a list of numbers instead of the number it expected.

Also just as a proposal, may i suggest that you don't repeat your self in your code: For example sum3digits1 and sum3digits2 are the same function so you could just name it sum3digits or perhaps even sum_digits and reuse it. :-)

CodePudding user response:

Try this:

def sum_half(lst):
    return sum(lst[:len(lst)//2]), sum(lst[len(lst)//2:])

Output:

>>> ticket_list = [1,2,3,4,5,6]
>>> sum_half(ticket_list)
(6, 15)
  • Related