[prev in list] [next in list] [prev in thread] [next in thread]
List: python-list
Subject: Re: WANT: bad code in python (for refactoring example)
From: Makoto Kuwata <kwa () kuwata-lab ! com>
Date: 2017-02-17 2:03:29
Message-ID: CAFTm5Rv9Q+Drxs1XJ3jX=2fNV+_3hy1rpzMBWWXjnGiZ1uBEFA () mail ! gmail ! com
[Download RAW message or body]
Thanks Erik,
On Thu, Feb 16, 2017 at 6:53 AM, Erik <python@lucidity.plus.com> wrote:
> (which is what I think you mean by "proper size")
>
As I explained at my first post, I'm teaching Python to novice programmers.
Therefore refactoring example code should be in the size what they can
understand.
It is hard for them to read and understand over than thousand lines of code.
Almost of all projects have code over than thousand lines of code,
but it is possible to quote a part of them for refactoring example, I think.
>
> (Python code examples of what you think is "bad" vs "good" would be
> useful).
>
You are right.
Bad code Example:
#
https://codewords.recurse.com/issues/one/an-introduction-to-functional-programming
from random import random
def move_cars(car_positions):
return map(lambda x: x + 1 if random() > 0.3 else x,
car_positions)
def output_car(car_position):
return '-' * car_position
def run_step_of_race(state):
return {'time': state['time'] - 1,
'car_positions': move_cars(state['car_positions'])}
def draw(state):
print ''
print '\n'.join(map(output_car, state['car_positions']))
def race(state):
draw(state)
if state['time']:
race(run_step_of_race(state))
race({'time': 5,
'car_positions': [1, 1, 1]})
Refactoring example:
from random import random
class Car(object):
def __init__(self):
self.position = 1
def move(self):
if random() > 0.3:
self.position += 1
return self.position
class Race(object):
def __init__(self, n_cars=3):
self._cars = [ Car() for _ in range(n_cars) ]
def round(self):
for car in self._cars:
car.move()
def report(self):
print("")
for car in self._cars:
print('-' * car.position)
def run(self, n_rounds=5):
self.report()
for _ in range(n_rounds):
self.round()
self.report()
if __name__ == '__main__':
Race(3).run(5)
--
regards,
makoto kuwata
--
https://mail.python.org/mailman/listinfo/python-list
[prev in list] [next in list] [prev in thread] [next in thread]
Configure |
About |
News |
Add a list |
Sponsored by KoreLogic