Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate x+xx+xxx+xxxx ... for a given integer (for 4 -> 4+44+444...)

Tags:

python

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!

like image 762
Claudiu Creanga Avatar asked Jan 01 '16 21:01

Claudiu Creanga


3 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
like image 83
Iron Fist Avatar answered Nov 12 '22 16:11

Iron Fist


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)
like image 21
chepner Avatar answered Nov 12 '22 17:11

chepner


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
like image 2
Untitled123 Avatar answered Nov 12 '22 17:11

Untitled123