Reputation: 161
Given an integer. for each individual digit that is greater than 4, i need to add it to all the next digits that greater than 4. For example: a = 4567; the result should be 0 + (5) + (5+6) + (5+6+7) = 34 So far in my code, I was able to get the sum for single digit only. If the integer is greater 10, it will only give the sum of the very first digit. Any idea why this happening?
def morethanfour(number):
num = 0
num = [int(d) for d in str(number)] #seperate into individual digit
total = 0
for i in range (len(num)):
if num[i] > 4:
total = sum(x for x in range(5, num[i]+1)) #adding the sum
return total
num = 9
print(morethanfour(num))
the result when num = 9 is 35 (5+6+7+8+9) However, when num = 178, it gave me 0
Upvotes: 0
Views: 950
Reputation: 18018
Try this:
>>> def morethanfour(number):
return sum(sum(range(5,x+1)) for x in map(int,str(number)) if x>4)
>>> morethanfour(9)
35
>>> morethanfour(4567)
34
>>> morethanfour(178)
44
Upvotes: 2
Reputation: 799230
>>> sum(sum(num[j] for j in range(0, i+1) if num[j] > 4) for i in range(len(num)))
34
Upvotes: -1