Home > Software engineering >  Implement division as a series of subtraction - Python
Implement division as a series of subtraction - Python

Time:12-11

I'm trying to implement Division as a series of substractions. For example: 10/2 => 10-2-2-2-2-2=0, 10 minus 2 five times, with a remainder of 0.

I have done this with a while loop which seems appropiate for the task. However, I also tried to implement with a for loop. The following is my while loop.

#Trying a while loop
numerator = 20
denominator = 4
results = []
 
while numerator >= denominator:
    numerator = int(numerator) - int(denominator)
    remainder = numerator  
    results.append(remainder)
    print ('The remainder is:', remainder)
    print(results)
else: 
    print ('Numerator must be bigger than denominator') # if the numerator is less than the denominator

I'm experiencing some issues with my for loop. I had to use a list comprehension to rule out any negative numbers within range(denominator, numerator 1 (using 1 so it can take the full value of the numerator). It seems that the operation numerator = int(numerator) - int(denominator) keeps going into the negatives. If you print the below you will get [16, 12, 8, 4, 0, -4, -8, -12, -16, -20, -24, -28, -32, -36, -40, -44, -48]. If you uncomment the list comprehension you will get [16, 12, 8, 4, 0] (which is what I want) I would like to understand why this range keeps going into negatives.

numerator = 20
denominator = 4


if numerator >= denominator:
  results=[]
  for i in range(denominator, numerator 1):
    numerator = int(numerator) - int(denominator)
    results.append(numerator)
  print(results)
  #   filter_negative = [i for i in results if i >=0]
  # print('The results are:', filter_negative)
  # print('The remainder is:', filter_negative[-1] )
else:
    print('Numerator must be bigger than denominator')

Thank you all !

CodePudding user response:

the range(denominator, numerator 1) in your example gives you an iterable from 4 to 21; this means that the denominator will be subtracted from the numerator (21-4) = 17 times that's why you have 17 values in output [16, 12, 8, 4, 0, -4, -8, -12, -16, -20, -24, -28, -32, -36, -40, -44, -48].

But if you want to use a loop for to solve this problem you have to do it as follows:

numerator = 20
denominator = 4
if numerator >= denominator:
  results=[]
  for i in range(0, numerator//denominator):
    numerator = int(numerator) - int(denominator)
    results.append(numerator)
  print(results)
else:
    print('Numerator must be bigger than denominator')
    

CodePudding user response:

What you're trying to do is essentially what the range function does, you can get the pattern you want by using a negative step with the denominator:

>>> a = range(numerator, -1, -denominator)
>>> print( list(a) )
[20, 16, 12, 8, 4, 0]

>>> print( list(a)[1:] ) # To exclude the first value
[16, 12, 8, 4, 0]
  • Related