English:Search, ranking and recommendation algorithms - AI Year 7
Introduction

Compare query-based search with profile-based suggestions. Calculate two orders for the same six cards, follow three scripted feedback rounds and test a diversity control and a reset without confusing rank, popularity and source evidence.
Separate search recommendation and source evidence
Separate a request from a suggestion
Search starts with an information request, such as renewable energy. A recommender can suggest items from content features, an explicitly chosen preference or other signals without a new search query. Both need a way to retrieve candidates and order them. Ranking means putting candidates into an order under a selected objective; it is not automatically a statement of truth, quality or what a person should like.
CodeAI: The Internet, How Search Works. Use the verified recording to connect a query with finding and ordering information. Our small program below scans six original cards, rather than crawling or indexing the real web. Real search systems use richer language processing and many signals; our transparent tag counts are a classroom model, not an account of Google's full ranking implementation.
Inspect six original cards before calculating any score
All titles, tags, topic counts and review flags in the table are fictional. No real energy claim, website, clip or popularity measurement is represented. The source-review field means a review record is marked present or pending in this invented exercise. It is not an automatic truth detector: recorded review does not guarantee correctness, and pending review does not establish that a claim is false.
| ID | Original fictional title | Tags | Topic | Popularity count | Source-review record |
|---|---|---|---|---|---|
| A | Solar cells guide | renewable, energy, solar | solar | 2 | recorded |
| B | Solar energy facts | renewable, energy, solar | solar | 1 | recorded |
| C | Solar miracle clip | renewable, energy, solar | solar | 9 | pending |
| D | Wind energy explained | renewable, energy, wind | wind | 3 | recorded |
| E | Coal energy report | energy, coal | coal | 8 | recorded |
| F | Hydropower introduction | renewable, energy, hydro | hydro | 4 | recorded |
The query renewable energy contains two distinct words. Our tokenizer lowercases ASCII alphabetic words and ignores punctuation; it does not understand synonyms or meanings. The program counts how many distinct query words occur in a card's tags. Any positive overlap makes a candidate. Therefore E, with energy but not renewable, remains a candidate with only one match; the other five cards have both query tags.
Declare the objective and the tie rule
The first search score is ten times the overlap count. Five cards score 20 and E scores 10. Equal scores are broken by the card identifier in ascending order, giving A, B, C, D, F, E. The identifier tie rule is a declared convention, not an evaluation of authority. A and C can have the same query relevance count despite different fictional review status.
When you compare rankings, hold the catalogue and query fixed and change one specified signal. Keep relevance, popularity, user preference, topic variety and source evidence separate. A result can be relevant but require source checking; a popular result need not answer the exact query. Explain what a score measures before deciding whether it helps the user's actual need.
Calculate rankings trace feedback and inspect the complete program
Change one ranking weight and calculate the new order
Keep the six cards and the query unchanged. Add popularity multiplied by an integer weight. With weight zero, the search score uses only overlap. With weight three, C scores 20 plus 27, or 47. E scores 10 plus 24, or 34. F scores 20 plus 12, or 32. The same candidates now appear in a different order.
| ID in relevance-only order | Matched distinct query words | Score at weight zero |
|---|---|---|
| A | 2 | 20 |
| B | 2 | 20 |
| C | 2 | 20 |
| D | 2 | 20 |
| F | 2 | 20 |
| E | 1 | 10 |
| ID in new order | Matched distinct query words | Score at weight three |
|---|---|---|
| C | 2 | 47 |
| E | 1 | 34 |
| F | 2 | 32 |
| D | 2 | 29 |
| A | 2 | 26 |
| B | 2 | 23 |
E moves ahead of F and D despite matching only one query word. C becomes first even though its source-review record is pending. The calculation does not establish that C is false or that E is useless; it establishes which chosen signals produced this order. A top rank cannot replace checking an actual source's evidence and suitability.
Build a separate content-profile recommender
Our original fictional profile starts with solar count one and wind, coal and hydro counts zero. The recommendation score is ten times the count for an item's topic, plus that item's popularity. There is no search query in this calculation. The first three suggestions are C, A and B with scores 19, 12 and 11, all solar-topic cards.
This is a simple content-topic profile with a human-designed scoring rule, not a trained neural recommender or collaborative filtering over real users. The counts are supplied and updated in a fictional replay. The program never observes a real learner, watch history or account. It also does not filter already clicked titles; this declared simplification makes repeated exposure easy to inspect, not a claim about every service.
Trace three predeclared fictional choices
The original script chooses C in the first round, A in the second and B in the third, each from the displayed three suggestions. Every chosen card is solar, so its topic count rises by one. These choices are teacher-prepared fixtures, not predictions or observations of a real person.
| Round | Solar count before | Suggestions in order | Their scores | Scripted choice | Solar count after |
|---|---|---|---|---|---|
| 1 | 1 | C, A, B | 19, 12, 11 | C | 2 |
| 2 | 2 | C, A, B | 29, 22, 21 | A | 3 |
| 3 | 3 | C, A, B | 39, 32, 31 | B | 4 |
The order C, A, B stays the same while the scores rise. Nine displayed positions across the three rounds are solar-topic positions. This is not nine distinct items or a measurement that a real person was persuaded. It demonstrates a possible feedback mechanism in this toy rule: exposure and selected interactions reinforce a topic count and can narrow what the rule shows.
Compare a diversity cap with a profile reset
With the original profile, request three results but allow at most one per topic. Scanning the ranked list gives C from solar, E from coal and F from hydro. You get three topics rather than three solar cards, but C's pending source-review status remains. Topic variety is not a truth guarantee or proof that the result fits a renewable-only purpose. If a constraint makes fewer results possible, this implementation returns fewer rather than silently relaxing the cap.
Resetting the fictional profile to all zero removes its personal topic counts, so recommendation order is driven by popularity and the identifier tie rule. Its first three are also C, E and F, now with scores 9, 8 and 4. The matching IDs do not make reset and diversity the same mechanism. Reset does not remove the popularity signal or verify any content. These are toy parameters, not changes to a real MOOCwiki user's settings.
Inspect and run the complete original Python
Trace the tables on paper or use an approved Python environment. The standard-library program validates the declared catalogue, scores candidates, applies a cap and replays three scripted choices. It has no web crawler, remote model, actual user tracking or paid API.
"""Original fictional content cards and scripted clicks; no actual user tracking."""
from copy import deepcopy
import json
import re
CARDS = [
dict(id="A", title="Solar cells guide", tags=["renewable", "energy", "solar"],
topic="solar", popularity=2, source_review_recorded=True),
dict(id="B", title="Solar energy facts", tags=["renewable", "energy", "solar"],
topic="solar", popularity=1, source_review_recorded=True),
dict(id="C", title="Solar miracle clip", tags=["renewable", "energy", "solar"],
topic="solar", popularity=9, source_review_recorded=False),
dict(id="D", title="Wind energy explained", tags=["renewable", "energy", "wind"],
topic="wind", popularity=3, source_review_recorded=True),
dict(id="E", title="Coal energy report", tags=["energy", "coal"],
topic="coal", popularity=8, source_review_recorded=True),
dict(id="F", title="Hydropower introduction", tags=["renewable", "energy", "hydro"],
topic="hydro", popularity=4, source_review_recorded=True),
]
def validate_cards(cards):
if type(cards) is not list or not cards:
raise ValueError("Use a nonempty fictional catalogue")
expected = set(["id", "title", "tags", "topic", "popularity", "source_review_recorded"])
seen = set()
for row in cards:
if type(row) is not dict or set(row) != expected:
raise ValueError("Use exactly the declared catalogue fields")
if type(row["id"]) is not str or not row["id"] or row["id"] in seen:
raise ValueError("Catalogue identities must be unique")
if type(row["title"]) is not str or not row["title"]:
raise ValueError("Title required")
if type(row["tags"]) is not list or not row["tags"]:
raise ValueError("Use declared word tags")
if any(type(t) is not str or not re.fullmatch("[a-z]+", t) for t in row["tags"]):
raise ValueError("Tags use the declared lowercase ASCII word format")
if len(row["tags"]) != len(set(row["tags"])) or row["topic"] not in row["tags"]:
raise ValueError("Unique tags must include the topic")
if type(row["popularity"]) is not int or row["popularity"] < 0:
raise ValueError("Popularity must be a nonnegative count")
if type(row["source_review_recorded"]) is not bool:
raise ValueError("Review status must be an explicit boolean")
seen.add(row["id"])
def search(cards, query, popularity_weight=0):
validate_cards(cards)
if type(query) is not str or type(popularity_weight) is not int or not 0 <= popularity_weight <= 3:
raise ValueError("Use a text query and integer weight from zero to three")
words = set(re.findall("[a-z]+", query.lower()))
scored = []
for row in cards:
overlap = len(words & set(row["tags"]))
if overlap:
scored.append(dict(id=row["id"], overlap=overlap,
score=10 * overlap + popularity_weight * row["popularity"]))
return sorted(scored, key=lambda r: (-r["score"], r["id"]))
def validate_profile(cards, profile):
topics = set(row["topic"] for row in cards)
if type(profile) is not dict or set(profile) != topics:
raise ValueError("Use one count for each declared topic")
if any(type(n) is not int or n < 0 for n in profile.values()):
raise ValueError("Topic counts must be nonnegative integers")
def recommend(cards, profile, k=3, topic_cap=None):
validate_cards(cards)
validate_profile(cards, profile)
if type(k) is not int or not 1 <= k <= len(cards):
raise ValueError("Choose a result count within the catalogue")
if topic_cap is not None and (type(topic_cap) is not int or topic_cap < 1):
raise ValueError("Use a positive per-topic cap")
ranked = sorted(cards, key=lambda r: (-(10 * profile[r["topic"]] + r["popularity"]), r["id"]))
chosen, counts = [], dict()
for row in ranked:
count = counts.get(row["topic"], 0)
if topic_cap is None or topic_cap > count:
chosen.append(dict(id=row["id"], topic=row["topic"],
score=10 * profile[row["topic"]] + row["popularity"]))
counts[row["topic"]] = count + 1
if len(chosen) == k:
break
return chosen
def scripted_rounds(cards, initial_profile, clicks):
validate_cards(cards)
validate_profile(cards, initial_profile)
if type(clicks) is not list or len(clicks) != 3:
raise ValueError("This exercise has three predeclared fictional choices")
profile = deepcopy(initial_profile)
trace = []
for number, click in enumerate(clicks, 1):
shown = recommend(cards, profile)
if click not in [r["id"] for r in shown]:
raise ValueError("The scripted choice must be among the shown cards")
item = next(r for r in cards if r["id"] == click)
before = deepcopy(profile)
profile[item["topic"]] += 1
trace.append(dict(round=number, before=before, shown=shown, clicked=click,
after=deepcopy(profile)))
return dict(trace=trace, final_profile=profile)
def demonstrate():
profile = dict(solar=1, wind=0, coal=0, hydro=0)
reset = dict((topic, 0) for topic in profile)
return dict(catalogue=deepcopy(CARDS), query="renewable energy",
relevance_only=search(CARDS, "renewable energy", 0),
popularity_weight_three=search(CARDS, "renewable energy", 3),
initial_recommendations=recommend(CARDS, profile),
three_rounds=scripted_rounds(CARDS, profile, ["C", "A", "B"]),
diversity_cap_one=recommend(CARDS, profile, topic_cap=1),
reset_recommendations=recommend(CARDS, reset),
review_status_used_as_ranking_signal=False,
actual_user_behaviour_observed=False)
if __name__ == "__main__":
print(json.dumps(demonstrate(), indent=2))The complete program was actually executed. The two search orders, recommendation scores, three updates, cap and reset shown above match its retained output. If you change a weight or profile, state an expectation before running and keep both the original and changed result. Do not claim that a paper prediction was a real run or that this limited model reproduces a commercial service.
Test controls boundaries and a new information need
Explain a feedback-loop risk without claiming inevitability
CodeAI: AI, Training Data & Bias. Use the verified creator recording to ask what an example or interaction represents. A click can reflect curiosity, disagreement, convenience or an accidental choice; it is not a direct measurement of enduring interest or educational value. Our script deliberately treats every chosen topic as positive feedback, which is one inspectable assumption rather than a universal model of human behaviour.
The three-round trace shows narrowing under this exact rule and scripted choices. It does not establish that every recommender traps every user or that diverse recommendations are always preferable for every task. Possible controls include an explicit query, editing or resetting an interest profile, a topic cap and a clear explanation of signals. Evaluate those controls against the purpose instead of assuming a larger variety count solves every concern.
Design boundaries and isolate one change
Test an empty query and a query with no matching tags: this search returns no candidates, even if a card is popular. Test mixed case, punctuation and repeated words. Renewable energy and RENEWABLE, energy energy produce the same two distinct query terms under the declared tokenizer. A synonym absent from the tags does not acquire a match magically; this limitation needs to be stated.
At popularity weight zero, equal overlap scores use identifier order. Changing only the weight can change the order. Changing only the review flag cannot change it because that flag is not a scoring input. This is a useful test of what the implementation actually uses, not a recommendation to ignore sources in real learning.
For recommendations, compare a zero profile, a tied topic count and a single-topic catalogue with a cap of one. The last can return only one item even if three were requested. Duplicate IDs, negative or boolean counts, invalid result counts and a scripted choice absent from the shown items must stop the teaching program for review. Keep the original data and explain the failed contract rather than invent a result.
Transfer to a fictional music archive
Suppose an original music archive wants to help someone find acoustic rhythm examples. Search needs an explicit information need and suitable tags or other retrieval evidence. A recommender may use a user-selected interest, but play count alone is not proof of appropriate difficulty, rights, reliable context or educational value. Revisit the catalogue fields, scoring weights and manual checks instead of reusing solar-topic counts.
Choose a purpose-specific comparison: relevance to the request, appropriate variety, accessibility and source evidence are distinct criteria. A reset can change personal signals while leaving global popularity, and a diversity rule can change topic coverage without improving factual quality. Use original or properly authorised examples and no real pupil listening history. Your transfer product is a justified design and test plan unless you actually implement and evaluate it.
Keep a clear ranking evidence log
Record the catalogue and query, selected objective, exact signals and weight, tie rule, expected and actual order, three scripted updates and two controls. State what review flags mean and what they do not prove. Link each proposed improvement to an information need and a test. A transparent score helps explanation; it is not a neutral definition of what is best for every learner.
Interactive Tasks
Quiz: Test Your Knowledge
What starts the search calculation in this course? (An explicit query) (!A real pupil watch history) (!An automatically verified truth label) (!A physical robot action)
Why does E remain a candidate for renewable energy? (The retrieval rule accepts any positive tag overlap) (!Coal is automatically classified as renewable) (!Popularity creates a new matching query word) (!Every item must match every query word)
How are equal relevance-only scores ordered? (By card identifier in ascending order) (!By verified scientific authority) (!By secret learner identity) (!By the pending review flag)
What is the weight-three search score for C? (Forty-seven) (!Twenty) (!Twenty-seven) (!Nine)
Why can E outrank a two-word match when the weight is three? (Its popularity contribution outweighs the overlap difference) (!Its tags secretly contain both query words) (!Its review status was used as a numeric bonus) (!The catalogue was replaced)
Which signal drives the profile part of the recommendation score? (The supplied count for the item topic) (!The words in a new search query) (!A real account password) (!An automatic factual accuracy measurement)
What happens to the solar count across the three scripted choices? (It rises from one to four) (!It remains one because no choice is recorded) (!It becomes a real learner score) (!It falls to zero after each round)
What does a topic cap of one change in the original top three? (It permits at most one chosen card per topic) (!It proves every selected source is correct) (!It turns coal into renewable energy) (!It removes the popularity signal from every score)
Why are reset and diversity different despite matching example IDs? (They alter different mechanisms and give different scores) (!Both secretly use actual learner tracking) (!Both certify the pending source review) (!Neither changes any algorithm input)
What should happen when a query has no matching tag? (Return no candidates under the declared retrieval rule) (!Choose the most popular item as a claimed match) (!Invent a new tag from a private profile) (!Claim that no relevant real source exists anywhere)
Memory Game
| Query | An explicit information request |
| Candidate | An item retrieved for possible ranking |
| Ranking | Ordering items under selected signals and an objective |
| Recommendation | A suggestion using content or other chosen signals |
| Feedback | An interaction used to update the next calculation |
| Diversity | Variety under a stated criterion |
Drag and Drop
| Count distinct matching words in the declared tags | Query overlap |
| Use a stated ordering convention for equal scores | Tie breaking |
| Update a topic count after a scripted choice | Profile feedback |
| Limit how many results share a topic | Diversity cap |
| Clear fictional personal topic counts | Profile reset |
Crossword Puzzle
| QUERY | What explicit request starts a search? |
| RANKING | What process orders candidates? |
| SIGNAL | What selected input contributes to a score? |
| PROFILE | What can retain supplied topic counts? |
| FEEDBACK | What can update a later calculation after an interaction? |
| DIVERSITY | What refers to variety under a stated criterion? |
LearningApps
Optional extra practice. Choose an appropriate activity with your teacher. If the external collection is unavailable, use the native activities and independent tasks in this course.
Cloze Text
Open Tasks
Easy
- Separate search and recommendation: Explain the role of the query versus the fictional topic profile, and name the signals in each score.
- Calculate the relevance order: Count distinct query-tag matches, apply the score and tie rule and reconstruct the six-card order.
- Change the popularity weight: Keep query and catalogue fixed, compute C and E at weight three and explain the changed order.
- Trace three rounds: Record the scripted choices, shown IDs, scores and before/after topic counts without inventing real user behaviour.
Standard
- Compare two controls: Apply the cap and reset, compare IDs and scores and explain why neither proves source quality.
- Test retrieval boundaries: Check empty, unmatched, repeated-word and mixed-case/punctuation queries, retaining expected and actual results.
- Test the review signal: Change only a fictional review flag, check the ranking and explain the difference between algorithmic signals and a real source check.
- Diagnose the feedback assumption: Explain what a click may mean, which assumption the toy replay makes and a control worth evaluating.
Advanced
- Design a purpose-specific ranker: Choose a fictional information need, declare candidate retrieval, signals, weights and tie rule, then compare controlled alternatives.
- Investigate constrained results: Create an original single-topic catalogue, apply a one-topic cap and explain a shorter result list without silently relaxing the rule.
- Transfer to a music archive: Reconsider tags, interests, accessibility, rights, source evidence and variety for acoustic rhythm examples without using real listening history.
- Review a best-for-everyone claim: Use the actual weight change, scripted feedback and control results to challenge neutrality, distinguish tested evidence from wider claims and propose independent follow-up.
Learning Check
- Reconstruct the two search orders: How do the unchanged cards produce different orders?
- Separate relevance from source evidence: What does C being first establish about its content?
- Trace the feedback mechanism: What changes across the three original rounds?
- Explain the two controls: Why do both example controls show C, E, F but remain different?
- Interpret boundaries: What should empty queries, repeated words and a single-topic cap do?
- Transfer with a justified objective: What changes for an original acoustic-rhythm archive?
Worked checks and assessment guidance
- With weight zero, five two-word matches score 20 and E scores 10; identifier ties give A/B/C/D/F/E. At weight three, scores are C 47, E 34, F 32, D 29, A 26, B 23, giving that order. E has only one query word, but its popularity contribution moves it ahead of some two-word matches. These are original invented scores, not actual web rankings.
- Only the chosen scoring calculation. Its review record is pending in the fictional catalogue, and the algorithm does not use that flag. Pending does not mean false and recorded does not guarantee true. A high rank cannot replace an actual evidence, context and suitability check. The candidate titles are fictional, not scientific sources.
- The scripted choices C, A and B are all solar-topic cards, so the supplied solar count goes from 1 to 2 to 3 to 4. Shown IDs stay C, A, B while their scores rise from 19/12/11 to 29/22/21 to 39/32/31. Nine displayed positions are solar, not nine distinct items or observed persuasion. Repetition follows the stated toy rule and its lack of a seen-item filter.
- The cap retains the original profile and chooses at most one item per topic, with scores 19/8/4. Reset clears topic counts, leaving popularity and tie order, with scores 9/8/4. Matching IDs do not make the mechanisms equal. Neither resolves C review status or proves the selected items satisfy a renewable-only information need.
- Empty or unmatched queries return no candidates. Case and punctuation are normalised by the tiny ASCII-word tokenizer and repeated query words count once. A single-topic catalogue capped at one can yield one result even when more were requested; it must not claim impossible variety. Invalid catalogue identities, profile counts or choices stop under the declared contract.
- Define the information need and suitable retrieval tags, then reconsider scoring signals, interests, variety, accessibility, source evidence and rights. Distinguish a search request from a profile-driven suggestion. Test controls separately and report limitations; do not reuse solar counts or treat play counts as proof of educational value. A design plan is not a deployed or empirically evaluated recommendation service.
Learning evidence
Retain the fictional catalogue, exact query and objective, tag-overlap calculations, two weighted orders with tie rule, three scripted update traces, cap/reset results with scores, source-review distinctions, expected and actual boundary checks or a labelled paper trace, and a purpose-specific music-archive transfer. Separate algorithm execution, a fictional interaction and actual learner work. No real user tracking, content truth guarantee, independent expert certification, deployed service or complete curriculum coverage is implied.
OER and Wikipedia
DfE Computing, Key Stage 3 supplies the broader algorithms context. This AI Year 7 ranking application and assessments are editorial enrichment. Google: Automatically generating and ranking results describes multiple search signals; our tag counts do not reproduce that service. Google: Recommendations, what and why explains discovery through recommendations and content/interest signals. Relevant primary sections read 15 November 2026. The exact scoring rules, fictional profile, catalogue, three choices and controls are original teaching examples, not claims about a commercial algorithm or a general filter-bubble effect.
International books at Kent Library.jpg, Roc0ast3r, CC0. Original library photograph unchanged; it illustrates discovering information, not the fictional catalogue or anyone's tracked preferences.
https://www.youtube.com/watch?v=LVV_93mBfSU — CodeAI: The Internet, How Search Works. https://www.youtube.com/watch?v=x2mRoFNm22g — CodeAI: AI, Training Data & Bias. Actual publisher records, playability, embedding status and preview bytes checked; search video independently reverified 15 November 2026. Recordings embedded unchanged, with no copied transcript, endorsement or relicensing implied.
The complete original standard-library Python was actually executed and independently checked. No real popularity data, pupil profile, watch history, recommendation service, web crawler, remote model, local generative LLM or paid API is used. A source-review flag is an invented process field, not automatic truth verification. User settings on MOOCwiki are not changed by this exercise.
Linked learning areas
aiMOOC Projects
Schulfach+


aiMOOCs


aiMOOC Projekte


MOOCwiki · Deutsch
Nach dem Lernen ist vor dem Lernen
Entdecke direkt den nächsten Lernkurs. Weitere Inhalte erscheinen, wenn Du weiter nach unten scrollst.
Zur MOOCwiki-HauptseiteMediathek
Mediathek wird aus dem Wiki geladen ...
Keine passenden Inhalte gefunden. Bitte ändere Suche oder Filter.
NEWSLernweltNOAH fragen