I'm trying to solve this coding excercise I was given to practice my skills. It involves extracting some .JSON data for basketball players. My program has to find all the possible player pairs which heights when summed are equal to a given integer input.
Here's the code I devised it:
import json
import requests
def to_number(A):
B = int(A)
return B
def search(Number):
response = requests.get("https://mach-eight.uc.r.appspot.com/")
data = json.loads(response.text)
PLAYERS = data["values"]
answer_list = []
for player1 in PLAYERS:
raw_height = player1['h_in']
height_1 = to_number(raw_height)
PLAYERS.remove(player1)
for player2 in PLAYERS:
raw_height = player2['h_in']
height_2 = to_number(raw_height)
result = height_1 + height_2
if result == Number:
par = (player1['first_name'] + ' ' + player1['last_name'] + ' & ' +
player2['first_name'] + ' ' + player2['last_name'])
answer_list.append(par)
return answer_list
def executer():
Number = int(input("insert your integer: "))
result = search(Number)
return result
if __name__=="__main__":
result = executer()
stop_here = len(result)
while stop_here == 0:
print("No matches found, please try with a new number \n\n")
result = executer()
stop_here = len(result)
print(result)
So far it does complete the objective of finding the pairs, but at the expense of a nested for loop and I need to come up with a way of decreasing the computation time, for example, as a O(n) algorithm.
What I've tried so far has been making the pairs without a loop, using the itertools package and a permutation function, but I quickly realized that just made it slower.
On the other hand, I thought about Subtracting each height of the players to the integer input, which would return the only possible heights that pair up with the initial one:
This approach would guide me directly to the only possible pairs, right? But I'm having trouble with what to do after this. I'm not sure how to pinpoint the players that correspond to the resulting height of the operation with only one loop.
If you could help me untangle this conundrum, I would be really thankful. Likewise, if you can think of another approach, I'm all ears and eyes.