得到除以零的python

时间:2019-03-14 20:44:27

标签: python

这是我的代码。

public class LRUCache {

    struct Cache {
        public int Key { get;set; }
        public int Val { get;set; }
    }

    private int _capacity;
    private LinkedList<Cache> _cache = new LinkedList<Cache>();
    private Dictionary<int, LinkedListNode<Cache>> _keys = new Dictionary<int, LinkedListNode<Cache>>();

    public LRUCache(int capacity) {
        _capacity = capacity;
    }

    public int Get(int key) {

        if (_keys.TryGetValue(key, out var node)) {

            _cache.Remove(node);
            _cache.AddLast(node);

            return node.Value.Val;
        }

        return -1;
    }

    public void Put(int key, int value) {

        LinkedListNode<Cache> n;
        var containsKey = _keys.TryGetValue(key, out n);
        if (_cache.Count >= _capacity && !containsKey) {
            var invalidNode = _cache.First;
            _cache.RemoveFirst();
            _keys.Remove(invalidNode.Value.Key);
        }

        if (containsKey) {

            _cache.Remove(n);

        } 

        var cache = new Cache { Key = key, Val = value };
        var node = new LinkedListNode<Cache>(cache);
        _cache.AddLast(node);
        _keys[key] = node;
    }        
}

但是当我以捐款0进行def percent_of_goal(donation, goal): """ percentofgoal """ perc = float(goal/donation) return 100/perc 时,会得到零除错误吗?我该如何解决?

错误消息:

print(percent_of_goal(0, 1000))

4 个答案:

答案 0 :(得分:1)

函数的第一行导致了问题... perc = float(goal/donation)

通过替换为此值来反转比率(考虑到此注释:您无需处理目标为零的情况):

def percent_of_goal(donation, goal): 
    """ percentofgoal
    """
    return (donation/goal) * 100

否则,只需添加一个简单的if语句:

def percent_of_goal(donation, goal): 
    """ percentofgoal
    """
    return (donation/goal) * 100 if goal != 0 else 0

答案 1 :(得分:0)

要计算捐赠与目标的比率,应将捐赠除以目标,而不是相反:

def percent_of_goal(donation, goal): 
    perc = donation / goal
    return  perc * 100

答案 2 :(得分:0)

在使用除法运算符之前,应始终检查分母是否有效,并提供适合您的用例的备用输出。

在此示例中,也许您想要这样的功能而不是使用/

def protected_div(n, d):
    return float(n)/d if d != 0 else 0

答案 3 :(得分:-1)

问题是您无法将其除以零(只是常规数学运算),也许您可​​以尝试使用if语句,如果donation <= 0,则perc返回零:

if donation <= 0:
  perc = 0
else:
  perc = goal/donation