Create x + xx + xxx + xxxx ... for the given integer (for 4 & # 8594; 4 + 44 + 444 ...)

I need to stepwise concatenate the given number at each iteration so that it returns the sum and concatenated string. This is my attempt:

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) 

return 11106

But I need to generate a sum for any given integer, so I need a loop, but I'm stuck.

Thanks!

+5
source share
8 answers

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 
+4
source

Given digit and n (for example, digit=4 and n=3 are 4 + 44 + 444 ), you just need to create a sequence of them 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) 
+5
source

There are several ways to do this. I will start with the solution that is most similar to yours, and if you want, I can introduce a quicker way :).

 def digit_sum_from_letters(digit,count): suma=0 cur=digit for _ in xrange(count): suma+=int(cur) cur+=digit return suma 
+2
source

Just for fun:

 def f(n): return n*int("123456789"[:n]) 

He gives:

 1 -> 1 2 -> 24 3 -> 369 4 -> 4936 5 -> 61725 6 -> 740736 7 -> 8641969 8 -> 98765424 9 -> 1111111101 
+2
source

Who told you you need a loop? Don't listen to them

 def fn(n): x,z = n,10 return x*(z*(z**n-1) // (z-1) - n) // (z-1) print(fn(1)) # 1 print(fn(2)) # 24 print(fn(3)) # 369 print(fn(4)) # 4936 

EDIT: It's a shame that they also require an expression string. In this part you should use the loop sad

+2
source

The next function will do, n is your number (4) m is the number of iterations (4, 44, 444, 4444, ...).

 def digit_sum_from_letters(n, m): sum = 0 # this is the multiplier. # throughout the iterations it will be 1, 11, 111, 1111 ... currMult = 1 for i in range(0,m): sum += n*currMult currMult = currMult*10 + 1 return sum 

Execution Example:

 >>> sumLetters(9,4 ) 11106 >>> 
+1
source
 def sum_n(x, n): s = 0 for i in range(1,n+1): s += int(('%d'*i) % tuple([x]*i)) return s In [0]: print(sum_n(9,4)) Out[0]: 11106 
+1
source

You can do this using list compression:

 x = 9 c = 4 sum([int(str(x) * i) for i in xrange(1,c + 1)]) 11106 
+1
source

Source: https://habr.com/ru/post/1239637/


All Articles