I have three vertices of a rectangle and need to find the fourth vertex, and I need to find the missing vertex for N numbers of rectangles.
Sadly, I could not figure out how I can assign the vertices after the first rectangle :/.
Here is the example text file for input:
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)
Here was my approach:
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
When I run this code, I get the following:
5 5
5 7
7 5
5 7
7 5
30 20
What I wanted to get was:
5 5
5 7
7 5
30 20
10 10
10 20
3 Answers 3
You want
item += 3
inside your loop.
Looking at it again, that's not enough to make it work. You want to pass the line numbers
1, 4, 7, 10 .....
to your calculate
function. You can do this with the 3-argument version of range
for iLine in range( 1, 3*num-1, 3):
calculate( iLine)
The third argument tells it to skip by 3 each time, and you need to start at line #1, not #0, as line #0 contains your count.
You also need to get the upper limit right. The final value you want to pass into calculate
is actually 3*num-2
, but remember that the range
function does not include the upper limit, so we can use (highest desired value + 1) there, which is where the 3*num-1
comes from.
3 Comments
i
and passing the variable item
into your calculate
function. If you loop over the same variable that you pass to calculate
, like in my iLine
example, I think it's clearer.It seems that the code above is not your complete code, but I think you should correct it in your real code as follows:
instead of item +=1
you should write item = 1+ i*3
.
12 Comments
@Avilar - This is what happens in your code when num > 2
Your code suggestion is like this:
item = 1
for i in range(0, num):
item += i*3
As we go through the loop
i = 0
item += 0 --> item = 1
then
i = 1
item += 3 --> item = 4
then
i = 2
item += 2*3 --> item = 10
then
i = 3
item += 3*3 --> item = 19
then
i = 4
item += 3*4 --> item = 31
You will generate the numbers
1, 4, 10, 19, 31, 46, 64
when we want
1, 4, 7, 10, 13, 16, 19
grouper
recipe shown on theitertools
documentation page, you could easily (and efficiently) consume your file in chunks of three.'n
? where did you declare it? it seems that the code you posted above is not complete