首页 > 解决方案 > 如何在python程序中应用递归

问题描述

我目前正在开发一个 python 程序,该程序根据用户提供的订单信息运送书箱。我有两个大盒子和小盒子,完全专注于盒子或堆叠的高度尺寸。在数学上能够思考并生成所需的公式,但是对于这个程序,但将其放入代码中,我的大脑在某个步骤中会锁定是否应用递归。

首先,提示用户输入

# Box shipping

# Height in inches
big_box_height = int(input('Please enter the hieght of Large box: '))

# Height in inches
small_box_height = int(input('Please enter the hieght of Small box: '))

# Height/thickness in inches
book_thickness = int(input('Please enter the thickness of your books: '))

# Number of books
num_of_books = int(input('Please enetr the numbers of books to order: '))

其次,使用用户输入进行数学评估,以获得填充大盒子的书籍总数,程序应尽一切可能填充大盒子而不是部分填充。

我为这种情况创建了一个函数

# Fill large box.

def large_box(big_box_height, book_thickness, num_of_books):

    # Get total number of books to fill the large box
    total_num_of_books_to_fill_big_box = big_box_height % book_thickness

    # Check users input, number of books given equal number of books to fill large book
    if num_of_books == total_num_of_books_to_fill_big_box:
        print('Shipping 1 box\n 1 large')

下一部分是添加 else 语句来评估给定的书籍数量是否大于填充大盒子所需的书籍数量。我创建了一个空列表来尝试根据用户的数据输入评估附加要填充的大框的总数。

  elif num_of_books > total_num_of_books_to_fill_big_box:
        big_boxes = []

数学描述。我有 2 个宽度和底数相同的盒子,只有高度根据用户输入而有所不同。样本数据。如果用户输入的是大盒子的高度= 20英寸小盒子的高度= 10英寸盒子的厚度= 2英寸书籍数量= 10本书通过简单的交叉乘法,我知道10本书2英寸将一次填满大盒子然后运送或打印运送 1 个大盒子。

现在如果用户输入的书籍数量是 30 本书,这将填充 3 个大框,这就是第二个 else 语句派上用场的时候,现在我的问题是我需要如何为大框函数应用递归或者我应该怎么做. 这也适用于小盒子,前提是我不运送部分填充盒子。第一次尝试填充是大盒子。我知道递归可以帮助遍历书籍总数,直到我剩下零本书。但是实现它的方式,我卡住了。请帮忙。

标签: python

解决方案


推荐阅读