Skip to content

6-01: Model Solution: What if the largest number is smaller than 0? #52

Description

@ni6hant

The model solution assigns 0 as the biggest number but the question didn't specify that the question will always have at least one non-negative number.

What if the list only have negative numbers?
In that case instead of returning the largest number, it will return 0.

def largest():
    with open("numbers.txt") as file:
        start = True
        biggest = 0
        for number in file:
            if start or int(number) > biggest:
                biggest = int(number)
                start = False
        return biggest

A simple solution would be to store the first number as the largest number instead. I am adding my solution but I believe this could be shortened:

def largest():
    with open("numbers.txt") as new_file:

        flag = True

        for line in new_file:
            line = int(line.replace("\n",""))

            #store the first value then skip all else
            if flag:
                largest_number = line
            flag = False

            if largest_number<line:
                largest_number = line
    return largest_number

if __name__ == "__main__":
    largest()

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions