1
people = ["James","COP","George","COP","Sam","Mac","Johnny","Karina"] cops = [(idx+1) for idx, val in enumerate(people) if val == "COP"] #cops' positions peoplePositions = [(x+1) for x in range(len(people))] #index positions distances = [] for x in peoplePositions: for y in cops: distances.append(abs(x-y)) #the output would be "Johnny" 

Hello, guys! I'm working on this question and basically I have a list with some people/objects that is actually a circular table, i.e., its head it is connected to its tail. Now I want to take the distance (of index positions) between the "COPs" and people, then output who got the maximum distance from the "COPs". In case all of them got the same distance, the output must be all of them.

This is my code and in the end I got the distances between all the people and the "COPs". I thought about making a nested loop through the distances with a range of len(peoplePositions) and a range of len(cops), but I had no progress.

6
  • What is peoplePositions? Commented Oct 5, 2020 at 23:46
  • It's the people's index positions. Commented Oct 5, 2020 at 23:46
  • It would help if your code defined all variables. There are many ways to interpret a description of a variable. But if you actually define it in the code, then there is no chance for us to get it wrong. Commented Oct 5, 2020 at 23:48
  • oh, sorry! I just missclicked the code. Now it's correct. Commented Oct 5, 2020 at 23:50
  • Also, I do not understand the final comment the output would be "Johnny". This code has no print statements, so there is no output. Where are you expecting "Johnny" to come from? Commented Oct 5, 2020 at 23:53

1 Answer 1

4

You need to compute the minimum distance from each person to each COP. This can be computed as:

min((p - c) % l, (c - p) % l) 

where p is the index of the person, c is the index of the COP and l the length of the array. Then you can compute the minimum of those distances to get the minimum distance from a person to any of the COPs. You can then compute the maximum of those values, and filter the people array based on their distance being equal to the maximum:

people = ["James","COP","George","COP","Sam","Mac","Johnny","Karina"] cops = [idx for idx, val in enumerate(people) if val == "COP"] l = len(people) distances = [min(min((p - c) % l, (c - p) % l) for c in cops) for p in range(l)] maxd = max(distances) pmax = [p for i, p in enumerate(people) if distances[i] == maxd] print(pmax) 

Output:

['Johnny'] 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.