Python代码求助!为什么全都是RE啊啊啊

P1015 [NOIP1999 普及组] 回文数

SwordRain @ 2023-10-08 20:14:19

import sys

def to_base_N(decimal: int):
    if N == 16:
        return hex(decimal)[2:]
    if N == 8:
        return oct(decimal)[2:]
    if N == 10:
        return str(decimal)
    result = ''
    while decimal > 0:
        temp = decimal % N
        result = str(temp) + result
        decimal = decimal // N
    return result

def add(num_str):
    result = 0
    if N == 16:
        shun = [int(i, 16) for i in num_str]
        fan = [int(i, 16) for i in num_str[::-1]]
        shun_add_fan = [shun[i] + fan[i] for i in range(len(num_str))][::-1]
        for i in range(len(shun_add_fan)):
            result += shun_add_fan[i] * (16 ** i)
        return to_base_N(result)
    else:
        shun = [int(i) for i in num_str]
        fan = [int(i) for i in num_str[::-1]]
        shun_add_fan = [shun[i] + fan[i] for i in range(len(num_str))][::-1]
        for i in range(len(shun_add_fan)):
            result += shun_add_fan[i] * (N ** i)
        return to_base_N(result)

N = int(input())
M = input()
count = 0
while count <= 30:
    print(M)
    if M == M[::-1]:
        print(f"STEP={count}")
        sys.exit()
    count += 1
    # 倒置相加操作,返回一个字符串赋值给M
    M = add(M)

print("Impossible!")

为什么全都是RE?我在PyCharm可以正确运行啊,样例和第一个检查点都正确


by Operation0701 @ 2023-11-12 00:41:05

题解里有一个说的很清楚,就是读入的数据里有一个回车,必须得处理异常否则会报错。

instr = input()
l = []
for ch in instr:
    try:
        l.append(int(ch,base=n))
    except Exception:
        pass

还有你没有对输入的N进制数字进行转换,你要先转换为10进制数字才能模拟运算。


|