-1

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()
Kay
  • 17
  • 2
  • 3
    Why are you passing P and Q just to overwrite them nearly immediately after? Also, how do you define "midpoint" of a tuple? What if it contains even number of elements? – matszwecja Nov 10 '22 at 15:21
  • 1
    What is a midpoint of _two_ tuples? Could you clarify what "midpoint" means for your situation, please? – StonedTensor Nov 10 '22 at 15:24
  • 1
    If this is a homework question, perhaps you misunderstood the question. It seems like you maybe want the midpoint between two points P and Q, each being a tuple of some length (2 or 3 probably?). Is that what you want? – PirateNinjas Nov 10 '22 at 15:27

1 Answers1

-1

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".

PirateNinjas
  • 1,908
  • 1
  • 16
  • 21