无法对 Python 中的非正方形整数进行编码
Unable to code for non-squares integers in Python
如何创建一个代码来打印出所有小于 100 且不是任何整数的平方的整数?
例如,3^2=9 不打印,但 30 应该打印。
我已经设法打印出平方值,但不确定如何打印出不是正方形的值。
这是我的代码:
for i in range(1,100):
square = i**2
print(square)
您可以将整数的平方存储到数组中。
squares =[]
for i in range(1,100):
squares.append(i**2)
j = 0
for k in range(1,100):
if k==squares[j]:
j=j+1
elif k>squares[j]:
print(k)
j=j+1
else:
print(k)
您可以通过多种方式编写此代码。我想你可以在这里使用两个 for 循环来让你更容易。我正在使用评论,以便您作为新手更好地理解。您可以从这两个中选择一个您认为更容易理解的:
list_of_squares = [] #list to store the squares
for i in range(1, 11): #since we know 10's square is 100 and we only need numbers less than that
square = i ** 2
list_of_squares.append(square) #'append' keeps adding each number's square to this list
for i in range(1, 100):
if i not in list_of_squares: #'not in' selects only those numbers that are not in the squares' list
print(i)
或者
list_of_squares = []
for i in range(1, 100):
square = i ** 2
list_of_squares.append(square)
if square >= 100: #since we only need numbers less than 100
break #'break' breaks the loop when square reaches a value greater than or equal to 100
for i in range(1, 100):
if i not in list_of_squares:
print(i)
如何创建一个代码来打印出所有小于 100 且不是任何整数的平方的整数?
例如,3^2=9 不打印,但 30 应该打印。
我已经设法打印出平方值,但不确定如何打印出不是正方形的值。
这是我的代码:
for i in range(1,100):
square = i**2
print(square)
您可以将整数的平方存储到数组中。
squares =[]
for i in range(1,100):
squares.append(i**2)
j = 0
for k in range(1,100):
if k==squares[j]:
j=j+1
elif k>squares[j]:
print(k)
j=j+1
else:
print(k)
您可以通过多种方式编写此代码。我想你可以在这里使用两个 for 循环来让你更容易。我正在使用评论,以便您作为新手更好地理解。您可以从这两个中选择一个您认为更容易理解的:
list_of_squares = [] #list to store the squares
for i in range(1, 11): #since we know 10's square is 100 and we only need numbers less than that
square = i ** 2
list_of_squares.append(square) #'append' keeps adding each number's square to this list
for i in range(1, 100):
if i not in list_of_squares: #'not in' selects only those numbers that are not in the squares' list
print(i)
或者
list_of_squares = []
for i in range(1, 100):
square = i ** 2
list_of_squares.append(square)
if square >= 100: #since we only need numbers less than 100
break #'break' breaks the loop when square reaches a value greater than or equal to 100
for i in range(1, 100):
if i not in list_of_squares:
print(i)