From “Conditionals and loops”

Last updated: 2022-06-22 18:50:22

Exercise 03-a

lunch = [
    "Salad", 
    "Salad", 
    "Egg", 
    "Beef", 
    "Potato", 
    "Tea", 
    "Potato", 
    "Potato", 
    "Coffee"
]
result = {}
for i in lunch:
    if i in result:
        result[i] += 1
    else:
        result[i] = 1
result
{'Salad': 2, 'Egg': 1, 'Beef': 1, 'Potato': 3, 'Tea': 1, 'Coffee': 1}

Exercise 03-c

import csv
count = 0
file = open("data/gtfs/stops.txt", "r", encoding="utf-8-sig")
reader = csv.DictReader(file)
for row in reader:
    count += 1
file.close()
count
28255

Exercise 03-d

import csv
with open("data/gtfs/stops.txt", "r", encoding="utf-8-sig") as file:
    reader = csv.DictReader(file)
    row = next(reader)
    xmin = float(row["stop_lon"])
    xmax = float(row["stop_lon"])
    ymin = float(row["stop_lat"])
    ymax = float(row["stop_lon"])
    for row in reader:
        row["stop_lon"] = float(row["stop_lon"])
        row["stop_lat"] = float(row["stop_lat"])
        if row["stop_lon"] < xmin:
            xmin = row["stop_lon"]
        if row["stop_lon"] > xmax:
            xmax = row["stop_lon"]
        if row["stop_lat"] < ymin:
            ymin = row["stop_lat"]
        if row["stop_lat"] > ymax:
            ymax = row["stop_lat"]
[xmin, ymin, xmax, ymax]
[34.284672, 29.492193, 35.839108, 34.917554]

Exercise 03-g

def paste(*args):
    result = ""
    for i in args:
        result += str(i)
    return result
paste("Hello", "World")
'HelloWorld'
paste("A", "B", "C", 1, 2, 3)
'ABC123'

Exercise 03-i

import csv
file = open("data/gtfs/stops.txt", "r", encoding="utf-8-sig")
reader = csv.DictReader(file)
row = next(reader)
lat_min = float(row["stop_lat"])
for row in reader:
    lat_current = float(row["stop_lat"])
    if lat_current < lat_min:
        lat_min = lat_current
        result = row
file.close()
result
{'stop_id': '12510',
 'stop_code': '10615',
 'stop_name': 'מעבר גבול טאבה',
 'stop_desc': ' רחוב:דרך מצרים 168 עיר: אילת רציף:   קומה:  ',
 'stop_lat': '29.492193',
 'stop_lon': '34.904373',
 'location_type': '0',
 'parent_station': '',
 'zone_id': '2600'}

Exercise 03-j

import csv
result = {"ne": 0, "nw": 0, "se": 0, "sw": 0}
file = open("data/world_cities.csv", "r", encoding="utf-8")
reader = csv.DictReader(file)
for row in reader:
    lon = float(row["lon"])
    lat = float(row["lat"])
    if(lon > 0 and lat > 0):
        result["ne"] += 1
    if(lon < 0 and lat > 0):
        result["nw"] += 1
    if(lon > 0 and lat < 0):
        result["se"] += 1
    if(lon < 0 and lat < 0):
        result["sw"] += 1
file.close()
result
{'ne': 28485, 'nw': 10026, 'se': 2689, 'sw': 2445}