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

Normally, I would include a much more detailed explanation, but since I have to run, I'll leave you with an amended version of your code that will work

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

Of course, you could do all of it in one line:

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())

Hope this helps

于 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 に答える