I’m having trouble putting two matrices together

Asked

Viewed 50 times

0

def matrizsomada(a, b):

    num_elementos_a = len(a)
    num_elementos_b = len(b)

    x = []

    for i in range(num_elementos_a or num_elementos_b):
       x.append([a[i],b[i]])

    return x

a = [1,2,3]
b = ['a','b','c','d','e']

print(matrizsomada(a,b))
  • I want you to return the output as [1,'a',2,'b',3,'c',’d','e'] ,but it’s giving the error
  • What mistake you’re making?

1 answer

2

Your iterator should scroll through the larger list. Also create two index protections that allow you to add in x only elements of a and of b whose index i be individually validated:

def matrizsomada(a, b):    
    x = []
    lenA = len(a)
    lenB = len(b)
    # a função max(lenA,lenB) retornará o maior valor entre lenA e lenB
    for i in range(max(lenA,lenB)): 
      if i < lenA: x.append(a[i]) # Só adiciona se índice i for menor que o comprimento de a 
      if i < lenB: x.append(b[i]) # Só adiciona se índice i for menor que o comprimento de b

    return x

a = [1,2,3]
b = ['a','b','c','d','e']

print(matrizsomada(a,b))

Code in Repl.it: https://repl.it/repls/PlumpAdvancedFields

Browser other questions tagged

You are not signed in. Login or sign up in order to post.