Data Structures and Algorithms with Python › Module 1: Why Algorithms Matter › Lesson 1.1

What Algorithms and Data Structures Are

Free previewLesson 1.1 · about 30 minutes · 5 exercises

0 of 5 exercises completed
Python loads when you first press Run

Get the full course

10 modules of searching, sorting, hash maps, stacks and queues, recursion, linked lists, trees, graphs and dynamic programming, with live Python, a step counter and checked exercises in every lesson, in your browser, nothing to install. Lessons 1.1 and 1.2 are free; the rest of the course is Rs. 300 + 18% GST.

Enroll Now — Rs. 354.00

By the end of this lesson you will be able to

  • explain what an algorithm is, and write one down precisely enough for a computer to follow
  • explain what a data structure is, with three everyday examples: a list, a dictionary and a queue
  • say why choosing a good method matters as data grows, and why employers ask about it
  • use the parts of this course: Run, the step counter, Check my answer and Show solution
  • write short Python functions with lists, loops and dictionaries, and know the difference between returning and printing

A first morning at Brightwater Books

Lucy Carter has just started as a trainee programmer at Brightwater Books, an online bookshop with a busy warehouse and a small fleet of delivery vans. Before she has found the kettle, Grace Holloway, the warehouse manager, stops at her desk. “A customer wants to know if we have A Map of Small Rivers on shelf C. The system says yes, the picker says no. Could you check how the system decides?”

Lucy opens the code and finds a few lines that look through the shelf's list of titles one by one. Arthur Blake, the senior developer who will be her mentor, pulls up a chair. “Good first question,” he says. “Before you read the code, tell me how you would find a book on a shelf. Exactly how. As if I were a robot that does only what it is told.”

An algorithm is a precise recipe

Lucy's first answer is “look along the shelf until you see it”. Arthur shakes his head. “Where do I start? What do I do if it is not there? When do I stop?” A robot, and a computer, needs every detail spelled out. After a couple of tries, Lucy writes this:

  1. Start at the leftmost book on the shelf. Call its position 0.
  2. Read the title of the book at the current position.
  3. If it is the title you want, stop and report the position.
  4. Otherwise move one book to the right. If there are no more books, stop and report “not found”.
  5. Go back to step 2.

That is an algorithm: a finite list of exact instructions that takes some input (here, a shelf and a title), always finishes, and produces an answer (a position, or “not found”). A recipe for a cake is almost an algorithm, but recipes say things like “bake until golden”, which a computer cannot judge. An algorithm leaves nothing to judgement.

Here is Lucy's shelf, with positions counted from 0 as Python does:

position:    0          1          2          3
          +--------+ +--------+ +--------+ +--------+
shelf C:  | Tides  | |Lantern | | Map of | | Glass  |
          |  of W. | |Orchard | | Small R| |Beekeep.|
          +--------+ +--------+ +--------+ +--------+
             look 1     look 2     look 3  -> found at 2

Tracing it by hand: look at position 0 (Tides of Wrenhollow: no), position 1 (The Lantern Orchard: no), position 2 (A Map of Small Rivers: yes). Report 2. Three looks. If Grace had asked for a book that is not on the shelf, the algorithm would look at all four and then report “not found”. Every possible case has an answer.

The same algorithm in Python takes only a few lines. Python's lists count positions from 0, and this course follows the common habit of returning -1 to mean “not found”, because -1 can never be a real position.

It prints 2 and then -1. Notice the return -1 line: it sits outside the loop, lined up with for, so it runs only after every book has been checked. That detail is exactly the “if there are no more books” part of Lucy's written version. (The bug Grace saw turned out to be a title typed with two spaces in the stock list: the algorithm was right, the data was not.)

A data structure is a way of organising data

An algorithm works on data, and how that data is arranged makes a huge difference to how easy the job is. A data structure is a particular way of organising data in a computer so that certain jobs are quick and simple. You already know some from ordinary life and from Python.

Data structureIn the warehouseGood at
ListBooks standing on a shelf in order, each at a numbered positionKeeping things in order; going straight to “the book at position 7”
DictionaryA stock card index: look up a book's code, read how many copies are leftFinding the value for a key at once, without searching
QueueParcels waiting at the packing desk: the first to arrive is packed firstServing things fairly in the order they came

A dictionary in Python stores pairs: a key (such as a book code) and a value (such as the number of copies). You look up a value by its key in square brackets, and you can add or change pairs in the same way.

The book with code BW-10442 has 12 copies. A delivery of 30 copies of BW-20817 arrives, a new book BW-47720 is added, and the last line checks whether a code is known at all (it is not, so it prints False). No loop anywhere: the dictionary goes straight to the right entry.

A queue is a line where the first to join is the first to leave, like the packing desk:

  leave here                        join here
      |                                 |
      v                                 v
   [order 501] [order 502] [order 503] <- order 504

You will build queues properly in Module 6. For now, the point is that each structure makes some jobs easy and others awkward. A queue is perfect for “who is next?” and hopeless for “is order 377 waiting anywhere?”.

Why the choice matters: Arthur's slow report

Arthur tells Lucy a story from his own first year. Every night the warehouse ran a report that listed each order with the price of every book in it. The prices were kept as a Python list of pairs, (code, price), and for every book in every order the report searched the list from the start until it found the right code. “With a few hundred books it took a second,” Arthur says. “Then the catalogue grew to fifty thousand books and the report started finishing after breakfast.”

The fix did not need a faster computer. He stored the prices in a dictionary instead, so each price was found at once instead of by searching. Here is the difference for one lookup, on a made-up catalogue of 5,000 books. The first line after the functions builds the list of pairs with a short loop inside square brackets; you do not need to write lines like that yet.

Both functions find the price 5099. count_steps, a helper built into this course, reports how many lines of code each call carried out: 10,001 for the list search, which had to walk past 4,999 other books, and 1 for the dictionary. Now picture that search repeated for every book in thousands of orders, and you have a report that runs all night. Same answers, same computer; the only change is the data structure.

The main idea of this course

A correct program is not automatically a good one. When data is small, almost any method is fast enough. When data grows, the method you chose decides whether a job takes a moment or all night. Learning a handful of data structures and algorithms well lets you make that choice on purpose.

Why employers and interviews ask about this

Technical interviews and campus placement tests nearly always include problems of this kind: find a pair of prices that add up to a target, spot duplicates, find the shortest route between two places. Employers ask them for good reasons. The problems show whether you can turn a vague request into a precise method, whether you think about edge cases (an empty list, a missing item), and whether you notice when a method will not cope with real amounts of data. Those are daily skills in software work, not puzzles for their own sake.

This course teaches the structures and techniques that come up again and again: lists and strings, searching and sorting, dictionaries and sets, stacks and queues, recursion, linked lists and trees, graphs, and dynamic programming. Each lesson solves a real problem at Brightwater Books, measures how much work the solution does, and ends with exercises that are checked automatically.

How this course works

Two extra helpers, count_steps (which you met above) and step_table, are built into every box. They are not part of ordinary Python; they exist to make the amount of work visible.

Who you will meet

You follow Lucy through her first months. These are the people who bring her problems:

PersonRoleBrings problems about
Arthur BlakeSenior developer, Lucy's mentorAlways asks “how many steps?”
Grace HollowayWarehouse managerStock, shelves, orders and picking lists
Sam TurnerDelivery plannerVans, depots, stops and routes
Emma PriceCustomer service leadCustomer records, messages and the complaints queue
Oliver GrantRuns the websiteThe search box, recommendations and page logs

A quick Python refresher

This course assumes you know basic Python. The exercises in this lesson are warm-ups, so here is a short reminder of the pieces you will use most. Run each box and read the output.

Lists and loops. A list keeps items in order. for size in orders visits each item in turn; for i in range(len(orders)) visits each position, which is useful when you need to know where you are. Counting the items that pass a test is one of the most common patterns there is: start a counter at 0, add 1 each time.

Three orders have more than 5 items. The second loop shows each position next to its value; positions run from 0 to 4 for a list of five items, and orders[-1] would give the last item, 9.

Returning versus printing. This difference trips up many beginners, and it matters for every exercise in the course. return hands a value back to whoever called the function, so it can be stored and used. print only shows something on the screen; the function then hands back None, Python's word for “nothing”.

The screen shows 900 once (from inside show_total), then a is 900 and b is None. The checker in this course looks at what your function returns, so a function that prints its answer instead of returning it will be marked wrong even though the right number appears on the screen.

Tuples

A tuple is like a list written with round brackets, such as (3, 9), that cannot be changed after it is made. Functions often return two values at once as a tuple: return first, last hands back the tuple (first, last). The checker treats a tuple and a list as different things, so return exactly what the exercise asks for.

Worked example: turning a request into a function

Emma asks: “How many complaints came from customer 2207 this week?” Lucy restates it precisely: given a list of customer numbers (one per complaint) and one customer number, return how many times that number appears; an empty list gives 0. The algorithm is the counting pattern from above: start at 0, look at each number, add 1 when it matches, return the counter after the loop. Writing the request down precisely, including the empty case, is half the work. The code is the easy half.

Exercises

Each exercise has a code box. Press Check my answer when you are ready: your function is tested on many inputs, not only the examples shown.

Exercise 1 · Big orders

Grace wants to know how many orders are large. Write count_over(orders, limit) that returns how many numbers in the list orders are greater than limit (an order exactly equal to the limit does not count). An empty list gives 0.

Exercise 2 · Reverse a picking list

Pickers walk the aisles from the far end, so Grace needs each picking list backwards. Write reverse_list(items) that returns a new list with the items in reverse order, built with a loop. Do not use reversed(), .reverse() or slicing such as [::-1]: the point is to write the loop yourself. An empty list gives an empty list.

Exercise 3 · Find a title

Write find_title(titles, title) that returns the position of the first book in the list titles equal to title, or -1 if it is not there. Use a loop; do not use .index() (which raises an error when the title is missing).

Exercise 4 · Count the stock

When a delivery arrives, every copy is scanned, giving a list of book codes such as ["BW-10442", "BW-31105", "BW-10442"]. Write stock_counts(codes) that returns a dictionary giving, for each code, how many times it was scanned: here {"BW-10442": 2, "BW-31105": 1}. An empty list gives an empty dictionary. Build it with a loop; do not use Counter or .count().

Exercise 5 · Fix: first and last

Sam wants the first and last stop of each delivery run. The function in the box shows the right values on the screen, but the checker says it is wrong. Fix first_and_last(stops) so that it returns a tuple (first, last) for a non-empty list. A list with one stop gives that stop twice, for example ("Elmwick", "Elmwick").

0 of 5 exercises completed

Quick check

Choose an answer to see whether you are right and why.

1. Which of these is an algorithm in the sense used in this course?

2. You need to look up the number of copies left for a book, given its code, thousands of times a day. Which data structure fits best?

3. A function prints the right answer on the screen but the checker marks it wrong. What is the most likely reason?

4. Arthur's nightly report became fast again after he changed it. What did he change?

Summary

  • An algorithm is a finite list of exact instructions that takes an input and always finishes with an answer, including in awkward cases such as “not found”.
  • A data structure is a way of organising data so that some jobs are easy: a list keeps order, a dictionary finds a value by its key at once, a queue serves things in the order they arrived.
  • The choice matters as data grows: the same report can take seconds or all night depending on the method and the structure.
  • Interviews and placement tests ask about these ideas because they show precise thinking, care with edge cases and awareness of how programs scale.
  • In this course you Run and edit code, read the step count, Check your answer on many inputs, and can Show a model solution after one check.
  • A function should usually return its answer; printing only shows it and hands back None.

Found a mistake on this page, or something unclear? Report a problem and mention “Algorithms Lesson 1.1”.