初级
实现类型验证器
未完成
初级参考
完整示例代码供参考,建议自己理解后重新输入
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'
👑
升级 VIP
解锁全部题目,畅通无阻地学习
- ✓ 解锁全部训练包所有题目
- ✓ 查看完整参考代码和提示
- ✓ 浏览器内直接运行 Python 代码
- ✓ 自动批改 + 进度追踪
30天
¥18
1年
¥99
2年
¥158
3年
¥199