بتل کد Battle Codeدارد باز می‌شود…

جواب «Exact or Normalised?» چالش 2 از جلسه‌ی 76

سؤال

تابع normalise(text) را بنویس: حروف کوچک، strip، فقط حرف و عدد و فاصله نگه دار (isalnum)، و فاصله‌های پشت سر هم را یکی کن. برنامه هر جفت را یک بار دقیق و یک بار یکسان‌شده مقایسه می‌کند. خروجی:
'Paris' / 'paris.': exact no, normalised yes
'The Sun' / ' the sun ': exact no, normalised yes
'12' / 'twelve': exact no, normalised no
'water vapour' / 'Water vapour!': exact no, normalised yes
exact 0/4, normalised 3/4

راهنما

text = text.lower().strip()؛ text = "".join(ch for ch in text if ch.isalnum() or ch == " ")؛ return " ".join(text.split()).

یک جواب درست

def normalise(text):
    text = text.lower().strip()
    text = "".join(ch for ch in text if ch.isalnum() or ch == " ")
    return " ".join(text.split())


PAIRS = [("Paris", "paris."), ("The Sun", "  the sun "), ("12", "twelve"), ("water vapour", "Water  vapour!")]
exact = normal = 0
for expected, reply in PAIRS:
    e = expected == reply
    n = normalise(expected) == normalise(reply)
    exact += e
    normal += n
    print(f"{expected!r} / {reply!r}: exact {'yes' if e else 'no'}, normalised {'yes' if n else 'no'}")
print(f"exact {exact}/{len(PAIRS)}, normalised {normal}/{len(PAIRS)}")

اول خودت امتحان کن؛ جواب‌های دیگر هم قبول است. برگرد و خودت حلش کن