Home > Blockchain >  how to subtract elements within an array using for loops in python
how to subtract elements within an array using for loops in python

Time:01-30

I have an array a = [4,3,2,1] What I am trying to achieve is that I need a single value on subtracting the elements in the array that is 4-3-2-1.

I tried the below this using for loop but it does not seem to work. I don't seem to get the right value on execution.

def sub_num(arr):
    difference = arr[0]
    n = len(arr)
    print(n)
    print(i)
    for i in n: difference = arr[n] - arr[n-1]
    return(difference)

CodePudding user response:

If you have a list a:

a = [4, 3, 2, 1]

And wish to get the result of 4 - 3 - 2 - 1, you can use functools.reduce.

>>> from functools import reduce
>>> a = [4, 3, 2, 1]
>>> reduce(int.__sub__, a)
-2
>>>

CodePudding user response:

You can solve with nested lists:

b = sum([a[0],*[-x for x in a[1:]]])

Simpler solution without for:

Since 4-3-2-1 is equal to 4-(3 2 1):

a[0]-sum(a[1:])

CodePudding user response:

You could modify your code like this

def sub_num(arr):
    difference = arr[0]
    n = len(arr)
    print(n)
    for i in range(1,n): 
        difference = difference - arr[i]
    return difference

Note:

  1. Printing value of i without defining it is not possible
  •  Tags:  
  • Related