def formater_un_gobblet(gobblet):
if gobblet == []:
return None
w = [1,2]
for i in w:
x = GOBBLET_REPRÉSENTATION[int(i)]
z = [0,1,2,3]
for l in z:
y = x[int(l)]
gobblet = [x,y]
return (x,y)
This is my Gobblet_representation:
GOBBLET_REPRÉSENTATION = {1: ["▫", "◇", "◯", "□"],2: ["▪", "◆", "●", "■"],}
And when I made my test : gobblet[1,3], it is supposed to be ["▫", "◇", "◯", "□"] for x and "□" for y but it shows me ["▪", "◆", "●", "■"] for x and "■" for y all the time - same for gobblet[1,2]. What am I doing wrong?
you can use one of those
def formater_un_gobblet(gobblet):
if gobblet == []:
return None
w = [1,2]
for i in w:
x = GOBBLET_REPRÉSENTATION[int(i)]
if i == gobblet[0]:
break
z = [0,1,2,3]
for l in z:
y = x[int(l)]
if l == gobblet[1]:
break
gobblet = [x,y]
return (x,y)
or
def formater_un_gobblet2(gobblet):
if gobblet == []:
return None
x= GOBBLET_REPRÉSENTATION[int(gobblet[0])]
y=x[gobblet[1]]
return (x,y)
Related
I have written two algorithms for creating unique mazes, one of them using depth-first-search (DFS) and the other using Kruskal's. The DFS algorithm performs as expected, however Kruskal's algorithm runs marginally slower than DFS and I do not know why.
I had written Kruskal's algorithm in Python.
I suspect the random.choice() function seems to be the underlying problem. The difference in runtime becomes noticeable when (r, c) > 30.
Here is the code for Kruskal's algorithm:
# Create a list of all possible edges
def create_edges(r, c):
edges = []
for y in range(r):
for x in range(c):
i = (y, x)
for d in ((0, 1), (0, -1), (1, 0), (-1, 0)):
p = tuple(map(sum, zip(d, i)))
py = p[0]
px = p[1]
if px in range(c) and py in range(r):
edges.append([i, p])
return edges
def kruskal(r, c, sz):
path = []
# Create a list of parent root nodes
roots = {(y, x) : [(y, x)] for y in range(r) for x in range(c)}
edges = create_edges(r, c)
while edges:
# Choose a random edge
edge = random.choice(edges)
parent = edge[0]
child = edge[1]
parent_set = get_set(roots, parent)
child_set = get_set(roots, child)
# Check if the parent / child are already in the same set
if parent_set == child_set:
rev_edge = edge.reverse()
if rev_edge in edges:
edges.remove(rev_edge)
edges.remove(edge)
continue
roots[parent_set] += roots[child_set]
roots.pop(child_set)
path.extend((parent, child))
rev_edge = edge.reverse()
if rev_edge in edges:
edges.remove(rev_edge)
edges.remove(edge)
return path
def get_set(roots, member):
s = None
for parent, children in roots.items():
if member in children:
s = parent
return s
def create_maze(t, r, c, sz):
maze = [['|_' for _ in range(c)] for _ in range(r)]
for cell in maze: cell.append('| ')
wd = {'DOWN' : ( 1, 0),
'UP' : (-1, 0),
'LEFT' : ( 0, -1),
'RIGHT': ( 0, 1)}
for n in range(len(t) - 1):
a = n
b = n + 1
p1 = t[a]
p2 = t[b]
ay, ax = p1[0], p1[1]
by, bx = p2[0], p2[1]
w = tuple(numpy.array(p2) - numpy.array(p1))
if w in wd.values():
k = list(wd.keys())[list(wd.values()).index(w)]
if k == 'DOWN': maze[ay][ax] = maze[ay][ax].replace('_', ' ')
if k == 'UP': maze[by][bx] = maze[by][bx].replace('_', ' ')
if k == 'LEFT': maze[ay][ax] = maze[ay][ax].replace('|', ' ')
if k == 'RIGHT': maze[by][bx] = maze[by][bx].replace('|', ' ')
return maze
def print_maze(maze, r, c, delay = 0):
s, l = min((r, c)), max((r, c))
a = 1 / (4 * r * c)
e = (1 / (s * l)) ** 2
delay = (a * 2.718 ** (-1 * e)) ** 0.5
time.sleep(delay)
print(' _' * c)
for iy in range(r):
for ix in range(c + 1):
print(maze[iy][ix], end = '')
print('')
print('')
def main():
r = 30
c = 30
sz = r * c
path = kruskal(r, c, sz)
maze = create_maze(path, r, c, sz)
print_maze(maze, r, c)
if __name__ == "__main__":
main()
I read about the error and try to cast map into list, but the error still appeared, I will show you the main file that contain the error.
def power(L, C, Erange):
assert len(L) == len(C), "The L and C must be corresponded to each other"
E = copy.deepcopy(Erange)
E[0] -= 1
power_table = dict()
for c in set(C): # for each type of class
first = [index for index, eachc in enumerate(C) if eachc == c]
rest = [index for index, eachc in enumerate(C) if eachc != c]
p_first = len(first) / len(L)
p_rest = len(rest) / len(L)
powerc = []
for u, v in zip(E[0:-1], E[1:]): # checking the range (u,v]
like_first = sum([1 for i in first if u < L[i] <= v]) / len(first) * p_first
like_rest = sum([1 for i in rest if u < L[i] <= v]) / len(rest) * p_rest
try:
powerc.append((like_first ** 2 / (like_first + like_rest)))
except ZeroDivisionError:
powerc.append(0)
power_table[c] = powerc
power = []
for l, c in zip(L, C):
for e_cursor in range(len(E)):
if E[e_cursor] >= l: break
power.append(round(power_table[c][e_cursor - 1], 2))
return power
def cliff_core(data, percentage, obj_as_binary, handled_obj=False):
if len(data) < 50:
logging.debug("no enough data to cliff. return the whole dataset")
return range(len(data))
classes = map(toolkit.str2num, zip(*data)[-1])
if not handled_obj:
if obj_as_binary:
classes = [1 if i > 0 else 0 for i in classes]
else:
classes = toolkit.apply_bin_range(classes)
data_power = list()
for col in zip(*data):
col = map(toolkit.str2num, col)
E = toolkit.binrange(col)
data_power.append(power(col, classes, E))
data_power = map(list, zip(*data_power)) # transposing the data power
row_sum = [sum(row) for row in data_power]
index = range(len(data))
zips = zip(data, classes, row_sum, index)
output = list()
for cls in set(classes):
matched = filter(lambda z: z[1] == cls, zips)
random.shuffle(matched)
matched = sorted(matched, key=lambda z: z[2], reverse=True)
if len(matched) < 5:
output.extend([m[3] for m in matched]) # all saved
continue
for i in range(int(len(matched) * percentage)):
output.append(matched[i][3])
return sorted(output)
def cliff(attribute_names,data_matrix,independent_attrs,objective_attr,objective_as_binary=False,
cliff_percentage=0.4):
ori_attrs, alldata = attribute_names, data_matrix # load the database
alldata_t = map(list, zip(*alldata))
valued_data_t = list()
for attr, col in zip(ori_attrs, alldata_t):
if attr in independent_attrs:
valued_data_t.append(col)
valued_data_t.append(alldata_t[attribute_names.index(objective_attr)])
alldata = map(list, zip(*valued_data_t))
alldata = map(lambda row: map(toolkit.str2num, row), alldata) # numbering the 2d table
after_cliff = cliff_core(alldata, cliff_percentage, objective_as_binary)
res = [data_matrix[i] for i in after_cliff]
return res
I've been getting
TypeError: 'str' object is not callable
For the function below when style == "scatter" but not when style == "categories" and I can't for the life of me figure out why, when to me it seems like the function is supposed to do the same thing in both places. Any thoughts about what I am doing wrong?
edit: this error is occurring on the lines graph = graph + "\\node at (%s,%s)[circle,fill,inner sep=1pt]{};\n"(x+random.uniform(-0.5,0.5),y+random.uniform(-0.5,0.5)) and the like
def scatterPlotCreator(style,obs,corr):
obs = int(obs)
graph="""
\\documentclass[11pt]{article}
\\usepackage{geometry}
\\usepackage{amsmath}
\\usepackage{amssymb}
\\usepackage{textpos}
\\usepackage{setspace}
\\usepackage{color}
\\usepackage{tikz}
\\usetikzlibrary{calc,arrows,automata,shapes.misc,shapes.arrows,chains,matrix,positioning,scopes,decorations.pathmorphing,shadows}
\\usepackage{graphicx}
\\usepackage{everypage}
\\setlength\\TPHorizModule{1in}
\\setlength\\TPVertModule{1in}
\\topmargin .25 in
\\headheight 0in
\\headsep 0in
\\textheight 8.5in
\\textwidth 5.5in
\\oddsidemargin .5in
\\evensidemargin .5in
\\begin{document}
\\pagestyle{empty}
\\begin{tikzpicture}
\\draw [very thick, ->] (0,0) -- (5,0);
\\draw [very thick, ->] (0,0) -- (0,5);
"""
if style == "scatter":
if corr == "NONE":
for o in range(obs):
graph = graph + "\\node at (%s,%s)[circle,fill,inner sep=1pt]{};\n"(random.uniform(0,5),random.uniform(0,5))
elif corr == "weakPos":
for o in range(obs):
x = random.uniform(2,3)
y = x
graph = graph + "\\node at (%s,%s)[circle,fill,inner sep=1pt]{};\n"(x+random.uniform(-2,2),y+random.uniform(-2,2))
elif corr == "strongPos":
for o in range(obs):
x = random.uniform(0.5,4.5)
y = x
graph = graph + "\\node at (%s,%s)[circle,fill,inner sep=1pt]{};\n"(x+random.uniform(-0.5,0.5),y+random.uniform(-0.5,0.5))
elif corr == "weakNeg":
for o in range(obs):
x = random.uniform(2,3)
y = 5-x
graph = graph + "\\node at (%s,%s)[circle,fill,inner sep=1pt]{};\n"(x+random.uniform(-2,2),y+random.uniform(-2,2))
elif corr == "strongNeg":
for o in range(obs):
x = random.uniform(0.5,4.5)
x = float(x)
y = float(5-x)
x+=random.uniform(-0.5,0.5)
y+=random.uniform(-0.5,0.5)
graph = graph + "\\node at (%s,%s)[circle,fill,inner sep=1pt]{};\n"(x,y)
elif corr == "posQuad":
for o in range(obs):
x = random.uniform(0.5,4.5)
y = (x-2.5)**2
graph = graph + "\\node at (%s,%s)[circle,fill,inner sep=1pt]{};\n"(x+random.uniform(-0.5,0.5),y+random.uniform(-0.5,0.5))
elif corr == "negQuad":
for o in range(obs):
x = random.uniform(0.5,4.5)
y = 5-(x-2.5)**2
graph = graph + "\\node at (%s,%s)[circle,fill,inner sep=1pt]{};\n"(x+random.uniform(-0.5,0.5),y+random.uniform(-0.5,0.5))
elif style == "categories":
categories = int(corr)
yJump = float(3)/float(categories-1)
if categories == 2:
bounds = [[0.5,3.5],[1.5,4.5]]
elif categories == 3:
bounds = [[0.5,3],[1.25,3.75],[2,4.5]]
elif categories == 4:
bounds = [[0.5,2.75],[1.1,3.35],[1.7,3.95],[2.25,4.5]]
elif categories ==5:
bounds = [[0.5,2.5],[1,3],[1.5,3.5],[2,4],[2.5,4.5]]
for c in range(categories):
for o in range(obs):
graph = graph + "\\node at (%s,%s)[circle,fill,inner sep=1pt]{};\n"%(random.uniform(bounds[c][0],bounds[c][1]),1+(yJump*c))
graph = graph +"""
\\end{tikzpicture}
\\end{document}
"""
return graph
I have the following code to compute a desired quantity:
import numpy as np
N = 2
lamda = 2
mu = 1
a = 0.5
St_Sp = np.arange(- N, N + 1)
Card = St_Sp.shape[0]
#%% Define infintesimal generator
def In_Ge(x, y):
if x == N or x == - N:
re = 0
elif x - y == - 1:
re = lamda
elif x - y == 1:
re = mu
elif x - y == 0:
re = - (mu + lamda)
else: re = 0
return re
x = St_Sp[0]
y = In_Ge(x, x) / (In_Ge(x, x) + np.log(a))
b = - 1 / y
print(b)
The result is inf. I checked and see that the value of y is non-zero, so I could not understand why such phenomenon happens. Could you elaborate on this issue?
#pinegulf's comment solves my question:
Your 'In_Ge(x,x)' retruns 0, thus y= 0 and 1/0 is pretty badly defined. Edit: You say it's not, but your x==--2 and functions first if is invoked.
I have the following code that solves simultaneous linear equations by starting with the first equation and finding y when x=0, then putting that y into the second equation and finding x, then putting that x back into the first equation etc...
Obviously, this has the potential to reach infinity, so if it reaches +-inf then it swaps the order of the equations so the spiral/ladder goes the other way.
This seems to work, tho I'm not such a good mathematician that I can prove it will always work beyond a hunch, and of course some lines never meet (I know how to use matrices and linear algebra to check straight off whether they will never meet, but I'm not so interested in that atm).
Is there a better way to 'spiral' in on the answer? I'm not interested in using math functions or numpy for the whole solution - I want to be able to code the solution. I don't mind using libraries to improve the performance, for instance using some sort of statistical method.
This may be a very naive question from either a coding or maths point of view, but if so I'd like to know why!
My code is as follows:
# A python program to solve 2d simultaneous equations
# by iterating over coefficients in spirals
import numpy as np
def Input(coeff_or_constant, var, lower, upper):
val = int(input("Let the {} {} be a number between {} and {}: ".format(coeff_or_constant, var, lower, upper)))
if val >= lower and val <= upper :
return val
else:
print("Invalid input")
exit(0)
def Equation(equation_array):
a = Input("coefficient", "a", 0, 10)
b = Input("coefficient", "b", 0, 10)
c = Input("constant", "c", 0, 10)
equation_list = [a, b, c]
equation_array.append(equation_list)
return equation_array
def Stringify_Equations(equation_array):
A = str(equation_array[0][0])
B = str(equation_array[0][1])
C = str(equation_array[0][2])
D = str(equation_array[1][0])
E = str(equation_array[1][1])
F = str(equation_array[1][2])
eq1 = str(A + "y = " + B + "x + " + C)
eq2 = str(D + "y = " + E + "x + " + F)
print(eq1)
print(eq2)
def Spiral(equation_array):
a = equation_array[0][0]
b = equation_array[0][1]
c = equation_array[0][2]
d = equation_array[1][0]
e = equation_array[1][1]
f = equation_array[1][2]
# start at y when x = 0
x = 0
infinity_flag = False
count = 0
coords = []
coords.append([0, 0])
coords.append([1, 1])
# solve equation 2 for x when y = START
while not (coords[0][0] == coords[1][0]):
try:
y = ( ( b * x ) + c ) / a
except:
y = 0
print(y)
try:
x = ( ( d * y ) - f ) / e
except:
x = 0
if x >= 100000 or x <= -100000:
count = count + 1
if count >= 100000:
print("It\'s looking like these linear equations don\'t intersect!")
break
print(x)
new_coords = [x, y]
coords.append(new_coords)
coords.pop(0)
if not ((x == float("inf") or x == float("-inf")) and (y == float("inf") or y == float("-inf"))):
pass
else:
infinity_flag if False else True
if infinity_flag == False:
# if the spiral is divergent this switches the equations around so it converges
# the infinity_flag is to check if both spirals returned infinity meaning the lines do not intersect
# I think this would mostly work for linear equations, but for other kinds of equations it might not
x = 0
a = equation_array[1][0]
b = equation_array[1][1]
c = equation_array[1][2]
d = equation_array[0][0]
e = equation_array[0][1]
f = equation_array[0][2]
infinity_flag = False
else:
print("These linear equations do not intersect")
break
y = round(y, 3)
x = round(x, 3)
print(x, y)
equation_array = []
print("Specify coefficients a and b, and a constant c for equation 1")
equations = Equation(equation_array)
print("Specify coefficients a and b, and a constant c for equation 1")
equations = Equation(equation_array)
print(equation_array)
Stringify_Equations(equation_array)
Spiral(equation_array)