Home > front end >  Python doing addition without sum or numpy
Python doing addition without sum or numpy

Time:05-09

I am very very new in Python and I am trying to create a new list out of two lists when I add the two. But my code doesn't work. I cannot use sum or numpy.

For addition I wrote:

x=[24,54,84]
y=[2]

def addition(x,y):
    a=len(x)
    for i in range(a):
    x[i]=x[i] y
    return x[i]

print(addition(x,y))  

not sure what I am doing wrong.

CodePudding user response:

x=[24,54,84]
y=[2]

def addition(x,y):
    for i in range(len(x)):
        x[i]=x[i] y[0]
    return x

print(addition(x,y)) 

Two thing where wrong:

  1. Indent in the for item to loop (need to be spaced out to be in the for)

  2. return ends the function, so return the vector instead once the loop is over

  3. i made the correction as similar as I can to your code. This code rewrites x, so instead define another variable and return that variable if is what you want.

Things i changed:

  1. a is not necessary, can be put in the for the len itself

  2. i made the suposition that y is like a constant, you have defined it like a vector so i need to take the first item of the vector in each loop

EDIT: Here's the same code without modifing x, meaning you have a new vector in the addition function as you asked

x=[24,54,84]
y=[2]

def addition(x,y):
  temp = x.copy()
  for i in range(len(x)):
    temp[i] =x[i] y[0]
  return temp

print(addition(x,y)) 
print(x)
print(y)

CodePudding user response:

I'm not sure what you're asking for here. I'm assuming you want a new list with all the different ordered pairs of x and y added together. In your code, you're returning x[i] while in the for loop meaning it won't fully execute. On top of that, you're not creating a new list but changing the contents of x. Try running two loops and adding the sums to a new list, the original lists will remain unchanged.

EDIT: Oops sorry. At first glance I thought that the 'x[i]=x[i] y; return x[i]' were both indented into the loop hence my x[i] comment.

def addition(x, y):
  new_list = []
  for i in range(len(x)):
    for j in range(len(y)):
        new_list.append(x[i]   y[j])
  return new_list

CodePudding user response:

try this:

x=[24,54,84]
y=[2,5,6]

def addition(x,y):
    temp=x.copy()
    for i in range(len(y)):
        temp.append(y[i])
    return temp

print(addition(x,y))

Adding elements via append(), generating list "temp" so it isnt written into x. To write everything into x, y or other lists use x=addition(x,y).

If you want to add element for element: (Bothe Lists have to be the same length!)

def addition(x,y):
    temp=x.copy()
    for i in range(len(x)):
        temp[i]=x[i] y[i]
    return temp
  • Related