Related
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.
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()
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.
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!
I have the following labels
>>> lab
array([2, 2, 2, 2, 2, 3, 3, 0, 0, 0, 0, 1])
I want to assign this label to another numpy array i.e
>>> arr
array([[81, 1, 3, 87], # 2
[ 2, 0, 1, 0], # 2
[13, 6, 0, 0], # 2
[14, 0, 1, 30], # 2
[ 0, 0, 0, 0], # 2
[ 0, 0, 0, 0], # 3
[ 0, 0, 0, 0], # 3
[ 0, 0, 0, 0], # 0
[ 0, 0, 0, 0], # 0
[ 0, 0, 0, 0], # 0
[ 0, 0, 0, 0], # 0
[13, 2, 0, 11]]) # 1
and add the elements of 0th group, 1st group, 2nd group, 3rd group?
If the labels of equal values are contiguous, as in your example, then you may use np.add.reduceat:
>>> lab
array([2, 2, 2, 2, 2, 3, 3, 0, 0, 0, 0, 1])
>>> idx = np.r_[0, 1 + np.where(lab[1:] != lab[:-1])[0]]
>>> np.add.reduceat(arr, idx)
array([[110, 7, 5, 117], # 2
[ 0, 0, 0, 0], # 3
[ 0, 0, 0, 0], # 0
[ 13, 2, 0, 11]]) # 1
if they are not contiguous, then use np.argsort to align the array and labels such that labels of the same values are next to each other:
>>> i = np.argsort(lab)
>>> lab, arr = lab[i], arr[i, :] # aligns array and labels such that labels
>>> lab # are sorted and equal labels are contiguous
array([0, 0, 0, 0, 1, 2, 2, 2, 2, 2, 3, 3])
>>> idx = np.r_[0, 1 + np.where(lab[1:] != lab[:-1])[0]]
>>> np.add.reduceat(arr, idx)
array([[ 0, 0, 0, 0], # 0
[ 13, 2, 0, 11], # 1
[110, 7, 5, 117], # 2
[ 0, 0, 0, 0]]) # 3
or alternatively use groupby from pandas library:
>>> pd.DataFrame(arr).groupby(lab).sum().values
array([[ 0, 0, 0, 0],
[ 13, 2, 0, 11],
[110, 7, 5, 117],
[ 0, 0, 0, 0]])