搜尋此網誌

2026年6月2日星期二

Part I of Python test

def encodeString(stringVal):

    encodedList = []

    prevChar = stringVal[0]

    count = 0


    for char in stringVal:

        if prevChar != char:

            encodedList.append((prevChar, count))

            count = 0

            prevChar = char

        count = count + 1


    encodedList.append((prevChar, count))

    return encodedList


Step 1: Setup

  • encodedList = [] → empty list to store results.

  • prevChar = stringVal[0] → start with the first character of the string.

  • count = 0 → counter for consecutive occurrences.


Step 2: Loop through each character

for char in stringVal:

Goes through every character in the string one by one.


Step 3: Check if the character changes

if prevChar != char:
    encodedList.append((prevChar, count))
    count = 0
    prevChar = char

If the current character is different from the previous one:

  • Save the previous character and its count into encodedList.

  • Reset count to 0.

  • Update prevChar to the new character.

  • When you hit a character change, you first append the tuple (prevChar, count) to encodedList.

  • At that moment, the value of count is already finalized for that run (e.g., 3 for 'a').That tuple is stored in the list and won’t be touched again

  • After saving, you reset count = 0 because you’re about to start counting a new run for the next character.

  • This reset only affects future counting, not the already-saved tuple.


Step 4: Count occurrences

count = count + 1

Always increment the counter for the current character.


Step 5: Add the last group

encodedList.append((prevChar, count))

After the loop finishes, add the final character group to the list.


Step 6: Return result

return encodedList

The function returns the list of (character, count) tuples.

Take "aaabbc" as input:

  1. Start: prevChar = 'a', count = 0

  2. Loop:

    • 'a' → same as prevCharcount = 1

    • 'a' → same → count = 2

    • 'a' → same → count = 3

    • 'b' → different!

      • Save ('a', 3)

      • Reset count = 0

      • Update prevChar = 'b'

      • Then increment → count = 1

    • 'b' → same → count = 2

    • 'c' → different!

      • Save ('b', 2)

      • Reset count = 0

      • Update prevChar = 'c'

      • Then increment → count = 1

  3. End of loop → Save ('c', 1)

Result: [('a', 3), ('b', 2), ('c', 1)]


Microsoft Copilot

沒有留言:

發佈留言