관리 메뉴

솜씨좋은장씨

[HackerRank] Sock Merchant (Python) 본문

Programming/코딩 1일 1문제

[HackerRank] Sock Merchant (Python)

솜씨좋은장씨 2020. 3. 6. 12:45
728x90
반응형

John works at a clothing store. He has a large pile of socks that he must pair by color for sale. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are.

For example, there are  n = 7 socks with colors ar = [1, 2, 1, 2, 1, 3, 2] . There is one pair of color 1 and one of color 2. There are three odd socks left, one of each color. The number of pairs is 2.

 

Function Description

Complete the sockMerchant function in the editor below. It must return an integer representing the number of matching pairs of socks that are available.

sockMerchant has the following parameter(s):

  • n: the number of socks in the pile
  • ar: the colors of each sock

Input Format

The first line contains an integer n, the number of socks represented in ar.
The second line contains  space-separated integers describing the colors ar[ i ] of the socks in the pile.

 

Constraints

  • 1 <= n <= 100
  • 1 <= ar[ i ] <= 100 where 0 <= i < n

Output Format

Return the total number of matching pairs of socks that John can sell.

 

Sample Input

9
10 20 20 10 10 30 50 10 20

Sample Output

3

Explanation

John can match three pairs of socks.

 

 

Solution

#!/bin/python3

import math
import os
import random
import re
import sys

# Complete the sockMerchant function below.
def sockMerchant(n, ar):
    check_stack = []
    answer = 0

    for i in range(n):
        if ar[i] not in check_stack:
            check_stack.append(ar[i])

        else:
            check_stack.remove(ar[i])
            answer = answer + 1

    return answer

Solution 풀이

for 문을 돌면서 check_stack에 해당하는 인덱스의 값이 없으면 append 시켜주고

존재한다면 remove하면서 정답을 하나씩 카운트 합니다.

check_stack은 실제 스택은 아니며 그저 check하기위한 수단입니다.

 

 

 

SOMJANG/CODINGTEST_PRACTICE

1일 1문제 since 2020.02.07. Contribute to SOMJANG/CODINGTEST_PRACTICE development by creating an account on GitHub.

github.com

 

Comments