เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

enumerate()

มาลอง enumerate กัน! โจทย์คือ ให้รับ string เข้ามา แล้วนิยามฟังก์ชัน retrieve_character_indices() ที่สร้าง dictionary ชื่อ character_indices โดยแต่ละคีย์แทนอักขระที่ไม่ซ้ำกันใน string และค่าที่สอดคล้องกันเป็น list ของ index หรือตำแหน่งของอักขระนั้นใน string

ตัวอย่างเช่น หากส่ง string 'ukulele' เข้าไปในฟังก์ชัน retrieve_character_indices() ผลลัพธ์ที่ได้ควรเป็น: {'e': [4, 6], 'k': [1], 'l': [3, 5], 'u': [0, 2]}

ในแบบฝึกหัดนี้ ห้ามใช้ string method ใด ๆ ทั้งสิ้น

แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร

ฝึกทำโจทย์สัมภาษณ์งานเขียนโค้ดด้วย Python

ดูคอร์ส

คำแนะนำการฝึกหัด

  • นิยาม for loop ที่วนซ้ำผ่านอักขระใน string พร้อมกับ index ของแต่ละตัว
  • อัปเดต dictionary เมื่อคีย์นั้นมีอยู่แล้ว
  • อัปเดต dictionary เมื่อคีย์นั้นยังไม่มี

แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ

ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์

def retrieve_character_indices(string):
    character_indices = dict()
    # Define the 'for' loop
    for index, character in ____(____):
        # Update the dictionary if the key already exists
        if character in character_indices:
            ____[____].____(____)
        # Update the dictionary if the key is absent
        else:
            ____[____] = [____]
            
    return character_indices
  
print(retrieve_character_indices('enumerate an Iterable'))
แก้ไขและรันโค้ด