我需要像oct()Python一樣具有精確功能但不使用任何其他方法和函式的代碼。
我寫了這個,但我認為它太大了,而且我不想使用range和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))
uj5u.com熱心網友回復:
如果您希望它像內置的那樣作業oct(),則需要考慮零和負數。處理這個問題的更好方法是使用函式divmod()回傳整數除法和余數的結果。繼續這樣做直到值為零:
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))
uj5u.com熱心網友回復:
如果只需要在沒有oct()函式的情況下以八進制列印,字串格式可能是最簡單的選擇。
num = int(input("Enter a number: "))
print("{:o}".format(num))
輸出:
Enter a number: 10
12
這對于字串變數也是可能的
num = int(input("Enter a number: "))
s = "{:o}".format(num)
print(s)
輸出:
Enter a number: 10
12
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/358025.html
