← 返回题库
初级

实现类型验证器

未完成
初级参考 完整示例代码供参考,建议自己理解后重新输入
def solve():
    from pyodide.http import open_url
    from io import StringIO
    validation_rules_csv = open_url("https://data.zuihe.com/dbd/ms-shop/state_01/validation_rules.csv").read()
    import pandas as pd
    from io import StringIO
    def type_validate(value, expected_type):
        converters = {'int': int, 'float': float, 'str': str, 'bool': lambda v: str(v).lower() in ('true','1')}
        try:
            converted = converters[expected_type](value)
            return True, converted
        except (ValueError, KeyError):
            return False, None
    cases = [
        ('42', 'int'), ('3.14', 'float'), ('hello', 'int'),
        ('true', 'bool'), ('99.5', 'int'), ('alice', 'str'),
    ]
    for val, typ in cases:
        ok, converted = type_validate(val, typ)
        print(f"value={val!r}, type={typ}: ok={ok}, converted={converted!r}")

示例

输入
solve()
期望输出
value='42', type=int: ok=True, converted=42
value='3.14', type=float: ok=True, converted=3.14
value='hello', type=int: ok=False, converted=None
value='true', type=bool: ok=True, converted=True
value='99.5', type=int: ok=False, converted=None
value='alice', type=str: ok=True, converted='alice'
Python 代码 🔒 登录后使用
🔒

登录后即可练习

注册免费账号,在浏览器中直接运行 Python 代码