w3resource

Python: Test whether two lines PQ and RS are parallel

Python Basic - 1: Exercise-43 with Solution

Parallel Lines Tester

Write a Python program to test whether two lines PQ and RS are parallel. The four points are P(x1, y1), Q(x2, y2), R(x3, y3), S(x4, y4).

Input:
x1,y1,x2,y2,x3,y3,xp,yp separated by a single space

Sample Solution:

Python Code:

# Print statement to prompt the user to input coordinates of two line segments (PQ and RS)
print("Input x1, y1, x2, y2, x3, y3, x4, y4:")

# Take user input for coordinates of the two line segments and convert them to float
x1, y1, x2, y2, x3, y3, x4, y4 = map(float, input().split())

# Check if PQ and RS are parallel using the cross product of their direction vectors
# The condition uses a small tolerance (1e-10) to handle floating-point precision issues
print('PQ and RS are parallel.' if abs((x2 - x1)*(y4 - y3) - (x4 - x3)*(y2 - y1)) < 1e-10 else 'PQ and RS are not parallel')

Sample Output:

Input x1,y1,x2,y2,x3,y3,xp,yp:
 2 5 6 4 8 3 9 7
PQ and RS are not parallel

Explanation:

Here is a breakdown of the above Python code:

  • The code begins by printing a message to prompt the user to input the coordinates of two line segments (PQ and RS).
  • User input is obtained, where coordinates are separated by spaces and converted to floating-point numbers.
  • The code then checks if the two line segments PQ and RS are parallel using the cross product of their direction vectors.
  • The condition (x2 - x1)*(y4 - y3) - (x4 - x3)*(y2 - y1) compares the cross product with a small tolerance (1e-10).
  • Depending on the result of the condition, the code prints whether PQ and RS are parallel or not.

Flowchart:

Flowchart: Python - Test whether two lines PQ and RS are parallel

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program that accepts six numbers as input and sorts them in descending order.
Next: Write a Python program to find the maximum sum of a contiguous subsequence from a given sequence of numbers a1, a2, a3, ... an. A subsequence of one element is also a continuous subsequence.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/python-exercises/basic/python-basic-1-exercise-43.php