Insights

BOJ Problem 3052: Is "{}" a set or a dict?

funczun 2024. 11. 1. 11:01
For empty list generation

 Even if you plan to add a value to a list, you need to initialize that list beforehand for the program to function correctly. In Python, an empty list is created by entering "[]". The two codes below are examples of how I initialized a list while solving problems on BOJ.

# https://www.acmicpc.net/problem/10871

import sys

N, X = map(int, sys.stdin.readline().split())
A = list(map(int, sys.stdin.readline().split()))
less_than = []

for i in A:
    if i < X:
        less_than.append(i)

# To convert each element to a string, you should use the map function
result = map(str, less_than)

print(' '.join(result))
# https://www.acmicpc.net/problem/2562

import sys

inputs = []

for i in range(9):
    num = int(sys.stdin.readline())
    inputs.append(num)

max_num = max(inputs)

print(max_num)
print(inputs.index(max_num) + 1)

 

"{0}" is a set, but "{}" is a dict

 I encountered a situation where I needed to use the concept of a set while solving problem 3052 on BOJ. Without much thought, since a set is represented as "{}", I tried to initialize the set by entering "{}". However, the add method for adding elements to the set did not work properly in the for loop. Thanks to the syntax highlighting feature supported by VS Code, I intuitively realized that something was wrong.

# https://www.acmicpc.net/problem/3052

import sys

rest = {}

for i in range(10):
    n = int(sys.stdin.readline())
    rest.add(n % 42)

print(len(rest))

 The cause of the error is that the line "rest = {}" creates an empty dictionary, not a set. Dictionaries cannot use the add method. Both dictionaries and sets use '{}' for their representation, but dictionaries are in the format '{key1: value1, key2: value2}', while sets are in the format '{value1, value2}'. The key point is that if '{}' is empty, it is treated as a dictionary by default, and if you want to create an empty set, you need to use "set()".

# https://www.acmicpc.net/problem/3052

import sys

rest = set()

for i in range(10):
    n = int(sys.stdin.readline())
    rest.add(n % 42)

print(len(rest))