[Tutor] problem solving with lists: final (amateur) solution

Peter Otten __peter__ at web.de
Mon Jun 27 04:44:24 EDT 2022

```On 25/06/2022 20:45, marcus.luetolf at bluewin.ch wrote:

dn gave you a long list of things that are bad style or outright broken
in your code, a list that may look rather intimidating.

>      def day_1_flights():
>          key_hist = list(history.keys())
>          c_key_hist = key_hist[:]
>          for dummy_i in c_key_hist:
>              print('flights_day_1: ', c_key_hist[:num_in_flight])
>              for key in c_key_hist[:num_in_flight]:
>                  [history[key].append(player)for player in
> c_all_players[0:num_in_flight]]
>              del c_key_hist[:num_in_flight]
>              del c_all_players[0:num_in_flight]

If you want to fix your script and are looking for a starting point I
suggest that you begin with the function above and turn it into a
so-called "pure" one. In simple words this means it returns a result
that depends only on its arguments, does not print anything and does not
modify mutable arguments. Calling the function twice with the same input
will produce the same output twice. Pure functions are the easiest to

def day_one_flights(players, num_in_flight):
"""Create flights for the first day.

>>> day_one_flights(["Peter", "Paul", "Mary", "Marcus"], 2)
[['Peter', 'Paul'], ['Mary', 'Marcus']]
"""

The paragraph in the docstring that looks like an interactive Python
session is a "doctest". You can run it in a terminal window with

py -m doctest players_startlist_commented.py -v

and get a nice report on whether the expected output of the doctests
conforms with the actual, i. e. whether your script is bug free to the
extent that you tested it.

Now allow me to mention one issue specifically:

>          for dummy_i in c_key_hist:
...
>              del c_key_hist[:num_in_flight]

Here you modify the list you are iterating over. If you are smart enough
to understand what that does you should be too smart to do it ;)
Do not ever write such code!
```