I have to incrementally concatenate a given number on each iteration so that it returns a sum and the concatenated string. This is my try:
def digit_sum_from_letters(x):
a = int("%s" % x)
b = int("%s%s" % (x,x))
c = int("%s%s%s" % (x,x,x))
d = int("%s%s%s%s" % (x,x,x,x))
return a+b+c+d
print digit_sum_from_letters(9)
returning 11106
But I need to generate the sum for whatever given integer so I need a loop but I'm stuck.
Thanks!
This should work:
>>> def digit_sum(x):
lst = [str(x)*i for i in range(1,x+1)]
print '+'.join(lst)
return sum(map(int, lst))
>>> digit_sum(7)
7+77+777+7777+77777+777777+7777777
8641969
>>> digit_sum(9)
9+99+999+9999+99999+999999+9999999+99999999+999999999
1111111101
>>> digit_sum(3)
3+33+333
369
Given digit
and n
(for example, digit=4
and n=3
is 4 + 44 + 444
), you just need generate a sequence of ones, and multiply its sum by digit
.
digit = 4
n = 3
# 1, 11, 111
ones = [ int("1" * i) for i in range(1, n+1)]
# 4 + 44 + 444 = 4 * (1 + 11 + 111)
answer = digit * sum(ones)
There's a couple of ways to do this. I'll start with the solution most similar to yours, and if you want I can introduce a likely faster way :).
def digit_sum_from_letters(digit,count):
suma=0
cur=digit
for _ in xrange(count):
suma+=int(cur)
cur+=digit
return suma
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With