Reputation: 51
I intend writing a function which i can use to sum up all numbers of an list having two digit. for example :
a=[1,2,11,100,10]
should return 21 since 11 and 10 of the list are having two digits
i also want the range of number to be (0,1,2,...100000)
def solution(A):
for integer in A:
if integer > 9 and integer <100:
two_digits_array.append(integer)
return sum( two_digits_array )
I guess it was alright, so on testing :
Example test: numbers= [47, 1900, 1, 90, 45]
print (solution(numbers))
wow it works perfectly and returns 182
but i tried these :
q= [1, 1000, 80, -91]
WRONG ANSWER (got 80 expected -11)
how can i go about it please and why the failure.
Upvotes: 1
Views: 78
Reputation: 1653
You can use len() for calculating the no of digits:
ans=0
for i in a:
if(len(str(abs(i)))==2:
ans+=i
return ans
Upvotes: 1
Reputation: 80
Please use this updated script
def solution(A):
for integer in A:
if (integer > 9 and integer < 100) or (integer > -100 and integer < -9):
two_digits_array.append(integer)
return sum( two_digits_array )
Upvotes: 2
Reputation: 477437
Why making it so hard? You can simply use a generator with a filter and pass that generator to the sum(..)
builtin. Like:
def solution(A):
return sum(x for x in A if -100 < x < -9 or 9 < x < 100)
Or as @PawełKordowski suggests, use abs(..)
to make the condition more elegant:
def solution(A):
return sum(x for x in A if 9 < abs(x) < 100)
No need to declare an additional array (that will only consume memory).
The <expr> for <var> in <iterable> if <condition>
is a generator: it generates lazily a sequence of numbers by applying <expr>
on the <var>
for every element in <iterable>
if the <condition>
is met.
Upvotes: 4
Reputation: 1226
Try this
print sum(filter(lambda x: (x<100 and x>9) or (x>-100 and x<-9), a))
assuming a is the list.
Upvotes: 2
Reputation: 331
You are checking for the numbers greater than 9 and less than 100. Try this:
if integer > 9 and integer <100 or integer > -100 and integer < -9:
Upvotes: 1