Following is the code where in caller is called first from another module,
centroids is of float type (an array of numberofcluster * numberoffeatures)
labels is 1d array of numberofexplanations
array is not getting updated
def caller(centroids, labels):
number_of_features = len(centroids[0])
one_column = [0, 0, 0, 0, 0]
i = 0
j = 0
array = [[0 for x in xrange(number_of_features)] for x in xrange(5)]
while i < number_of_features:
j = 0
while j < 5:
one_column[j] = centroids[j][i]
j += 1
rank(one_column, i, array)
i += 1
return calculatemean(number_of_features, array)
def rank(one_column, ithfeature, array):
temp_dict = {}
i = 0
while i < 5:
temp_dict[one_column[i]] = i
i += 1
number_of_uniquevalues = len(set(temp_dict))
sorted_dict = OrderedDict(sorted(temp_dict.items()))
i = 0
keys_list = sorted_dict.keys()
while i < 5:
array[one_column.index(keys_list[i])][ithfeature] = sorted_dict[keys_list[i]]
i += 1
I have referred to this link
Two dimensional array in python
and the issue is resolved
Related
generate a random (height x width) grid such that for every coordinate (i, j), there can be no three consecutive same colors in a row or in a column.
generate(int: width, int: height, list: colors)
Example:
getvalidMatrix(3, 3, [0, 1, 2])
output:
[
[1, 2, 1],
[1, 0, 2],
[0, 1, 2],
]
import random
def getvalidMatrix(length,width,colors):
map = dict()
for i in range(len(colors)):
map[colors[i]]=i
res = [[0] * length] * width
for i in range(length):
for j in range(width):
end = len(colors)
if i - 1 >= 0 and i - 2 >= 0 and res[i-1][j] == res[i-2][j]:
index = map[res[i-1][j]]
colors[index] = colors[end]
colors[end] = map[res[i-1]][j]
end -= 1
if j - 1 >= 0 and j - 2 >= 0 and res[i][j-1] == res[i][j-2]:
index = map[res[i][j-1]]
colors[index] = colors[end]
colors[end] = map[res[i][j-1]]
end -= 1
next=random.randint(0,end)
res[i][j] = colors[next]
return res
if __name__ == '__main__':
length = 3
width = 3
colors = [0,1,2]
print(getvalidMatrix(length, width, colors))
I got IndexError: list index out of range with the code above. Which part of the code should I fix in order to avoid the IndexError?
Although I didn't completely understand de algorithm used to solve the problem, I can see that you are committing a few mistakes:
You're retrieving a multidimensional list element incorrectly, e.g., list_var[a][b] instead of list_var[b][a]. This can be solved in the for loops.
You're indexing variable colors this way: colors[end] = ..., but variable end is initialized as end = len(colors), i.e., with a value 1 unit greater than the maximum index allowed, remember that lists are zero-indexed.
A misplaced closing bracket.
Here's the corrected code. Run a file diff to see the changes I've made. I don't guarantee it now solves the problem you were given but the errors you came across are gone.
import random
def getvalidMatrix(length,width,colors):
map = dict()
for i in range(len(colors)):
map[colors[i]]=i
res = [[0] * length] * width
for i in range(width):
for j in range(length):
end = len(colors)-1
if i - 1 >= 0 and i - 2 >= 0 and res[i-1][j] == res[i-2][j]:
index = map[res[i-1][j]]
colors[index] = colors[end]
colors[end] = map[res[i-1][j]]
end -= 1
if j - 1 >= 0 and j - 2 >= 0 and res[i][j-1] == res[i][j-2]:
index = map[res[i][j-1]]
colors[index] = colors[end]
colors[end] = map[res[i][j-1]]
end -= 1
next=random.randint(0,end)
res[i][j] = colors[next]
return res
if __name__ == '__main__':
length = 3
width = 3
colors = [0,1,2]
print(getvalidMatrix(length, width, colors))
I have this code where st is an array of a class that have x and y parameters. I have to sort their x or y. How can i reduce it so i dont have to write the same code 2 times (one for each case)?
def sort(st, coor):
for i in range(len(st)):
if coor == 'x':
selected = st[i]
j = i - 1
while j >= 0 and st[j].x > selected.x:
st[j + 1], st[j] = st[j], st[j + 1]
j -= 1
st[j + 1] = selected
i += 1
else:
selected = st[i]
j = i - 1
while j >= 0 and st[j].y > selected.y:
st[j + 1], st[j] = st[j], st[j + 1]
j -= 1
st[j + 1] = selected
i += 1
Extract a method for the code that is duplicated.
https://refactoring.guru/extract-method
In that new method, the part that is different is calling the x or y attribute of an instance, and this can be replaced by a call to getattr.
I've been working on this leetcode problem, which is essentially finding the number of valid paths in a maze given some obstacleGrid matrix. If obstacleGrid[i][j] == 1, then we have an obstacle at (i,j) and we have zero otherwise, which a valid spot. We can only move down and right with the goal of starting from the upper left to the bottom right.
I have written the code below:
def uniquePathsWithObstacles(self, obstacleGrid):
# obstruction at the start
if (obstacleGrid[0][0] == 1): return 0
# obstruction at the end
if (obstacleGrid[-1][-1] == 1): return 0
m, n = len(obstacleGrid), len(obstacleGrid[0])
memo = [[0] * n] * m
# starting move
memo[0][0] = 1
# now check the first row
for j in range(1, n):
memo[0][j] = 1 if (obstacleGrid[0][j] == 0 and memo[0][j-1] != 0) else 0
# now check the first column
for i in range(1, m):
memo[i][0] = 1 if (obstacleGrid[i][0] == 0 and memo[i-1][0] != 0) else 0
# now check everything else
for i in range(1, m):
for j in range(1, n):
if (obstacleGrid[i][j] == 1): memo[i][j] = 0
else: memo[i][j] = memo[i-1][j] + memo[i][j-1]
return memo[-1][-1]
I took the obvious DP approach and I know the idea works but something is wrong with the code; for some reason I don't think my memo matrix is being updated properly? I feel like the problem is staring at me in the face but for some reason I can't see it. Any help appreciated!
Edit: For obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]] and if I had a print(memo) right before the return statement, I get [[1, 1, 2], [1, 1, 2], [1, 1, 2]]. This happens to give me the right answer, but the memo matrix is wrong!
One problem lies in the line memo = [[0] * n] * m.
This does not really create mcopies of the same list, but instead, it only creates the [0] * n list once and then creates memo as a list of m references to this list. Any change to any of these lists therefore modifies all other lists!
You can try this yourself:
memo = [[0] * 3] * 4
memo[0][1] = 1
print(memo)
This gives [[0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0]].
Instead, you have to initialize each list on their own, e.g.,
memo = []
for i in range(m):
memo.append([0] * n)
I just tried to do this with recursion as an comparison rather than an answer.
import numpy as np
def number_of_paths(obstacles):
"""
Calculate the number of paths available in a maze with obstacles, with only right and down moves, from top left
to bottom right.
Args:
obstacles (ndarray): binary matrix with 1 representing obstacle
Returns:
int: the number of paths
"""
if obstacles[0,0] == 1:
raise ValueError # cannot start on an obstacle
count = 0
if obstacles.shape == (2,1):
return 1
if obstacles.shape == (1,2):
return 1
if obstacles.shape[1] > 1 and obstacles[0,1] == 0:
count += number_of_paths(obstacles[:,1:])
if obstacles.shape[0] > 1 and obstacles[1,0] == 0:
count += number_of_paths(obstacles[1:,:])
return count
your code is correct and 1 line must be updated per the below:
def uniquePathsWithObstacles(self, obstacleGrid):
# obstruction at the start
if (obstacleGrid[0][0] == 1): return 0
# obstruction at the end
if (obstacleGrid[-1][-1] == 1): return 0
m, n = len(obstacleGrid), len(obstacleGrid[0])
memo = [[0] * n for i in range(m)]
# starting move
memo[0][0] = 1
# now check the first row
for j in range(1, n):
#memo[0][j] = 1 if (obstacleGrid[0][j] == 0 and memo[0][j-1] != 0) else 0
memo[0][j] = 1 if (obstacleGrid[0][j] == 0 and memo[0][j-1] != 0) else 0
# now check the first column
for i in range(1, m):
memo[i][0] = 1 if (obstacleGrid[i][0] == 0 and memo[i-1][0] != 0) else 0
# now check everything else
for i in range(1, m):
for j in range(1, n):
if (obstacleGrid[i][j] == 1): memo[i][j] = 0
else: memo[i][j] = memo[i-1][j] + memo[i][j-1]
return memo[-1][-1]
import random
def lottery(lucky_numbers, run):
i = 0
while i < run:
x = random.uniform(0, 1) #prints out a random number between 0 and 1
numbers = lucky_numbers
NewNumbers = numbers[-1:] + numbers[:-1] #shifts each element in the to the right
lucky_numbers = NewNumbers
print(lucky_numbers, x)
i += 1
lottery([1, 2, 0], 3)
This code prints out something like:
>>>>>>>>>>
[0, 1, 2] 0.33016179294984127
[2, 0, 1] 0.7797639530009745
[1, 2, 0] 0.6292245916315391
>>>>>>>>>>
The x values will always be different because they are random numbers between 0 and 1.
I am trying to add a function that says if x is the lowest value(min) in the loop then the programme should print the list of that iteration, for example in this case the lowest value of x in this loop is 0.33016179.. , the program should therefore print the list [0, 1, 2]
I would just save the info in a variable and print it after the loop ends:
import random
def lottery(lucky_numbers, run):
i = 0
min_x = 1
while i < run:
x = random.uniform(0, 1) #prints out a random number between 0 and 1
numbers = lucky_numbers
NewNumbers = numbers[-1:] + numbers[:-1] #shifts each element in the to the right
lucky_numbers = NewNumbers
if x < min_x:
min_x = x
min_lucky_numbers = lucky_numbers
i += 1
print(min_lucky_numbers, min_x)
lottery([1, 2, 0], 3)
You can create a "cache" that stores all the x values then call the lowest value.
cache = []
for _ in range(3):
x = random.uniform(0, 1)
cache.append(x)
print min(cache)
to do what you want, you have just to store your items in two different lists, sort them and display the firt elements of each one :
import random
luckiest_num = list()
luckiest_list = list()
def lottery(lucky_numbers, run):
i = 0
while i < run:
x = random.uniform(0, 1)
numbers = lucky_numbers
NewNumbers = numbers[-1:] + numbers[:-1]
print(NewNumbers, x)
i += 1
luckiest_num.append(x)
luckiest_list.append(NewNumbers)
lottery([1, 2, 0], 3)
luckiest_num.sort()
luckiest_list.sort()
print ("The luckiest item is : ")
print(luckiest_num[0],luckiest_list[0])
I created a program in python bees,lowers, and trees at different locations and I want the bees to be able to move. However, when I run my program, it always gets stuck because of a type error. Could somebody please explain to me what is causing the issue and how to fix it. Also, I am a complete beginner to programming so any tips on how to make my code faster or more logical would be gladly accepted. The code to the program is below:
import random
wb0,wb1,wb2,wb3,wb4,wb5,wb6,wb7,wb8,wb9 = [],[],[],[],[],[],[],[],[],[]
worker_bees = [wb0,wb1,wb2,wb3,wb4,wb5,wb6,wb7,wb8,wb9]
f0,f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14 = [],[],[],[],[],[],[],[],[],[],[],[],[],[],[]
flowers = [f0,f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14]
t0,t1,t2,t3,t4 = [],[],[],[],[]
trees = [t0,t1,t2,t3,t4]
def world_generate():
def worker_bee_spawn():
x = 0
i = 0
while i < 10:
worker_bees[x] = (random.randrange(0,100), random.randrange(0,100))
x += 1
i += 1
def flower_spawn():
x = 0
i = 0
while i < 15:
flowers[x] = (random.randrange(0,100), random.randrange(0,100))
x += 1
i += 1
if flowers[x - 1] == worker_bees:
x -= 1
i -= 1
def tree_spawn():
x = 0
i = 0
while i < 5:
trees[x] = (random.randrange(0,100), random.randrange(0,100))
x += 1
i += 1
if trees[x - 1] == worker_bees:
x -= 1
i -= 1
elif trees[x - 1] == flowers:
x -= 1
i -= 1
worker_bee_spawn()
flower_spawn()
tree_spawn()
world_generate()
def worker_bee_movement():
x = 0
i = 0
while i < 10:
worker_bee = worker_bees[x]
worker_bee_x = worker_bee[0]
worker_bee_x += 1
worker_bee[0] = worker_bee_x
worker_bees_x = worker_bee
x += 1
i += 1
worker_bee_movement()
Change the following line:
while i < 10:
worker_bee = list(worker_bees[x])
worker_bees[x] is a tuple, so worker_bee = worker_bees[x] then make worker_bee a tuple and your worker_bee[0] = worker_bee_x will fail with:
'tuple' object does not support item assignment
To make it clear, (1,2,3)[0] = 3 is not allowed, [1,2,3][0] = 3 is allowed
And use range to create your lists of lists
worker_bees = [[] for _ in range(10)]
flowers = [[] for _ in range(15)]
trees = [[] for _ in range(4)]