Python3关于循环迭代多变量简单算法

标签 python loops iteration

我要做的是有T个测试用例,这就是我会进行多少次 获取每个测试用例中“n”个学生的平均值,我需要显示每个测试用例的平均分数以及该测试用例中的最高分以及学生的姓名

如果您能告诉我编码的正确方法并解释为什么必须这样做,我将不胜感激!我迷路了

我的代码:

t = int(input("enter number of cases: "))
def casing(t):
    for case in range (1, t+1):
        n = int(input("enter number of students: "))
        def studentmarks(n):
            total = 0
            student = "none"
            for computetotal in range(1,n+1):
                student = input("please enter student name: ")
                mark = int(input("please enter mark: ")) 
                total = total+ mark
                highestmark = mark
                if studentmark(n) > mark:
                    highestmark = mark
                    achieve = student
                    return highestmark, acheive
            return total, studentmark()[0], studentmark()[1]
        average = float((studentmarks(n)[0])/ n)
        print("average: ", average, "highest: ",studentmark(n)[1], "student: ", studentmark(n)[2])

最佳答案

我认为,如果没有函数声明,代码就更容易理解和调试。除非您正在进行函数式编程(例如传递函数对象),否则很少有充分的理由使用嵌套函数。在这里,您定义了函数,然后立即调用它们一次,这是相当没有意义的。这是代码的简化版本:

t = int(input("enter number of cases: "))
for _ in range (t):
    total = 0
    highest_mark = 0
    best_student = "none"

    n = int(input("enter number of students: "))

    for _ in range(n):
        student = input("please enter student name: ")
        mark = int(input("please enter mark: ")) 
        total = total+ mark
        if mark > highestmark:
            highestmark = mark
            beststudent = student

    average = total / n
    print("average: {}, highest: {}, student: {}"
          .format(average, highestmark beststudent))

我还消除了您的代码正在调用但从未定义的名为 studentmark 的函数(没有“s”)。我不确定我是否正确解释了它应该做什么,但我认为是的。以前肯定行不通。

关于Python3关于循环迭代多变量简单算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12791546/

相关文章:

loops - 在 groovy 中迭代 Map<Map<String,String>, Map<String,String>>

c - C 中的数组到列表(迭代)

algorithm - 构造二叉树给定其中序和前序遍历而不递归

python - 遍历 numpy.ma 数组,忽略屏蔽值

python - 使用 Azure 函数在 HTTP 响应中导出 CSV 数据格式时出错

python - 当Python中的字典中找不到键值时,如何为字典中的键设置默认值

python - 有中英翻译API服务吗?

Java:如何在一维数组中存储二维数组

Java循环编译错误

python - 样式表未从 Django 中的相对路径加载