Home > Net >  This is the sum problem between the elements in the list. Why does "None" come out?
This is the sum problem between the elements in the list. Why does "None" come out?

Time:10-06

def add(t1, t2):
if len(t1) == len(t2):
    for i in range(len(t1)):
        [t1[i] t2[i]]
elif len(t1) != len(t2):
    return None

t1 = [42, 1024, 23]
t2 = [6, 28, 496]
t3 = add(t1, t2)
print(t1)
print(t2)
print(t3)

The problem of elements in the list is too difficult for me. Please give me a little help.

CodePudding user response:

For a list of pairwise sums, you can modify your code as follows:

def add(t1, t2):
    if len(t1) == len(t2):
        result = []
        for i in range(len(t1)):
            result.append(t1[i] t2[i])
        return result
    else:
        return None

Of course, there are utils that make this shorter:

def add(t1, t2):
    if len(t1) == len(t2):
        return [*map(sum, zip(t1, t2))]
    # None returned implicitly

This built-in-ladden code can be interpreted as "map the sum function onto the pairs produced by zip and unpack the resulting sums into a list".

See some documentation:

CodePudding user response:

Try this by returning from if statement.

def add(t1, t2):
    if len(t1) == len(t2):
        return [(t1[i]   t2[i] ) for i in range(len(t1)) ]
    
    return None

CodePudding user response:

or be short:

def add(t1, t2):
    return [sum(i) for i in zip(t1, t2)] if len(t1) == len(t2) else None

or even shorter:

def add(*x):
    return [*map(sum, zip(*x))] if set(map(len, x)) == 1 else None
  • Related