0

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)
2
  • just basic subtraction of numbers , in this case the answer shoud be -1 Commented Jan 30, 2022 at 6:05
  • Should not 4 - 3 - 2 - 1 be -2? Commented Jan 30, 2022 at 6:07

3 Answers 3

3

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
>>>
Sign up to request clarification or add additional context in comments.

Comments

0

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:])

1 Comment

This would be better with some elaboration as to how and why this works.
-1

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

1 Comment

thanks you all fot the help. was able to solve my issue

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.