【问题标题】:Why is this simple program exercise not returning False?为什么这个简单的程序练习没有返回 False?
【发布时间】:2021-12-20 13:16:52
【问题描述】:

写一个函数is_better_than_avg(students, pos),它有两个参数students是所有学生字典的列表位置是一个整数——学生在我们要检查的列表中的位置。像这样检查工作 - 计算学校所有成绩的平均值(上层单元格),将值与学生的平均值进行比较。如果学生的 avg 大于学校的 avg,则返回 True,否则返回 False

我不知道为什么程序的第二次执行显示True 而不是False

# Function for testing purposes
def test(got, expected):
  if got == expected:
    prefix = ' OK '
  else:
    prefix = "  Something's wrong  "
  print(prefix,' got:',repr(got),'expected:',repr(expected))
list_of_students = []
list_of_students.append(kosma) # appending the student k1sma

def is_passed(student_dict):
  return avg(student_dict)>=3.0
  
def school_avg(students):
  all = 0
  licznik = 0
  for a in students:
    all = all + avg(a)  #dodaje średnią sprawdzanego studenta do 'all'
    licznik = licznik + 1 #dodaje 1 do liczniku

  return all / licznik

list_of_students.append({
    "username": "mikub",
    "age":24,
    "is_blocked": False,
    "grades": [5,5,5,5]
})

list_of_students.append({
    "username": "ewa",
    "age":24,
    "is_blocked": False,
    "grades": [1,3,3,2,1,1,1,1,1,1]
})

list_of_students.append({
    "username": "robert",
    "age":24,
    "is_blocked": False,
    "grades": [5,5,5,5,5,1]
})
list_of_students.append({
    "username": "radek",
    "age":24,
    "is_blocked": False,
    "grades": [1,3,3,2,5,5,5]
})

list_of_students.append({
    "username": "kasia",
    "age":24,
    "is_blocked": False,
    "grades": [5,5,5,1]
})

list_of_students.append({
    "username": "kasia",
    "age":24,
    "is_blocked": False,
    "grades": [5,1,1,1,1,5,1]
})
list_of_students.append({
    "username": "jola",
    "age":24,
    "is_blocked": False,
    "grades": [5,4,5,5,5,4]
})

#this is the important part

def is_better_than_avg(students,pos):
  for pos in students:
    if avg(pos) > school_avg(students):
      return True
    elif avg(pos) < school_avg(students):
      return False

test(is_better_than_avg(list_of_students,0),True) #returns True as it should
test(is_better_than_avg(list_of_students,6),False) #idk why this returns True as well

【问题讨论】:

  • kosmaavg 未定义,请修复
  • 你计算一个成绩的平均值,以及所有成绩的平均值?还是每个 avg 的平均值?
  • 学校平均分3.5分,所选学生平均分5分
  • jola 平均为 4.6,高于学校平均 3.5

标签: python dictionary for-loop if-statement


【解决方案1】:

我认为你应该像这样更改is_better_than_avg 函数:

def is_better_than_avg(students,pos):
    student = students[pos]
    if avg(student) > school_avg(students):
        return True
    elif avg(student) < school_avg(students):
        return False

【讨论】:

  • 是的,非常感谢!我知道我还必须包括字典,因为 pos 只是一个数字。
猜你喜欢
  • 1970-01-01
  • 2014-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-05
相关资源
最近更新 更多