课程 3:逐步求精

  1. 什么是逐步求精: 逐步求精是一种将复杂问题逐层细化、逐步完善解决方案的编程思想。先写出高层次的伪代码或主要步骤,再逐步将每一步细化为具体实现。
  2. 详情请查看《Karel the Robot Learns Python》8 - 逐步求精 点击查看
  3. 基本步骤:
    • 1. 明确总体目标,写出高层次的解决方案。
    • 2. 将每个大步骤细化为更具体的小步骤或函数。
    • 3. 重复细化,直到每一步都可以直接用代码实现。
  4. 举例:

    任务目标:让Karel把房间里的所有beeper清理干净。

    清理前
    清理前
    清理后
    清理后

    逐步求精分解思路:

    1.清理当前行

    2.移动到下一行

    3.清理当前行

    4.重复

    # 高层次伪代码
    def main():
        清理当前行
        while 左侧有路:
            移动到下一行
            清理当前行
    
    # 细化每一步
    def main():
        清理当前行
        while 左侧有路:
            移动到下一行并向西
            清理当前行
            if 右侧有路:
                移动到下一行并向东
                清理当前行
            else:
                转身
    
    # 进一步细化为具体函数
    def main():
        clean_current_row()
        while left_is_clear():
            reposition_for_row_to_west()
            clean_current_row()
            if right_is_clear():
                reposition_for_row_to_east()
                clean_current_row()
            else:
                turn_around()
    
    # 细化子任务:清理当前行
    def clean_current_row():
        while front_is_clear():
            if beepers_present():
                pick_beeper()
            else:
                move()
        # 仿照栅栏柱错误:
        if beepers_present():
            pick_beeper()
    
    # 细化子任务:移动到下一行并向西
    def reposition_for_row_to_west():
        turn_left()
        move()
        turn_left()
    
    # 细化子任务:移动到下一行并向东
    def reposition_for_row_to_east():
        turn_right()
        move()
        turn_right()
    
    # 细化子任务:向右转
    def turn_right():
        for i in range(3):
            turn_left()
    
    # 细化子任务:向后转
    def turn_around():
        turn_left()
        turn_left()
                    

    下面是清理房间任务的完整实现示例:

    def main():
        clear_to_line_of_beepers()
        while left_is_clear():
            move_to_west_line()
            clear_to_line_of_beepers()
            if right_is_clear():
                move_to_east_line()
                clear_to_line_of_beepers()
            else:
                turn_around()
    
    def clear_to_line_of_beepers():
        while front_is_clear():
            if beepers_present():
                pick_beeper()
            else:
                move()
        if beepers_present():
            pick_beeper()
    
    def move_to_west_line():
        if left_is_clear():
            turn_left()
            move()
            turn_left()
    
    def move_to_east_line():
        if right_is_clear():
            turn_right()
            move()
            turn_right()
    
    def turn_right():
        for i in range(3):
            turn_left()
    
    def turn_around():
        turn_left()
        turn_left()
                    
  5. 好处: 逐步求精有助于理清思路、降低编程难度、提升代码可读性和可维护性。
知识补充:逐步求精
温馨提示:编程时遇到复杂问题,不要急于写代码,先用逐步求精的方法理清思路,再动手实现。