JESKO GARAGE All topicsViva questions ▶ Open the practice garage

Python Unit 4 / course objective — building a basic ai chatbot: 12 practice problems

UNIT 4 of the free Python for AI course. Read the short theory, then solve the problems below with instant tests. Python runs in your browser.

▶ Practise Unit 4 / course objective — building a basic ai chatbot nowAll topics

Theory: Unit 4 / course objective — building a basic ai chatbot in Python

THEORY
------
* CHATBOT = a program that converses with users in natural language.
  RULE-BASED: keyword / pattern matching -> scripted replies (ELIZA, 1966). Predictable, cheap,
              no training data; fails on unexpected input.
  RETRIEVAL-BASED: picks the best answer from a FAQ using text SIMILARITY.
  ML / GENERATIVE: learns intents from examples or uses a Large Language Model (Transformer)
              to generate replies (ChatGPT, Claude). Flexible; needs data/compute; can hallucinate.
* NLP PIPELINE
      1. PREPROCESS  lowercase, remove punctuation, TOKENIZE (split into words), remove STOPWORDS
                     ("the", "is", "a"), optionally stem/lemmatize ("running" -> "run")
      2. INTENT DETECTION  what does the user want?  (greet, order_pizza, ask_price, bye)
      3. ENTITY / SLOT EXTRACTION  the details: numbers, dates, names, sizes, emails
      4. DIALOGUE MANAGEMENT  keep CONTEXT/MEMORY (the user's name, the order so far)
      5. RESPONSE  template ("Hi {name}!") or retrieved/generated text; FALLBACK when unsure
* TEXT AS NUMBERS
      Bag-of-words: count of each vocabulary word in the sentence -> vector
      Jaccard similarity of word sets = |A ∩ B| / |A ∪ B|  (0 = nothing shared, 1 = identical)
      Cosine similarity of vectors = (a · b) / (|a| |b|)
      (Modern systems use EMBEDDINGS: dense vectors where similar meanings are close.)
* REGULAR EXPRESSIONS (re module) for entities:
      re.findall(r"\d+(?:\.\d+)?", text) numbers   re.findall(r"[\w.]+@[\w.]+\.\w+", text) emails
      re.search(pattern, text) -> match or None    re.sub(pattern, repl, text)
* Evaluate a chatbot: intent accuracy, task completion rate, fallback rate, user satisfaction.

12 Unit 4 / course objective — building a basic ai chatbot practice problems

1. NLP Preprocessing

Easy3 ways to solve
📤 OUTPUT: return a list, e.g. ['price', 'pizza']. Use `return`, not print().
Lowercase, remove punctuation (string.punctuation), split into words, drop STOPWORDS.
    preprocess("What is the PRICE of a Pizza?!") -> ["price", "pizza"]
Solve “NLP Preprocessing” in your browser →

2. Intent Detection by Keyword Score

Medium2 ways to solve
📤 OUTPUT: return a str (text), e.g. 'order'. Use `return`, not print().
intents: dict {intent_name: [keywords]}. Score = number of the intent's keywords appearing in the
preprocessed words. Return the intent with the highest score (ties -> earlier in the dict);
if every score is 0 return "fallback".
    intents = {"greet": ["hi", "hello"], "order": ["order", "buy", "pizza"], "bye": ["bye"]}
    detect_intent("Hello, I want to order a pizza", intents) -> "order"   (score 2 beats 1)
Solve “Intent Detection by Keyword Score” in your browser →

3. Entity Extraction: Numbers — re.findall

Easy2 ways to solve
📤 OUTPUT: return a list, e.g. [2, 450.5, 12]. Use `return`, not print().
Return ints for whole numbers, floats for decimals, in order.
    extract_numbers("2 tickets for 450.50 each, row 12") -> [2, 450.5, 12]
Solve “Entity Extraction: Numbers — re.findall” in your browser →

4. Jaccard Similarity of two sentences (use preprocess, then sets). Round to 2.

Easy1 way to solve
📤 OUTPUT: return a float, e.g. 0.67. Use `return`, not print().
Two empty sets -> 0.0.
    jaccard("pizza price please", "what is the pizza price") -> 0.67
Solve “Jaccard Similarity of two sentences (use preprocess, then sets). Round to 2.” in your browser →

5. Retrieval FAQ Bot

Medium2 ways to solve
📤 OUTPUT: return a str (text), e.g. '9 AM to 8 PM.'. Use `return`, not print().
Real world: A college help-desk bot. faq: dict {stored_question: answer}.
Return the answer whose stored question has the highest jaccard() with the user's question.
If the best score < 0.2 return "Sorry, I don't know that yet."
Solve “Retrieval FAQ Bot” in your browser →

6. Bag-of-Words Vector — count each vocab word in preprocess(sentence)

Easy2 ways to solve
📤 OUTPUT: return a list, e.g. [2, 1, 0]. Use `return`, not print().
    bag_of_words("pizza pizza price", ["pizza", "price", "size"]) -> [2, 1, 0]
Solve “Bag-of-Words Vector — count each vocab word in preprocess(sentence)” in your browser →

7. Cosine Similarity, rounded to 4. Zero vector -> 0.0.

Easy2 ways to solve
📤 OUTPUT: return a float, e.g. 0.7071. Use `return`, not print().
    cosine_similarity([1, 0], [1, 1]) -> 0.7071
Solve “Cosine Similarity, rounded to 4. Zero vector -> 0.0.” in your browser →

8. Response Templates — str.format_map with missing slots

Medium2 ways to solve
📤 OUTPUT: return a str (text), e.g. 'Hi Asha, order 7 ships ?.'. Use `return`, not print().
Fill {slot} placeholders from the dict; missing slots become "?".
    fill_template("Hi {name}, order {id} ships {day}.", {"name": "Asha", "id": 7})
    -> "Hi Asha, order 7 ships ?."
Hint: a dict subclass with __missing__, or re.sub with a function.
Solve “Response Templates — str.format_map with missing slots” in your browser →

9. Chatbot with Memory (context)

Medium1 way to solve
📤 OUTPUT: return the bot's reply as a str (and update memory). Use `return`, not print().
memory is a dict that persists between turns. Rules (check in order, case-insensitive):
    "my name is X"      -> remember X (title-cased) in memory["name"], reply "Nice to meet you, X!"
    contains "my name"  -> "Your name is X." or "I don't know your name yet." if unknown
    "hi"/"hello" word   -> "Hello X!" if the name is known, else "Hello!"
    "bye" word          -> "Goodbye!"
    otherwise           -> "Tell me more."
Solve “Chatbot with Memory (context)” in your browser →

10. Slot-Filling Order Bot

Hard1 way to solve
📤 OUTPUT: return a dict, e.g. {'size': 'large', 'toppings': ['paneer', 'corn…. Use `return`, not print().
Real world: A pizza shop's WhatsApp bot collects an order over several messages.
Read the messages in order and fill slots:
    size     — last of "small"/"medium"/"large" mentioned
    toppings — every topping from ["cheese", "onion", "paneer", "corn", "olives"] mentioned, in
               first-mention order, no duplicates
    quantity — last whole number mentioned (default 1)
Return {"size": size or None, "toppings": [...], "quantity": n}.
    pizza_order(["I want a large pizza", "add paneer and corn", "make it 2", "also corn"])
    -> {"size": "large", "toppings": ["paneer", "corn"], "quantity": 2}
Solve “Slot-Filling Order Bot” in your browser →

11. Banking Support Bot with Slot Filling — interview at a bank (conversational-AI team)

Project1 way to solve
📤 OUTPUT: return a list, e.g. ['Hello! I can block a card or tell your balan…. Use `return`, not print().
Return one bot reply per message. The bot REMEMBERS whether it's waiting for card digits.
  Waiting for digits:
    message contains exactly one standalone 4-digit number -> "Card ending 1234 is now blocked." (stop waiting)
    otherwise -> "Please send the LAST 4 digits of your card."
  Not waiting (lower-case the message, words = split with . , ! ? ' stripped):
    contains "block" and "card"     -> "Sure. What are the last 4 digits of the card?"  (start waiting)
    contains "balance"              -> "Your balance is Rs. 12,500."
    a WORD is "hi" or "hello"       -> "Hello! I can block a card or tell your balance."
    a WORD is "bye"                 -> "Goodbye!"
    otherwise                       -> "Sorry, I can only block cards or tell your balance."
Solve “Banking Support Bot with Slot Filling — interview at a bank (conversational-AI team)” in your browser →

12. Stage 20 — the AI Assistant inside your compiler (a rule-based chatbot)

Compiler1 way to solve
📤 OUTPUT: return a str (text), e.g. 'You used a name that was never defined.'. Use `return`, not print().
last_error looks like "NameError: pirnt", "SyntaxError: unexpected '*'", "ZeroDivisionError: division by zero" or None.
kind = text before ": ", detail = text after it.  Lower-case the question. First matching rule wins:
  1. last_error is None          -> "No errors. Your program compiled fine!"
  2. "what" or "mean" in question -> NameError: "You used a name that was never defined."
                                     SyntaxError: "The code breaks the grammar of the language."
                                     ZeroDivisionError: "Something was divided by zero."
                                     other: "That's a runtime error."
  3. "fix" or "how" in question   -> NameError: f"Define it with let, or check the spelling of '{detail}'."
                                     SyntaxError: f"Check the operators and brackets near: {detail}"
                                     ZeroDivisionError: "Make sure the divisor is not 0."
                                     other: "Read the message and check that line."
  4. otherwise -> "Ask me what the error means or how to fix it."
Solve “Stage 20 — the AI Assistant inside your compiler (a rule-based chatbot)” in your browser →

← BASICS OF NEURAL NETWORKS (with PREREQUISITE: derivatives & gradients)