2

If perfect division occurs between two numbers, I want the result to be converted into an integer but if perfect division does not occur between the two numbers, then no change should be made. For example, 6/2 gives the result 3.0. Since this is perfect division, the 3.0 should be converted into 3. On the other hand if I have 14/4, which gives result 3.5, it should stay as it is since perfect division has not occurred.

Here by perfect division I mean a divided by b yields an integer

Georgy
  • 12,464
  • 7
  • 65
  • 73
NePtUnE
  • 889
  • 1
  • 7
  • 10
  • You already have some solutions, but there are also some built-in functions which are described here, which might be useful: [How to convert a decimal number into fraction?](https://stackoverflow.com/questions/23344185/how-to-convert-a-decimal-number-into-fraction) – NewPythonUser Jun 09 '20 at 10:48

4 Answers4

2

This function checks if there is a remainder if you divide. If so, it's not an integer.

def divide_and_conquer(a, b):
    return a / b if a % b else a // b
0

Here is a step-by-step solution on how you can achieve that

# the numbers
num = 34
divisor = 17

# do the division
modula = num//divisor # modulus
quotient = num/divisor # normal division

# check if division is perfect
if modula  == quotient :
   result = int(quotient)
else:
   result = quotient
Edison
  • 870
  • 1
  • 13
  • 28
0

In python, you can use // to divide integers, and get an integer result. You can also use % to determine if two numbers divide perfectly (% returns the remainder, which is always zero if and only if the two numbers divide perfectly). To accomplish what you're asking, simply:

a = 6
b = 2
if a % b == 0:
  result = a // b
else:
  result = a / b

That said, you could also simply run the standard division and convert the result to an integer as well...

result = a / b
if result % 1 == 0:
  result = int(result)

However, in both of these cases, you might want to examine the broader context of what you're coding, because it can create real problems down the line if a variable is sometimes one data type, and other times a different data type - it might be best to leave the value as a float in every case until such time that you need for it to become an integer.

Note: Using '//' on two integers which do not divide perfectly will still result in an integer, as python will simply ignore the remainder. 6 // 4 = 1, 15 // 2 = 7.

Kyle Alm
  • 587
  • 3
  • 14
0

You can use // division to get an int:

def divide(a, b):
    return a / b if a % b else a//b

divide(2, 5)   # 0.4 (float)
divide(10, 5)  # 2 (int)
Basj
  • 41,386
  • 99
  • 383
  • 673