我正在写一个加权平均函数, 有四个例外,我被困在如何设置这些条件中:
这是我的代码:
def weighted_avg(grades,weights):
if sum(weights)<0:
print("weight is less than 0")
elif sum(weights)>100:
print("weight is greater than 100")
elif sum(weights)!=100:
print("weight do not add to 100")
elif for x in grades:
if grades[x]<0:
print("a grade is less than 0")
else:
s=0
for x, y in zip(grades,weights):
s+=x*y
return s/sum(weights)
print(weighted_avg(grades4, weights4) == 85.0)
我不确定代码中缺少哪一部分。
答案 0 :(得分:1)
我稍微整理了一下代码:
def weighted_avg(grades,weights):
total_weight = sum(weights)
if total_weight < 0 or total_weight > 100:
print("Total weights not between 0 and 100")
elif total_weight != 100:
print("Total weights do not total 100")
elif any(x < 0 for x in grades):
print("A grade is less than 0")
else:
cumulative_grades = sum(x * y for x, y in zip(grades,weights))
return cumulative_grades/total_weight
return 0
print(weighted_avg(grades4, weights4) == 85.0)
您不能在for
/ if
条件中使用elif
语句,但是可以简化循环,以便对其进行检查(无需遍历整个循环)列表)使用any
。您还应该计算一次total_weight
,以减少重复计算。 sum
也可以理解以获取总分。
答案 1 :(得分:0)
我只是在更改订单时解决了这个问题
library(evaluate)
code <- c('x <- "don\'t you ignore me!"',
'print(x)')
env <- list2env(list(y = 1:10), envir = parent.frame())
evaluate(code, envir = env)
replay(evaluate(code, envir = env))
## > x <- "don't you ignore me!"
## > print(x)
## [1] "don't you ignore me!"