我有一个矩形的三个顶点,需要找到第四个顶点,我需要为 N 个矩形找到缺失的顶点。
遗憾的是,我不知道如何在第一个矩形之后分配顶点:/。
这是输入的示例文本文件:
2 # '2' is the number of rectangles.
5 5 # (x1, y1)
5 7 # (x2, y2)
7 5 # (x3, y3)
30 20 # (x1, y1)
10 10 # (x2, y2)
10 20 # (x3, y3)
# (there could be more '**vertices**' and more than '**2**' cases)
这是我的方法:
import sys
def calculate(num):
x1 = lines[n].split()[0]
y1 = lines[n].split()[1]
x2 = lines[n+1].split()[0]
y2 = lines[n+1].split()[1]
x3 = lines[n+2].split()[0]
y3 = lines[n+2].split()[1]
print x1, y1
print x2, y2
print x3, y3
#Planning to write codes for calculation & results below inside this function.
readlines = sys.stdin.readlines() # reads
num = int(lines[0]) # assigns the number of cases
for i in range(0, num):
item += 1
calculate(item) # Calls the above function
当我运行这段代码时,我得到以下信息:
5 5
5 7
7 5
5 7
7 5
30 20
我想得到的是:
5 5
5 7
7 5
30 20
10 10
10 20
最佳答案
你想要
item += 3
在你的循环中。
再看一遍,这还不足以让它发挥作用。你想传递行号
1, 4, 7, 10 .....
到您的计算
函数。您可以使用 range
for iLine in range( 1, 3*num-1, 3):
calculate( iLine)
第三个参数告诉它每次跳过 3,你需要从第 1 行开始,而不是第 0 行,因为第 0 行包含你的计数。
您还需要正确设置上限。你要传入calculate
的最终值实际上是3*num-2
,但是记住range
函数不包括上限, 所以我们可以在那里使用 (highest desired value + 1) ,这是 3*num-1
的来源。
关于python - 如何在 for 循环中从列表中赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34871908/