检查给定基数中数字的表示形式是否有效

2024-04-26 00:13:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我写了这段代码来检查一个数在给定的基数中是否正确表示。对于所有无效的情况,它给出false,但对于真的情况,它表示字符串索引超出范围。在

def check(n,a,i=0):
    if int(n[i])>=a :
        return False
    else:
        return check(n,a,i+1)   
n = str(input('enter no:'))
a =int(input('enter base:'))
print(check(n,a,i=0))  

Tags: 字符串代码falseinputreturnifdefcheck
3条回答

如果它能检查10以上的基数就更好了。像这样:

import string

def check(num, base, i = 0):
    if i >= len(num):
        return True
    if not num[i].isdigit():
        val = string.ascii_lowercase.find(num[i].lower())
        if val == -1 or val + 10 >= base:
            return False
    elif int(num[i]) >= base:
        return False
    return check(num, base, i + 1)

while True:
    num = raw_input('Enter number: ')
    if len(num) == 0: break # null string breaks
    base = int(raw_input('Enter base: '))
    print(check(num, base))

正如@ooga指出的,当i大于数字的长度时,您需要进行检查,您可以这样做:

def check(n,a,i=0):
    if len(n) <= i:
        return True
    if int(n[i])>=a :
        return False
    else:
        return check(n,a,i+1)   

n = str(input('enter no:'))
a = int(input('enter base:'))

print(check(n,a,i=0))  

Python之道:

def is_base_x(num_string, base):
    for single_char in num_string:
        if int(single_char) >= int(base):
            return False
    return True

相关问题 更多 >