Append Function not giving desired results in python - python-3.x

the code given below does not give the desired results as specified below. i have tried many permutations without success.
posLabels = ['abc', 'def', 'ab3','ab4', 'ab5']
senPosList = [('abc','def','ghi'),('jkl','mno','pqr','123'),
('stu','vwx')]
senVecList= []
senVec = []
posLabels[0] in senPosList[0]
for x in range(3):
for i in range(5):
if posLabels[i] in senPosList[x]:
senVec.append(1)
else:
senVec.append(0)
senVecList.append(senVec)
print(senVecList)
Result:
[[1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
I want senVecList = [[1, 1, 0, 0, 0],[0, 0, 0, 0, 0],[0, 0, 0, 0, 0]]

I guess what you are trying to accompish is this
posLabels = ['abc', 'def', 'ab3','ab4', 'ab5']
senPosList = [('abc','def','ghi'),('jkl','mno','pqr','123'), ('stu','vwx')]
senVecList= []
for x in range(3):
senVec = []
for i in range(5):
if posLabels[i] in senPosList[x]:
senVec.append(1)
else:
senVec.append(0)
senVecList.append(senVec)
print(senVecList)
Note we are reassigning an empty list to senVec in the outer loop. Otherwise you are appending more values to the same old list which is being appended three times.

This produces the desired output, though I still don't understand the goal.
pos_labels = ['abc', 'def', 'ab3', 'ab4', 'ab5']
sen_pos_list = [
('abc', 'def', 'ghi'),
('jkl', 'mno', 'pqr', '123'),
('stu', 'vwx')
]
sen_vec_list = [[int(p in s) for p in pos_labels] for s in sen_pos_list]
print(sen_vec_list)

posLabels = ['abc', 'def', 'ab3','ab4', 'ab5']
senPosList = [('abc','def','ghi'),('jkl','mno','pqr','123'),('stu','vwx')]
senVecList= []
senVec = []
posLabels[0] in senPosList[0]
for x in senPosList:
for i in posLabels:
if i in x:
senVec.append(1)
else:
senVec.append(0)
senVecList.append(senVec)
senVec = [] #add this line to clear the list
print(senVecList)
You have to clear the list if not you keep adding to it after every loop.

Related

How to change only the diagonal elements of a 2D list?

So I am trying to create an NxN 2D array and then change its diagonal elemets to 1. Here is my code:
arr=[1,1,1,2,2,2]
table=[[0]*len(arr)]*len(arr)
for i in range(0,len(arr)):
table[i][i]=1
print(table)
However, whenever I run this code, I get this output:
[[1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1]]
I am looking to get this:
[[1, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 1]]
I have been staring at my code for hours and I cannot figure out what's wrong
The interesting thing about this is that you are really only editing one list in the for loop, but there are just five pointers to that list. (In this case, the list would be [0, 0, 0, 0, 0, 0].) You can see this by printing the id of each list in table by using id():
>>> for t in table:
print(id(t))
2236544254464
2236544254464
2236544254464
2236544254464
2236544254464
2236544254464
Your numbers are likely different than mine, but they are all the same number, nevertheless. You also can see that the edits to one list are applied to the others in table by putting a print(table) statement after each index assignment statement.
So in order to 'fix' this, I would recommend using list comprehension instead. For example:
table = [[0]*len(arr) for _ in range(len(arr))]
If you checkout the ids of each list:
>>> for t in table:
print(id(t))
2236544617664
2236544616064
2236544616320
2236544615872
2236544618368
2236544622720
Since they are different, you can now use the method for changing only the diagonals:
>>> for i in range(0,len(arr)):
table[i][i]=1
>>> table
[[1, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 1]]
Your 2D "array" contains 6 lists which are the same list. Changes to any of those lists will also be reflected in the other lists. Consider this:
>>> l = [0] * 6
>>> x = [l]
>>> l[0] = 1
>>> l
[1, 0, 0, 0, 0, 0]
>>> x
[[1, 0, 0, 0, 0, 0]]
>>> x = [l, l, l]
>>> x
[[1, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0]]
>>> x[-1][-1] = 100
>>> x
[[1, 0, 0, 0, 0, 100], [1, 0, 0, 0, 0, 100], [1, 0, 0, 0, 0, 100]]
This is because the list x contains the list l, so any changes to l are also seen through the reference to the same list in x.
The problem is when multiplying mutable objects because it creates multiple references to the same mutable object.
You should initialise your table like this:
table = [[0 for j in range(len(arr))] for i in range(len(arr))]
or
table = [[0] * len(arr) for i in range(len(arr))]
which, despite the use of multiplication, works because each list is different.
You can create your table and populate it simultaneously in nested loops:
arr=[1,1,1,2,2,2]
table = []
for i in range(len(arr)):
table.append([0]*len(arr))
for j in range(len(arr)):
if i == j:
table[i][j] = 1
print(table)
#[[1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0], [0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 1]]
Interesting.
Try to use numpy to avoid list trap:
import numpy as np
org_row = [0]*5
l = [org_row]*5
x = np.array(l, np.int32)
for i in range(len(x)):
x[i][i]=1
print(x)
output>:
output>
[[1 0 0 0 0]
[0 1 0 0 0]
[0 0 1 0 0]
[0 0 0 1 0]
[0 0 0 0 1]]

Python: Converting Binary to Decimal

What I'm currently doing is a implementation of Genetic Algorithms. I have written my Crossover and mutation methods and now i'm currently writing my Fitness method.
I need to convert my list of 0s and 1s to decimal values for calculating distance.
My current output that I'm working with are a list of integer values of 1s and 0s. (Example below):
[[0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1], [0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1]]
<class 'list'>
I want to convert these numbers to their respected binary equivalent.
I have tried converting the list to groups of 4 and then calling a binaryToDecimal function to convert the bits to decimal values. However, Im getting an error 'TypeError: 'numpy.ndarray' object is not callable'.
I have summarized my code and this is what it looks like so far.
def converting_binary_to_decimal(L):
output = []
for l in L:
l = list(map(str, l))
sub_output = []
for j in range(0, len(l)-1, 4):
sub_output.append(int(''.join(l[j:j+4]), 2))
output.append(sub_output)
return output
def chunks(L, n):
for i in range(0, len(L), n):
yield L[i:i+n]
def fitness(child):
newList1=list(chunks(child[0], 4))
newList2=list(chunks(child[1], 4))
if __name__ == "__main__":
myFitness = fitness(afterMU)
A sample output of what i want is:
[[0, 13, 6, 8, 12, 8, 10, 9, 15], [0, 8, 7, 0, 4, 4, 1, 8, 15]]
Try this code.
def converting_binary_to_decimal(L):
output = []
for l in L:
l = list(map(str, l))
sub_output = []
for j in range(0, len(l)-1, 4):
sub_output.append(int(''.join(l[j:j+4]), 2))
output.append(sub_output)
return output
L = [[0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1], [0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1]]
converting_binary_to_decimal(L)
I think i figured it out.
x=[0, 1, 1, 0]
k = 4
n = len(x)//k
for i in range(n):
y = x[i*k:(i+1)*k]
y = [str(j) for j in y]
y = ''.join(y)
y = int(y,2)
print(y)
Thank you.

Any idea why python3 is not treating False as bool?

Any idea why python3 is not treating False as bool?
I want to move all the zeros to the end of the list.
def move_zeros(array):
for i in array:
if type(i) is not bool:
if i == 0:
array.append(int(i)) # catching non bool values that are zeros, adding at the end of the list
array.remove(i) # removing original
elif type(i) is bool:
pass #Here it catches False from the input, it should do nothing but somehow it is moved to the end of the list as zero in the output.
return array
print(move_zeros(["a", 0, 0, "b", None, "c", "d", 0, 1,
False, 0, 1, 0, 3, [], 0, 1, 9, 0, 0, {}, 0, 0, 9]))
Output:
['a', 'b', None, 'c', 'd', 1, 1, 3, [], 1, 9, {}, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Try this slight modification to your code:
def move_zeros(array):
new_list = [] # Work a new list
for i in array:
print(f"I = {i}")
if type(i) is not bool:
if i == 0:
new_list.append(int(i))
else:
pass
return new_list
print(move_zeros(["a", 0, 0, "b", None, "c", "d", 0, 1,
False, 0, 1, 0, 3, [], 0, 1, 9, 0, 0, {}, 0, 0, 9]))

python for loop removing duplicated output data in list

from a python for loop i get duplicated output data for each iteration.
what i want is to only get the new data in each iteration.
How can i remove the repeated data from the list and only get the not repeated data
the data that gets dublicated is the hours minutes and seconds
sorry for my english .
import json
with open('activities.json') as f:
d = json.load(f)
keys = []
values = []
lijst = [[],[]]
def loop():
for y in d['activities']:
name = y['name']
lijst[0].append(name)
p = y['time_entries']
for e in p:
h = e['hours']
m = e['minutes']
s = e['seconds']
lijst[1].append(h)
lijst[1].append(m)
lijst[1].append(s)
print(lijst[1])
test = dict((k, lijst[1]) for k in [name])
loop()
output the first data is repeated in the second list the second is repeated in the third and so on:
[1, 2, 11, 0, 0, 1, 0, 0, 4, 0, 0, 2, 0, 0, 1, 0, 0, 13, 0, 0, 1]
[1, 2, 11, 0, 0, 1, 0, 0, 4, 0, 0, 2, 0, 0, 1, 0, 0, 13, 0, 0, 1, 0, 0, 6, 0, 0, 12, 0, 0, 10, 0, 0, 3]
[1, 2, 11, 0, 0, 1, 0, 0, 4, 0, 0, 2, 0, 0, 1, 0, 0, 13, 0, 0, 1, 0, 0, 6, 0, 0, 12, 0, 0, 10, 0, 0, 3, 0, 0, 5, 0, 0, 1, 0, 0, 2, 0, 0, 4, 0, 0, 1, 0, 0, 3, 0, 0, 8, 0, 0, 5, 0, 0, 9, 0, 0, 14]
Just reset lijst at the begging of each iteration:
import json
with open('activities.json') as f:
d = json.load(f)
keys = []
values = []
def loop():
for y in d['activities']:
lijst = [[],[]] #reset list
name = y['name']
lijst[0].append(name)
p = y['time_entries']
for e in p:
h = e['hours']
m = e['minutes']
s = e['seconds']
lijst[1].append(h)
lijst[1].append(m)
lijst[1].append(s)
print(lijst[1])
test = dict((k, lijst[1]) for k in [name])
loop()

Finding a sequence of numbers in a multi dimensional list

How do I find if a sequence of numbers exists in a two-dimensional list? i.e.
matrix: [[1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0], [0,
0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0]]
if [1,1,1] in matrix:
print("It's in there")
else: print("It's not there")
I guess I could turn every int into a string but is there a slicker way?
Using an iterator over each cell of the matrix, I've managed to get a basic idea of what you wanted to achieve in Python script.
matrix = [[1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0]]
matchCount = 0
lastNumber = None
for cell in matrix:
for number in cell:
if number == 1 and lastNumber == 1 or lastNumber == None:
matchCount += 1
if matchCount >= 3:
print("MATCH in cell " + str(cell))
lastNumber = number
matchCount = 0
lastNumber = None
What happens is, it steps into the cell. It it's the first iteration then allow entry into our iterator. We don't know if it's a match list yet, so push it back in our little list.
Stepping over and over, if we get enough matches in a row, then wonderful! Print we found a match in our matrix's cell!

Resources