Event 4 - 2025-11-12
Don't forget your homework, it's at the bottom of this page.
Homework review
The homework, part 2 of Advent of Code, 1st day of 2024 was an exercise in counting how many times an element appears in a list. More specifically, how many times a number appears in a list.
Here is an example where I use a for loop, "manually" counting the numbers.
f = open("puzzle.txt", "r")
lefties = []
righties = []
simalarity = 0
for line in f.readlines():
line = line.strip()
words = line.split()
left, right = words
left = int(left)
right = int(right)
lefties.append(left)
righties.append(right)
def count_similarities(left_number, righties):
simalarity = 0
for right_number in righties:
if right_number == left_number:
simalarity += 1
return simalarity
for left_number in lefties:
right_matching_numbers = count_similarities(left_number, righties)
score = left_number * right_matching_numbers
print(f"The number {left_number} appears {right_matching_numbers} times in the right left, score is {score}")
simalarity += score
print(f"Total simalarity is {simalarity}") Here is an another example where I list.count(n), which is builtin in Python itself.
f = open("puzzle.txt", "r")
lefties = []
righties = []
simalarity = 0
for line in f.readlines():
line = line.strip()
words = line.split()
left, right = words
left = int(left)
right = int(right)
lefties.append(left)
righties.append(right)
for left_number in lefties:
right_matching_numbers = righties.count(left_number)
score = left_number * right_matching_numbers
print(f"The number {left_number} appears {right_matching_numbers} times in the right left, score is {score}")
simalarity += score
print(f"Total simalarity is {simalarity}") Libraries
Writing your own code for everything is quite time consuming, and you (and I) will make mistakes, and it often requires very deep knowledge about the specific topic. There are often quite alot of details and quirks you need to know exists.
As an example, how much time do you want to spend of making a nice graph from some data you have? There are alot of people that already did alot of cool and useful code that creates graphs.
In Python there are alot of builtin libraries, that comes with Python itself. You can also find alot of libraries in Pip. We will talk about using such external libraries later on.
Importing in different ways
In python there are three ways to import things from libraries.
# The first is to use the entire library and then use it as a "handle"
import requests
response = requests.get("https://programming-course.vitberget.se/")
print("The best page on the internet looks like this:")
print(response.content)# The second is to just import a port of library
from requests import get
response = get("https://programming-course.vitberget.se/")
print("The best page on the internet looks like this:")
print(response.content)# The third is to just import a port of library, and use an alias.
# This is useful if many libraries use the same name, as you might
# imagine, "get" is quite common
from requests import get as requests_get
from other_libarry import get as other_get
response = requests_get("https://programming-course.vitberget.se/")
print("The best page on the internet looks like this:")
print(response.content)Manually parsing HTML comments
Because of reasons I won't go into here, Melinda was unable to use a library and wanted to
parse out the content of a HTML comment "by hand" as a part of a Python challenge.
The page with the Python challenge does not look like anything containing anything special, you need to look at the source code of the Page to find the comments with the secret puzzle in it.
I coded this live (including having and fixing bugs ):
import requests
response = requests.get("http://www.pythonchallenge.com/pc/def/ocr.html")
print("Reponse!")
print(response)
body = response.content.decode(encoding="utf-8")
current_comment = 0
target_text = ""
for line in body.splitlines():
line = line.strip()
if line == "<!--":
current_comment += 1
elif current_comment == 2:
if line == "-->":
current_comment += 1000
else:
target_text += line
print("target text")
print(target_text) Comments
Since we were parsing HTML comments, the question about comments came up.
When to use comments? In my opinion comments should be used to answer the question "why?". The "how?" and other such question should be expressed in code, for example, name your functions to what they actually do, name arguments and variables to show their purpose as well.
Commong project for the group - SL API
In my plan for this course, a common project is one of the things I want do do. SL can show you departures from chosen station on the web and in the app, but we can of course do it much better! 😀
API
API stands for Application Programming Interface. Or in other words, how computers talks with itself and with others. A function is a small API, that you only can "talk" to in certiain ways. Speaking to a webserver uses another API called HTTP, which is a text based API, as this example.
SL
SL is a swedish goverment authority, and such is is encouraged to expose their freely available data in an API. Read more on digg.se.
Exploring without code
With a little googling you can discover https://www.trafiklab.se/sv/api/our-apis/sl/transport/ and if you explore the site a bit you can something called OpenAPI which is a format to describe a http web service. It's also interactive, so you can test the services without any code, press the "Try it out" for each part of the service.
The SL API does not require any login or such, so you can just call them and explore. We can see that "departures" requires a "site id" so lets first find one we like. https://transport.integration.sl.se/v1/sites?expand=false shows us all the sites in SL. In the browser we can for example look for Gullmarsplan, and find it has the id 9189.
We can then use that id to look at departures from Gullmarsplan. https://transport.integration.sl.se/v1/sites/9189/departures?forecast=60 and we can see in our browser how the data is structured.
Exploring with code
The reponse is in JSON, which is a common format to represent data, and such easy to use someone elses code to parse it.
import requests
url = "https://transport.integration.sl.se/v1/sites/9189/departures?forecast=60"
response = requests.get(url)
json = response.json()
first_item_the_result = json['departures'][0]
print(f"first {first_item_the_result}")
Homework
This homework has a few question and then a task.
Questions
- How can we filter to only get for example buses in the response?
- How can we determine if the metro goes by the T-centralen without knowing where all the stations are located relative to it?
- What is "expanded" in the query for sites? (details please)
The task
Expand on my code in the "Exploring with code" and make it print like something this:
19 Odenplan - Inställd till Rådmansgatan pga tekniskt fel på banan
17 Ã…keshov - 3 min
18 Farsta - 3 min
... There was actually "tekniskt fel" when I looked at SL when writing this. 😲