AI Computer Institute
Expert-curated CS & AI curriculum aligned to CBSE standards. A bharath.ai initiative. About Us

Grade 9 AI & Computer Science Practice Questions — Set 8

20 questions from the Grade 9 bank, each with its answer and a full explanation. Set 8 of 11 · 221 questions in this grade.

Reading is revision; testing is practice. Take the same questions as a timed quiz →

Question 141 · Causal Inference: Understanding Cause and Effect · hard

A CS mentor at an Indian coding bootcamp analyzes results from 700 students who prepared for a certification test using either Method A (guided video tutorials) or Method B (unsupervised practice problems), split by which problem track each student attempted: ``` Easy Track: Method A -> 81 passed / 87 total (93.1%) Method B -> 234 passed / 270 total (86.7%) Hard Track: Method A -> 192 passed / 263 total (73.0%) Method B -> 55 passed / 80 total (68.8%) Overall: Method A -> 273 passed / 350 total (78.0%) Method B -> 289 passed / 350 total (82.6%) ``` Teachers mostly steered already-struggling students toward Method A on the Hard track, and confident students coasted through the Easy track using Method B. Given this, which conclusion about the causal effect of the two study methods is most defensible?

  1. Method B is the superior study method because its overall pass rate of 82.6% beats Method A's 78.0%, so the aggregate totals across all 700 students are the right basis for recommending one method over the other.
  2. Method A produces the higher pass rate within both the Easy track (93.1% vs 86.7%) and the Hard track (73.0% vs 68.8%); the reversed overall numbers arise because track difficulty is confounded with method choice — most Method A students came from the harder track — so the stratified, like-for-like comparison is the credible causal signal, not the aggregate.
  3. No causal claim can be trusted from this dataset because a reversal between the stratified and aggregate pass rates is a sign that the underlying counts were recorded or entered incorrectly and the data collection must be redone.
  4. Track difficulty cannot be a confounder here because Method A's own pass rate is lower on the Hard track than on the Easy track, which shows video tutorials specifically become ineffective once problems get harder, regardless of who chooses that track.

Answer: B. Method A produces the higher pass rate within both the Easy track (93.1% vs 86.7%) and the Hard track (73.0% vs 68.8%); the reversed overall numbers arise because track difficulty is confounded with method choice — most Method A students came from the harder track — so the stratified, like-for-like comparison is the credible causal signal, not the aggregate.

ExplanationThis is a textbook case of Simpson's Paradox, and it is exactly the trap causal inference is designed to catch: aggregating across groups without accounting for a confounder can flip the apparent direction of an effect. Within the Easy track, Method A's 93.1% pass rate (81/87) beats Method B's 86.7% (234/270). Within the Hard track, Method A's 73.0% (192/263) still beats Method B's 68.8% (55/80). Method A wins in both strata, every time it is compared like-for-like. Yet Method A's overall pass rate (273/350 = 78.0%) looks lower than Method B's (289/350 = 82.6%) — because track difficulty independently lowers pass rates for everyone and simultaneously determines which method a student was likely to receive: strugglers were pushed toward Method A on the Hard track, while confident students coasted through Method B on the Easy track. Comparing raw totals conflates the effect of the study method with the effect of track difficulty, so the 82.6% vs 78.0% aggregate is comparing two different populations, not two methods. Controlling for the confounder by comparing within each track is what a causal read requires, and that stratified comparison consistently favors Method A. A reversal of this kind is a known, real statistical phenomenon, not proof of bad data entry — and a lower absolute pass rate on the Hard track doesn't indict Method A specifically, since Method B's rate drops on the Hard track too; the track itself, not the method, is what is dragging both numbers down.

Question 142 · Model Drift Detection and Continuous Monitoring · hard

A bank's UPI fraud-detection model is deployed with a validation accuracy of 96.0% (the baseline). The monitoring team sets a drift-alert rule: raise an alert only if the live weekly accuracy falls below 94.0% (baseline minus 2 percentage points) for at least two consecutive weeks, so that a single unusually noisy week doesn't trigger a false alarm. Over the next five weeks, the model's live accuracy on real UPI transactions is: Week 1 – 95.5%, Week 2 – 94.6%, Week 3 – 93.8%, Week 4 – 93.5%, Week 5 – 95.1%. Applying this monitoring rule to the recorded weekly accuracies, in which week does the system correctly confirm and raise a drift alert?

  1. Week 3 already crosses the 94.0% line, so alerting the moment accuracy dips to 93.8% is the correct response.
  2. Confirmed drift is only reached at the end of Week 4, once accuracy has stayed below the 94.0% threshold for two straight weeks (93.8% in Week 3 and 93.5% in Week 4).
  3. Week 2's accuracy of 94.6% shows a clear downward trend, so raising the alert immediately is the safer choice.
  4. Averaging all five weeks gives 94.5% accuracy, which stays above the 94.0% cutoff, so no drift alert should ever be raised.

Answer: B. Confirmed drift is only reached at the end of Week 4, once accuracy has stayed below the 94.0% threshold for two straight weeks (93.8% in Week 3 and 93.5% in Week 4).

ExplanationThe alert rule requires two consecutive weekly readings below 94.0% (96.0% minus 2 percentage points), not a single dip and not an overall average. Week 1 (95.5%) and Week 2 (94.6%) are both still above 94.0%, so no breach has occurred yet. Week 3 (93.8%) is the first week below 94.0%, but that is only one breach — the rule needs a second consecutive week to rule out a one-off noisy week, such as a temporary payment-gateway outage or a festival-season shift in the transaction mix. Week 4 (93.5%) is also below 94.0%, giving two consecutive weeks of breach, so the drift alert is correctly confirmed and raised at the end of Week 4. Alerting already at Week 3 would fire on unconfirmed noise before the pattern is verified, and alerting at Week 2 is premature since 94.6% has not even crossed the threshold. Averaging all five weeks gives (95.5 + 94.6 + 93.8 + 93.5 + 95.1) / 5 = 94.5%, which stays above 94.0% and completely hides the real two-week drift episode in the middle of the window — this is exactly why robust drift-monitoring systems use a consecutive-window rule rather than a single long-run average that can smooth away localized drift.

Question 143 · Meta-Learning and Few-Shot Learning: Learning to Learn · hard

A team building a meta-learning classifier for a robotics club wants it to recognize brand-new hand-drawn symbols from the ancient Brahmi script — characters the model has never encountered during pre-training. They set up a classic N-way K-shot episodic training loop: each episode samples 5-way, 3-shot support examples (5 classes, 3 labeled example images per class) that the model briefly adapts to, followed by a query set of 10 unlabeled images per class used to test how well that adaptation worked. (The full dataset also holds 2 completely separate classes reserved only for a final generalization test after all training is done — these are not part of any individual episode.) How many total images make up one training episode, counting both the support set and the query set?

  1. 65 images — 15 in the support set (5 classes × 3 shots) plus 50 in the query set (5 classes × 10 queries).
  2. 15 images — only the support set counts as the episode; query images are used purely for evaluation afterward, not part of the episode.
  3. 53 images — the 3-shot support set contains 3 images total across all 5 classes, plus 50 query images.
  4. 25 images — the query set contains 10 images total across all 5 classes, plus 15 support images.

Answer: A. 65 images — 15 in the support set (5 classes × 3 shots) plus 50 in the query set (5 classes × 10 queries).

ExplanationIn N-way K-shot episodic meta-learning, N is the number of classes sampled per episode and K is the number of labeled examples per class in the support set — so the support set size is N × K, not K alone. Here that's 5 × 3 = 15 images. The query set draws from the same N classes with its own count of unlabeled examples per class, so its size is N × (queries per class) = 5 × 10 = 50 images, not just the queries-per-class figure. Both sets belong to the same episode: the model briefly adapts using the 15 support images, and that adapted model is then scored on the 50 query images to produce the training signal — so one full episode contains 15 + 50 = 65 images. The 2 classes held out for the final generalization test sit entirely outside the episodic training loop; they exist to check whether the trained model generalizes to genuinely unseen classes once training is finished, so they contribute 0 images to any individual episode and must not be folded into this count.

Question 144 · Android Development Basics: Building Apps for Billions of Users · hard

A shopping app aimed at the Indian market needs to show a scrollable catalog of 10,000 products so it stays smooth even on entry-level Android Go phones with just 1GB of RAM. At any given moment, the phone's screen can fit exactly 6 product cards. The app uses RecyclerView with the ViewHolder pattern, which keeps a small fixed number of extra off-screen views (2) ready for smooth scrolling. Approximately how many View objects actually get created in memory as the user scrolls through the entire 10,000-item catalog, and why?

  1. About 8 (6 visible + 2 buffer) view objects total — RecyclerView creates only enough views to fill the screen plus a small buffer, then recycles and rebinds them with new data as the user scrolls, regardless of catalog size
  2. Exactly 10,000 view objects — one per product — because Android must create a permanent View for every data item so that scrolling back up doesn't lose any product's display
  3. 6 view objects only, one for each visible slot — the 2 buffer views don't actually get created, and scrolling briefly pauses each time a new view must be inflated on demand
  4. 10,000/6 ≈ 1,667 view objects — RecyclerView groups the catalog into batches equal to the number of visible items and permanently creates one full batch of views per screenful scrolled

Answer: A. About 8 (6 visible + 2 buffer) view objects total — RecyclerView creates only enough views to fill the screen plus a small buffer, then recycles and rebinds them with new data as the user scrolls, regardless of catalog size

ExplanationRecyclerView's ViewHolder pattern breaks the older assumption that a scrollable list needs one permanent View object per data item. Instead of inflating a separate View for each of the 10,000 products, RecyclerView keeps only enough View objects to cover what's physically visible (6 cards) plus a small recycling buffer (2 extra), for a total of about 8. As the user scrolls, onBindViewHolder() re-populates these same 8 View objects with new product data — image, name, price — while the old data simply scrolls off-screen and gets overwritten, not the View itself. This is precisely why RecyclerView (and ListView's convertView mechanism before it) exists: on an Android Go phone with 1GB of RAM, holding 10,000 live View objects at once would exhaust memory and crash the app, while 8 recycled views keep memory usage flat no matter how large the catalog grows. That constant, catalog-size-independent memory footprint is what "building for billions of users" actually demands — most of those users are on entry-level hardware, not flagship phones with RAM to spare.

Question 145 · AI Bias and Fairness: Ensuring Ethical AI Systems · hard

A state education department deploys an AI tool to shortlist applicants for a coding-bootcamp scholarship. The tool is tested separately on 100 rural applicants and 100 urban applicants; in each group, exactly 40 students are truly capable of completing the bootcamp (the remaining 60 are not). Rural applicants (40 truly capable, 60 not capable): 20 truly capable students correctly shortlisted, 20 truly capable students wrongly rejected, 50 not-capable students correctly rejected, 10 not-capable students wrongly shortlisted. Urban applicants (40 truly capable, 60 not capable): 32 truly capable students correctly shortlisted, 8 truly capable students wrongly rejected, 38 not-capable students correctly rejected, 22 not-capable students wrongly shortlisted. Overall accuracy works out to exactly 70% for both groups. If you calculate the True Positive Rate (the fraction of truly capable students who actually get shortlisted) separately for each group, what does it reveal about the fairness of this tool?

  1. Calculating True Positive Rate (correctly shortlisted ÷ truly capable) gives 50% for rural applicants and 80% for urban applicants, revealing that an equally capable rural student is far less likely to be shortlisted than an equally capable urban student — a violation of equal-opportunity fairness despite matching overall accuracy.
  2. Because overall accuracy is identical at 70% in both groups, the tool treats rural and urban applicants fairly, and no further breakdown by group is necessary to confirm fairness.
  3. Dividing correctly shortlisted students by the total group size of 100 gives a True Positive Rate of 20% for rural and 32% for urban applicants, showing only a mild bias favouring urban applicants.
  4. The 50%-vs-80% True Positive Rate gap is real, but since urban applicants also have a higher false-positive rate (36.7% vs 16.7%), these two error types cancel out and the tool ends up equally fair to both groups overall.

Answer: A. Calculating True Positive Rate (correctly shortlisted ÷ truly capable) gives 50% for rural applicants and 80% for urban applicants, revealing that an equally capable rural student is far less likely to be shortlisted than an equally capable urban student — a violation of equal-opportunity fairness despite matching overall accuracy.

ExplanationTrue Positive Rate (also called recall or sensitivity) is calculated as correctly shortlisted truly-capable students divided by the total number of truly-capable students in that group — not divided by the group's total size. For rural applicants that is 20 ÷ 40 = 50%; for urban applicants it is 32 ÷ 40 = 80%. Even though both groups show identical 70% overall accuracy — (20+50)/100 for rural and (32+38)/100 for urban — a truly capable rural student has only a 50% chance of being shortlisted while an equally capable urban student has an 80% chance, a 30-percentage-point gap in opportunity that the aggregate accuracy figure completely hides. This is exactly why fairness audits of real screening systems — scholarship, loan, and college-admission tools used across India included — must check group-wise error rates such as True Positive Rate and False Positive Rate separately, not just overall accuracy. Two models can post the same accuracy while delivering very different real-world outcomes to different communities, so matching accuracy numbers is not proof of fairness. Error types also do not simply cancel out: a higher false-positive rate among urban applicants does nothing to help the truly qualified rural students who were wrongly rejected. The equal-opportunity fairness criterion specifically compares True Positive Rates across groups, and here it is clearly violated.

Question 146 · Augmented and Virtual Reality: Immersive Technology · hard

A VR headset advertises a 90 Hz refresh rate, and it's tempting to assume that alone guarantees a comfortable experience. VR engineers actually track a stricter budget: total motion-to-photon latency — the delay between a head movement and the display updating to match it — should stay under 20 ms, the point beyond which most users start to notice a mismatch between their inner ear's sense of motion and what their eyes see, a common trigger for VR-induced motion sickness. For one headset, the pipeline breaks down as: head-tracking sensor sampling and pose calculation = 2 ms, scene rendering on the GPU = 11 ms, frame buffer transfer to the display = 3 ms, and display panel pixel-switching time = 5 ms. Based on this breakdown, what is the total motion-to-photon latency, and does the headset meet the 20 ms comfort threshold?

  1. Because the display refreshes at 90 Hz, each frame takes about 11.1 ms, and since refresh rate is what motion-to-photon latency measures, the pipeline finishes well within the 20 ms threshold.
  2. Rendering runs on the GPU while tracking and display output happen on separate hardware, so only the non-render stages count: 2 + 3 + 5 = 10 ms, comfortably under the 20 ms threshold.
  3. The stages sum to 2 + 11 + 3 + 5 = 21 ms, which is 1 ms above the 20 ms comfort threshold — so despite refreshing 90 times a second, the user may still perceive a lag between turning their head and seeing the world respond.
  4. The 21 ms figure is correct, but it stays comfortable for most users because the recognized motion-to-photon threshold for avoiding simulator sickness is closer to 50 ms, not 20 ms.

Answer: C. The stages sum to 2 + 11 + 3 + 5 = 21 ms, which is 1 ms above the 20 ms comfort threshold — so despite refreshing 90 times a second, the user may still perceive a lag between turning their head and seeing the world respond.

ExplanationMotion-to-photon latency is a chain of dependent stages, not a single number set by refresh rate: the display can't scan out a frame until rendering finishes, and rendering can't start until the sensor has reported the head's new position. So the four stages here add sequentially: 2 ms (sensor + pose) + 11 ms (render) + 3 ms (buffer transfer) + 5 ms (panel switch) = 21 ms. Since the widely used comfort ceiling for motion-to-photon latency in VR is 20 ms — the point below which most users don't consciously notice the world lagging behind their head movement — this headset sits 1 ms above the line, and a sensitive user could still feel a faint disconnect between their inner ear and what they see, even at a smooth 90 Hz. A 90 Hz refresh rate only guarantees that a new frame is displayed every 11.1 ms once the pipeline is running steadily — it says nothing about how long any single frame took to travel from sensor to screen; a headset can render at a buttery 90 fps while still carrying 21 ms of accumulated pipeline lag on every frame. Rendering also can't be dropped from the total as if it ran for free in parallel: the GPU needs the tracking data before it can even start drawing, and the display needs the finished frame before it can start transferring it, so each stage waits on the one before it. And while much larger delays — nearer 50-100 ms — cause the obvious stutter people associate with a laggy game, the specific 20 ms figure (popularized by VR pioneers like John Carmack) is the accepted motion-to-photon threshold for headsets specifically; treating 50 ms as the real limit would let a genuinely uncomfortable headset pass as fine.

Question 147 · Web Forms and Validation: User Input Done Right · hard

A student building an IRCTC-style train-ticket-booking form for a school project writes this JavaScript function to validate the mobile number field before the form submits: ```js function isValidMobile(value) { const pattern = /^[6-9]\d{9}$/; return pattern.test(value); } ``` Indian mobile numbers are always exactly 10 digits, and under TRAI's numbering plan the first digit must be 6, 7, 8, or 9. Which one of these raw input values, when passed directly into isValidMobile(), will make the function return true?

  1. "9876543210" — exactly 10 digits, starting with 9
  2. "9876543210 " — the same 10 digits, but with one trailing space after the final 0
  3. "5987654321" — 10 digits, but starting with 5
  4. "98765432100" — 11 digits, starting with 9

Answer: A. "9876543210" — exactly 10 digits, starting with 9

ExplanationThe pattern /^[6-9]\d{9}$/ has to match the entire string, not just part of it. The ^ anchor pins the very first character to the class [6-9], \d{9} then demands exactly nine more digits right after it, and the $ anchor demands the string end at that exact point — nothing before, nothing after. "9876543210" satisfies all three conditions in order: the first character is 9 (inside [6-9]), it is followed by exactly nine more digits (876543210), and the string stops there, so $ matches immediately — pattern.test() returns true. "9876543210 " fails because after the 10th digit the string still has a trailing space; $ needs the string to end right after \d{9} finishes matching, but a space character remains, so no match is found. "5987654321" fails at the very first position: 5 does not fall inside the character class [6-9], so the regex engine rejects it before it even gets to checking the remaining digits — this is the classic mistake of assuming any 10-digit number is a valid Indian mobile number instead of restricting the leading digit to 6-9. "98765432100" has 11 digits, not 10. \d{9} greedily consumes nine digits after the first one (reaching the 10th digit overall), but $ then fails because there is still an 11th digit left before the actual end of the string — an easy miscount if you only check the starting digit and total character feel rather than the exact length.

Question 148 · CSS Grid and Flexbox Mastery: Complex Layouts · hard

Your school's AI club is building a photo gallery for the annual ISRO Space Week exhibit. The gallery `<div>` is exactly 1000px wide (no padding or border) and holds 6 photo cards using this CSS: ```css .gallery { width: 1000px; display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 20px; } ``` How many columns will the first row of this grid create, and how wide will each column be, in pixels?

  1. 6 columns, each approximately 150px wide, since auto-fit always creates exactly as many columns as there are grid items, regardless of the minimum size specified in minmax().
  2. 5 columns, each 184px wide, because auto-fit fits the largest number of 180px-minimum columns without overflowing the container, then distributes the leftover 20px of space equally across the five 1fr columns.
  3. 5 columns, each exactly 200px wide, since the container's 1000px width is divided evenly by 5 columns without setting aside any space for the four 20px gaps between them.
  4. 6 columns, each 180px wide, since dividing 1000px by the 180px minimum column width (1000 ÷ 180 ≈ 5.6) rounds up to 6 columns that each fit at exactly their minimum size.

Answer: B. 5 columns, each 184px wide, because auto-fit fits the largest number of 180px-minimum columns without overflowing the container, then distributes the leftover 20px of space equally across the five 1fr columns.

ExplanationCSS Grid's auto-fit works in two stages, and both matter here. First, the browser determines the largest number of columns that can each be at least 180px wide without the row overflowing the 1000px container, accounting for the 20px gaps between columns. For n columns there are (n − 1) gaps, so the space needed is n × 180 + (n − 1) × 20. Testing n = 5: 5 × 180 + 4 × 20 = 900 + 80 = 980px, which fits inside 1000px. Testing n = 6: 6 × 180 + 5 × 20 = 1080 + 100 = 1180px, which overflows. So only 5 columns can share the first row, and the 6th card wraps down to a new row underneath. Second, because each column is defined as 1fr rather than a fixed 180px, the leftover space (1000 − 980 = 20px) doesn't sit empty — it is shared equally across the five fr columns: 20 ÷ 5 = 4px extra per column, making each column 180 + 4 = 184px wide. Checking the total confirms it: 5 × 184 + 4 × 20 = 920 + 80 = 1000px, exactly the container's width. The frequent errors here are forgetting that minmax()'s first value is a hard floor (so columns can never shrink below 180px just to fit more items in a row), and forgetting that gap space must be subtracted before dividing the remaining width among columns.

Question 149 · Browser DevTools: Your Debugging Superpower · hard

A Grade 9 student is debugging a shopping-cart script for a school project using the Chrome DevTools Console panel. They run this code: ```js let cart = { item: "notebook", price: 40 }; console.log(cart); // Log A cart.price = 55; // price updated after applying a coupon console.log(cart); // Log B ``` After the entire script has finished running, the student clicks the disclosure triangle (▶) to expand Log A — the console entry that was printed *before* the price was changed. What value does `price` show inside the expanded Log A, and why?

  1. Both Log A and Log B display price: 55, because Chrome's console panel stores a reference to the live object and only reads its properties when you click to expand it — by then the mutation has already happened.
  2. Log A freezes at price: 40 while Log B shows price: 55, since console.log immediately captures a snapshot of every value, primitive or object, at the exact instant it executes.
  3. Both entries display price: 40, since reassigning cart.price with an = operator inside a let-declared object creates a brand-new object rather than mutating the original.
  4. Expanding Log A throws a reference error, because the original cart object gets garbage-collected the moment cart.price is reassigned in the line below it.

Answer: A. Both Log A and Log B display price: 55, because Chrome's console panel stores a reference to the live object and only reads its properties when you click to expand it — by then the mutation has already happened.

ExplanationChrome DevTools does not convert an object into readable text the instant console.log() runs. The console entry instead stores a reference to the actual object in memory, and only renders its properties into an expandable tree when you click the disclosure triangle — which in this trace happens after cart.price has already changed from 40 to 55. Because Log A and Log B both point to the exact same object, expanding either one at that later moment shows price: 55, even though Log A was printed to the panel first, before the mutation occurred. This is precisely why experienced developers avoid logging live objects when they need to inspect state at a specific instant — they instead write console.log(JSON.parse(JSON.stringify(cart))) or console.log(structuredClone(cart)) to freeze a copy of the values before later code can change them. The assumption that console.log() snapshots everything at call time is a natural mistake carried over from how primitive values like numbers and strings behave (they are copied by value), but objects are logged by reference — so any mutation made before you actually expand the entry becomes retroactively visible, even in a log that was written earlier.

Question 150 · JSON and Data Formats: The Language of APIs · hard

You're parsing an IRCTC-style PNR status response using `JSON.parse()` in JavaScript (or Python's `json.loads()`). A teammate pastes four candidate response bodies below, each claiming to be what the API returned — but only one is syntactically valid JSON that will parse without throwing an error. Which one is valid JSON?

  1. Keys are double-quoted throughout, but `chartPrepared` is written as Python's capitalized `True`: ```json { "pnr": "4508213967", "trainNumber": "12951", "chartPrepared": True, "passengers": [ {"seat": "B3-45", "status": "CNF"}, {"seat": "B3-46", "status": "CNF"} ], "fare": 1495.50 } ```
  2. Double-quoted keys and strings, lowercase `true`, and no trailing comma anywhere in the array: ```json { "pnr": "4508213967", "trainNumber": "12951", "chartPrepared": true, "passengers": [ {"seat": "B3-45", "status": "CNF"}, {"seat": "B3-46", "status": "CNF"} ], "fare": 1495.50 } ```
  3. Identical to a standard response, except a comma trails the last passenger object right before the closing `]`: ```json { "pnr": "4508213967", "trainNumber": "12951", "chartPrepared": true, "passengers": [ {"seat": "B3-45", "status": "CNF"}, {"seat": "B3-46", "status": "CNF"}, ], "fare": 1495.50 } ```
  4. Written like a JavaScript object literal — keys are unquoted and every string uses single quotes: ```json { pnr: '4508213967', trainNumber: '12951', chartPrepared: true, passengers: [ {seat: 'B3-45', status: 'CNF'}, {seat: 'B3-46', status: 'CNF'} ], fare: 1495.50 } ```

Answer: B. Double-quoted keys and strings, lowercase `true`, and no trailing comma anywhere in the array: ```json { "pnr": "4508213967", "trainNumber": "12951", "chartPrepared": true, "passengers": [ {"seat": "B3-45", "status": "CNF"}, {"seat": "B3-46", "status": "CNF"} ], "fare": 1495.50 } ```

ExplanationJSON's grammar is stricter than the language features it superficially resembles, and each flawed version above breaks a different rule. The response with double-quoted keys and strings, lowercase `true`, and no dangling comma after the second passenger object parses cleanly — `JSON.parse()` or `json.loads()` returns a nested object with `pnr: "4508213967"`, `trainNumber: "12951"`, and `fare: 1495.50` intact. The version with a comma trailing the last passenger entry before `]` fails because JSON — unlike a JavaScript array literal or a Python list — never permits a trailing comma after the final element; the parser expects either another element or the closing bracket, not a comma immediately followed by `]`. The version using unquoted keys and single-quoted strings is valid JavaScript object-literal syntax but not JSON: the spec requires every key and every string value to be wrapped in double quotes, with no exception for identifier-style keys. The version with `True` for `chartPrepared` fails for a related reason — JSON defines exactly three case-sensitive literal keywords, `true`, `false`, and `null`; capitalizing the first letter turns it into a bare, unrecognized token (borrowed from Python's `True`) that no JSON parser accepts, so parsing throws a syntax error before it ever reaches the passengers array.

Question 151 · Web Scraping and Data Extraction: Ethics and Practice · hard

An Indian student is scraping publicly listed train fare data from a train-ticket booking website for a school project comparing dynamic ("surge") pricing over a week. Before writing any code, she reads the site's robots.txt file, which contains: ``` User-agent: * Crawl-delay: 8 Disallow: /eticketing/ Allow: /fare-enquiry/ ``` Her scraper will only ever request pages under /fare-enquiry/. To be a well-behaved crawler, she configures it to wait the full 8-second crawl-delay before sending every single request, including the very first one, so no two requests are ever fired less than 8 seconds apart. She needs exactly 450 fare-enquiry pages to finish her dataset. Which statement about her plan is correct?

  1. Her plan is correct: the minimum time needed is 450 × 8 = 3,600 seconds (60 minutes), because /fare-enquiry/ is explicitly listed under Allow while only /eticketing/ is Disallowed — her scraper is fetching permitted pages, and following the crawl-delay is good etiquette rather than a legal requirement, since robots.txt itself carries no force of law.
  2. The 3,600-second (60-minute) total is correct, but she is also legally bound to respect it — Crawl-delay directives are directly enforceable under India's IT Act, so skipping the wait would by itself be a punishable offence regardless of which pages she requests.
  3. Only 450 seconds (7.5 minutes) are actually needed in total, because a Crawl-delay value is a one-time warm-up wait applied before the first request of a scraping session, not a gap that has to be repeated before every request that follows it.
  4. No wait is required at all for pages under /fare-enquiry/, since a Crawl-delay directive only restricts paths that appear under Disallow — any path covered by an explicit Allow rule is exempt from the site-wide Crawl-delay value.

Answer: A. Her plan is correct: the minimum time needed is 450 × 8 = 3,600 seconds (60 minutes), because /fare-enquiry/ is explicitly listed under Allow while only /eticketing/ is Disallowed — her scraper is fetching permitted pages, and following the crawl-delay is good etiquette rather than a legal requirement, since robots.txt itself carries no force of law.

ExplanationWith one request permitted every 8 seconds and 450 pages to fetch, waiting the crawl-delay before every request (including the first) gives 450 x 8 = 3,600 seconds, which is 60 minutes, as the minimum time the scraper needs to finish. The pages themselves are safe to request: robots.txt lists /fare-enquiry/ under Allow and only /eticketing/ under Disallow, so the scraper is only ever touching permitted URLs. Two details are easy to get backwards here. First, a Crawl-delay value under "User-agent: *" is a site-wide throttle for that agent — it applies to every path the agent is allowed to crawl, not just the Disallowed ones; an Allow entry means "you may fetch this," not "you're exempt from the delay." Second, robots.txt is a voluntary convention read by cooperative crawlers, not a statute — India's IT Act does not make ignoring a Crawl-delay directive a criminal offence on its own. Any real legal exposure from scraping would come from other sources entirely, such as a site's Terms of Service, copyright over the content, or data-protection law governing what is later done with any personal data collected — not from the robots.txt file itself. A scraper that gets both the arithmetic and these two distinctions right is behaving efficiently and ethically at the same time.

Question 152 · Data Pipelines and ETL: From Raw Data to Insights · hard

A UPI payments dashboard ingests a raw transaction log where each row is one attempt — a single payment can appear more than once if the network retried it after a timeout. The table below shows seven raw log entries covering five unique transaction IDs: | txn_id | status | amount (₹) | |---|---|---| | T1 | SUCCESS | 500 | | T1 | SUCCESS | 500 | | T2 | FAILED | 1200 | | T3 | SUCCESS | 300 | | T4 | SUCCESS | 750 | | T4 | FAILED | 750 | | T5 | SUCCESS | 900 | The transform stage groups rows by txn_id. For each group, it adds that transaction's amount to the daily total exactly once, if at least one row in the group has status SUCCESS (using the amount from that SUCCESS row); a group with no SUCCESS row at all is dropped entirely: ```python groups = defaultdict(list) for record in raw_log: groups[record["txn_id"]].append(record) total = 0 for txn_id, records in groups.items(): statuses = [r["status"] for r in records] if "SUCCESS" in statuses: amount = next(r["amount"] for r in records if r["status"] == "SUCCESS") total += amount ``` What total amount, in rupees, does this pipeline load into the dashboard?

  1. ₹2,450
  2. ₹2,950
  3. ₹1,700
  4. ₹4,900

Answer: A. ₹2,450

ExplanationFive unique transactions exist in the log — T1 through T5 — but T1 and T4 each appear twice because of a retry. Grouping by txn_id and checking each group for at least one SUCCESS row gives: T1's two rows are both SUCCESS for the same retry attempt, so it contributes ₹500 exactly once; T2 has no SUCCESS row at all, so it is dropped entirely; T3 contributes ₹300; T4 has one FAILED row and one SUCCESS row — since a SUCCESS exists somewhere in the group, the transaction counts as successful and contributes its SUCCESS amount, ₹750, while the FAILED duplicate is simply ignored; T5 contributes ₹900. Adding these: 500 + 300 + 750 + 900 = ₹2,450. The most common trap is forgetting that T1's two SUCCESS rows are the same retried payment and adding ₹500 twice, which overcounts the total to ₹2,950. A second trap is assuming that any FAILED row disqualifies its whole txn_id — that logic wrongly throws out T4 even though it eventually succeeded, undercounting to ₹1,700. A third trap is summing every row in the raw log with no grouping or filtering at all, which includes T2's failed ₹1,200 along with both of T4's rows and lands on ₹4,900 — this defeats the entire purpose of the transform stage, which exists precisely to deduplicate retries and drop genuinely failed transactions before clean data reaches the dashboard.

Question 153 · India's Open Data Ecosystem: Building with Government APIs · hard

A student is building a civic-tech project using India's data.gov.in Open Government Data API to pull the full "List of Government Primary Schools in Karnataka" dataset. The API paginates results and caps the `limit` parameter at 500 records per call, and her API key is rate-limited to at most 12 calls per minute before the server responds with a 429 "Too Many Requests" error. If the dataset contains 8,742 total records and she calls the API back-to-back at the maximum allowed rate, what is the minimum whole number of minutes she needs to fetch every record?

  1. 18 minutes, since a 12-calls-per-minute cap means the server can only be trusted to process roughly one call per minute in practice
  2. 1 minute, since 18 calls at 12 calls per minute works out to 1.5 minutes, which rounds down to the nearest whole minute
  3. 2 minutes, since 18 calls at up to 12 calls per minute finish within the second minute
  4. 3 minutes, since the final call only returns a partial page of 242 records and must be scheduled in a minute of its own, separate from the other 17 calls

Answer: C. 2 minutes, since 18 calls at up to 12 calls per minute finish within the second minute

ExplanationWork it in two stages, and round up at both. First, how many calls are needed: each call returns at most 500 records, and 8,742 ÷ 500 = 17.484. Since a call can't return a fraction of a page, this needs ceil(17.484) = 18 calls — 17 calls covering 8,500 records, plus one more call to pick up the remaining 242 records (that last call being a partial page doesn't change that it's still just one call among the 18). Second, how many minutes those 18 calls take at a cap of 12 calls per minute: 18 ÷ 12 = 1.5, which again must round up to ceil(1.5) = 2, because a minute can't be fractional either — 12 calls complete in minute one, and the remaining 6 calls complete during minute two. Rounding 1.5 down to 1 minute (as in one distractor) ignores that those last 6 calls still need server time; treating the rate limit as "about one call per minute" (as in another) misreads what "12 calls per minute" means; and giving the partial last page its own separate minute (as in the third) double-counts a call that's already included in the 18.

Question 154 · BFS and DFS: Exploring Graphs Systematically · hard

Seven railway stations — A, B, C, D, E, F, and G — are connected by track segments as follows: ``` A–B, A–C, B–D, B–E, C–F, E–F, E–G ``` Starting a Depth-First Search from station A, and at every station always choosing to visit the alphabetically-earliest unvisited neighbouring station first (exploring that branch completely before backtracking), what is the exact order in which the seven stations get visited?

  1. A, B, D, E, F, C, G
  2. A, B, C, D, E, F, G
  3. A, B, D, E, G, F, C
  4. A, B, D, E, C, F, G

Answer: A. A, B, D, E, F, C, G

ExplanationBuilding the adjacency list from the track segments gives A: {B, C}, B: {A, D, E}, C: {A, F}, D: {B}, E: {B, F, G}, F: {C, E}, G: {E}. Following alphabetical order at every branch, DFS starts at A and immediately dives into B (A's earliest neighbour). From B, D comes before E alphabetically, so D is visited next; D has no unvisited neighbours, so the search backtracks to B and moves on to E. From E, F comes before G, so F is visited next. F's neighbours are C and E; E is already visited, so C — reached only through this F branch, even though it is also a direct neighbour of A — gets visited here, at position six. Only after this entire branch is exhausted does the search backtrack all the way up to E and finally pick up G, the one remaining unvisited neighbour. This produces A, B, D, E, F, C, G. The sequence A, B, C, D, E, F, G is what breadth-first search produces on this same graph, since BFS visits every neighbour of a station before going deeper into any of them — DFS instead commits to one branch and exhausts it fully before trying another. The sequence A, B, D, E, G, F, C comes from breaking the tie-break rule at E by visiting G before F, even though F is alphabetically earlier. The sequence A, B, D, E, C, F, G comes from jumping straight to C right after E, as if C's direct edge back to A gives it priority — but DFS never returns to A's second neighbour until every station reachable through the first branch, including C (reached via F), has already been visited.

Question 155 · Minimum Spanning Trees: Connecting Networks Efficiently · hard

A State Disaster Management Authority wants to connect six district control rooms — P, Q, R, S, T, and U — into one flood-warning network using optical-fibre links. The cost of laying each possible direct link is: P–Q: ₹4 lakh, P–R: ₹9 lakh, Q–R: ₹5 lakh, Q–S: ₹10 lakh, R–S: ₹3 lakh, R–T: ₹8 lakh, S–T: ₹6 lakh, S–U: ₹2 lakh, T–U: ₹7 lakh. Running Kruskal's algorithm on this network gives a minimum spanning tree of cost ₹20 lakh, built from the links S–U, R–S, P–Q, Q–R, and S–T. Just before construction begins, a land dispute permanently rules out the S–T link. What does the minimum total cost become once the network is rebuilt around this constraint, and which link replaces S–T?

  1. ₹22 lakh in total, reconnecting T through the R–T link on the other side of the network
  2. ₹20 lakh in total, since removing S–T doesn't change the minimum cost — T stays reachable through the existing tree at no extra charge
  3. ₹21 lakh in total, reconnecting T through the T–U link, the cheapest option still available
  4. ₹24 lakh in total, adding both T–U and R–T as a redundant backup pair so the network has no single point of failure

Answer: C. ₹21 lakh in total, reconnecting T through the T–U link, the cheapest option still available

ExplanationKruskal's algorithm sorts every link by cost and adds each one only if it doesn't close a cycle. Sorted by cost, the links here are S–U (₹2L), R–S (₹3L), P–Q (₹4L), Q–R (₹5L), S–T (₹6L), T–U (₹7L), R–T (₹8L), P–R (₹9L), Q–S (₹10L). The first five of these — S–U, R–S, P–Q, Q–R, S–T — connect all six control rooms without ever forming a cycle, so they make up the tree, giving the stated ₹2L + ₹3L + ₹4L + ₹5L + ₹6L = ₹20 lakh. Once S–T is ruled out, T has no remaining connection to the rest of the network at all — it must be reconnected through whichever of its other links is cheapest and doesn't create a cycle. T's remaining links are T–U (₹7 lakh) and R–T (₹8 lakh); T–U is the cheaper of the two, so it takes S–T's place. The rest of the tree (S–U, R–S, P–Q, Q–R) is untouched because none of those links depended on S–T. The new total is ₹2L + ₹3L + ₹4L + ₹5L + ₹7L = ₹21 lakh, exactly ₹1 lakh more than before — matching the ₹1 lakh gap between S–T's cost and T–U's cost. Using R–T instead gives a valid spanning tree too, but at ₹22 lakh it isn't the cheapest one, so it's not minimum. The cost can't stay at ₹20 lakh, because S–T was actually load-bearing — it was the only link touching T in the original tree, so losing it forces a real replacement cost. And adding both T–U and R–T would give T two links into the tree, which isn't a spanning tree at all: a spanning tree connects every new node through exactly one edge, with zero redundancy by definition.

Question 156 · Binary Trees and BST: Hierarchical Data Mastery · hard

IRCTC's Tatkal quick-search server indexes waiting-list priority scores using a Binary Search Tree, inserting distinct scores one at a time (each new value becomes a fresh node placed by comparing against existing nodes, never rebalancing) in this arrival order: 42, 23, 68, 15, 30, 55, 81, 4, 19, 27. What is the height of the resulting BST, measured as the number of edges on the longest path from the root to any leaf?

  1. 2, because the tree self-balances once it holds more than eight nodes
  2. 3, matching the path from root 42 down through 23 and 15 to leaf 4 (or 19)
  3. 4, since ten insertions into a BST always produce four full levels
  4. 5, because inserting in non-sorted order forces the tree into a fully skewed chain

Answer: B. 3, matching the path from root 42 down through 23 and 15 to leaf 4 (or 19)

ExplanationTrace each insertion using the BST rule (smaller goes left, larger goes right, starting the comparison at the root each time). 42 becomes the root. 23 < 42 goes left of 42; 68 > 42 goes right of 42. 15 < 42 then < 23 becomes the left child of 23; 30 < 42 then > 23 becomes the right child of 23. 55 > 42 then < 68 becomes the left child of 68; 81 > 42 then > 68 becomes the right child of 68. 4 < 42, < 23, < 15 becomes the left child of 15. 19 < 42, < 23, > 15 becomes the right child of 15. 27 < 42, > 23, < 30 becomes the left child of 30. The finished shape is: root 42; level 1 has 23 and 68; level 2 has 15, 30, 55, 81; level 3 has 4, 19 (under 15) and 27 (under 30), while 55 and 81 are leaves at level 2. Counting edges from the root to the deepest nodes (4, 19, or 27) gives 42-23-15-4, which is 3 edges, so the height is 3. Plain BSTs (unlike AVL or red-black trees) never self-balance on their own, which rules out the "self-balances" claim; counting 4 as the height confuses total levels of nodes with edge-count height and also wrongly assumes every ten-node BST fills four full levels, which only happens for a perfect tree of 15 nodes, not this one; and the tree is not a fully skewed chain because the arrival order 42, 23, 68, ... sends values to both left and right subtrees rather than always the same side, so a height of 5 would require a much more lopsided insertion order than the one given.

Question 157 · What is Machine Learning? Teaching Computers to Learn · hard

An IRCTC-linked payments team wants to catch fraudulent UPI transactions before they are approved. Four engineers each built a different system for this. Using Tom Mitchell's formal definition of machine learning — a program learns from experience E with respect to a task T and performance measure P if its performance at T, as measured by P, improves with E — which engineer's system is a genuine example of machine learning?

  1. Arjun wrote fixed if-else rules that flag a transaction as fraud when the amount exceeds ₹50,000, the transaction time is between 1 AM and 4 AM, and the receiving UPI ID has never been used by that account before; these three thresholds stay exactly the same every day regardless of how many transactions the system processes.
  2. Priya trained a decision-tree model on 2 lakh past transactions labelled fraud or genuine, using features like amount, time gap, and location mismatch; when she retrained the same model each month on the growing transaction history, its fraud-detection accuracy on new transactions rose from 82% to 94% without her changing any rule by hand.
  3. Rohit built a live dashboard that tallies and displays how many transactions bank officials have manually marked as fraud versus genuine each day, sorted by rupee amount, while every fraud-or-genuine decision is still made by a human officer looking at each case.
  4. Meera maintains a blocklist of 500 scammer UPI IDs taken from RBI advisories; any transaction involving one of these exact IDs is instantly rejected, and her compliance team manually appends newly reported scammer IDs to this list every week.

Answer: B. Priya trained a decision-tree model on 2 lakh past transactions labelled fraud or genuine, using features like amount, time gap, and location mismatch; when she retrained the same model each month on the growing transaction history, its fraud-detection accuracy on new transactions rose from 82% to 94% without her changing any rule by hand.

ExplanationThe defining test from Mitchell's definition is not "does the system use data" but "does its performance at a task automatically improve as experience grows, without a human rewriting the logic." Priya's system passes this test on all three counts: the experience E is the 2-lakh-transaction labelled history, the task T is classifying a transaction as fraud or genuine, and the performance measure P is accuracy — which climbed from 82% to 94% purely because the decision-tree algorithm re-learned patterns from a larger dataset each month, with no rule hand-edited. Arjun's system fails because the ₹50,000/1 AM–4 AM/new-UPI-ID thresholds are permanently fixed by a human programmer; no matter how many transactions flow through it, the logic never adapts, so it is traditional rule-based programming, not learning. Rohit's system fails because it performs no prediction task at all — every fraud/genuine label is assigned by a human officer, and the dashboard merely counts and sorts those human decisions, so there is no P being improved by the software itself. Meera's blocklist is the subtlest trap: it looks data-driven because it references 500 real scammer IDs, but the list only grows because her compliance team manually types in new entries each week. The system's own accuracy at catching new, previously unseen scammers never improves on its own — the improvement comes from human labour, not from a learning algorithm processing experience, so it is an expert-style lookup table rather than machine learning.

Question 158 · Data Collection and Cleaning: Garbage In, Garbage Out · hard

A Class 9 AI student in Delhi is building a machine-learning model to predict campus temperature. She has 10 IoT sensors placed around the school, and on one day they report (in °C): 28, 29, 27, 30, 28, 29, 0, 28, 27, 29. Sensor #7 is later found to be physically stuck, always outputting 0°C regardless of the actual temperature — a hardware fault, not a real cold snap. She computes the "uncorrected" mean using all 10 readings, then correctly cleans the data by discarding sensor #7's readings entirely and recomputes the mean using only the 9 working sensors. What are the two means, and what does the comparison show?

  1. The uncorrected mean (all 10 readings) is 25.50°C, while the corrected mean (the remaining 9 valid readings) is 28.33°C — a difference of 2.83°C. Because the stuck sensor was reporting bad data rather than a real temperature, including it artificially drags the average down; cleaning it out removes that downward bias and gives a more trustworthy value for the model to learn from.
  2. Both the uncorrected and corrected means come out to 25.50°C, because deleting the one faulty 0°C reading removes nothing from the sum of the readings, so the two averages end up identical either way.
  3. Since only 1 of the 10 sensors (10% of the data) is faulty, its effect on the mean is negligible — the corrected mean is only marginally higher, around 25.78°C, a difference of just 0.28°C, so cleaning barely matters here.
  4. The corrected mean actually falls to 22.67°C, a decrease of 2.83°C from the uncorrected value, since removing any single data point from a small sample generally pulls the average further away from the value that was removed.

Answer: A. The uncorrected mean (all 10 readings) is 25.50°C, while the corrected mean (the remaining 9 valid readings) is 28.33°C — a difference of 2.83°C. Because the stuck sensor was reporting bad data rather than a real temperature, including it artificially drags the average down; cleaning it out removes that downward bias and gives a more trustworthy value for the model to learn from.

ExplanationSumming all 10 readings — 28+29+27+30+28+29+0+28+27+29 — gives 255, so the uncorrected mean is 255 ÷ 10 = 25.50°C. The stuck sensor's 0°C contributes nothing to that sum, but it does count toward the divisor, so it silently pulls the average down even though a genuinely broken sensor should not influence the result at all. Cleaning means removing that sensor's reading from the dataset entirely — not just from the sum but from the count of readings being averaged. The 9 remaining valid readings still sum to 255 (since the 0 added nothing), but now 255 ÷ 9 = 28.33°C. The two means differ by 28.33 − 25.50 = 2.83°C, and this whole 2.83°C gap exists purely because one faulty sensor was left in the calculation — nothing about the real campus temperature changed. This is the core "Garbage In, Garbage Out" lesson: a single unfiltered bad reading, even 1 out of 10 data points, can shift a summary statistic by several degrees, and any ML model trained on the uncorrected data would learn a systematically colder, wrong picture of the campus. The most common cleaning mistake is remembering to zero out the bad value's contribution to the sum but forgetting to shrink the count of readings being divided by — that error, dividing 255 by 10 instead of 9, is exactly what produces a false "no difference" result.

Question 159 · Training and Testing: Why You Can't Grade Your Own Exam · hard

Reya, a Class 9 student, builds a simple 1-nearest-neighbour (1-NN) model that predicts whether a student will Pass or Fail a test, using only hours studied. The rule: to predict a student's result, find the training student whose hours-studied value is closest (smallest absolute difference), and copy that student's result. Her training data (hours studied, result) is: (1, Fail), (3, Fail), (6, Pass), (7, Fail), (10, Pass), (12, Pass). She checks her model in two ways. Way 1: she runs all 6 training students back through the model and compares each prediction to that student's actual result. Way 2: she tests two students who were never in the training data — one who studied 5 hours and actually Passed, and one who studied 9 hours and actually Failed — and compares the model's predictions to their actual results. What accuracy does the model score in Way 1, and what accuracy does it score in Way 2?

  1. 100% in Way 1 and 50% in Way 2, because in Way 1 every training student's nearest neighbour (at a distance of exactly 0 hours) is that same student, so the model always copies its own true result, while in Way 2 the model must instead copy a different, nearby student's result, which is wrong for the 9-hour student.
  2. 100% in Way 1 and 100% in Way 2, because a 1-NN model always searches the entire training set for the single closest match in hours studied, so it is mathematically guaranteed to predict correctly whether the student being tested was part of the training data or not.
  3. 83% in Way 1 (5 correct out of 6) and 50% in Way 2, because the training student who studied 7 hours sits closer to the Pass-labelled student at 6 hours than to any Fail-labelled student, so the model copies the wrong result even when tested on its own training data.
  4. 50% in Way 1 and 100% in Way 2, because several of the training students have hours-studied values close enough together to cause tie-breaking errors, while the two new test students happen to fall exactly on hours values that match a same-labelled training student.

Answer: A. 100% in Way 1 and 50% in Way 2, because in Way 1 every training student's nearest neighbour (at a distance of exactly 0 hours) is that same student, so the model always copies its own true result, while in Way 2 the model must instead copy a different, nearby student's result, which is wrong for the 9-hour student.

ExplanationTrace the 1-NN rule by hand. In Way 1, every one of the 6 training students is compared against the full training set — including itself. Since all six hours-studied values (1, 3, 6, 7, 10, 12) are distinct, each student's own record is always the closest match, at a distance of 0 hours, so the model simply reads back that student's own true result. That makes Way 1 a perfect 6-out-of-6, or 100% — but this number says nothing about the model's real ability to predict new students, because the "test" data was already sitting inside the training set. Way 2 is the honest test: for a 5-hour student, the distances to the six training hours are 4, 2, 1, 2, 5, and 7 hours, so the closest match is the 6-hour student (distance 1), labelled Pass — matching the 5-hour student's actual Pass, a correct prediction. For a 9-hour student, the distances are 8, 6, 3, 2, 1, and 3 hours, so the closest match is the 10-hour student (distance 1), labelled Pass — but the 9-hour student actually Failed, so this prediction is wrong. That gives 1 correct out of 2, or 50%, in Way 2. The 50-point gap between the 100% and the 50% is exactly why evaluating a model on its own training data is like letting a student grade their own exam with the answer key already memorised: it always looks perfect, while a genuinely unseen test set reveals the model is just copying the nearest label rather than learning the real relationship between hours studied and passing.

Question 160 · K-Nearest Neighbors: Your Neighborhood Decides · hard

A UPI fraud-detection system uses a k-Nearest Neighbors classifier with two raw (unscaled) features — transaction amount in rupees, and number of past customer complaints against the payee. The training data is: | Point | Amount (Rs) | Complaints | Label | |-------|------------|------------|-------| | P1 | 500 | 1 | Legit | | P2 | 520 | 4 | Fraud | | P3 | 480 | 0 | Legit | | P4 | 5000 | 1 | Fraud | | P5 | 510 | 5 | Fraud | A new transaction arrives at (500 rupees, 3 complaints). Using k = 3 and standard (unscaled) Euclidean distance, what does the classifier predict for this transaction, and why?

  1. Fraud — the three nearest neighbours by Euclidean distance are P1 (distance 2.00), P5 (distance ≈10.20), and P2 (distance ≈20.02), giving two Fraud votes against one Legit vote
  2. Legit — the three nearest neighbours by Euclidean distance are P1, P5, and P3 (distance ≈20.22), giving two Legit votes against one Fraud vote
  3. The prediction cannot be determined with k = 3 because P2 and P3 are nearly equidistant from the query point, so k must be increased until the near-tie is resolved
  4. Legit — since the query's transaction amount of Rs 500 is nearly identical to two Legit training points, the amount feature should be trusted over the complaint count whenever the two features disagree

Answer: A. Fraud — the three nearest neighbours by Euclidean distance are P1 (distance 2.00), P5 (distance ≈10.20), and P2 (distance ≈20.02), giving two Fraud votes against one Legit vote

ExplanationCompute the Euclidean distance from the query (500, 3) to every training point using distance = √((Δamount)² + (Δcomplaints)²). P1 (500, 1): Δ = (0, −2) → √(0² + 2²) = √4 = 2.00 P5 (510, 5): Δ = (10, 2) → √(10² + 2²) = √104 ≈ 10.20 P2 (520, 4): Δ = (20, 1) → √(20² + 1²) = √401 ≈ 20.02 P3 (480, 0): Δ = (−20, −3) → √(20² + 3²) = √409 ≈ 20.22 P4 (5000, 1): Δ = (4500, −2) → distance ≈ 4500.00 Ranking these five distances gives P1 (2.00) < P5 (10.20) < P2 (20.02) < P3 (20.22) < P4 (4500.00). With k = 3, the three closest points are P1, P5, and P2 — labelled Legit, Fraud, Fraud. Majority vote is 2 Fraud to 1 Legit, so the classifier predicts Fraud. The near-miss between P2 (≈20.02) and P3 (≈20.22) is the trap: swapping them — picking P1, P5, P3 instead of P1, P5, P2 — flips the vote to Legit, which is exactly the arithmetic slip a rushed calculation produces. But 20.02 is genuinely smaller than 20.22, so P2 belongs in the neighbourhood, not P3. There is also no real tie to justify raising k — 20.02 and 20.22 differ, they're merely close, and "closer" is well-defined the moment you compute both distances precisely. And KNN doesn't let one feature override the distance calculation by fiat; every feature enters the same sum of squares (this is exactly why unscaled features with very different numeric ranges — like Rs 500 versus a 0–5 complaint count — need normalization in real systems, since a large-range feature can dominate distance regardless of how predictive it actually is).
← Set 7Set 9 →