如何相邻使用一个变量的多个实例?

2024-04-18 05:33:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我真的不知道如何更好地描述它,但我需要编写一个程序来回答这个问题:

Write a loop that computes the value of a + aa + aaa + aaaa with a given digit as the value of a.

有什么建议吗?在


Tags: ofthe程序loopthatvalueaswith
2条回答

我能想到的最短的

digit = "1"

result = sum([int("{}".format(digit * x)) for x in [1,2,3]])
print(result)
# 123

这会重复字符串(原文如此!)x次,将结果转换为整数,并将各部分相加为result。在

以下是一种使用(稍微复杂)列表理解的方法:

number = 1
length = 4
sum(int(str(number) * i) for i in range(1,length+1))

相关问题 更多 >