Home > database >  Code that have exact function like oct() in Python
Code that have exact function like oct() in Python

Time:11-14

I need code that have exact function like oct() in Python but without using any other methods and functions.
I wrote this, but I think it's so large and also I don't want use range and len:

def get_oct(x):
    next_step = [x]
    r_mod = []
    while True:
        x /= 8
        i = int(x)
        next_step.append(i)
        if int(x / 8) == 0:
            break
    for m in range(len(next_step)):
        next_step[m] %= 8
        j = int(next_step[m])
        r_mod.append(j)
    t_mod = r_mod[::-1]
    return "0o"   "".join(str(e) for e in t_mod)

entry = int(input("Enter a number: "))
print(get_oct(entry))

CodePudding user response:

If you want this to work like the built-in oct(), you need to account for zero and negative numbers. A nicer way to deal with this is to use the function divmod() the returns the result of integer division and the remainder. Just keep doing that until the value is zero:

def get_oct(x):
    if x == 0: return '0o0'
    prefix = '-0o' if  x < 0 else '0o'
    x = abs(x)
    res = ''
    while x:
        x, rem = divmod(x, 8)
        res = str(rem)   res
        
    return (prefix   res)

assert(get_oct(80) == oct(80))
assert(get_oct(1) == oct(1))
assert(get_oct(0) == oct(0))
assert(get_oct(-2) == oct(-2))
assert(get_oct(-201920) == oct(-201920))
assert(get_oct(12345678910) == oct(12345678910))

CodePudding user response:

If all that is needed is to print in octal without oct() function,string formatting could be the easiest option.

num = int(input("Enter a number: "))
print("{:o}".format(num))

Output:

Enter a number: 10
12

This is also possible with string variable

num = int(input("Enter a number: "))
s = "{:o}".format(num)
print(s)

Output:

Enter a number: 10
12
  • Related