# Tactiverge Academy — companion code for "Lists, dictionaries and looping over data"
# Lesson: https://tactiverge.win/academy/computational-engineering/python-fundamentals/lists-dictionaries-loops/
# Licence: MIT (see https://tactiverge.win/open-engineering/). Examples appear in lesson order.

# ── Example 1 ────────────────────────────────────────
readings = [20.1, 20.3, 20.2, 35.9, 20.4, 20.2, 20.5]   # °C

print(readings[0:3])      # items 0, 1 and 2
print(readings[-3:])      # the last three
print(readings[::2])      # every second item
print(35.9 in readings)   # is this value in the list?
print(sorted(readings))   # a new, sorted copy


# ── Example 2 ────────────────────────────────────────
readings = [20.1, 20.3, 20.2, 35.9, 20.4]
cleaned = readings        # this does NOT copy the list
cleaned[3] = 20.3         # "fix" the spike
print(readings)

readings = [20.1, 20.3, 20.2, 35.9, 20.4]
cleaned = readings.copy() # a genuine, separate copy
cleaned[3] = 20.3
print(readings)


# ── Example 3 ────────────────────────────────────────
raw_counts = [512, 530, 498, 1023, 505]

volts = [round(c * 3.3 / 1023, 2) for c in raw_counts]
print(volts)

saturated = [i for i, c in enumerate(raw_counts) if c >= 1023]
print("Saturated at indices:", saturated)


# ── Example 4 ────────────────────────────────────────
left = [100, 102, 98, 101]    # mm/s
right = [100, 110, 120, 101]  # mm/s
print([r - l for l, r in zip(left, right)])


# ── Example 5 ────────────────────────────────────────
readings = [20.1, 20.3, 20.2, 35.9, 20.4, 20.2, 20.5]
window = 3

smoothed = []
for i in range(len(readings) - window + 1):
    chunk = readings[i:i + window]
    smoothed.append(round(sum(chunk) / window, 2))
print(smoothed)


# ── Example 6 ────────────────────────────────────────
drive = {"name": "left_drive", "max_rpm": 300, "gear_ratio": 30}

print(drive["max_rpm"])                    # look up by key
drive["max_rpm"] = 280                     # change a value
drive["encoder_cpr"] = 12                  # add a new key
print(drive.get("current_limit_a", 2.0))   # missing key: use a default
print("gear_ratio" in drive)               # does the key exist?

for key, value in drive.items():
    print(f"{key:12} = {value}")


# ── Example 7 ────────────────────────────────────────
log = ["OK", "OK", "LOW_BATTERY", "OK", "STALL", "OK", "STALL"]

counts = {}
for status in log:
    counts[status] = counts.get(status, 0) + 1
print(counts)


# ── Example 8 ────────────────────────────────────────
samples = [
    {"t": 0.0, "sensor": "front", "mm": 412},
    {"t": 0.0, "sensor": "left", "mm": 95},
    {"t": 0.1, "sensor": "front", "mm": 398},
    {"t": 0.1, "sensor": "left", "mm": 97},
    {"t": 0.2, "sensor": "front", "mm": 381},
    {"t": 0.2, "sensor": "left", "mm": 96},
]

by_sensor = {}
for s in samples:
    name = s["sensor"]
    if name not in by_sensor:
        by_sensor[name] = []
    by_sensor[name].append(s["mm"])

print(by_sensor)
for name, values in by_sensor.items():
    print(f"{name}: closest {min(values)} mm")


# ── Example 9 ────────────────────────────────────────
grid = [
    [0, 0, 0, 1, 0],
    [0, 1, 0, 1, 0],
    [0, 1, 0, 0, 0],
    [0, 0, 0, 1, 0],
]

print(grid[1][3])   # row 1, column 3

obstacles = 0
for row in grid:
    for cell in row:
        if cell == 1:
            obstacles += 1
print(f"{len(grid)} x {len(grid[0])} grid, {obstacles} obstacle cells")

for row in grid:
    print("".join("#" if cell == 1 else "." for cell in row))
