Python Forum

Full Version: calculation with list in list
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
hello. with this code i can calculate 1 + 2 + 3 = 6
l = [1,2,3,]
def suml(l):
  s= 0
  for i in l:
    s = s + i
  return s  


but what can i do if i want to calculate this list ( 1 + 2 +3 +( 1 + 2) = 9)
l = [1,2,3,[1,2]]
What have you thought about, or tried?
Somehow I have to use the def inside the def but I cant solve it . Or call the def repeatedly
You can try to flatten the nested lists first. There is a topic here about that.
Well I need the code to work for both lists. It has to calculate every list that you can give .
(Aug-08-2019, 06:43 PM)gianniskampanakis Wrote: [ -> ]Somehow I have to use the def inside the def but I cant solve it . Or call the def repeatedly

Do you have to use Recursion ?
No recursion is not needed. I study this exercise in order to give exams at university. Theoretically we have not learn yet recursion

The help note says: Write a sumL function that will calculate the sum of the elements of a list of numbers and call this function repeatedly.]
Γεια σου γιαννη






l = [1,2,3,[1,2]]

def suml(l, s=0):
    for i in l:
        if type(i) == int:
            s +=i 
        else:
            return suml(i, s)
    return s
l = [1,2,3,[1,2]]

def suml(l):
    s = 0 
    for i in l:
        if type(i) == int:
            s +=i 
        else:
            for t in i:
                s +=t      
    return s
This looks like recursion
Σε ευχαριστώ το type(i) εκτός από int τι τιμες μπορεί να πάρει στην περίπτωση μας ;
Pages: 1 2