Python 에서 세트의 특정 크기를 확인하는 방법

PythonBeginner
지금 연습하기

소개

이 랩에서는 Python 에서 특정 세트의 크기를 확인하는 방법을 배우게 됩니다. 이 랩은 다양한 프로그래밍 작업에 필수적인 len() 함수를 사용하여 세트의 요소 수를 결정하는 데 중점을 둡니다.

Python 스크립트에서 숫자와 문자열의 세트를 생성하는 것으로 시작하여 len() 함수를 사용하여 세트의 크기를 찾습니다. 마지막으로, 세트의 크기를 원하는 크기와 비교하여 일치하는지 확인합니다.

세트 크기 이해

이 단계에서는 len() 함수를 사용하여 세트의 요소 수를 결정하는 방법을 배우게 됩니다. 세트의 크기를 이해하는 것은 세트가 비어 있는지 확인하거나 서로 다른 세트의 크기를 비교하는 등 다양한 프로그래밍 작업에 매우 중요합니다.

먼저, Python 스크립트에서 간단한 세트를 만들어 보겠습니다. LabEx 환경에서 VS Code 편집기를 열고 ~/project 디렉토리에 set_size.py라는 새 파일을 만듭니다.

## Create a set of numbers
my_set = {1, 2, 3, 4, 5}

## Print the set
print(my_set)

파일을 저장합니다. 이제 이 스크립트를 실행하여 출력을 확인해 보겠습니다. VS Code 에서 터미널을 열고 (하단 패널에서 찾을 수 있습니다) ~/project 디렉토리로 이동합니다 (기본적으로 이미 해당 디렉토리에 있을 것입니다). 다음 명령을 사용하여 스크립트를 실행합니다.

python set_size.py

다음 출력이 표시됩니다.

{1, 2, 3, 4, 5}

이제 세트가 있으므로, 세트에 몇 개의 요소가 포함되어 있는지 알아보겠습니다. set_size.py 스크립트에 다음 줄을 추가합니다.

## Create a set of numbers
my_set = {1, 2, 3, 4, 5}

## Print the set
print(my_set)

## Get the size of the set using the len() function
set_size = len(my_set)

## Print the size of the set
print("The size of the set is:", set_size)

변경 사항을 저장하고 스크립트를 다시 실행합니다.

python set_size.py

이번에는 다음 출력이 표시됩니다.

{1, 2, 3, 4, 5}
The size of the set is: 5

len() 함수는 세트의 요소 수를 반환합니다. 이 경우, my_set 세트는 5 개의 요소를 포함합니다.

문자열 세트로 다른 예를 시도해 보겠습니다. set_size.py 스크립트를 다음과 같이 수정합니다.

## Create a set of strings
my_set = {"apple", "banana", "cherry"}

## Print the set
print(my_set)

## Get the size of the set using the len() function
set_size = len(my_set)

## Print the size of the set
print("The size of the set is:", set_size)

파일을 저장하고 실행합니다.

python set_size.py

다음 출력이 표시됩니다.

{'cherry', 'banana', 'apple'}
The size of the set is: 3

보시다시피, len() 함수는 서로 다른 유형의 데이터를 포함하는 세트에서도 작동합니다.

len() 함수 사용

이전 단계에서는 len() 함수를 사용하여 세트의 크기를 얻는 방법을 배웠습니다. 이 단계에서는 조건문과 루프 내에서 사용하는 것을 포함하여 세트와 함께 len() 함수를 사용하는 더 고급 방법을 살펴보겠습니다.

set_size.py 스크립트를 수정하여 세트가 비어 있는지 확인하는 조건문을 포함하는 것으로 시작해 보겠습니다. VS Code 편집기에서 set_size.py 파일을 열고 다음과 같이 수정합니다.

## Create a set of numbers
my_set = {1, 2, 3, 4, 5}

## Print the set
print(my_set)

## Get the size of the set using the len() function
set_size = len(my_set)

## Print the size of the set
print("The size of the set is:", set_size)

## Check if the set is empty
if set_size == 0:
    print("The set is empty.")
else:
    print("The set is not empty.")

파일을 저장하고 실행합니다.

python set_size.py

다음 출력이 표시됩니다.

{1, 2, 3, 4, 5}
The size of the set is: 5
The set is not empty.

이제 스크립트를 수정하여 빈 세트를 만들고 크기를 확인해 보겠습니다. set_size.py 스크립트의 첫 번째 줄을 변경하여 빈 세트를 만듭니다.

## Create an empty set
my_set = set()

## Print the set
print(my_set)

## Get the size of the set using the len() function
set_size = len(my_set)

## Print the size of the set
print("The size of the set is:", set_size)

## Check if the set is empty
if set_size == 0:
    print("The set is empty.")
else:
    print("The set is not empty.")

파일을 저장하고 다시 실행합니다.

python set_size.py

이번에는 다음 출력이 표시됩니다.

set()
The size of the set is: 0
The set is empty.

보시다시피, len() 함수는 빈 세트에 대해 0 을 반환하고, 조건문은 세트가 비어 있음을 올바르게 식별합니다.

이제 루프에서 len() 함수를 사용해 보겠습니다. 세트가 비어 있을 때까지 세트에서 요소를 제거하려는 경우를 가정해 보겠습니다. set_size.py 스크립트를 다음과 같이 수정합니다.

## Create a set of numbers
my_set = {1, 2, 3, 4, 5}

## Print the set
print(my_set)

## Remove elements from the set until it is empty
while len(my_set) > 0:
    ## Remove an arbitrary element from the set
    element = my_set.pop()
    print("Removed element:", element)
    print("The set is now:", my_set)

print("The set is now empty.")

파일을 저장하고 실행합니다.

python set_size.py

다음과 유사한 출력이 표시됩니다 (제거된 요소의 순서는 다를 수 있습니다).

{1, 2, 3, 4, 5}
Removed element: 1
The set is now: {2, 3, 4, 5}
Removed element: 2
The set is now: {3, 4, 5}
Removed element: 3
The set is now: {4, 5}
Removed element: 4
The set is now: {5}
Removed element: 5
The set is now: set()
The set is now empty.

이 예제에서는 len() 함수를 사용하여 while 루프의 각 반복에서 세트가 비어 있는지 확인합니다. pop() 메서드는 세트에서 임의의 요소를 제거합니다. 루프는 세트가 비어 있을 때까지 계속됩니다.

원하는 크기와 비교

이 단계에서는 조건문을 사용하여 세트의 크기를 원하는 크기와 비교하는 방법을 배우게 됩니다. 이는 특정 작업을 수행하기 전에 세트에 특정 수의 요소가 포함되어 있는지 확인해야 할 때 유용합니다.

set_size.py 스크립트를 수정하여 세트의 크기를 원하는 크기와 비교해 보겠습니다. VS Code 편집기에서 set_size.py 파일을 열고 다음과 같이 수정합니다.

## Create a set of numbers
my_set = {1, 2, 3}

## Print the set
print(my_set)

## Get the size of the set using the len() function
set_size = len(my_set)

## Print the size of the set
print("The size of the set is:", set_size)

## Define the desired size
desired_size = 5

## Compare the size of the set with the desired size
if set_size == desired_size:
    print("The set has the desired size.")
elif set_size < desired_size:
    print("The set is smaller than the desired size.")
else:
    print("The set is larger than the desired size.")

파일을 저장하고 실행합니다.

python set_size.py

다음 출력이 표시됩니다.

{1, 2, 3}
The size of the set is: 3
The set is smaller than the desired size.

이제 스크립트를 수정하여 원하는 크기의 세트를 만들어 보겠습니다. set_size.py 스크립트의 첫 번째 줄을 변경하여 5 개의 요소를 가진 세트를 만듭니다.

## Create a set of numbers
my_set = {1, 2, 3, 4, 5}

## Print the set
print(my_set)

## Get the size of the set using the len() function
set_size = len(my_set)

## Print the size of the set
print("The size of the set is:", set_size)

## Define the desired size
desired_size = 5

## Compare the size of the set with the desired size
if set_size == desired_size:
    print("The set has the desired size.")
elif set_size < desired_size:
    print("The set is smaller than the desired size.")
else:
    print("The set is larger than the desired size.")

파일을 저장하고 다시 실행합니다.

python set_size.py

이번에는 다음 출력이 표시됩니다.

{1, 2, 3, 4, 5}
The size of the set is: 5
The set has the desired size.

마지막으로, 스크립트를 수정하여 원하는 크기보다 큰 세트를 만들어 보겠습니다. set_size.py 스크립트의 첫 번째 줄을 변경하여 7 개의 요소를 가진 세트를 만듭니다.

## Create a set of numbers
my_set = {1, 2, 3, 4, 5, 6, 7}

## Print the set
print(my_set)

## Get the size of the set using the len() function
set_size = len(my_set)

## Print the size of the set
print("The size of the set is:", set_size)

## Define the desired size
desired_size = 5

## Compare the size of the set with the desired size
if set_size == desired_size:
    print("The set has the desired size.")
elif set_size < desired_size:
    print("The set is smaller than the desired size.")
else:
    print("The set is larger than the desired size.")

파일을 저장하고 실행합니다.

python set_size.py

다음 출력이 표시됩니다.

{1, 2, 3, 4, 5, 6, 7}
The size of the set is: 7
The set is larger than the desired size.

이것은 len() 함수를 사용하여 세트의 크기를 원하는 크기와 비교하고 비교를 기반으로 다른 작업을 수행하는 방법을 보여줍니다.

요약

이 랩에서는 len() 함수를 사용하여 Python 세트의 크기를 결정하는 방법을 배웠습니다. set_size.py라는 Python 스크립트를 생성하고 숫자와 문자열을 포함하는 세트로 채웠습니다. 그런 다음 len() 함수를 사용하여 각 세트 내의 요소 수를 검색하여 다양한 데이터 유형에서 해당 적용을 시연했습니다.

이 랩에서는 세트를 생성하고 내용을 출력한 다음 len()을 사용하여 세트의 크기를 얻고 출력하는 작업을 포함했습니다. 이 프로세스는 정수 세트와 문자열 세트 모두에서 반복되어 세트의 요소 수를 결정하기 위해 len() 함수를 효과적으로 사용하는 방법에 대한 이해를 강화했습니다.