# 一个关于python的函数式编程的问题,哪位可以帮忙解答下~~~谢谢

0

car1.py:

``````from random import random

time = 5
car_positions = [1,1,1]

while time:
# decrease time
time -= 1

print ('')
for i in range(len(car_positions)):
# move car
if random() > 0.3:
car_positions[i] += 1

# draw car
print ('-' * car_positions[i])
``````

car_function.py: (执行的输出不太对)

``````from random import random

def race(state):
draw(state)
if state['time']:
race(run_step_of_race(state))

def draw(state):
print ('')
print ('\n'.join(map(output_car,state['car_positions'])))

def output_car(car_positions):
return '-' * car_positions

def run_step_of_race(state):
return {'time':state['time']-1,'car_positions':move_cars(state['car_positions'])}

def move_cars(car_positions):
return map(lambda x : x+1 if random() > 0.3 else x,car_positions)

race({'time':5,'car_positions':[1,1,1]})
``````

ukyo--阿涅丝 | 初学一级 | 园豆：27

dudu 2年前

@dudu: 不提倡挂外链接吗

@dudu: 悬赏的豆豆该怎样给回答人呢...点不了选项

dudu 2年前

1

def move_cars(car_positions):
return map(lambda x : x+1 if random() > 0.3 else x,car_positions)

def move_cars(car_positions):
return list(map(lambda x : x+1 if random() > 0.3 else x,car_positions))

Python2中，map直接返回元素列表
Python3中，map函数返回一个map类型对象。

ukyo--阿涅丝 | 园豆：27 (初学一级) | 2020-10-09 11:57

0
``````from random import random

def race(state):
draw(state)
if state['time']:
race(run_step_of_race(state))

def draw(state):
print('')
print('\n'.join(map(output_car, state['car_positions'])))

def output_car(car_positions):
return '-' * car_positions

def run_step_of_race(state):
return {'time': state['time'] - 1, 'car_positions': move_cars(state['car_positions'])}

def move_cars(car_positions):
return list(map(lambda x: x + 1 if random() > 0.3 else x, car_positions)) #这个地方应该返回list，而不是map

race({'time': 5, 'car_positions': [1, 1, 1]})
``````

E行者 | 园豆：1761 (小虾三级) | 2020-10-09 11:55