Python: Total sum of a list of numbers with the for loop [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
The community reviewed whether to reopen this question last year and left it closed:
Original close reason(s) were not resolved
Improve this question
I'm new to Python and I have this problem:
I need to program a Python function that gives me back the sum of a list of numbers using a for loop.
I just know the following:
sum = 0
for x in [1,2,3,4,5]:
sum = sum + x
print(sum)

I think what you mean is how to encapsulate that for general use, e.g. in a function:
def sum_list(l):
sum = 0
for x in l:
sum += x
return sum
Now you can apply this to any list. Examples:
l = [1, 2, 3, 4, 5]
sum_list(l)
l = list(map(int, input("Enter numbers separated by spaces: ").split()))
sum_list(l)
But note that sum is already built in!

l = [1,2,3,4,5]
sum = 0
for x in l:
sum = sum + x
And you can change l for any list you want.

x=[1,2,3,4,5]
sum=0
for s in range(0,len(x)):
sum=sum+x[s]
print sum

Related

New to programming, help in sum of matrix using for loop [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Anyone pls help me in program to find out sum of elements in matrix using for loop.
This is my code.
a = [[1,2,3],[1,2,3],[1,2,3]]
total = 0
sha = np.shape(a)
for i in range(sha[0]):
for j in range(sha[1]):
total= total+a[i,j]
return total
Simply use sum
a = [[1,2,3],[1,2,3],[1,2,3]]
sum([sum(i) for i in a])
As it is nested list (list inside a list) you can refer to the following
a=[[1,2],[2,3],[4,5]]
total=0
for i in a:
total+=sum(i)
print(total)
a = [[1,2,3],[1,2,3],[1,2,3]]
Sum = 0
sha = np.shape(a)
for r in range(len(sha)):
for c in range(len(sha)):
sum = sum + a[r][c]
print(Sum)
Sum is looped and calculated for r->row and c-> column

Tuple into list to find max value and if there is a duplicate [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I am creating a function that takes any quantity of numbers, and tell you what is the max value or if there is a tie for largest. I am wondering what I could do to simplify what I have.
def max_num(*args):
nums = []
nums_1 = []
nums.append(args)
i = 0
while i < len(nums[0]):
nums_1.append(nums[0][i])
i += 1
c = max(nums_1)
nums_1.remove(c)
if c in nums_1:
print("It's a tie!")
else:
print(c)
max_num(-10, 0, 10, 10)
So when I initially make a list with the arguments given, it gives me a tuple inside the list. This is why I create a new list to dissect the tuple into separate values. I have the feeling that wasn't necessary, and that there is a much simpler way to do this. Any advice would be great.
Just get the max, and count how many times it appears in your data:
def max_num(*args):
maxi = max(args)
if args.count(maxi) == 1:
print(maxi)
else:
print('Tie')
max_num(2, 5, 1)
#5
max_num(2, 5, 1, 5)
#Tie

Deleting max value in set without max() [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have a working code
task = set()
x = 1
while x != 0:
x = int(input('input your number '))
task.add(x)
print('Just 0 could stop it!')
task.remove(max(task))
print(max(task))
And need to get the same result without using max(). What could be an alternative?
Something like this, unless you have really large sets, I don`t see the advantage
task = set()
x = 1
m = 0
while x != 0:
x = int(input('input your number '))
task.add(x)
if x > m:
m = x
print('Just 0 could stop it!')
task.remove(m)
print(max(task))
Notice this will only work for positive numbers, if you want to the complete int range you should init m like this m = -sys.maxsize - 1
You could use min with a key arg that inverts the element:
>>> task = {1, 2, 3, 4, 5}
>>> max(task)
5
>>> min(task, key=lambda x: -x)
5
Or you could sort it and take the last element...
>>> sorted(task)[-1]
5

How to shift list indexes by a certain value in Python [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I need to create a python function that right shifts values in a list by a given value.
For example if the list is [1,2,3,4] and the shift is 2 it will become [2,3,4,1]. the shift value must be a non negative integer. I can only use the len and range functions.
This is what I have so far
def shift(array, value):
if value < 0:
return
for i in range(len(array)):
arr[i] = arr[(i + shift_amount) % len(arr)]
Usually you can do this with slicing
arr = arr[shift:] + arr[:shift]
Your shifted list is only shift = 1, not 2. You can't get your output by shifting 2 positions.
I make some modifications in your code (If you have to use len and range functions) :
def shift(array, shift_amount):
if shift_amount < 0:
return
ans = []
for i in range(len(array)):
ans.append(array[(i + shift_amount) % len(array)])
print ans
shift([1,2,3,4],2)
Output:
[3, 4, 1, 2]
Note:
Your's logic is correct but your overriding values in same array, So I created another list and append value to it.
If shift value is 1 then output will be [2, 3, 4, 1]. So for value 2 it will be two shifts that's why output should be [3, 4,
1, 2]
value and shift_amount are two different variables in your code, So I use only single variable.
You can use list comprehension (If you want to check in detail about list comprehension see this article Python List Comprehensions: Explained Visually) like
def shift(array, shift_amount):
if shift_amount < 0:
return
length = len(array)
print [array[(i + shift_amount) % length] for i in range(length)]
shift([1,2,3,4],0)

Multiply digits in list [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Let's say we have list of numbers and we want to multiply all numbers in it as long as product is digit.
For Example:
[2,2,5] => [4,5]
[3,3,7] => [9,7]
[5,5,5,5,5] => [5,5,5,5,5]
Can I somehow use functools.reduce here? What's pythonic way to solve this problem?
This can be solved easily by a simple stateful algorithm:
def multiply_digits(lst):
res = []
for x in lst:
if res and res[-1] * x < 10:
res[-1] *= x
else:
res.append(x)
return res
While there is an equivalent functional way (with reduce), that will not be as simple since you either need to reassemble the result list in each step, or carry the current number value separately.
This might do the trick:
def process(lst):
lst = sorted(lst)
last = 1
result = []
for el in lst:
if last * el >= 10:
result.append(last)
last = el
continue
last *= el
result.append(last)
return result
This is better I guess:
from numpy import product
reduce(lambda x , y : (x[0:-1]+[y*x[-1]] if product(x+[y])<10 else x+[y]) if len(x)>0 else [y] ,[21,1,2,3,4,5,6],[])

Categories