Skip to main content
Code Review

Return to Revisions

2 of 8
Improved formatting

Python - Slicing and removing elements from list - Need an optimal solution

Input list has n elements, each element has a score. The goal is to assemble a group (of size ‘team’) of elements together and to find their total score.

Inputs:

  • score [] of size n,
  • team which is the team size,
  • m tells us how to slice the list

Selection of elements from the list is done in the following way:

  1. During each selection, we have to choose an element with the highest score among either the first m in available elements or the last m available elements in the list. The element is then removed from the list and added to the team total score.
  2. If there are multiple elements with the same highest score among the first or last in available elements, the element closest to the start of the line is picked.
  3. If there are less than in available elements. then we pick the highest scored element from all available elements.

Sample Input and Output:

Sample 1

n:9, score:[17,12,10,2,7,2,11,20,8,],team:3,m:4
OUTPUT : 49

Sample 2

n:8,score:[18,5,15,18,11,15,9,7],team:5,m:1
OUTPUT : 60

Need an optimal solution for this Python code. I am getting the desired output. But I am looking for a better solution.

def teamFormation(score, team, m):
 total_score = 0
 for _ in range(team):
 if len(score) >= 2*m:
 max_score = max(score[:m]+score[-m:])
 total_score += max_score
 if((score[:m]+score[-m:]).index(max_score)/m >= 1):
 score.pop((score[:m]+score[-m:]).index(max_score) - 2*m)
 else:
 score.remove(max_score)
 elif len(score) > 0:
 max_score = max(score)
 total_score += max_score
 score.remove(max_score)
 return total_score
Johnny
  • 115
  • 1
  • 7
lang-py

AltStyle によって変換されたページ (->オリジナル) /