gpt4 book ai didi

python - 在 Python 中计算文件的平方和

转载 作者:太空宇宙 更新时间:2023-11-04 10:51:14 24 4
gpt4 key购买 nike

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

.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

最佳答案

通常,我会提供更详细的解释,但由于我必须运行,所以我会给您留下可以运行的代码修改版本

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

希望对你有帮助

关于python - 在 Python 中计算文件的平方和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13747601/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com