포스트

[Python] Programmers - Creating minimum value

Product sum minimization by sorting arrays in opposite directions, and efficiency improvement using Python sort() method

한국어 원문은 여기에서 볼 수 있습니다.
[Python] Programmers - Creating minimum value

Programmers Creating the Minimum

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
def solution(A,B):

    A.sort()

    B.sort(reverse=True)

    answer = 0

    for i in range(len(A)):

        answer += A[i] * B[i]
 
    return answer
  • At first

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    
      def solution(A,B):
          answer = 0
    
          cnt = len(A)
          for i in range(len(A)-1):
              cnt -= 1
              for j in range(cnt):
                  if A[j] > A[j+1]:
                      A[j], A[j+1] = A[j+1], A[j]
    
          cnt = len(B)
          for i in range(len(B)-1):
              cnt -= 1
              for j in range(cnt):
                  if B[j] < B[j+1]:
                      B[j], B[j+1] = B[j+1], B[j]
    
          for i in range(len(A)):
              answer += A[i] * B[i]
    
          return answer
    

I wrote the following, but it doesn’t pass the efficiency test:

  • In Python, bubble sort is not used separately, but can be sorted simply through the sort() function.

sort()

  • Built-in method of List object

  • Immediately sort the original list in ascending order (in-place)

  • You can sort in descending order with list.sort(reverse=True), and the return value is None.

  • If you need sorted copies, use the built-in function sorted().

    • list.sort() (modify the original list) Features: Changes the original list itself and does not return a new list (returns None)