Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 The difference between two functions
I am a newbie to python and going through the NLTK book to learn a bit about using python for natural language processing. This post is not about NLTK, but about the difference in object classes that occur in the following two functions:

The first function is used to find the percentage of times that a single word occurs within the body of a text:

def percent1(text, word):
    a = text.count(word) #counts the number of 'words' (items) in the list (i.e. text)
    b = len(text)
    perc = a / b 
    print(f"{perc} %")
    #an example of the output of this function is: 7.2385e-05%
The second function does the same thing, except it returns the output as a decimal:

def percent2(text, word):
    from decimal import Decimal
    a = text.count(word)
    b = len(text)
    perc = Decimal(a / b)
    output = round(perc, 8) #rounds the variable perc to the 8th decimal place
    print(f"{output} %")
    #an example of the output of this function 
    #(from the same text) is: 0.00007285%
In trying to understand the difference between floats and integers, my question is this: Does the first function return a float (floating point integer?) while the second function returns a decimal integer? Would stating it that way be correct? (My apologies, I'm brushing up on math while coding, but I am not the most adept with such terminology) All thoughts and considerations are appreciated.
division of two integers returns a float
>>> a = 6
>>> b = 3
>>> c = a/b
>>> print(f"type(a): {type(a)}, type(b): {type(b)}, type(c): {type(c)}")
type(a): <class 'int'>, type(b): <class 'int'>, type(c): <class 'float'>
Yes. You can always use the type function to test that.
Examples (Out[10] is the output for the line of code above it):
from decimal import Decimal

Out[10]: 0.4

Out[11]: float

Out[12]: Decimal('0.40000000000000002220446049250313080847263336181640625')

Out[13]: decimal.Decimal

Out[14]: 0

Out[15]: int


Top Page

Forum Jump:

Users browsing this thread: 1 Guest(s)