2016-01-19 29 views
3

我有三個矩形頂點,需要找到第四個頂點,我需要找到N個矩形的缺失頂點。如何從列表中分配for循環中的值

不幸的是,我無法弄清楚如何在第一個矩形之後分配頂點:/。

下面是輸入例如文本文件:

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 
+0

使用['itertools'](https://docs.python.org/2/library/itertools.html)文檔頁面上顯示的'grouper'配方,您可以輕鬆(並且高效地)使用大塊文件三個。 –

+0

這是我第一次在這裏註冊併發布我的問題。我真的很感謝你的幫助! – DavidC

+0

什麼是'n'?你在哪裏申報?看來你上面貼的代碼不完整 – Ali

回答

2

你想

item += 3 

你的循環中。


再次看它,這還不夠,使其工作。你想行號

1, 4, 7, 10 ..... 

傳遞給你的calculate功能。你可以用range

for iLine in range(1, 3*num-1, 3): 
    calculate(iLine) 

第三個參數告訴它由3每次跳過3參數版本做到這一點,你需要線#1,不#0開始,如線#0包含你的數量。

您還需要獲得正確的上限。您想要傳入的最終值calculate實際上是3*num-2,但請記住range函數不包含上限,因此我們可以使用(最高期望值+ 1),這是3*num-1的來源。

+1

謝謝喬納森,我試過了,但它給了我一個超出範圍的錯誤。這是我得到的7 5,30 20,10 10 – DavidC

+0

是的,我被循環變量'i'弄糊塗了,並將變量'item'傳遞到'calculate'函數中。如果你循環傳遞給'calculate'的變量,就像我的'iLine'例子中那樣,我認爲它更清晰。 – JonathanZ

+0

再次感謝你喬納森。我按照你的建議嘗試過,而且它非常完美!我非常感謝您的幫助! – DavidC

2

看起來上面的代碼並不是您的完整代碼,但我認爲您應該在您的實際代碼中更正它,如下所示: 而不是item +=1您應該編寫item = 1+ i*3

+0

謝謝你的幫助! – DavidC

+0

@DavidC不客氣。在有人回答你的問題時,如果你發現它有幫助,請點擊這裏回答。謝謝 – Ali

+0

哦,好吧,我很樂意爲您的答案提供答案。我如何點擊?我現在點擊向上箭頭! :) 謝謝。 – DavidC

1

@Avilar - 這是在你的代碼時會發生什麼num > 2 你的代碼的建議是這樣的:

item = 1 
for i in range(0, num): 
    item += i*3 

,因爲我們通過循環

i = 0 
item += 0 --> item = 1 

然後

i = 1 
item += 3 --> item = 4 

then

i = 2 
item += 2*3 --> item = 10 

然後

i = 3 
item += 3*3 --> item = 19 

然後

i = 4 
item += 3*4 --> item = 31 

您將生成的數字

1, 4, 10, 19, 31, 46, 64 

,當我們想

1, 4, 7, 10, 13, 16, 19