I’m making a gravity simulator and I need to calculate the resultant force acting upon each body.
In order to do this, I need to iterate through every pair of bodies in a dictionary (id: instance of Body class) and get the gravitational force between those two bodies. Then, I would add up all the forces and get the resultants.
But, how do I iterate over each pair of items in a dictionary only once in Python? If the celestial bodies were kept in a list, it would be simple:
for i in range(len(bodies)):
for j in range(len(bodies) - i - 1):
k = j - i + 1
b1 = bodies[i]
b2 = bodies[k]
values()anditertools‘combinationsare ideal for this use case.