Skip to content

Commit

Permalink
Added number.random_() method
Browse files Browse the repository at this point in the history
  • Loading branch information
bharadwajyarlagadda committed Oct 28, 2016
1 parent dc15a73 commit 36689f6
Show file tree
Hide file tree
Showing 6 changed files with 82 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ Changelog
- Add ``is_number()``.
- Add ``is_string()``.
- Add ``last()``.
- Add ``random_()``.


v0.1.1 (2016-10-10)
Expand Down
13 changes: 13 additions & 0 deletions docs/example.rst
Original file line number Diff line number Diff line change
Expand Up @@ -140,3 +140,16 @@ Arrays
>>> _.subtract([1, 2, 3], 4)
[1, 2, 3]
Numbers
-------

.. code-block:: python
>>> import sugar as _
>>> result = random_(5, 6)
>>> assert 5 <= result <= 6
>>> result = random_(5)
>>> assert 0 <= result <= 5
4 changes: 4 additions & 0 deletions sugar/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@
subtract
)

from .number import (
random_
)

from .predicates import (
is_array,
is_boolean,
Expand Down
2 changes: 1 addition & 1 deletion sugar/arrays.py
Original file line number Diff line number Diff line change
Expand Up @@ -516,7 +516,7 @@ def subtract(array, item):
return [element for element in array if element not in item]

#
# Utility methods not a part of the main API
# Helper methods not a part of the main API
#


Expand Down
46 changes: 46 additions & 0 deletions sugar/number.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# -*- coding: utf-8 -*-

from __future__ import absolute_import

import sys
import random
import math


def random_(n1=None, n2=None):
"""Returns a random integer/float from :attr:`n1` to :attr:`n2` (both
inclusive)
Args:
n1 (int/float/str): Value given by the user.
n2 (int/float/str): Value given by the user.
Returns:
int/float: Random integer/float value between :attr:`n1` and
:attr:`n2`.
Example:
>>> result = random_(5, 6)
>>> assert 5 <= result <= 6
>>> result = random_(5)
>>> assert 0 <= result <= 5
.. versionadded:: TODO
"""
n1 = 0 if not n1 else n1
n2 = 0 if not n2 else n2

n1 = float(n1)
n2 = float(n2)

max_value = max(n1, n2)
min_value = min(n1, n2)
diff = max_value - min_value

result = (random.random() * diff) + min_value

if diff <= 1 or (diff > 1 and math.ceil(result) > max_value):
return round(result, 2)
else:
return math.ceil(result)
17 changes: 17 additions & 0 deletions tests/test_number.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# -*- coding: utf-8 -*-

from .fixtures import parametrize

import sugar as _
import time


@parametrize('args', [
(0, 5),
(2, 5),
(-6, 0),
(5.5, 11.7),
(5.5, 6.5)
])
def test_random(args):
assert args[0] <= _.random_(*args) <= args[1]

0 comments on commit 36689f6

Please sign in to comment.