change base python

Solutions on MaxInterview for change base python by the best coders in the world

showing results for - "change base python"
Samia
14 Aug 2017
1>>>import numpy as np
2>>>np.base_repr(10, base=3)
3'101'
4
Blanche
27 Jun 2018
1def base_repr(number, base=2, padding=0):
2    """
3    Return a string representation of a number in the given base system.
4    Parameters
5    ----------
6    number : int
7        The value to convert. Positive and negative values are handled.
8    base : int, optional
9        Convert `number` to the `base` number system. The valid range is 2-36,
10        the default value is 2.
11    padding : int, optional
12        Number of zeros padded on the left. Default is 0 (no padding).
13    Returns
14    -------
15    out : str
16        String representation of `number` in `base` system.
17    See Also
18    --------
19    binary_repr : Faster version of `base_repr` for base 2.
20    Examples
21    --------
22    >>> np.base_repr(5)
23    '101'
24    >>> np.base_repr(6, 5)
25    '11'
26    >>> np.base_repr(7, base=5, padding=3)
27    '00012'
28    >>> np.base_repr(10, base=16)
29    'A'
30    >>> np.base_repr(32, base=16)
31    '20'
32    """
33    digits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
34    if base > len(digits):
35        raise ValueError("Bases greater than 36 not handled in base_repr.")
36    elif base < 2:
37        raise ValueError("Bases less than 2 not handled in base_repr.")
38
39    num = abs(number)
40    res = []
41    while num:
42        res.append(digits[num % base])
43        num //= base
44    if padding:
45        res.append('0' * padding)
46    if number < 0:
47        res.append('-')
48    return ''.join(reversed(res or '0'))