Skip to content

Commit

Permalink
add issue#13
Browse files Browse the repository at this point in the history
  • Loading branch information
Sup2point0 committed Dec 12, 2024
1 parent 64385ce commit 52bf4df
Show file tree
Hide file tree
Showing 4 changed files with 216 additions and 9 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ If you’ve got questons, check the [FAQ](faq.md). You can learn about how pycob

| issue | date | title |
| :---- | :--- | :---- |
| [13](issues/13.md) | 12/12/24 | *Counting* |
| [12](issues/12.md) | 06/12/24 | *import math* |
| [11](issues/11.md) | 03/12/24 | *Short Circuits* |
| [10](issues/10.md) | 26/11/24 | *For Any, For All* |
Expand Down
173 changes: 173 additions & 0 deletions issues/13.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
# pycobytes[13] := Counting
<!-- #SQUARK live!
| dest = 13
| title = Counting
| head = Counting
| index = 13
| shard = functions / challenge
| date = 2025 December
-->

> *If at first you do not succeed, call it version 1.0.*
Hey pips!

When using a `for` loop, it’s often really useful to know which iteration number we’re on.

```py
>>> for i in range(3):
print(f"iteration {i}")
iteration 0
iteration 1
iteration 2
```

But if we’re iterating over an iterable, we don’t have a variable to count the iteration...

```py
>>> l = ["clear", "wing"]

>>> for item in l:
print(f"unknown iteration: {item}")
unknown iteration: clear
unknown iteration: wing
```

A pretty quick fix is to just make your own counting variable, and manually increment it each iteration.

```py
>>> i = 0
>>> l = ["starving", "venom"]

>>> for item in l:
print(f"iteration {i}: {item}")
i += 1 # manually increment
iteration 0: starving
iteration 1: venom
```

> [!Tip]
> This approach is useful when you need to do other stuff with the increment variable – although to be honest, if you’ve reached that stage it may be indicative of other issues.
But with how often this comes up, you would think there’s an in-built solution.

Well this is Python, so of course there is!

```py
>>> l = ["phantom", "knight"]

>>> for i, item in enumerate(l):
print(f"iteration {i}: {item}")
iteration 0: phantom
iteration 1: knight
```

The built-in `enumerate()` function works on any iterable. It pairs each item with its index to form an `(index, item)` tuple, so that when you iterate over it you can extract both the iteration index and item value.

```py
>>> l = ["blue", "eyes", "white", "dragon"]

>>> list(enumerate(l))
[(0, "blue"),
(1, "eyes"),
(2, "white"),
(3, "dragon")]
```

You can use `enumerate()` on any iterable, including `str`, `tuple` and even `dict` objects.

```py
>>> list(enumerate("sup"))
[(0, "s"),
(1, "u"),
(2, "p")]
```

Using this, we now have an extremely convenient way to count iterations while we’re looping – particularly in list comprehensions:

```py
>>> text = "Never Gonna Give You Up"
>>> out = [
# capitalise every other character
char.upper() if i % 2 == 0 else char.lower()
for i, char in enumerate(text)
]
>>> "".join(out)
NeVeR GoNnA GiVe yOu uP
```

And fun fact, you can even pass in a second numerical argument to specify the starting index!

```py
>>> l = ["iTechnicals", "Sup"]
>>> [f"{i}: {player}" for i, player in enumerate(l, 1)]
["1: iTechnicals", "2: Sup"]
```

Keep in mind `enumerate()` doesn’t exactly return a `list`, so you can’t index it:

```py
>>> e = enumerate("phantasm")
>>> e[1]
Error:
```

If you want the raw items, just convert the output to a `list` with the `list()` constructor.

```py
>>> l = list(enumerate("desync"))
>>> l[2]
(2, "s")
```

This is because `enumerate()` actually returns an **iterator** which acts as a proxy to the original object. We’ll take a closer look at these a future issue!


<br>


## Challenge

Given a list of fruit and how many to purchase as tuples, can you print a shopping list?

```py
>>> shopping = [
("apricots", 3),
("bloomerangs", 4),
("carrots", 2),
("dragonfruit", 1)
]

>>> (your_expression)
1. apricots x3
2. bloomerangs x4
3. carrots x2
4. dragonfruit
```

And bonus points for making it as fancy as you can :P

```
=====================
| 1 | durian | x7 |
| 2 | acai | x3 |
| 3 | lychee | x10 |
| 4 | pomelo | x2 |
---------------------
| TOTAL | x22 |
=====================
```


<br>


---

<div align="center">

[![The Codeless Code, Case 158](../assets/issues/13-codeless.png)](http://thecodelesscode.com/case/158)

[*The Codeless Code*, Case 158](http://thecodelesscode.com/case/158)

</div>
50 changes: 41 additions & 9 deletions site/src/data/site.json
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
{
"meta": {
"exported": "2024-12-05",
"file_count": 13,
"page_count": 13
"exported": "2024-12-12",
"file_count": 14,
"page_count": 14
},
"index": {
"01": {
Expand Down Expand Up @@ -77,6 +77,12 @@
"issues/12.md"
]
},
"13": {
"route": null,
"pages": [
"issues/13.md"
]
},
"404": {
"route": null,
"pages": [
Expand All @@ -103,7 +109,8 @@
"issues/08.md",
"issues/09.md",
"issues/10.md",
"issues/11.md"
"issues/11.md",
"issues/13.md"
],
"strings": [
"issues/02.md",
Expand Down Expand Up @@ -142,7 +149,8 @@
"issues/11.md"
],
"functions": [
"issues/10.md"
"issues/10.md",
"issues/13.md"
],
"modules": [
"issues/12.md"
Expand Down Expand Up @@ -328,9 +336,9 @@
},
"issues/08.md": {
"path": "issues/08.md",
"last_deploy": "2024-11-13 17:28:39 +0000",
"last_deploy": "2024-12-12 10:03:36 +0000",
"slocs": 160,
"chars": 3855,
"chars": 3856,
"isIndex": false,
"flags": [
"live"
Expand Down Expand Up @@ -428,9 +436,9 @@
},
"issues/12.md": {
"path": "issues/12.md",
"last_deploy": "2024-12-05 18:17:20 +0000",
"last_deploy": "2024-12-05 18:26:23 +0000",
"slocs": 144,
"chars": 2866,
"chars": 2850,
"isIndex": false,
"flags": [
"live"
Expand All @@ -450,6 +458,30 @@
"date": "2024-12-06",
"date_display": "2024 December 6"
},
"issues/13.md": {
"path": "issues/13.md",
"last_deploy": "2024-12-12 10:02:20 +0000",
"slocs": 161,
"chars": 3656,
"isIndex": false,
"flags": [
"live"
],
"dest": "13",
"title": "Counting",
"head": "Counting",
"capt": null,
"desc": null,
"index": [
"13"
],
"shard": [
"functions",
"challenge"
],
"date": "2025-12-01",
"date_display": "2025 December"
},
"issues/404.md": {
"path": "issues/404.md",
"last_deploy": "2024-12-02 20:46:06 +0000",
Expand Down
1 change: 1 addition & 0 deletions site/src/parts/nav/Nav.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ nav {
flex-direction: row;
align-items: center;
justify-content: space-between;
background-color: white; // fallback
background-color: $col-idle;
border-bottom: 2px solid $col-flavour;
@include fade-duality;
Expand Down

0 comments on commit 52bf4df

Please sign in to comment.