Summing elements in a list
You can sum numbers in a list simply with the sum() built-in:
sum(your_list)
It will sum as many number items as you have. Example:
my_list = range(10, 17)
my_list
[10, 11, 12, 13, 14, 15, 16]
sum(my_list)
91
For your specific case:
For your data convert the numbers into int
first and then sum the numbers:
data = ['5', '4', '9']
sum(int(i) for i in data)
18
This will work for undefined number of elements in your list (as long as they are "numbers")
Thanks for @senderle's comment re conversion in case the data is in string format.
Sum a list of numbers until a number 0 is found
- Iterate through the list and just add every time a non - zero number
and append a zero to the list. - when there is a 0 appearing just append the sum and make sum 0.
- if the last element is 0 add zero to the last number or the
respective last number. - Just remove the first zero and return the list.
.
data = [1, 0, 0, 0, 1, 1, 1, 0, 2, 3, 1, 0, 0, 1, 1, 1, 0]
def calc(data):
sum = 0
new = []
for i in range(len(data)):
if data[i] == 0:
new.append(sum)
if i == len(data) - 1:
new.append(0)
sum = 0
else:
sum = sum = sum + data[i]
new.append(0)
if i == len(data) - 1:
new.append(sum)
if new[0] == 0:
del new[0]
return new
How can I sum a list of numbers?
Use this:
list_of_nums = []
loop = True
while loop == True:
try: num = int(input("Enter Integer: "))
except ValueError: num = "invalid"
if num == "invalid": print("\nPlease Print A Valid Integer!\n");
elif num != 0: list_of_nums.append(num)
else: loop = False
print("\nSum of Inputed Integers: " + str(sum(list_of_nums)) + "\n")
Sum a list of numbers in string representation with leading whitespace
You could convert the strings to numbers already while reading the file, then just use sum
on the list:
AtBats = []
with open(ff, "r") as file:
next(file)
while line := file.readline():
AtBats.append(int(line.split(",")[-1]))
print(AtBats)
print(sum(AtBats))
Output:
[2, 6, 3, 5, 2]
18
Summing numbers from list with spaces in Python
There is several problems in your code
You don't use the iterated
line
and useinfile.read()
that reads the whole file at once, so there is only one iteration, and one value set in the array. You'd need someting like thatnumbers = []
for line in infile:
row_values = [int(i) for i in line.split()]
numbers.extend(row_values)you don't split each line, so you try to convert strings like
'7 8'
as oneint
that isn't possiblebetter use files with
with
statement, it autocloses them
The loop for reading is nice, but with your input format there is a better solution : str.split()
without any parameter, it'll split on any amonut of whitespace, newlines included. So it can saparate each int, from each line at once
infile.read().split() # ['0', '1', '2', '4', '3', '8', '7', '8', '5', '6', '6', '7']
numbers = [int(i) for i in infile.read().split()]
# [0, 1, 2, 4, 3, 8, 7, 8, 5, 6, 6, 7]
Giving something like :
infileName = "test.txt"
with open(infileName, "r") as infile:
numbers = [int(i) for i in infile.read().split()]
print(numbers)
total = sum(numbers)
outfilename = "out.txt"
with open(outfilename, "w") as outfile:
outfile.write(str(total))
A very condensed version, with the files open at the same place would be
infileName, outfilename = "test.txt", "out.txt"
with open(infileName, "r") as infile, open(outfilename, "w") as outfile:
outfile.write(str(sum(map(int, infile.read().split()))))
Prints a sub-list where the sum of its elements is the same as the sum of all the elements of the original list
If lst
is your list of numbers then:
def get_sublist(lst):
tot = sum(lst)
for i in range(len(lst)):
for j in range(i + 1, len(lst) + 1):
sub_lst = lst[i:j]
if sum(sub_lst) == tot:
return sub_lst
sub_lst = get_sublist(lst)
This code generates every possible sublist, computes their sum and compares it with the sum of the entire list.
The complexity is not optimal, i.e. there are faster algorithms to solve this problem out there. For example, you don't need to compute the sum of the entire sublist every time you add a new element to it...
Related Topics
How to Have Clusters of Stacked Bars
X, = ... - Is This Trailing Comma the Comma Operator
Using Python Requests with JavaScript Pages
Intuition and Idea Behind Reshaping 4D Array to 2D Array in Numpy
What Are the Arguments to Tkinter Variable Trace Method Callbacks
Scrape Multiple Urls Using Qwebpage
Python Socket Not Receiving Without Sending
How to Delete Rows from a Pandas Dataframe Based on a Conditional Expression
Good Python Modules for Fuzzy String Comparison
Change One Value Based on Another Value in Pandas
Strings in a Dataframe, But Dtype Is Object
Python Garbage Collector Documentation
How to Convert a String of Bytes into an Int
Checking Whether a String Starts with Xxxx
Differencebetween a Function, an Unbound Method and a Bound Method