搜尋此網誌

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.


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.

Microsoft Copilot

沒有留言:

發佈留言