트랙
/
Python
Python
/
연습 문제
/
Tisbury 보물찾기
Tisbury 보물찾기

Tisbury 보물찾기

학습 연습 문제

소개

Python에서 튜플은 항목을 순서대로 담는 불변 컬렉션이에요. 대부분의 컬렉션처럼 tuples는 모든 (또는 여러) 데이터 타입을 담을 수 있어요. 다른 tuples도 포함해서요. 튜플은 모든 일반 시퀀스 연산을 지원하지만, 가변 시퀀스 연산은 지원하지 않아요.

튜플의 원소는 for item in <tuple> 구문으로 반복할 수 있어요. 원소의 인덱스와 값이 둘 다 필요하면 for index, item in enumerate(<tuple>)를 사용할 수 있어요. 다른 시퀀스처럼, tuples 안의 원소는 왼쪽에서부터 0-based index 숫자를, 또는 오른쪽에서부터 -1-based index 숫자를 사용하는 대괄호 표기법 으로 접근할 수 있어요. 튜플은 슬라이스 표기법(<tuple>[<start>:<stop>:<step>])을 사용해 전체 또는 일부를 복사할 수도 있어요.

튜플 생성

튜플은 tuple(<iterable>) 클래스 생성자를 사용하거나 tuple 리터럴 선언을 사용하는 등 여러 방법으로 만들 수 있어요.

tuple() 생성자를 비워 두거나 이터러블 과 함께 사용하기:

>>> no_elements = tuple()
()

# The constructor *requires* an iterable, so single elements must be passed in a list or another tuple.
>>> one_element = tuple([16])
(16,)

문자열은 이터러블이라서, tuple() 생성자의 인자로 str 하나를 넘기면 놀라운 결과가 나올 수 있어요:

# String elements (characters) are iterated through and added to the tuple
>>> multiple_elements_string = tuple("Timbuktu")
('T', 'i', 'm', 'b', 'u', 'k', 't', 'u')

하나의 이터러블은 원소가 하나씩 추가돼요:

>>> multiple_elements_list = tuple(["Parrot", "Bird", 334782])
("Parrot", "Bird", 334782)

>>> multiple_elements_set = tuple({2, 3, 5, 7, 11})
(2,3,5,7,11)
튜플을 리터럴 로 선언하기:

tuple(<iterable>) 생성자는 이터러블(또는 아무것도)만 인자로 받기 때문에, 리터럴 방식으로 하나짜리 튜플을 만드는 게 훨씬 쉬워요.

>>> no_elements = ()
()

>>> one_element = ("Guava",)
("Guava",)

중첩된 자료 구조도 다른 tuples를 포함해 tuple의 원소로 넣을 수 있어요:

>>> nested_data_structures = ({"fish": "gold", "monkey": "brown", "parrot" : "grey"}, ("fish", "mammal", "bird"))
({"fish": "gold", "monkey": "brown", "parrot" : "grey"}, ("fish", "mammal", "bird"))

>>> nested_data_structures_1 = (["fish", "gold", "monkey", "brown", "parrot", "grey"], ("fish", "mammal", "bird"))
(["fish", "gold", "monkey", "brown", "parrot", "grey"], ("fish", "mammal", "bird"))

튜플 연결

튜플은 더하기 + 연산자로 연결할 수 있는데, 이 연산자는 각 tuple을 풀어서 새로운 하나의 tuple을 만들어요.

>>> new_via_concatenate = ("George", 5) + ("cat", "Tabby")
("George", 5, "cat", "Tabby")

#likewise, using the multiplication operator * is the equivalent of using + n times
>>> first_group = ("cat", "dog", "elephant")

>>> multiplied_group = first_group * 3
('cat', 'dog', 'elephant', 'cat', 'dog', 'elephant', 'cat', 'dog', 'elephant')

튜플 안의 원소에 접근하기

tuple 안의 원소는 왼쪽에서부터 0-based index 숫자를, 또는 오른쪽에서부터 -1-based index 숫자를 사용하는 대괄호 표기법 으로 접근할 수 있어요.

student_info = ("Alyssa", "grade 3", "female", 8 )

#gender is at index 2 or index -2
>>> student_gender = student_info[2]
'female'

>>> student_gender = student_info[-2]
'female'

#name is at index 0 or index -4
>>> student_name = student_info[0]
Alyssa

>>> student_name = student_info[-4]
Alyssa

튜플의 원소 반복하기

tuple 안의 원소는 for item in <tuple> 구문을 사용해 루프에서 반복 할 수 있어요. 인덱스와 값이 둘 다 필요하면 for index, item in enumerate(<tuple>)를 사용할 수 있어요.

>>> student_info = ("Alyssa", "grade 3", "female", 8 )
>>> for item in student_info:
...   print(item)

...
Alyssa
grade 3
female
8

>>> for index, item in enumerate(student_info):
...  print("Index is: " + str(index) + ", value is: " + str(item) +".")

...
Index is: 0, value is: Alyssa.
Index is: 1, value is: grade 3.
Index is: 2, value is: female.
Index is: 3, value is: 8.

튜플에 값이 들어 있는지 확인하기

in 연산자를 사용해 tuple에 값이 들어 있는지 확인할 수 있어요.

>>> multiple_elements_list = tuple(["Parrot", "Bird", 334782])
("Parrot", "Bird", 334782)

>>> "Parrot" in multiple_elements_list
True

지침

Azara와 Rui는 해적을 주제로 한 보물찾기에서 겨루는 팀 동료예요. 한 명은 지도 좌표가 붙은 보물 목록을, 다른 한 명은 지도 좌표가 붙은 위치 이름 목록을 가지고 있어요. 두 사람은 또한 출발 지점에 '현재 위치'가 표시된 빈 지도도 함께 받았어요.


Azara의 목록 Rui의 목록
보물 좌표
Amethyst Octopus 1F
Angry Monkey Figurine 5B
Antique Glass Fishnet Float 3D
Brass Spyglass 4B
Carved Wooden Elephant 8C
Crystal Crab 6A
Glass Starfish 6D
Model Ship in Large Bottle 8A
Pirate Flag 7F
Robot Parrot 1C
Scrimshawed Whale Tooth 2A
Silver Seahorse 4E
Vintage Pirate Hat 7E
위치 이름 좌표 사분면
Seaside Cottages ("1", "C") Blue
Aqua Lagoon (Island of Mystery) ("1", "F") Yellow
Deserted Docks ("2", "A") Blue
Spiky Rocks ("3", "D") Yellow
Abandoned Lighthouse ("4", "B") Blue
Hidden Spring (Island of Mystery) ("4", "E") Yellow
Stormy Breakwater ("5", "B") Purple
Old Schooner ("6", "A") Purple
Tangled Seaweed Patch ("6", "D") Orange
Quiet Inlet (Island of Mystery) ("7", "E") Orange
Windswept Hilltop (Island of Mystery) ("7", "F") Orange
Harbor Managers Office ("8", "A") Purple
Foggy Seacave ("8", "C") Purple

그런데 상황이 조금 엉망이에요. Azara의 좌표는 Rui의 좌표와 형식도, 정렬 순서도 다르게 보여서, 어떤 보물이 어떤 위치에 해당하는지 알아내려면 두 목록을 계속 번갈아 봐야 해요. 이제 막 파이썬을 배우기 시작한 두 사람은 탐색 정보를 더 잘 정리할 작은 프로그램(사실은 함수 몇 개)을 짜는 데 도움을 청하러 왔어요.

1. 좌표 추출하기

Azara의 목록에 있는 (treasure, coordinate) 쌍을 받아 추출한 지도 좌표만 반환하는 get_coordinate() 함수를 구현해요.

>>> get_coordinate(('Scrimshawed Whale Tooth', '2A'))
2A

2. 좌표 형식 맞추기

"2A" 형식의 좌표를 받아 ("2", "A") 형식의 튜플을 반환하는 convert_coordinate() 함수를 구현해요.

>>> convert_coordinate("2A")
("2", "A")

3. 좌표 대조하기

(treasure, coordinate) 쌍과 (location, coordinate, quadrant) 레코드를 받아 각각의 좌표를 비교하는 compare_records() 함수를 구현해요. 좌표가 "일치"하면 **True**를 반환하고, 일치하지 않으면 **False**를 반환해요. 정확하게 비교하려면 필요에 따라 좌표 형식을 다시 맞춰요.

>>> compare_records(('Brass Spyglass', '4B'), ('Seaside Cottages', ('1', 'C'), 'blue'))
False

>>> compare_records(('Model Ship in Large Bottle', '8A'), ('Harbor Managers Office', ('8', 'A'), 'purple'))
True

4. 일치하는 레코드 합치기

Azara의 목록에 있는 (treasure, coordinate) 쌍과 Rui의 목록에 있는 (location, coordinate, quadrant) 레코드를 받아, 좌표가 일치하면 (treasure, coordinate, location, coordinate, quadrant)를 반환하는 create_record() 함수를 구현해요. 좌표가 일치하지 않으면 문자열 **"not a match"**를 반환해요. 정확하게 비교하려면 필요에 따라 좌표 형식을 다시 맞춰요.

>>> create_record(('Brass Spyglass', '4B'), ('Abandoned Lighthouse', ('4', 'B'), 'Blue'))
('Brass Spyglass', '4B', 'Abandoned Lighthouse', ('4', 'B'), 'Blue')

>>> create_record(('Brass Spyglass', '4B'), ('Seaside Cottages', ('1', 'C'), 'blue'))
"not a match"

5. "정리"하고 모든 레코드의 보고서 만들기

Azara와 Rui의 레코드를 합친 것을 레코드마다 좌표가 한 세트만 남도록 정리해요. 지도에 표시해야 할 모든 것을 하나의 목록으로 볼 수 있도록 보고서를 만들어요. _두 목록의 모든 것_을 담은 튜플의 튜플을 받는 clean_up() 함수를 구현해요. 바깥 튜플을 순회하면서 각 안쪽 튜플에서 필요 없는 좌표를 버리고, 각각을 'report'에 추가해요. 정리된 레코드가 각 줄에 하나씩 오도록 'report'의 형식을 맞춰 반환해요.

>>> clean_up((('Brass Spyglass', '4B', 'Abandoned Lighthouse', ('4', 'B'), 'Blue'), ('Vintage Pirate Hat', '7E', 'Quiet Inlet (Island of Mystery)', ('7', 'E'), 'Orange'), ('Crystal Crab', '6A', 'Old Schooner', ('6', 'A'), 'Purple')))

"""
('Brass Spyglass', 'Abandoned Lighthouse', ('4', 'B'), 'Blue')\n
('Vintage Pirate Hat', 'Quiet Inlet (Island of Mystery)', ('7', 'E'), 'Orange')\n
('Crystal Crab', 'Old Schooner', ('6', 'A'), 'Purple')\n
"""
GitHub에서 편집 링크가 새 창이나 탭에서 열려요
Python Exercism

Tisbury 보물찾기 문제를 시작해 볼 준비가 됐나요?

Exercism에 가입하고 Python 트랙을 개념 17개연습 문제 146개, 그리고 실제 사람의 멘토링과 함께 배우고 익혀 보세요. 모두 무료예요.