【问题标题】:Avoiding division by zero避免除以零
【发布时间】:2020-06-25 15:52:28
【问题描述】:

我知道这是基本的,所以任何帮助表示赞赏。

这是我的代码 - 我只是无法使用 if 语句来避免除以零的工作。

谁能帮忙?

# problem: calculate what percent of car park spaces are occupied
# input: integers 1 or 0, 1 signals an occupied space and 0 is empty

car_park_spaces = []
          
# sub problem: number of occupied spaces
occupied = 0

for car_park_space in car_park_spaces:
    if car_park_space == 1:
        occupied += 1
    occupied_spaces = occupied

    # sub problem: find the length of the list
    percentage = occupied_spaces / len(car_park_spaces) * 100

    # output: percent of occupied spaces
    if not car_park_spaces:
        print('The list is empty')
    else:
        print ('The percentage of occupied spaces is', percentage, '%')

【问题讨论】:

    标签: python python-3.x python-2.7 divide-by-zero


    【解决方案1】:

    我将代码移到了函数中,这样它就更有条理了。函数如下所示:

    def occupied_percent(car_park_spaces):
        if not car_park_spaces:
            return None
            
        occupied = 0
        total_spaces = len(car_park_spaces)
    
        for space in car_park_spaces:
            if space:
                occupied += 1
    
        return occupied / total_spaces * 100
    

    如果百分比计算成功,则输出为float,否则输出为None。使用该函数时,您必须在打印结果之前检查返回值。

    接下来我创建了简化使用的打印功能:

    def print_percentage(car_park_spaces):
        result = occupied_percent(car_park_spaces)
        print('The list is empty.' if result is None else f'The percentage of occupied spaces is {result}%.')
    

    我运行了一些测试用例:

    print_percentage([])
    print_percentage([0])
    print_percentage([1])
    print_percentage([1, 0])
    print_percentage([1, 0, 1, 1])
    

    那些产生这个输出:

    The list is empty.
    The percentage of occupied spaces is 0.0%.
    The percentage of occupied spaces is 100.0%.
    The percentage of occupied spaces is 50.0%.
    The percentage of occupied spaces is 75.0%.
    

    请注意,代码可能会进一步简化,因为 Python 倾向于使用大量单行代码。

    【讨论】:

    • 感谢您的帮助.. 我仍然无法让它工作。我已经改变了我的代码如下。是什么让 if 语句停止工作?它是独立工作的,但是当我添加其余代码时,它不再打印“行为空”占用空间= []汽车=占用空间.count(1)空间=占用空间.计数(0)百分比=汽车/长度(占用空间) * 100 如果占用空间为 []: print('列表为空') else: print (percentage, '%')
    • @MissusMcgthefirst if occupied_spaces is []: 不检查是否为空,而是检查对象的地址。不要那样做,而是写if not occupied_spaces:。如果代码仍然无法运行,请提出新问题或在其他网站上分享您的代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-03
    • 2013-07-14
    • 2010-10-26
    相关资源
    最近更新 更多