#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    100
    Rep Power
    2

    Can this code be made more efficient?


    You know, fewer lines of code to get the same job done.
    Code:
    # Redefining the round function of Python
    def rounder(number):
        """
        round(number) -> number
    
        Equivalent to the round built-in function.
        Round a number to a given precision in decimal digits (default 0 digits).
        This returns an int when called with one argument, otherwise the
        same type as the number.
    
    """
        
        if isinstance(number, int): return number
        elif isinstance(number, float):
            number = str(number)
            position = number.find('.')
            position1 = number[position + 1]
    
            if int(position1) >= 5:
                return int(float(number) + 1)
            else:
                return int(float(number))
        else:
            return ('Wrong Input')
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    114
    Rep Power
    3
    One-liner.
    Code:
    def my_round(num):
        return int(num) + int(2 * (num - int(num)))
    Last edited by Nyktos; May 5th, 2013 at 04:38 AM.
  4. #3
  5. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,841
    Rep Power
    480
    I had planned to compare the running time of the codes in posts 1 and 2. Instead discovering that the proposed replacement for round takes only 1 argument and does not comply with the description in its own doc string.

    Originally Posted by Akshat1
    rounder(number)

    Originally Posted by http://docs.python.org/3/library/functions.html#round
    round(number[, ndigits])
    [code]Code tags[/code] are essential for python code and Makefiles!
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    100
    Rep Power
    2
    Originally Posted by Nyktos
    One-liner.
    Code:
    def my_round(num):
        return int(num) + int(2 * (num - int(num)))
    Jesus Christ!
    Genus!
    Thanks
  8. #5
  9. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    194
    Rep Power
    2
    What b49 was referring to is the fact that neither of these solutions (nor the def signature of the function) take into account that the doc string for the function says:
    Round a number to a given precision in decimal digits (default 0 digits).
    In other words neither of these emulate the functionality of the builtin round (which is supposedly the goal of the assignment).

    -Mek

IMN logo majestic logo threadwatch logo seochat tools logo