Несколько функций, но одна не работает - PullRequest
0 голосов
/ 11 апреля 2019

Я кодирую процесс извлечения информации из текстового файла, превращения файла из строк в целые числа, возведения в квадрат целых чисел и суммирования квадратов перед окончательной печатью результата.Последняя часть кода (суммирование квадратов) не работает, и я не могу определить, почему.Я использую Python 3.7.2.Любая помощь будет оценена.

"""
Use the functions from the previous three problems to implement a main() program that computes the sums of the squares of the numbers read from a file.
Your program should prompt for a file name and print out the sum of the squares of the numbers in the file.
Hint: You may want to use readline()

Test Cases
Input(s)  :  Output(s)
4numsin.txt  

"""
def main():
    f = open("4numsin.txt", "r")
    for line in f:
        line = line.strip()
        strNumber = line
        number = []
        result = []

        def toNumbers():
            for n in strNumber:
                n = int(strNumber)
                x = number.append(n)
            return number
        toNumbers()

        for line in number:
            def squareEach():
                z = 0
                result = []
                while number != []:
                    z = number.pop(0)
                    a = int(z) ** 2
                    b = result.append(a)
                print(strNumber, result)
            squareEach()

        while result != []:
            def Total():
                i = 0
                theSum = 0
                i = result.pop()
                theSum += i
            print(theSum)
            Total()
main()

"""Text File:
4numsin.txt
0
1
2
3
4
5
6
7
8
"""

Ответы [ 2 ]

0 голосов
/ 11 апреля 2019

В вашем коде есть несколько ошибок.Мое основное правило - сделать каждый шаг своей функцией.Вы можете сделать все это в одной функции, но потом будет сложно добавлять вещи.

# Opens the file and appends each number to a list, returns list
def open_file(filename):
    output = []
    f = open(filename, "r")
    for line in f:
        output.append(int(line.strip()))
    return output

# Takes an input like a list and squared each number, returns the list
def square_number(input):
    return [num*num for num in input]

# sums the list
def sum_numbers(input):
    return sum(input)

# the start, function calls within function calls
the_sum = sum_numbers(square_number(open_file('4numsin.txt')))

#check the result
print(the_sum)
>> 204

Посмотрите, насколько эффективнее иметь отдельные методы / функции?

# look at other things
print(open_file('4numsin.txt'))
>> [0, 1, 2, 3, 4, 5, 6, 7, 8]

print(sum_numbers(open_file('4numsin.txt')))
>> 36
0 голосов
/ 11 апреля 2019

В вашем коде много проблем. Никогда не определяйте функцию внутри цикла. Это не очень хорошая практика программирования и сильно влияет на вашу программу. Например, когда вы используете result = [] в цикле, каждый раз значение result становится пустым, а в выражении result.append (a) содержится только самое последнее значение. Также вы объявили результат = [] дважды. То же самое с другими переменными. Всегда пытайтесь передавать и возвращать переменные, когда вы используете много функций. Измените свою программу следующим образом.

def readfile(filepath):
    #Your code to read the contents and store them
    return number_list

def squares(n):
    #code to square the numbers, store and return the numbers
    return ans

def Total():
    #code to calculate the sum
    # you can also check out the built-in sum() function
    return sum

def main():
    numbers = readfile(filepath)
    sq = squares(numbers)
    result = Total(sq)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...