Kay
Kay

Reputation: 17

Finding the midpoint of tuple of any length in python

I need to take a tuple of any length and preforming an operation to return the midpoint. However, I need to function to work with a tuple of any length so I'm not sure how to go about it.

def findMidpoint(P: tuple, Q: tuple) -> tuple:
    user_input1 = input('Enter space-separated integers: ')
    P = tuple(int(item) for item in user_input1.split())
    user_input2 = input('Enter space-separated integers: ')
    Q = tuple(int(item) for item in user_input2.split())
    Midpoint 
    pass

def main():
   # use to test the findMidpoint function
   pass

if __name__ == "__main__":
    main()

Upvotes: -1

Views: 344

Answers (1)

PirateNinjas
PirateNinjas

Reputation: 2086

Okay, taking some liberties here with what you're asking, but assuming what you want is to find the midpoint of any two points in an N-dimensional space, you can average the value of each point axis-wise. For example:

P = (px, py)
Q = (qx, qy)

midpoint = ( (px + qx)*0.5, (py + qy)*0.5 ) 

Obviously, for more dimensions you have to extend this. A general N-dimensional solution, with your code, can make use of zip:

def findMidpoint(P: tuple, Q: tuple) -> tuple:
    return tuple((q + p) / 2 for p, q in zip(P, Q))


def main():
    # use to test the findMidpoint function
    assert findMidpoint(P=(0, 0), Q=(2, 2)) == (1, 1)
    assert findMidpoint(P=(0, 0, 0), Q=(2, 2, 2)) == (1, 1, 1)
    assert findMidpoint(P=(-2, -2, -2), Q=(2, 2, 2)) == (0, 0, 0)


if __name__ == "__main__":
    main()

This assumes P and Q are the same length. If they're not, you could go one further and use zip_longest:

from itertools import zip_longest

def findMidpoint(P: tuple, Q: tuple) -> tuple:
    return tuple((q + p) / 2 for p, q in zip_longest(P, Q, fillvalue=0))


def main():
    # use to test the findMidpoint function
    assert findMidpoint(P=(0, 0), Q=(2, 2, 2)) == (1, 1, 1)


if __name__ == "__main__":
    main()

This would essentially say "if no coordinate is given for an axis, assume it is zero".

Upvotes: -1

Related Questions