1

我正在尝试实现一个程序,该程序计算从文件中读取的数字的平方和。

.txt 文件中的数字是:

37
42
59
14
25
95
6

到目前为止,我有:

def squareEach(nums):
    nums = nums * nums

def sumList(nums):
    nums = nums + nums

def toNumbers(strList):
    while line != "":
            line = int(line)
            line = infile.readline()

def main():
    print "** Program to find sum of squares from numbers in a file **"
    fileName = raw_input("What file are the numbers in?")
    infile = open(fileName, 'r')
    line = infile.readline()
    toNumbers(line)
    squareEach(line)
    sumList(line)
    print sum

当我运行程序时,我得到:

main()
** Program to find sum of squares from numbers in a file **
What file are the numbers in?C:\Users\lablogin\Desktop\mytextfile.txt

Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
main()
File "<pyshell#16>", line 6, in main
toNumbers(strList)
NameError: global name 'strList' is not defined
4

2 回答 2

4

通常,我会提供更详细的解释,但由于我必须运行,我会给你留下一个可以工作的修改后的代码版本

def squareEach(nums):
    answer = []
    for num in nums:
        answer.append(num*num)
    return answer

def sumList(nums):
    answer = 0
    for num in nums:
        answer += num
    return answer

def toNumbers(strList):
    answer = []
    for numStr in strList.split():
        try:
            num = int(numStr)
            answer.append(num)
        except:
            pass
    return answer

def main():
    print "** Program to find sum of squares from numbers in a file **"
    fileName = raw_input("What file are the numbers in? ")
    sum = 0
    with open(fileName, 'r') as infile:
        for line in infile:
            nums = toNumbers(line)
            squares = squareEach(nums)
            sum += sumList(squares)
        print sum

当然,您可以在一行中完成所有操作:

print "the sum is", sum(int(num)**2 for line in open(raw_input("What file are the numbers in? ")) for num in line.strip()split())

希望这可以帮助

于 2012-12-06T16:12:27.290 回答
0

好的,这不是在 python 中做的最好的事情我在这里提出一个新的解决方案:

def main():
    print "** Program to find sum of squares from numbers in a file **"
    fileName = raw_input("What file are the numbers in?")
    infile = open(fileName, 'r')
    lines = infile.readlines() # this will return a list of numbers in your file
    squared_number_list = [ int(i)**2 for l in lines ]  # return a squared number of list
    print sum(squared_number_list) # using sum to add up all numbers in list
于 2012-12-06T16:14:16.517 回答