This is an answer to this question on Code-Golf.SE (but obviously not golfed). How can I shorten the runtime of my program? It is taking far too long to run some of the test cases. Can I utilise Python map()
or lambda
?
def main():
# Store number of test cases
T = int(input())
# Loop for each test case:
for testCase in range(0, T):
# Store number of members each team can have
N = int(input())
# Store power of beyblades of Team G-Revolution members
teamG_beybladePowers = [int(x) for x in input().split()]
# Store power of beyblades of opponent team members
opponentBeybladePowers = [int(x) for x in input().split()]
# Store the calculated order of our team members as a list
teamG_calculatedOrder = []
# Store the caclulated order of opponent team members as a list
opponentCalculatedOrder = []
# Loop through each of the team members and opponent team members, and match them
for index in range(0, N):
# Check if Team G's highest beyblade power is lower than or equal to opponent's highest
if max(teamG_beybladePowers) <= max(opponentBeybladePowers):
# Team G's highest beyblade power is weaker than opponent's highest.
# We need not waste our best player on their best player, when we will lose.
# Match our lowest player against their highest player.
teamG_calculatedOrder.append(min(teamG_beybladePowers))
opponentCalculatedOrder.append(max(opponentBeybladePowers))
# Remove these members from original list
teamG_beybladePowers.remove(min(teamG_beybladePowers))
opponentBeybladePowers.remove(max(opponentBeybladePowers))
else:
# Team G's highest beyblade power is more than opponent's highest.
# We can use our best player to beat the opponent's best player.
# Match them up:
teamG_calculatedOrder.append(max(teamG_beybladePowers))
opponentCalculatedOrder.append(max(opponentBeybladePowers))
# Remove these members from the original list
teamG_beybladePowers.remove(max(teamG_beybladePowers))
opponentBeybladePowers.remove(max(opponentBeybladePowers))
# Store total number of wins
totalWins = 0
# Calculate number of wins
for index in range(0, N):
# Check if current match was won
if teamG_calculatedOrder[index] > opponentCalculatedOrder[index]:
# This match was won
# Increment total wins:
totalWins += 1
else:
# This match was lost
pass
# Print total number of wins
print(totalWins)
main()