Python3 sums.py

时间:2014-03-11 06:14:01

标签: python python-3.x python-idle

所以我整晚都在这。编程很新,我的目标是使用squareEach(nums),这是我通过平方每个条目修改的数字列表。接下来,sumList(nums)是一个数字列表,返回列表中数字的总和。然后,toNumbers(strList)strList是一个字符串列表,每个字符串代表一个数字。通过将其转换为数字来修改每个。最后使用这些函数来实现一个程序,该程序计算从文件中读取的数字的平方和。

为此,我使用的是一个名为numbers.txt的文件,其中包含...

1

2

3

到目前为止,这是我的程序,虽然使用numbers.txt我想得到14作为答案,但我得到的是无答案。

#!/usr/bin/env python3

# Caleb Webb
# 03/08/14
# A program which takes 3 functions and computes the sum of the squares of the
# numbers read from a file.

def toNumbers(strList):
    for i in range(len(strList)):
        strList[i] = int(strList[i])

def squareEach(nums):
    nums = []
    for i in nums:
        nums = nums.append(i**2)
    return nums

def sumList(x):
    return (x[0] + sumList(x[1:])) if x else 0

def main():
    file = input("Please enter a file name: ")
    fobj = open(file, "r")
    strList = fobj.readlines()
    fobj.close()
    nums = toNumbers(strList)
    x = squareEach(nums)
    result = sumList(x)
    print("The sum of the squares of the values in the file is", result)
main()

2 个答案:

答案 0 :(得分:1)

你有几个问题,已在你的问题的评论中指出。他们可以用这样的东西来修复:

def toNumbers(strList):
    return [int(s) for s in strList]

def squareEach(nums):
    return [a**2 for a in nums]

def sumList(nums):
    return sum(nums)

或者您的整个程序可以写成:

with open(input('File name: '), 'r') as f:
    print('The square sum is ', sum(int(l)**2 for l in f))

您拥有sum累加器:

def sumList(nums):
    accumulator = 0
    for i in nums:
        accumulator += i
    return accumulator  

(虽然当我听到“累加器”时,我必须考虑函数编程,你使用累加器来获得尾递归。这在python中完全没有意义,因为python通过设计避免了TCO。)

答案 1 :(得分:0)

f=open('num.txt','r+')
numArray=[]
for line in f:
   numArray.append(int(line))
result=sum(int(i)**2 for i in numArray)
print(result)

num.txt

1

3

5

3

1