python - 为给定的整数生成 x+xx+xxx+xxxx ...(对于 4 -> 4+44+444...)

标签 python

我必须在每次迭代中递增地连接给定的数字,以便它返回一个总和和连接的字符串。这是我的尝试:

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) 

返回 11106
但是我需要为任何给定的整数生成总和,所以我需要一个循环,但我被卡住了。

谢谢!

最佳答案

给定 digitn (例如, digit=4n=34 + 44 + 444 ),您只需要生成一个 1 的序列,并将其总和乘以 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)

关于python - 为给定的整数生成 x+xx+xxx+xxxx ...(对于 4 -> 4+44+444...),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34560006/

相关文章:

python - python 中的累加器

python - 如何使用 python-libtorrent 获取 torrent 的对等列表?

python - replaceWith() 后的 find() 不起作用(使用 BeautifulSoup)

python - 通过 CGI (Python) 运行 sudo 命令

python - Plotly:如何使用按钮以交互方式设置热图色标?

python - PySpark : Setting Executors/Cores and Memory Local Machine

python - 向 tkinter 小部件添加标签会更改整个布局

python - 如何在 python 中渲染 3D 直方图?

python - Cython 和 numpy 速度

Python itertools.groupby 长度键?