Click here to Skip to main content
15,889,216 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am finding it difficult to store the first value, which is dynamically passed through a function.

I tried using the below code but the first value as shown will store -3(expected value 3) as the logic "subtraction-=i" will calculate 0-first value which will be negative.Please help me with the right process to follow.

Similarly,logic for division

Thanks.

What I have tried:

Python
subtraction = 0
def sub(*x):
    l2 =list(x)
    l2.sort(reverse=True)
    sortedValue = l2
    for i in sortedValue:
        global subtraction
        subtraction-=i  #first parameter should not change.but here the value becomes negative
    print("Subtraction of numbers{0} = ".format(sortedValue),subtraction)
    return subtraction

SubtractionResult = sub(20,2,5)
Posted
Updated 18-Jan-18 3:02am
v6

1 solution

Python
Subtraction = 0
def sub(*x):
    l2 =list(x)
    l2.sort(reverse=True)
    sortedValue = l2
    for i in sortedValue:
        global subtraction

You have two different spellings: Subtraction and subtraction
 
Share this answer
 
Comments
codeXprojectX 18-Jan-18 5:32am    
Thanks for the reply Richard.Still,output remains the same..(subtraction-=i does subtraction = 0-i). I want to have my first value intact not a negative integer. This should work perfect when there are 'n' number of values passed in a function call.

If def(20,2,5) is passed the temp variable(subtraction) should iterate like
subtraction = 20/2 -- 10
subtraction = 10/5 -- 2

finally returning value 2
Richard MacCutchan 18-Jan-18 5:38am    
I ran your original code and it correctly returned the value -4, by doing repeated subtractions. Where does the division come from?
codeXprojectX 18-Jan-18 6:08am    
Sorry,that was by mistake.

when function sub(20,2,5) is called, after repeated subtractions,my expected result is 13.

like subtraction = 18(20-2) and then subtraction = 13 (18-5)

But with the above code it returns value -27 when function sub(20,2,5) is called
Richard MacCutchan 18-Jan-18 6:41am    
Yes, -27 is the correct answer. Your code starts with a value of 0 and repeatedly subtracts each number from that value. If you want some other calculation then your code needs to be changed. Why do you need the list sorted in reverse order?
codeXprojectX 18-Jan-18 9:06am    
I understand that code has to be changed. Like mentioned in my previous comment,my expected output is different.I wanted to know what changes in my code will result in getting the desired result.. like temp=param1-param2 and then temp = param3-temp.

I want the subtracted value of three parameters passed..20-2-5 resulting 13 after iterating.

Thanks

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900