CCCPaste

字串壓縮的方法之一,是用重複次數來編碼

def parse(s):
    nums = []
    words = []

    expecting_num = True if ord('9') >= ord(s[0]) >= ord('0') else False
    if not expecting_num:
        nums = [1]

    num_buf = []
    word_buf = []
    for i, x in enumerate(s):
        if ord('9') >= ord(x) >= ord('0'): # if x.isdigit():
            if not expecting_num:
                # word ends, start num
                words.append(''.join(word_buf))
                word_buf = []
                expecting_num = True
            num_buf.append(x)
        else:
            if expecting_num:
                # num ends, start word
                nums.append(int(''.join(num_buf)))
                num_buf = []
                expecting_num = False
            word_buf.append(x)

    if num_buf:
        nums.append(int(''.join(num_buf)))
    if word_buf:
        words.append(''.join(word_buf))

    return nums, words

while (s := input("Enter string (e.g., 3a2bc1xyz): ")):
	print(list(zip(*parse(s))))
	# 3. Use zip() to pair the nums with the *following* string
	#    and use a generator expression (like a list comprehension)
	#    Example: [('3', 'bc'), ('2', 'xyz'), ('1', '')]
	ans = "".join(s_part * n_part for n_part, s_part in
   		          zip(*parse(s)))

	print(f"Final Answer: {ans}")