How can I test if a number is an integer without using type( )?


#1

Question

How can I test if a number is an integer without using type( )?

Answer

The instructions want us to not use the built in type() function to determine if the given number x is an integer or not. To do this, we’ll need to round the value given to us, and we can do that using one of two functions: ceil() or floor(), which are both available through the math module we learned about earlier.
We can do this because if we round a number and it’s different than our initial number, we know the number given was a float. For example, if we’re given 78.6 and we round it, we’ll have 79. The difference between the two is not 0, so we know we were given a float!


FAQ: Learn Python - Practice Makes Perfect - is_int
#2

Way without using additional modules.

def is_int(x):
  print x
  print int(x)
  if x==0:
    return True
  elif (x/int(x))==1:
    return True
  else:
    return False

#3

I totally forgot about those functions in the math module, So I just simply compared the x to what x would be if it’s an integer using int(x). If it doesn’t match then its a float or something else

def is_int(x):
  if x == int(x):
    return True
  else:
    return False

#4

I used modulo (which was in the previous lesson) - if it can be divided by 1 without a remainder, then it’s an integer ??:
def is_int(x):
if x % 1 == 0:
return True
else:
return False


#6

I have tried to reduce it down:

def is_int(x):
  return not bool(x%1)

For those that are interested. I have to note that i never coded in Python before (though in other languages); The function does what was requested. Be aware that if you feed Boolean values, the function still work, due to True===1 and False===0; Would be interesting to see how all these variants do in comparison, when feeding a list of millions.

Ah, by the way the version of cheecat works, but if you feed it negative numbers it tumbles from a division-by-zero–error.


How can I break down these problems into easier parts?
#9

For ex:
from math import * # for the program to understand what “floor” or “ceil” is. The functions aren’t build in by default
def is_int(x):
if floor(x)-x==0: #here you can use “ceil” instead of "floor"
return True
else:
return False


#10

I did the exact same. I thought that would be the best solution to the problem. It would take negatives and positive numbers no problem. I am not sure if I completely agree with the solution that they provide to be honest.


#11

This also seemed like the obvious and simplest solution to me, I’d like to see if someone can comment on if/how this is not the case, or why the described answer was chosen.


#12

May have something to do with it.

Another take on n mod 1
>>> def is_int(x):
    try:
        return not (x % 1)
    except TypeError:
        return "Not a Number"

>>> is_int('5')
'Not a Number'
>>> is_int(5)
True
>>> is_int(5.0)
True
>>> is_int(5.2)
False
>>> 

#13

So while it works when only ints or floats are entered, it will hit an error when confronted with a string, or give a false positive with a bool.


#14

No false positive. the type error is raised on any non-numeric inputs. The no-error return is purely numeric in nature and always correct.

We still should work out one of the prescribed solutions for the sake of due dilligence. ceil? or floor? It’s pretty much the same as above, just with a different function.

by floor
>>> from math import floor
>>> def is_int(x):
    try:
        return not (x - floor(x))
    except TypeError:
        return "Not a Number"

>>> is_int('5')
'Not a Number'
>>> is_int(5)
True
>>> is_int(5.0)
True
>>> is_int(5.2)
False
>>> 

#15

The solution code here doesn’t seem to use the ceil() or floor() functions.
I understand it for the most part, but wanted to find out exactly what is being ask for the conditional “if and” statement. So it asks “if typeCount and absoluteCount - roundCount = 0:”, does this mean if both are true? But what is a true value for type?

def is_int_sol(x):
    absoluteCount = abs(x)
    typeCount = type(x)
    roundCount = round(absoluteCount)
    if typeCount and absoluteCount - roundCount == 0:
        return True
    else:
        return False

#16

Integers are signed numbers from negative infinity to positive infinity. The abs() function has no place here.

Fuzzy logic with little no meaning. We are not supposed to be using the type() function, for starters, and in a conditional, it will always be True since it returns an object (<class 'int'>).

if x - round(x) != 0:
    return False

#17

That’s what I thought…this code came up and (a little annoyingly) replaced the code I had written for this exercise, when I requested the solution for a problem later on.


#18

In my function, what I did was compare the number X as an integer minus the number X as floating, and if it gives 0.0 then it is True


#19

It’s interesting to see how everyone else completed this exercise.

This worked fine with the given arguments,


def is_int(x):
if x - int(x) == 0:
return True
else:
return False


The given solution seems overly complex. Is there a reason for it?

please excuse my ignorance,

Thank you!


#20

Because we asked to not use the int() constructor so have to come up with some other method.

Not sure I’ve ever seen the given solution. Does it use the round() function? Or does it use the modulo operator (%)?


#21

This is what we’re given if we have the program fill in the solution.

On a side note, I double-checked my code replacing int() with ceil(), floor(), and round(). The logic remains the same, as do the results.


#22
def is_int_sol(x): 
    absoluteCount = abs(x) 
    typeCount = type(x) 
    roundCount = round(absoluteCount) 
    if typeCount and absoluteCount - roundCount == 0: 
        return True
    else: 
        return False

If the objective was simplicity, it is lost on me; and, probably many learners, too.

A quick solution can be got using floor().

from math import floor

def is_int(x):
    return x - floor(x) == 0

We don’t need to worry about the signs. The floor of a negative number is still negative.

The converse is,

def is_float(x):
    return x - floor(x) > 0

floor always moves leftward on the number line. ceil always moves to the right. round moves both directions but we still do not need absolute().

return x - round(x) == 0    # is integer
return x - round(x) != 0    # is float

Using ceil is pretty much the same…

from math import ceil

def is_int(x):
    return ceil(x) - x == 0

The thing about this lesson I believe the author wanted was for learners to do a little research to find as many different ways to accomplish this task as one could.

Take for instance exception handling. This one leverages the fact that floats cannot be interpreted as integer.

def is_int(x):
    try:
        return bin(x) and True
    except TypeError:
        return False

It smacks of using int() or type() but this will work…

return isinstance(x, int)

Cheap and dirty, anyway. My favorite is,

return not x % 1

No functions at work, at all. Just the logical not and the modulo operator. When the reader sees the not they know immediately that the return value is bool.

In my own view, this is not the naive solution and very rarely ever surfaces. I lean towards doubt when anyone posts this as their solution.

The simple truth (as I see it) is that a great many learners simply breeze through the lessons and not much sticks. When they get to the Practice Makes Perfect module it shows.


#24