Number plus number from array in loops [duplicate] - python

This question already has answers here:
Sum a list of numbers in Python
(26 answers)
Closed last year.
This post was edited and submitted for review last year and failed to reopen the post:
Original close reason(s) were not resolved
For example array [1, 2, 4, 5, 6] it must be 1 + 2 + 4 + 5 + 6. so how is the result in these loops? so look below the script
number = [1, 2, 4, 5, 6]
for x in number:
x + x
print(x)

Just add a += and a new variable like so:
number = [1, 2, 4, 5, 6]
y = 0 #new variable (output variable)
for x in number:
y += x #add = sign here
print(y)
Output:
18
But it would be better to use:
y = sum(number)
print(y)
Output:
18

Related

can't modify global 2-D matrix in python properly [duplicate]

This question already has answers here:
List of lists changes reflected across sublists unexpectedly
(17 answers)
Closed 2 years ago.
I was trying a program in which I declared a 2D array named grid of size 5 x 5 globally in python.
grid = [[0] * 5] * 5
def main():
global grid
n,m = map(int,input().split())
for i in range(n):
li = list(map(int,input().split()))
for j in range(m):
if j < 5:
grid[i][j] = li[j]
print(grid)
if __name__ == "__main__":
main()
Modifying the grid gives a weird answer. For example if the input is :-
2 3
1 2 3
4 5 6
2 rows and 3 columns (n and m)
It gives the following output:-
[[4, 5, 6, 0, 0], [4, 5, 6, 0, 0], [4, 5, 6, 0, 0], [4, 5, 6, 0, 0], [4, 5, 6, 0, 0]]
Even when I remove the line global grid from the main function, output remains the same. What is going on? I want it to update grid according to the input and leave the extra cells untouched i.e value 0. If input is of size 2 x 3 then only the first 2 rows and 3 columns of the grid should be modified according to the input and rest of the elements should remain 0.
You should use:
[[0]*5 for _ in range(5)]
Instead of:
[[0] * 5] * 5
for more information, check this question.

How can i sum every nth number from list recursively?

I want to add every nth number from list recursively, but NOT the first number, so lets say I have a list [1, 2, 3, 4, 5, 6] and I want to add every 2nd number, so that would mean I need to add 2 + 4 + 6 but if I want to add every 3rd number, then it should add 3 + 6.
So right now I have this much, I want to add every 2nd number so that means I want to add 2, 4 and 6, but I can't seem to figure out why it doesn't work, what should I do differently?
def getsum(numbers):
if len(piece)==0:
return 0
else:
return getsum(numbers[2:]) + numbers[0]
print getSum([1, 2, 3, 4, 5, 6])
You can pick out the nth number, then recursively slice off everything after that when you call the function again
def get_sum(numbers, n):
if len(numbers) < n:
return 0
return numbers[n-1] + get_sum(numbers[n:], n)
For example with n = 2 and n = 3 respectively
>>> get_sum([1, 2, 3, 4, 5, 6], 2) # 2 + 4 + 6
12
>>> get_sum([1, 2, 3, 4, 5, 6], 3) # 3 + 6
9

Python: for-loop wrong output [duplicate]

This question already has answers here:
Removing elements from a List in Python
(3 answers)
Closed 6 years ago.
Can't understand why it missing some indexes in loop?
Index number 3 for example.
I just want to delete the unique elements this way. I know another one but I don't know what's wrong with this one (or me).
lst = [2, 7, 1, 9, 3, 5, 2, 1]
def check(lst):
result = lst
print(lst) #checking
for num in lst:
print("index:", num) #checking
print("num:", num) #checking
if lst.count(num) < 2:
print("count:", lst.count(num)) #checking
result.remove(num)
return(result)
print(check(lst))
Output
[2, 7, 1, 9, 3, 5, 2, 1]
index: 2
num: 2
index: 7
num: 7
count: 1
index: 9
num: 9
count: 1
index: 5
num: 5
count: 1
index: 1
num: 1
[2, 1, 3, 2, 1]
You're removing items from a list as you're iterating over it, which you shouldn't do.
(result = lst does NOT make a copy of lst; it creates a new name which refers to the same object.)
If you just want to remove duplicate elements, you can use a set (although you may lose your ordering):
lst = list(set(lst))

python - How to move back an iteration in a for loop list [duplicate]

This question already has answers here:
Making a python iterator go backwards?
(14 answers)
Closed 6 years ago.
Given the list: a = [1, 2, 3, 4 5] in a for loop, suppose that the current item is 2, and next item is 3. If some condition is true, how can I make the next item be 2 again, which means the iteration should continue from 2 again instead of 3?
a = [1, 2, 3, 4, 5]
for item in a:
print item
if condition:
do something, and go back to previous iterator
The output would be:
1
2
2
3
4
5
Beware of an infinite loop, and it's not very Pythonic.
i = 0
a = [1, 2, 3, 4, 5]
hasBeenReset = False
while i < len(a):
if a[i] == 3 and not hasBeenReset:
i = 1
hasBeenReset = True
print(a[i])
i += 1

Python comma separated print changes function behavior [duplicate]

This question already has answers here:
Why does this script print an extraneous 'none' in the output
(3 answers)
Closed 9 years ago.
Although I've seen other questions on Python delimiters I haven't been able to find a question answering this so here goes. I'm writing a function that will recursively print an array backwards, and it appears to work just fine:
def print_array_backwards(array):
if (len(array) == 1):
print array[0],
return
print_array_backwards(array[1:])
print array[0],
##########################################
x = [0, 1, 2, 3, 4, 0, 1, 2, 3, 4]
print 'Array = ', x
print_array_backwards(x)
Will output:
Array = [0, 1, 2, 3, 4, 0, 1, 2, 3, 4]
4 3 2 1 0 4 3 2 1 0
The problem is when I try to print the output of the print_array_backwards function in line with other text, like this:
print 'Array = ', x
print 'The array backwards is', print_array_backwards(x)
This will output:
Array = [0, 1, 2, 3, 4, 0, 1, 2, 3, 4]
The array backwards is 4 3 2 1 0 4 3 2 1 0 None
My question is, where does this extra None value come from??
If I push the function output to the next line but leave the comma with the print statement like this:
print 'Array = ', x
print 'The array backwards is',
print_array_backwards(x)
I obviously get the desired output:
Array = [0, 1, 2, 3, 4, 0, 1, 2, 3, 4]
The array backwards is 4 3 2 1 0 4 3 2 1 0
Can anyone help me understand why leaving the function in the same line of the print statement causes the function to behave differently?
Thanks for your time!
You are calling a function that does not return anything explicitly. The default return value of such a function is None.
Simply don't print the return value of the function:
print 'Array = ', x
print 'The array backwards is',
print_array_backwards(x)
Change print array[0] to return array[0]. The None comes from the return value of print_array_backwards(), which since you specified nothing is None.

Categories