자료구조🍋

맵Map(Dictionary), 집합(Set)🍈

Jeein0313 2022. 7. 12. 21:23

맵(C++:map, python : dictionary)

- Allows us to store data in key-value pairs : {"key1":"value1","key2":"value2"}

- 삽입/삭제 시간복잡도 : C++의 경우 O(logN), python의 경우 O(1)

 

Code😁(python):

 

my_dict={
    "chef":"Amy",
    "ceo":"Jason",
}

print(my_dict.get("chef")); #Amy
print(my_dict["chef"]); #Amy
print(my_dict.keys()) #dict_keys(['chef', 'ceo'])
print(my_dict.values()) #dict_values(['Amy', 'Jason'])
print(my_dict.items()) #dict_items([('chef', 'Amy'), ('ceo', 'Jason')])

if "chef" in my_dict:
    print("chef is "+ my_dict["chef"]); #chef is Amy
    
my_dict.update({"cfo":"jeein"}); 
print(my_dict); #{'chef': 'Amy', 'ceo': 'Jason', 'cfo': 'jeein'}

my_dict.pop("chef") 
print(my_dict); #{'ceo': 'Jason', 'cfo': 'jeein'}

my_dict.popitem();
print(my_dict); #{'ceo': 'Jason'}

for x, y in my_dict.items():
    print(x,y); #ceo Jason

 

집합 Set

- 중복을 허용하지 않음. 

- 삽입/삭제 시간복잡도 : c++의 경우 O(logN), python의 경우 O(1)

 

Code😂(Python):

 

my_set={1,2,3,4};
print(my_set); #{1, 2, 3, 4}

my_set.add(1);
print(my_set); #{1, 2, 3, 4}

your_set={3,4,5,6};
print(my_set&your_set); #{3, 4} 교집합
print(my_set|your_set); #{1, 2, 3, 4, 5, 6} 합집합
print(my_set-your_set); #{1, 2} 차집합
print(my_set^your_set); #{1, 2, 5, 6} 합집합-교집합

your_set.remove(6);
print(your_set) #{3, 4, 5}