python - 查找文件中的最大值

标签 python

我正在参加一年级的 CompSci 类(class)并学习 Python,所以请耐心等待。作业是使用 Python 打开一个文件,读取它,然后找到该文件中的最大值,而不使用任何我们在类里面未讨论过的内置函数或概念。我可以通读该文件并获取值,但我的问题是我的代码会将值“30”视为“3”和“0”而不是三十。这是我到目前为止所拥有的:

def maxValueInFile(fileName):
    inputFile = open(fileName, "r")
    currentMax = int(0)
    for value in inputFile.read():
        if value.isdigit():
            value = int(value)
            if value > currentMax:
                currentMax = value
    inputFile.close()
    return currentMax

当我运行该文件时,它不会返回大于 9 的数字,大概是因为

最佳答案

如果要逐位读取,可以将临时结果连续乘以 10,然后加上最后读取的数字的值来构建实数。

def maxValueInFile(fileName):
    inputFile = open(fileName, "r")
    currentMax = int(0)
    number = 0
    for value in inputFile.read():
        if value.isdigit():  # again found a digit
            number = number * 10 + int(value)
        else:   # found a non-digit
            if number > currentMax:
                currentMax = number
            number = 0
    if number > currentMax:  # in case the for-loop ended with a digit, the last number still needs to be tested
        currentMax = number
    inputFile.close()
    return currentMax

关于python - 查找文件中的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58684378/

相关文章:

python - sqlalchemy 中是否有一种解决方法可以在没有任何主键的情况下从数据库加载表?

python - Python 中的嵌套 for 循环

python - 使用列表划分并存储要在变量中使用的字符串

python - 谷歌应用引擎 - 权限被拒绝错误

python - 从二维数组python创建直方图

python - 导入错误: No module named inspect

python - 计算 Pandas 中某个类别的百分比

python - 防止 pandas read_csv 将第一行视为列名的标题

python - 如何将字典列表转换为 Pyspark DataFrame

python - linux离线模式下的pip安装要求