Multiplying every second number in a list - python

I need to be able to multiply every second number in a list by 2 so say:
List = [1,2,3,4]
I want this to return [1,4,3,8] but all the ways that I have tried it such as
credit_card = [int(x) for x in input().split()]
credit_card[::2] = [x*2 for x in credit_card[::2]]
print(credit_card)
If i input the same list from before it returns [2,2,6,4]
Is there a way to accomplish what I'm trying to accomplish?

You are almost there, you just need to start from the second (1-indexed) element:
credit_card[1::2] = [x*2 for x in credit_card[1::2]]
That said, since you seem to be implementing the Lunh checksum, you only need a sum of those digits without having to update the original data, like done in this example.

lst = [1,2,3,4]
new_lst = [2*n if i%2 else n for i,n in enumerate(lst)] # => [1, 4, 3, 8]

credit_card = input().split()
for x in len(credit_card)
if x % 2 != 0
credit_card[x] = credit_card[x] * 2
print (credit_card)

for i,_ in enumerate(credit_card):
if i%2:
credit_card[i] *= 2
or if you want to be fancy:
credit_card=[credit_card[i]*(2**(i%2)) for i in range(len(credit_card))]

Another solution using enumerate:
[i* 2 if p % 2 else i for p, i in enumerate(l)]
where i is the p-th element of l.

>>> l = [1,2,3,4]
>>>
>>> list(map(lambda x: x*2 if l.index(x)%2 else x, l))
[1, 4, 3, 8]

Related

Check for equal values in lists and set them to 0

I want the elements from list a to be zero in list b
a = [80,85,140,145]
b = list(range(200))
Is there a way to do it instead of writing it manually:
b[80]=0
b[140]=0
because I am running simulations and the values in list a and also the list length of a are always changing from one simulation to another and I would like to find a way to automatically set the values of list a to 0 in list b
Why not use a list comprehension to filter on creation:
b = [x if x not in a else 0 for x in range(200)]
The if x not in a checks the number isn't suppose to be filtered or not, if it's to be filtered the else 0 will set it to zero.
Why not just do a simple loop? Naive solution is to just do the following:
a = [8,5,1, 14]
b = list(range(20))
i = 0
while (i < len(a)):
b[a[i]] = 0
i = i+1
print(b)
If I understand the question correctly, this will replace the items in b with zero at the indices contained in a:
for i in a:
b[i] = 0
You can use a list comprehension for this.
c = [0 for x in b if x in a]
You can try this:
for i in b:
if i in a:
b[i]=0
Hope this helps :D
Simple list comprehension is good for this:
a = [2, 4]
b = list(range(10))
[x if x not in a else 0 for x in b]
## [0, 1, 0, 3, 0, 5, 6, 7, 8, 9]

print number if its higher than the previous number othervise dont print it python

so if
mylist = [2,3,4,1,9,4]
it needs to output
[3,4,9]
because 3 is higher than 2, 4 is higher than 3,1 is NOT higher than 4 and like that continues....
You can employ code similar to the pairwise recipe from the itertools recipe section
>>> it = iter(mylist)
>>> next(it, None)
2
>>> [y for x, y in zip(mylist, it) if y > x]
[3, 4, 9]
This is one approach. Using a simple iteration and enumerate
Demo:
mylist = [2,3,4,1,9,4]
res = []
for i, v in enumerate(mylist):
try:
if mylist[i+1] > v:
res.append(mylist[i+1])
except IndexError:
pass
print(res)
Output:
[3, 4, 9]
How about the simple solution? Loop through the array and check the items
i = 0
prevValue=0;
while i < len(mylist ):
if mylist[i] > prevValue:
print(prevValue)
prevValue=mylist[i]
Here's a one-liner:
[i for idx, i in enumerate(mylist) if idx != 0 and i > mylist[idx - 1]]
Output:
[3, 4, 9]
Soo I read all the answers,thanks for sparing your time to answer my question,I really appreciate that.But I found the most suitable answer for me and the code is:
num = [1,2,3,4,5,2,0,3,9]
for i in range(len(num)):
if(num[i]>num[i-1]):
print(num[i], end = " ")

How to add numbers in a smaller list into a larger list of python continiously

I'm trying to build a poly-alphabetic cipher but I can't find a way of adding a smaller list into a larger list, I have tried with list comprehensions, but still cannot do it. Please help! I want the smaller list to keep adding the same numbers to the larger list
so lets say I have 2 lists like this:
x = [1,2,3]
y = [4,5,6,7,8,9]
z = [i + j for i,j in zip(x,y)]
the result is the following
print(z)
[5,7,9]
how can I make it so it is:
[5,7,9,8,10,12]
meaning it keeps adding the same numbers to the longer list,
thank you for the help
You can use itertools.cycle to loop back through x as needed
>>> import itertools
>>> x = [1,2,3]
>>> y = [4,5,6,7,8,9]
>>> z = [i + j for i, j in zip(itertools.cycle(x), y)]
>>> z
[5, 7, 9, 8, 10, 12]
This is the simplest way, I think:
z = [y[i] + x[i % len(x)] for i in range(len(y))]
x = [1,2,3]
y = [4,5,6,7,8,9]
z=[a+b for a,b in zip((x*(int(len(y)/len(x))))[:len(y)],y)]
How about this with zip

iterating to nth value in python

How I will iterate for loop in python for 1 to specific value?
I can iterate on list in python like :
for x in l:
print x
But.
If i wanted to iterate from 1 to number th, in matlab I will do :
str = "abcd"
for i=1:z
for j=1:y
if s(:,i)==s(j,:)'
Seq(i)=str(j);
end
end
end
How I will iterate such in python?
for i in range(0, 11):
print i
HTH
To access values in lists, use the square brackets for slicing along with the index.
for x in l[start:end]:
print x
You have a grate post here about slice notation
Another grate link about lists
Example 1:
myList = [1, 2, 3, 4]
for x in myList[:-1]:
print x
Output:
1
2
3
Example 2:
myList = [1, 2, 3, 4]
for x in myList[1:3]:
print x
Output:
2
3
You need to get use to the idea of slicing in python, see Explain Python's slice notation
Non-slicing:
a = [1,2,3,4,5,6,7,8]
n = 5
for i in range(n):
print a[i]
With slices:
a = [1,2,3,4,5,6,7,8]
n = 5
print a[:n]
Use slice notation (This creates temporary list that contains first n items):
>>> s = "abcd"
>>> for x in s[:2]:
... print(x)
...
a
b
or use itertools.islice:
>>> import itertools
>>> for x in itertools.islice(s, 2):
... print(x)
...
a
b

sum function not working

I am trying to write a program that sums the integers in the odd columns of a list
def sum_of_odd_cols(x):
for j in range(len(x)):
odds=[x[k][j] for k in range(len(x)) if j%2!=0]
return sum(odds)
x=[[1,2,5],[3,4,6],[7,8,9]]
print(sum_of_odd_cols(x))
What I get from this is '0', why is this happening?
Also one more question
x=[[1,2,5],[3,4,6],[7,8,9]]
for j in range(len(x)):
col=[column[j] for column in x]
this also seems to create a list of the columns in list x, however I don't understand how this works
is 'column' a built in function in python?
How about:
def sum_of_odd_cols(x):
oddsum = 0
for j in range(len(x)):
oddsum += sum([x[k][j] for k in range(len(x)) if j%2!=0])
return oddsum
x=[[1,2,5],[3,4,6],[7,8,9]]
print(sum_of_odd_cols(x))
This probably isn't the best way of doing it, but it will get your code working. The odds variable was getting overwritten by a new list in each iteration of the loop, and since the final column was empty (it's index is even), the sum was always 0.
The reason it returns 0 is because your odds array is empty at the end of the for loop; because in each iteration of the loop you are resetting odds. If you write your loop the 'long' way, it will return the correct results:
odds = []
for j in range(len(x)):
for k in range(len(x)):
if j % 2 != 0:
odds.append(x[k][j])
If I add some print statements, this is what happens:
j is: 0
k is: 0
k is: 1
k is: 2
j is: 1
k is: 0
Adding: 2 to odds
k is: 1
Adding: 4 to odds
k is: 2
Adding: 8 to odds
j is: 2
k is: 0
k is: 1
k is: 2
>>> odds
[2, 4, 8]
For the second part of your question:
Also one more question
x=[[1,2,5],[3,4,6],[7,8,9]] for j in range(len(x)):
col=[column[j] for column in x]
this also seems to create a list of the columns in list x, however I
don't understand how this works is 'column' a built in function in
python?
No, this is a list comprehension, a short-hand way of constructing lists.
The loop is actually:
col = []
for column in x:
col.append(column[j])
Where j is some other variable (set above the comprehension).
If you are comfortable with NumPy:
import numpy as np
a = np.array([[1,2,3], [1,2,3]])
b = np.sum(a[:,::2], axis=0) # column 0, 2, ...
# b = [2, 6]
b = np.sum(a[:,::2])
# b = 8
c = np.sum(a[:,1::2], axis=0) # column 1, 3, ...
You can do
x = [[1,2,5],[3,4,6],[7,8,9]] # Generate the list
sum([sum(k[1::2]) for k in x]) # Sum the numbers in odd columns
# 14
if you need the combined sum for all the numbers in the odd columns.
Your first question has been answered various times.
As for your second question, think about unzipping your nested list (supposing it is not ragged):
>>> x=[[1,2,5],[3,4,6],[7,8,9]]
>>> [x for x in zip(*x)]
[(1, 3, 7), (2, 4, 8), (5, 6, 9)]
This gives you a list containing the columns.
If the tuples are a problem and you need lists inside the list, use the builtin list:
>>> [list(x) for x in zip(*x)]
[[1, 3, 7], [2, 4, 8], [5, 6, 9]]
So basically your two questions boil down to this:
def sum_of_odd_cols(x):
return sum(sum(x[1::2]) for x in x)
def rows_to_columns(x):
return [list(x) for x in zip(*x)]

Categories

Resources