循环中的平方数

2024-05-23 14:08:55 发布

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

我有个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}$

Tags: thenumberforthathereisprogrammax
3条回答

首先,对现有代码的最简单的更改是去掉嵌套循环。只要有for循环和一个if

for i in range(1, maximum+1):
    if i*i > maximum:
        break
    print(i*i)

或者只需执行while循环并手动递增:

^{pr2}$

有一件事:注意我用了range(1, maximum+1)?范围是半开的:range(1, maximum)给了我们所有到maximum的数字,我们需要包括maximum本身,以使所有到maximum平方的数字都是1。(这就是在while版本中使用<=而不是{}的相同原因。在


但让我们玩得开心点。如果你有所有的自然数:

numbers = itertools.count(1)

…你可以把它变成所有的方块:

squares = (i*i for i in numbers)

不要担心它们的数量是无限的;我们在计算它们,一旦通过maximum,我们就会停止:

smallsquares = itertools.takewhile(lambda n: n<=maximum, squares)

…现在我们有了一个很好的有限序列,我们可以打印出来:

print(*smallsquares)

或者,如果您更喜欢if all在一行(在这种情况下,您可能还喜欢from itertools import count, takewhile):

print(*takewhile(lambda n: n<=maximum, (i*i for i in count(1)))

但实际上,lambda表达式有点难看;也许(使用from functools import partialfrom operator import ge)它更易读:

print(*takewhile(partial(ge, maximum), (i*i for i in count(1)))
'''
Ask the user input a limit and
convert input string into integer value
'''
limit = int(input("Please input the limit: "))

'''
Extract the squre root of `limit`.
In this way we discard every number (i) in range [0, limit]
whose square number ( i * i ) is not in range [0, limit].
This step improves the efficiency of your program.
'''
limit = int(limit ** .5)

'''
`range(a, b)` defines a range of [a, b)
In order to exclude zero,
we assign `a = 1`;
in order to include `limit`,
we assign `b = limit + 1`;

thus we use `range(1, limit + 1)`.
'''
for i in range(1, limit + 1):
    print(i * i)

我认为while循环可能更适合这个问题。在

maximum = int(input("Max: "))

i = 1
while(i*i <= maximum):
   print(i*i) 
   i+=1

相关问题 更多 >