【问题标题】:What do these subprograms do?这些子程序有什么作用?
【发布时间】:2016-05-22 04:17:41
【问题描述】:

我正在练习 Python - 使用 Python 3.5.0 - 我遇到了这个使用子程序的简短程序。我想弄清楚每个子程序的作用是什么?

非常感谢您。

def A(target,mark)
    target=mark[0]
    for numbers in range(10):
        if mark[numbers] > target:
    target = mark[numbers]
    return target


def B (target, mark)
    target=mark[0]
    for numbers in range(10):
        if mark[numbers] < target:
            target = mark[numbers]
    return target


def C (vote,total,vote1,vote0)
    for noofvotes in range(total):
    if vote[noofvotes]==1:
    vote1=vote1 + 1
        else:
    vote0=vote0 + 1
    return vote0, vote1


def D(target,Name):
    found="NO"
    namesinarray=0
    while namesinarray != len(Name) and found == "NO":
        if Name[namesinarray]==target:
            found="YES"
            indexmark= namesinarray
        namesinarray = namesinarray +1

    if found=="YES":
        print(target + " has been found at position " + str(indexmark))
    else:
        print("This name is not in the list")

【问题讨论】:

  • 不知道谁写了这段代码,但太可怕了。话虽如此,您仍然应该能够自己找出每个功能的作用。提示:如果仅仅阅读和推理代码还不够,Python 有一个交互式解释器和一个步进调试器(您可以从交互式解释器启动)。

标签: python python-3.x for-loop python-3.5


【解决方案1】:

A() 搜索mark 的前10 个元素中的每一个,如果该元素大于target,则不断更新target。结果是,它返回mark 的最大元素。 B() 类似,但它返回mark 的最小元素。然而,这些并不是必需的,因为有一些名为 max()min() 的内置函数就是为此而生的。 C() 收到一份选票列表、总票数、到目前为止给一个人的票数以及迄今为止给另一个人的票数。它通过投票并检查它是 0 还是 1。然后它相应地更新投票计数。添加完所有选票后,它会将它们返回到tuple。 (也就是说,如果缩进正确,它会这样做)。 D() 的参数是 targetName,它搜索 Name 直到找到 target。如果找到target,则打印出目标已在某个位置找到。如果未找到,则打印This name is not in the list。这个函数可以改进,因为它使用"YES""NO" 作为它的布尔值。布尔值内置于 Python 语言中,因此应该使用。它也可以像这样使用内置方法index()

def D(target, Name):
    try:
        index = Name.index(target)
    except IndexError:
        print("This name is not in the list")
    else:
        print(target + " has been found at position " + str(index))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-28
    • 2015-07-04
    • 2011-12-31
    • 1970-01-01
    • 2021-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多