我有个python问题:
Write a program that asks the user for a limit, and then prints out the sequence of square numbers that are less than or equal to the limit provided.
Max: 10
1
4
9
Here the last number is 9 because the next square number (16) would be greater than the limit (10).
Here is another example where the maximum is a square number:
Max: 100 1
4
9
16
25
36
49
64
81
100
但我不知道怎么做。到目前为止
maximum = int(input("Max: "))
for i in range(1, maximum):
但不知道如何处理这些数字并使之平方。在
谢谢
编辑:我有
^{pr2}$
首先,对现有代码的最简单的更改是去掉嵌套循环。只要有
for
循环和一个if
:或者只需执行
^{pr2}$while
循环并手动递增:有一件事:注意我用了}的相同原因。在
range(1, maximum+1)
?范围是半开的:range(1, maximum)
给了我们所有到maximum
的数字,我们需要包括maximum
本身,以使所有到maximum
平方的数字都是1。(这就是在while
版本中使用<=
而不是{但让我们玩得开心点。如果你有所有的自然数:
…你可以把它变成所有的方块:
不要担心它们的数量是无限的;我们在计算它们,一旦通过
maximum
,我们就会停止:…现在我们有了一个很好的有限序列,我们可以打印出来:
或者,如果您更喜欢if all在一行(在这种情况下,您可能还喜欢
from itertools import count, takewhile
):但实际上,lambda表达式有点难看;也许(使用
from functools import partial
和from operator import ge
)它更易读:我认为while循环可能更适合这个问题。在
相关问题 更多 >
编程相关推荐