Python 에서 집합이 숫자만 포함하는지 확인하는 방법

PythonBeginner
지금 연습하기

소개

이 랩에서는 Python 에서 집합이 숫자만 포함하는지 확인하는 방법을 배우게 됩니다. 이 랩은 빈 집합, 정수 집합, 부동 소수점 집합, 그리고 정수와 부동 소수점을 모두 포함하는 혼합 집합을 포함하여 숫자 집합을 정의하는 데 중점을 둡니다. 또한 집합이 중복 값을 어떻게 처리하여 고유성을 보장하는지도 살펴봅니다.

이 랩에서는 numeric_sets.py라는 Python 파일을 생성하고, 다양한 집합을 정의하고 출력하는 코드를 추가하며, 스크립트를 실행하여 출력을 관찰하는 과정을 안내합니다. set() 생성자를 사용하는 방법과 집합이 중복 값을 자동으로 제거하는 방법을 배우면서 Python 에서 집합의 기본적인 속성을 보여줍니다.

숫자 집합 정의

이 단계에서는 Python 에서 숫자를 포함하는 집합을 정의하는 방법을 배우게 됩니다. 집합은 고유한 요소들의 정렬되지 않은 컬렉션입니다. 즉, 집합은 중복된 값을 포함할 수 없습니다. 우리는 정수와 부동 소수점 숫자의 집합을 생성하는 데 집중할 것입니다.

먼저, VS Code 편집기를 사용하여 ~/project 디렉토리에 numeric_sets.py라는 Python 파일을 생성해 보겠습니다.

## Create an empty set
empty_set = set()
print("Empty Set:", empty_set)

## Create a set of integers
integer_set = {1, 2, 3, 4, 5}
print("Integer Set:", integer_set)

## Create a set of floats
float_set = {1.0, 2.5, 3.7, 4.2, 5.9}
print("Float Set:", float_set)

## Create a mixed set (integers and floats)
mixed_set = {1, 2.0, 3, 4.5, 5}
print("Mixed Set:", mixed_set)

~/project 디렉토리에 파일을 numeric_sets.py로 저장합니다. 이제 터미널에서 다음 명령을 사용하여 스크립트를 실행합니다.

python numeric_sets.py

다음과 같은 출력을 볼 수 있습니다.

Empty Set: set()
Integer Set: {1, 2, 3, 4, 5}
Float Set: {1.0, 2.5, 3.7, 4.2, 5.9}
Mixed Set: {1, 2.0, 3, 4.5, 5}

집합의 요소 순서가 정의된 순서와 다를 수 있다는 점에 유의하십시오. 이는 집합이 정렬되지 않은 컬렉션이기 때문입니다. 또한 집합은 자동으로 중복 값을 제거합니다.

이제 numeric_sets.py 파일에 몇 가지 더 많은 예제를 추가하여 집합의 고유성을 보여드리겠습니다.

## Create a set with duplicate values
duplicate_set = {1, 2, 2, 3, 4, 4, 5}
print("Duplicate Set:", duplicate_set)

## Create a set from a list with duplicate values
duplicate_list = [1, 2, 2, 3, 4, 4, 5]
unique_set = set(duplicate_list)
print("Unique Set from List:", unique_set)

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

python numeric_sets.py

다음과 같은 출력을 볼 수 있습니다.

Empty Set: set()
Integer Set: {1, 2, 3, 4, 5}
Float Set: {1.0, 2.5, 3.7, 4.2, 5.9}
Mixed Set: {1, 2.0, 3, 4.5, 5}
Duplicate Set: {1, 2, 3, 4, 5}
Unique Set from List: {1, 2, 3, 4, 5}

보시다시피, duplicate_setunique_set 모두 중복된 값으로 생성하려고 했음에도 불구하고 고유한 값만 포함합니다.

isinstance() 와 함께 all() 사용

이 단계에서는 all() 함수를 isinstance() 함수와 함께 사용하여 집합의 모든 요소가 특정 숫자 유형인지 확인하는 방법을 배우게 됩니다. 이는 집합에 대한 작업을 수행하기 전에 집합의 내용을 검증하는 데 유용합니다.

all() 함수는 반복 가능한 객체 (예: 집합) 의 모든 요소가 참이면 True를 반환합니다. isinstance() 함수는 객체가 지정된 클래스 또는 유형의 인스턴스인지 확인합니다.

이러한 검사를 포함하도록 이전 단계에서 생성한 numeric_sets.py 파일을 수정해 보겠습니다. VS Code 편집기에서 numeric_sets.py를 열고 다음 코드를 추가합니다.

def check_if_all_are_integers(input_set):
  """Checks if all elements in the set are integers."""
  return all(isinstance(x, int) for x in input_set)

def check_if_all_are_floats(input_set):
  """Checks if all elements in the set are floats."""
  return all(isinstance(x, float) for x in input_set)

## Example usage:
integer_set = {1, 2, 3, 4, 5}
float_set = {1.0, 2.5, 3.7, 4.2, 5.9}
mixed_set = {1, 2.0, 3, 4.5, 5}

print("Are all elements in integer_set integers?", check_if_all_are_integers(integer_set))
print("Are all elements in float_set floats?", check_if_all_are_floats(float_set))
print("Are all elements in mixed_set integers?", check_if_all_are_integers(mixed_set))
print("Are all elements in mixed_set floats?", check_if_all_are_floats(mixed_set))

파일을 저장하고 다음 명령을 사용하여 실행합니다.

python numeric_sets.py

다음과 같은 출력을 볼 수 있습니다.

Are all elements in integer_set integers? True
Are all elements in float_set floats? True
Are all elements in mixed_set integers? False
Are all elements in mixed_set floats? False

출력은 integer_set이 정수만 포함하고, float_set이 부동 소수점 숫자만 포함하며, mixed_set이 정수와 부동 소수점 숫자를 혼합하여 포함하므로, 검사가 정수 및 부동 소수점 숫자 검사 모두에 대해 False를 반환함을 보여줍니다.

이제 모든 요소가 정수 또는 부동 소수점 숫자 (즉, 숫자) 인지 확인하는 함수를 추가해 보겠습니다.

def check_if_all_are_numeric(input_set):
  """Checks if all elements in the set are either integers or floats."""
  return all(isinstance(x, (int, float)) for x in input_set)

print("Are all elements in mixed_set numeric?", check_if_all_are_numeric(mixed_set))

string_set = {"a", "b", "c"}
print("Are all elements in string_set numeric?", check_if_all_are_numeric(string_set))

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

python numeric_sets.py

다음과 같은 출력을 볼 수 있습니다.

Are all elements in integer_set integers? True
Are all elements in float_set floats? True
Are all elements in mixed_set integers? False
Are all elements in mixed_set floats? False
Are all elements in mixed_set numeric? True
Are all elements in string_set numeric? False

이것은 all()isinstance()를 사용하여 집합 내의 요소 유형을 검증하는 방법을 보여줍니다.

빈 집합 처리

이 단계에서는 all()isinstance() 함수를 사용할 때 빈 집합을 처리하는 방법을 배우게 됩니다. 빈 집합은 요소가 없기 때문에 특별한 경우입니다. 이러한 함수가 빈 집합에서 어떻게 동작하는지 이해하는 것은 견고한 코드를 작성하는 데 매우 중요합니다.

all()을 빈 집합과 함께 사용할 때 어떤 일이 발생하는지 생각해 보겠습니다. all() 함수는 반복 가능한 객체의 모든 요소가 참이면 True를 반환합니다. 빈 집합에는 요소가 없으므로, "모든" 요소가 참이라고 주장할 수 있습니다. 즉, 거짓이 될 요소가 없기 때문입니다.

이를 보여주기 위해 numeric_sets.py 파일을 수정해 보겠습니다. VS Code 편집기에서 numeric_sets.py를 열고 다음 코드를 추가합니다.

def check_if_all_are_integers(input_set):
  """Checks if all elements in the set are integers."""
  return all(isinstance(x, int) for x in input_set)

## Example with an empty set:
empty_set = set()
print("Is empty_set all integers?", check_if_all_are_integers(empty_set))

파일을 저장하고 다음 명령을 사용하여 실행합니다.

python numeric_sets.py

다음과 같은 출력을 볼 수 있습니다.

Is empty_set all integers? True

이 결과는 처음에는 직관적이지 않을 수 있습니다. 그러나 all()의 정의와 일치합니다.

이제 빈 집합을 명시적으로 다르게 처리하려는 시나리오를 고려해 보겠습니다. all()을 사용하기 전에 빈 집합에 대한 검사를 추가할 수 있습니다.

def check_if_all_are_integers_safe(input_set):
  """Checks if all elements in the set are integers, handling empty sets explicitly."""
  if not input_set:
    return False  ## Or True, depending on your desired behavior for empty sets
  return all(isinstance(x, int) for x in input_set)

empty_set = set()
print("Is empty_set all integers (safe)?", check_if_all_are_integers_safe(empty_set))

integer_set = {1, 2, 3}
print("Is integer_set all integers (safe)?", check_if_all_are_integers_safe(integer_set))

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

python numeric_sets.py

다음과 같은 출력을 볼 수 있습니다.

Is empty_set all integers (safe)? False
Is integer_set all integers (safe)? True

이 예제에서 check_if_all_are_integers_safe 함수는 빈 집합에 대해 False를 반환합니다. if not input_set: 블록에서 반환 값을 수정하여 특정 요구 사항에 맞게 조정할 수 있습니다. 빈 집합을 명시적으로 처리하면 코드에서 예기치 않은 동작을 방지할 수 있습니다.

요약

이 랩에서는 Python 에서 숫자 집합을 정의하는 방법을 배웠습니다. 여기에는 빈 집합, 정수 집합, 부동 소수점 숫자 집합, 정수와 부동 소수점 숫자를 모두 포함하는 혼합 집합이 포함됩니다. 또한 집합이 정렬되지 않은 컬렉션이며 중복 값을 자동으로 제거한다는 것을 관찰했습니다.

이 랩에서는 중복 값을 포함하는 리스트에서 직접 집합을 생성하는 방법을 보여주었으며, 고유한 요소만 유지하는 집합의 속성을 강조했습니다. 예제는 집합이 다양한 숫자 유형을 처리하고 중복성을 제거하는 방법에 대한 실질적인 이해를 제공했습니다.