Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I improve this code?

# max_list = [83, 1350, 1, 100]
for i in range(len(max_list)):
     new_value = 1
     while new_value < max_list[i]:
          new_value *= 10
     max_list = new_value

What I'm doing is rounding numbers up to the closest, uhm, zero filled value? I'm not sure what it would be called. But basically, I want 83 -> 100, 1 -> 1, 1350 -> 10000, 100 -> 100. I tried using the round() function but couldn't get it to do what I wanted.

This does it but I thought it could be written in less lines.

like image 777
iceburn Avatar asked Dec 05 '22 02:12

iceburn


2 Answers

I'd do it mathematically:

from math import ceil, log10
int(pow(10, ceil(log10(abs(x or 0.1)))))
like image 200
danlei Avatar answered Dec 10 '22 10:12

danlei


def nextPowerOfTen(x):
  if x in [0, 1]:
     return x
  elif x < 1:
    return -nextPowerOfTen(abs(x))
  else:
    return 10**len(str(int(x) - 1))

>>> nextPowerOfTen(83)
100
>>> nextPowerOfTen(1350)
10000
>>> nextPowerOfTen(1)
1
>>> nextPowerOfTen(100)
100
>>> nextPowerOfTen(0)
0
>>> nextPowerOfTen(-1)
-1
>>> nextPowerOfTen(-2)
-10

It does something sensible with negatives, not sure if that is the behaviour you want or not.

like image 30
fmark Avatar answered Dec 10 '22 10:12

fmark