백준 Set, Map 정리

Posted by : on

Category : PS


Set 기본형 코드

  • Set(집합): 데이터의 집합을 관리하기 위한 자료구조, 중복요소 처리에 용이
    # Set의 생성 및 초기화
      my_set = set()
      my_set.add(1)  # 요소 추가
      my_set.add(2)
      my_set.add(2)  # 중복 요소 추가 시도 (실제로는 추가되지 않음)
    
      # 요소 존재 여부 확인
      if 1 in my_set:
          print("1 is in the set")
    
      # 요소 삭제
      my_set.remove(1)  # 요소 삭제 (요소가 존재하지 않으면 KeyError 발생)
      my_set.discard(2)  # 요소 삭제 (요소가 존재하지 않아도 에러 발생하지 않음)
    
      # Set의 크기
      print(len(my_set))  # Set에 저장된 요소의 개수 출력
    
      # Set 순회
      for item in my_set:
          print(item)
    
    
    

Map 기본형 코드

  • Map(Dictionary): Set과 마찬가지로 데이터 집합 관리용 자료구조. 키-값 구조로 이루어져 있음.
      # Dictionary의 생성 및 초기화
      my_map = {}
      my_map["apple"] = "A fruit"  # 키-값 쌍 추가
      my_map["python"] = "A programming language"
    
      # 키를 통한 값 접근
      print(my_map["apple"])  # "A fruit" 출력
    
      # 키 존재 여부 확인
      if "python" in my_map:
          print("python is in the map")
    
      # 키-값 쌍 삭제
      del my_map["apple"]  # 키-값 쌍 삭제
    
      # Dictionary의 크기
      print(len(my_map))  # Dictionary에 저장된 키-값 쌍의 개수 출력
    
      # Dictionary 순회
      for key, value in my_map.items():
          print(f"Key: {key}, Value: {value}")
    
    

About Sejun Jeong
Sejun Jeong

Seize the day with programming

Email : usopked16496@gmail.com

Website : https://usopked.github.io

About UPKED

2024년
2025년

Star
Categories
Useful Links