编辑代码

def encode(s):
    if not s:
        return ""
    current_char = s[0]
    count = 1
    encoded = []
    for char in s[1:]:
        if char == current_char:
            count += 1
        else:
            if count > 1:
                encoded.append(f"{current_char}{count}")
            else:
                encoded.append(current_char)
            current_char = char
            count = 1
    # 处理最后一个字符
    if count > 1:
        encoded.append(f"{current_char}{count}")
    else:
        encoded.append(current_char)

    return "".join(encoded)

def decode(s):
    decoded = []
    i = 0
    n = len(s)
    while i < n:
        char = s[i]
        i += 1
        num_str = ""
        while i < n and s[i].isdigit():
            num_str += s[i]
            i += 1
        count = int(num_str) if num_str else 1
        decoded.append(char * count)
    return "".join(decoded)

def is_encoded(s):
    i = 0
    while i < len(s):
        if not s[i].isalpha():
            return False
        i += 1
        num_str = ""
        while i < len(s) and s[i].isdigit():
            num_str += s[i]
            i += 1
        if not num_str:
            return False
    return True

def is_valid_input(s):
    if s.isalpha():
        return True
    if is_encoded(s):
        return True
    return False

# 获取用户输入
user_input = input("请输入字符串: ")

if not is_valid_input(user_input):
    print("输入的字符串不满足编码或解码条件")
else:
    if is_encoded(user_input):
        result = decode(user_input)
        print(f"解码结果: {result}")
    else:
        result = encode(user_input)
        print(f"编码结果: {result}")

    # 验证编码解码的一致性
    if not is_encoded(user_input):
        assert decode(result) == user_input, "编码解码一致性验证失败"
        print("编码解码一致性验证通过")