Reputation: 13349
For example If the list contains numbers 3 , 14 , 24 , 6 , 157 , 132 ,12 It should give the maximum no of digits as 3
Upvotes: 2
Views: 1487
Reputation: 71
The key is to treat the elements as strings so you can ask for their length or number of digits.
Some code
#Your list
L = [ 3 , 14 , 24 , 6 , 157 , 132 ,12]
# Imperative
max_digits = 0
for element in L:
n_digits = len(str(element))
if n_digits > max_digits:
max_digits = n_digits
# Funtional
max_digits = reduce(lambda x,y: x if x>y else y, map(lambda x: len(str(x)), L), 0)
Upvotes: 1
Reputation: 17263
In case your list contains negative numbers you could pass generator expression calling abs
as an argument for max
:
>>> mylist = [3, 14, 24, 6, 157, 132, 12, -100]
>>> len(str(max(abs(x) for x in mylist)))
3
Note that above only works with integers. If your list contains other types of numbers, like float
or Decimal
then changes are required.
Upvotes: 4
Reputation: 8945
The first requirement is to decide exactly what you mean by "number of digits." For example, -2.1352
contains ... how many digits? One? Five? Six? Seven? An argument could be made in favor of each of these.
Then, in the case of floating point numbers, there's the question of rounding. Float-binary is base-two which must be converted to base-ten at some number of digits' (decimal) precision. Is that number fixed? Would -2.3
(two digits? one? three?) be displayed as -2.3000
hence five digits (four? six?).
A "code golf" exercise like this can be tackled in any number of ways. Step-one is to hammer out exactly what you mean in your statement of the problem to be coded.
Upvotes: 2
Reputation: 1624
Try this
mylist = [3, 14, 24, 6, 157, 132, 12]
print (len(str(max([abs(element) for element in mylist]))))
#3
#This will work for negative numbers too
Upvotes: 4
Reputation: 359
"Try this
mylist = [3, 14, 24, 6, 157, 132, 12]
print (len(str(max(mylist)))
"
Sorry I would comment but < 50 rep. Credit to @soumendra
Soumendra's solution works but not for negative numbers. Easy way to do this is:
mylist = [3, 14, 24, 6, 157, 132, 12]
a = len(str(max(mylist)))
b = len(str(min(mylist)))
print max([a, b])
Upvotes: 1
Reputation: 3244
Just use :
len(str(max(list)))
what we are doing here finding the maximum number, then lenght of that.
Upvotes: 1
Reputation: 345
tempMaxDig = 0
for item in numList:
num = len(str(item))
if num > tempMaxDig:
tempMaxDig = num
return tempMaxDig
Upvotes: 1
Reputation: 1118
Try this:
max = list[0]
for i in range(1,len(list)):
if len(list[i]) > max:
max = len(list[i])
Upvotes: 1