Related
import numpy as np
class RubikCube:
def __init__(self,size):
self.size = size
self.A = np.zeros((size,size), dtype = np.int8)
self.B = np.zeros((size,size), dtype = np.int8)
self.C = np.zeros((size,size), dtype = np.int8)
self.D = np.zeros((size,size), dtype = np.int8)
self.E = np.zeros((size,size), dtype = np.int8)
self.F = np.zeros((size,size), dtype = np.int8)
self.faces = [self.A, self.B, self.C, self.D, self.E, self.F]
def __str__(self):
current_printoptions = np.get_printoptions()
np.set_printoptions(formatter={'str': '{: 3d}'.format})
output = ""
indent = " " * (1 + self.size * 4)
for row in self.A:
output += indent + str(row) + "\n"
for zipped_row in zip(self.B, self.C, self.D, self.E):
for row in zipped_row:
output += str(row)
output += "\n"
for row in self.F: output += indent + str(row) + "\n"
np.set_printoptions(current_printoptions)
return output
def init_arange(self):
i = 0
for face in self.faces:
for y in range(self.size):
for x in range(self.size):
face[y][x] = i
i += 1
def init_plainteks(self, teks):
i = 0
for face in self.faces:
for y in range(self.size):
for x in range(self.size):
if len(teks)>i:
face[y][x] = ord(teks[i])
else:
face[y][x] = 37
i += 1
def encrypt(self,key):
for move in key.split('-'):
if move[0] == 'R':
self.rotate_row(int(move[1]))
if move[0] == 'C':
self.rotate_column(int(move[1]))
if move[0] == 'L':
self.rotate_level(int(move[1]))
def decrypt(self,key):
rev_moves = key.split('-')
new_moves = list()
for i in range(1, len(rev_moves) + 1):
new_moves.append(rev_moves[-1 * i])
for move in new_moves:
if move[0] == 'R':
self.rev_rotate_row(int(move[1]))
if move[0] == 'C':
self.rev_rotate_column(int(move[1]))
if move[0] == 'L':
self.rev_rotate_level(int(move[1]))
def rotate_row(self, n):
# B -> C -> D -> E -> B
if n in (1,2,3):
for i in range(n):
tmpB = np.copy(self.B[-1])
self.B[-1] = self.E[-1]
self.E[-1] = self.D[-1]
self.D[-1] = self.C[-1]
self.C[-1] = tmpB
# rotate F by - 90*n
self.F = np.rot90(self.F, 4-n)
elif n in (4,5,6):
for i in range(n-3):
tmpB = np.copy(selef.B[:1])
self.B[:1] = self.E[:1]
self.E[:1] = self.D[:1]
self.D[:1] = self.C[:1]
self.C[:1] = tmpB
# rotate A by 90 derajat*n
self.A = np.rot90(self.A, n-3)
def rev_rotate_row(self,n):
# B -> C -> D -> E -> B
if n in (1,2,3):
for i in range(n):
tmpB = np.copy(self.B[-1])
self.B[-1] = self.C[-1]
self.C[-1] = self.D[-1]
self.D[-1] = self.E[-1]
self.E[-1] = tmpB
# rotate F by -90*n
self.F = np.rot90(self.F, n-4)
elif n in (4,5,6):
for i in range(n-3):
tmpB = np.copy(self.B[-1])
self.B[:1] = self.C[:1]
self.C[:1] = self.D[:1]
self.D[:1] = self.E[:1]
self.E[:1] = tmpB
# rotate A by 90*n
self.A = np.rot90(self.A, 3-n)
def rotate_column(self, n):
# A -> E -> F -> C -> A
if n in (1,2,3):
for i in range(n):
tmpA = np.copy(self.A[:,-1])
self.A[:,-1] = self.C[:,-1]
self.C[:,-1] = self.F[:,-1]
self.F[:,-1] = np.flip(self.E[:,0])
self.E[:,0] = np.flip(tmpA)
# rotate D by -90*n
self.D = np.rot90(self.D, 4-n)
elif n in (4,5,6):
for i in range(n-3):
tmpA = np.copy(self.A[:,:1])
self.A[:,:1] = self.C[:,:1]
self.C[:,:1] = self.F[:,:1]
self.F[:,:1] = np.flip(self.E[:,-1:])
self.E[:,-1:] = np.flip(tmpA)
# rotate B by 90*n
self.B = np.rot90(self.B, n-3)
def rev_rotate_column(self,n):
# A -> E -> F -> C -> A
if n in (1,2,3):
for i in range(n):
tmpA = np.copy(self.A[:,-1])
self.A[:,-1] = self.E[:,-1]
self.E[:,-1] = self.F[:,-1]
self.F[:,-1] = np.flip(self.C[:,0])
self.C[:,0] = np.flip(tmpA)
# rotate D by -90*n
self.D = np.rot90(self.D, 4-n)
elif n in (4,5,6):
for i in range(n-3):
tmpA = np.copy(self.A[:,:1])
self.A[:,:1] = self.E[:,:1]
self.E[:,:1] = self.F[:,:1]
self.F[:,:1] = np.flip(self.C[:,-1:])
self.C[:,-1:] = np.flip(tmpA)
# rotate B by 90*n
self.B = np.rot90(self.B, n-3)
def rotate_level(self,n):
# A -> B -> F -> D -> A
if n in range(n):
for i in range(n):
tmpA = np.copy(self.A[0])
self.A[0] = self.D[:,-1]
self.D[:,-1] = np.flip(self.F[-1])
self.F[-1] = self.B[:,0]
self.B[:,0] = np.flip(tmpA)
# rotate E by -90*n
self.E = np.rot90(self.E, 4-n)
elif n in (4,5,6):
for i in range(n-3):
tmpA = np.copy(self.A[1:])
self.A[-1:] = np.rot90(self.D[:,:1])
self.D[:,:1] = np.rot90(self.F[:1])
self.F[:1] = np.rot90(self.B[:,-1:])
self.B[:,1:] = np.rot90(tmpA)
# rotate C by 90*n
self.C = np.rot90(self.C, n-3)
def rev_rotate_level(self,n):
# A -> B -> F -> D -> A
if n in (1,2,3):
for i in range(n):
tmpA = np.copy(self.A[-1])
self.A[0] = self.B[:,-1]
self.B[:, -1] = np.flip(self.F[-1])
self.F[-1] = self.D[:,0]
self.D[:,0] = np.flip(tmpA)
# rotate E by -90*n
self.E = np.rot90(self.E, n-4)
elif n in (4,5,6):
for i in range(n-3):
tmpA = np.copy(self.A[-1:])
self.A[-1:] = np.rot90(self.B[:,:1])
self.B[:,:1] = np.rot90(self.F[:1])
self.F[:1] = np.rot90(self.D[:,-1:])
self.D[:,-1:] = np.rot90(tmpA)
# rotate C by 90*n
self.C = np.rot90(self.C, 3-n)
if name == "main":
msg = input("Message: ")
rubikcube = RubikCube(size=3)
rubikcube.init_plainteks(msg)
# rubikcube.init_arange()
print(rubikcube)
key = input("Key: ")
rubikcube.encrypt(key)
print(rubikcube)
the output i expected :
Input :
Message : POIMSQ&P7-D&X?(<3J*Q
Key : C1-R4-C6-R6-C3-L1-R1-C4-C3-L4
Output : 3%%O∗%%%%−%%7&Q∗%%%M?J%X∗(< %%%Q%%%%P %%S%%IP %%&%%D%%%%%
enter image description here
I have tried to modify it, can anyone help me to fix the error? thank you very much
So my problem seems quite trivial, but I'm new to python and am writing a simple program that calculates the reactions of a beam. My program does that successfully, but now I want to expand the capabilities to being able to plot the shear and bending moment diagrams along each beam. My thought process is to use a list and add the shear values (for now) to that list, in increments that divides the beam into 100 segments. Afterwards I want to be able to retrieve them and use these values to plot them.
class beam:
def __init__(self, emod, i, length):
self.emod = emod
self.i = i
self.length = length
def A(self, a, p): # Calculate reaction at A
return p * (self.length - a) / self.length
def B(self, a, p): # Calculate reaction at B
return p * a / self.length
def Mc(self, a, p): # Calculate moment at C
return p * a * (self.length - a) / self.length
def delc(self, a, p):
return p * a * a * (self.length - a) ** 2 / 3 / self.emod / self.i / self.length
def delx(self, x, a, p):
beta = (self.length - a) / self.length
delta = x / self.length
return p * self.length * self.length * (self.length - a) * delta * (
1 - beta * beta - delta * delta) / 6 / self.emod / self.i
def delx1(self, x, a, p):
alpha = a / self.length
delta = x / self.length
return p * self.length * self.length * a * delta * (
1 - alpha * alpha - delta * delta) / 6 / self.emod / self.i
def maxDisplacementCoords(self, a):
return a * (1.0 / 3 + 2 * (self.length - a) / 3 / a) ** 0.5
class shearValues: # This is the class that adds the shear values to a list
def __init__(self):
self.values = []
def add_values(self, beam, a_val, p):
j = float(0)
v = beam.A(a_val, p)
while j < beam.length:
if j < a_val:
continue
elif j > a_val:
continue
elif j == a_val:
v -= p
self.values.append(v)
j += beam.length / float(100)
v += beam.B(a_val, p)
self.values.append(v)
if __name__ == '__main__':
def inertia_x(h, w, t):
iy1 = w * h * h * h / 12
iy2 = (w - t) * (h - 2 * t) ** 3 / 12
return iy1 - 2 * iy2
beam_list = []
beam1 = beam(200000000000, inertia_x(0.203, 0.133, 0.025), 5)
beam2 = beam(200000000000, inertia_x(0.254, 0.146, 0.031), 5)
beam3 = beam(200000000000, inertia_x(0.305, 0.102, 0.025), 5)
beam_list.append(beam1)
beam_list.append(beam2)
beam_list.append(beam3)
while True:
my_beam = beam_list[1]
beam_choice = input("Which beam would you like to evaluate? 1, 2 or 3 ")
if beam_choice == '1':
my_beam = beam_list[0]
elif beam_choice == '2':
my_beam = beam_list[1]
elif beam_choice == '3':
my_beam = beam_list[2]
p = float(input("Enter the required load "))
a_val = float(input("Enter displacement of point load (origin at LHS) "))
print("Ay = {}".format(my_beam.A(a_val, p)))
print("By = {}".format(my_beam.B(a_val, p)))
print("Mc = {}".format(my_beam.Mc(a_val, p)))
print("Displacement at C = {}".format(my_beam.delc(a_val, p)))
displacement = input("Do you want to calculate a specific displacement? [Y]es or [N]o ").upper()
if displacement not in 'YN' or len(displacement) != 1:
print("Not a valid option")
continue
if displacement == 'Y':
x = float(input("Enter location on beam to calculate displacement (origin on LHS) "))
if x < a_val:
print("Displacement at {} = {}".format(x, my_beam.delx(x, a_val, p)))
elif x > a_val:
print("Displacement at {} = {}".format(x, my_beam.delx1(my_beam.length - x, a_val, p)))
elif x == displacement:
print("Displacement at {} = {}".format(x, my_beam.delc(a_val, p)))
elif displacement == 'N':
continue
print("Max displacement is at {} and is = {}".format(my_beam.maxDisplacementCoords(a_val),
my_beam.delx(my_beam.maxDisplacementCoords(a_val), a_val,
p)))
# The code doesn't execute the way it is intended from here
sv = shearValues()
sv.add_values(my_beam,a_val,p)
Currently it seems as if I have created an infinite loop.
As you can see, the code is not optimized at all but any help would be appreciated. And the calculations are correct.
here's the code i made
def bisection(f, a, b, e):
step = 1
condition = True
while condition:
c = (a+b)/2
if f(a) * f(c) < 0:
b = c
else:
a = c
if f(c) == 0:
break
step = step + 1
condition = abs(f(a)-f(b)) > e
print(c)
return(c)
if f(a)* f(b) > 0:
print("no roots")
else:
bisection(f, a, b, e)
a, b, e = input().split(' ')
a = float(a)
b = float(b)
print(round(root, 4))
but I'm getting a root of c = 0.171875
instead of 0.6875
for the problem Ax ≡ B (MOD C) I did this, and it was okay:
def congru(a,b,c):
for i in range(0,c):
if ((a*i - b)%c)== 0 :
print(i)
Now I have to solve a system of equations, where A = ( 5x + 7y) and A= (6x + 2y),
and B= 4 and B = 12 , respectively, and C is 26.
In other words:
( 5x + 7y)≡ 4 (mod 26)
(6x + 2y)≡ 12 (mod 26)
How do I do that?
Thanks.
For the aX ≡ b (mod m) linear congruence, here is a more powerful Python solution, based on Euler's theorem, which will work well even for very large numbers:
def linear_congruence(a, b, m):
if b == 0:
return 0
if a < 0:
a = -a
b = -b
b %= m
while a > m:
a -= m
return (m * linear_congruence(m, -b, a) + b) // a
>>> linear_congruence(80484954784936, 69992716484293, 119315717514047)
>>> 45347150615590
For the X, Y system: multiply 1st equation by 2 and the 2nd one by -7, add them together and solve for X. Then substitute X and solve for Y.
This is a very fast linear congruence solver that can solve a 4096 byte number in a second. Recursion versions meet their max depth at this length:
#included if you use withstats=True, not needed otherwise
def ltrailing(N):
return len(str(bin(N))) - len(str(bin(N)).rstrip('0'))
#included if you use withstats=True, not needed otherwise
def _testx(n, b, withstats=False):
s = ltrailing(n - 1)
t = n >> s
if b == 1 or b == n - 1:
return True
else:
for j in range(0, s):
b = pow_mod(b, 2, n, withstats)
if b == n - 1:
return True
if b == 1:
return False
if withstats == True:
print(f"{n}, {b}, {s}, {t}, {j}")
if withstats == True:
print(f"{n}, {b}, {s}, {t}")
return False
def fastlinearcongruence(powx, divmodx, N, withstats=False):
x, y, z = egcditer(powx, N, withstats)
answer = (y*divmodx)%N
if withstats == True:
print(f"answer = {answer}, mrbt = {a}, mrst = {b}, mranswer = {_testx(N, answer)}")
if x > 1:
powx//=x
divmodx//=x
N//=x
if withstats == True:
print(f"powx = {powx}, divmodx = {divmodx}, N = {N}")
x, y, z = egcditer(powx, N, withstats)
if withstats == True:
print(f"x = {x}, y = {y}, z = {z}")
answer = (y*divmodx)%N
if withstats == True:
print(f"answer = {answer}, mrbt = {a}, mrst = {b}, mranswer = {_testx(N, answer)}")
answer = (y*divmodx)%N
if withstats == True:
print(f"answer = {answer}, mrbt = {a}, mrst = {b}, mranswer = {_testx(N, answer)}")
return answer
def egcditer(a, b, withstats=False):
s = 0
r = b
old_s = 1
old_r = a
quotient = 0
if withstats == True:
print(f"quotient = {quotient}, old_r = {old_r}, r = {r}, old_s = {old_s}, s = {s}")
while r!= 0:
quotient = old_r // r
old_r, r = r, old_r - quotient * r
old_s, s = s, old_s - quotient * s
if withstats == True:
print(f"quotient = {quotient}, old_r = {old_r}, r = {r}, old_s = {old_s}, s = {s}")
if b != 0:
bezout_t = quotient = (old_r - old_s * a) // b
if withstats == True:
print(f"bezout_t = {bezout_t}")
else:
bezout_t = 0
if withstats == True:
print("Bézout coefficients:", (old_s, bezout_t))
print("greatest common divisor:", old_r)
return old_r, old_s, bezout_t
To use:
In [2703]: fastlinearcongruence(63,1,1009)
Out[2703]: 993
In [2705]: fastlinearcongruence(993,1,1009)
Out[2705]: 63
Also this is 100x faster than pow when performing this pow:
pow(1009, 2**bit_length()-1, 2**bit_length())
where the answer is 273.
This is equivalent to the much faster:
In [2713]: fastlinearcongruence(1009,1,1024)
Out[2713]: 273
Solved, here's the code for it:
def congru(a0,a1,a2,b0,b1,b2,c):
for i in range(0,c):
for j in range(0,c):
if ((a0*i + a1*j) - a2)%c ==0 and ((b0*i +b1*j)-b2)%c==0:
print('x: %d y: %d' %( i, j))
If you need a congruence system you can use this code.
from functools import reduce
class CI:
"""
cX=a (mod m)
"""
def __init__(self, c, a, m):
self.c = c%m
self.a = a%m
self.m = m
def solve(self, x):
return (x*self.c)%self.m == self.a
def find(cil):
espacio = reduce(lambda acc, ci: acc*ci.m, cil, 1)+1
for x in range(0, espacio):
if reduce(lambda acc, ci: acc and ci.solve(x), cil, True):
return x
print(find([CI(3, 2, 4), CI(4, 1, 5), CI(6, 3, 9)]))
this example will solve for x
3x=2 (mod 2)
4x=1 (mod 1)
6x=3 (mod 9)
To solve linear congruence system, You should use Chinese theorem of reminders.
I wrote full code using python and AppJar (AppJar is for grafics).
And You can download it from my github profile: github profile, full code there
There You can find all the functions I used.
It is very simple and I am sure You will understand the code, although it is written in serbian language.
Despite my function returning an array, I get an TypeError: 'NoneType' object is not callable error. I first define classes, and then insert the function.
I'm relatively new to Python, and would appreciate any help/comments.
The Classes are:
from scipy import array, dot, zeros, empty
from scipy.optimize import brentq
from numpy import *
from numpy.random import uniform
from time import time
# from mpi4py import MPI
class UtilTheory:
"""
"""
def utility(self, other):
raise NotImplementedError("You need to implement method 'utility' "
"in the child class.")
def demand(self, p):
raise NotImplementedError("You need to implement method 'demand' "
"in the child class.")
def excessDemand(self, p):
p = array(p)
return self.demand(p) - self.endowment
def indUtility(self, p):
x = self.demand(p)
return self.utility(x)
def __add__(self, other):
economy = Economy([self, other])
return economy
def __radd__(self, other):
economy = Economy([self] + other)
def __rmul__(self, other):
economy = Economy(other * [self])
return economy
class Consumer(UtilTheory, object):
"""
Defines general features of a consumer
"""
def __init__(self, endowment=array([1,1]), alpha=0.5, rho=0.0):
self.endowment = array(endowment)
self.alpha = float(alpha)
self.rho = rho
self.sigma = 1.0 / (1.0 - rho)
def __str__(self):
return ('e=' + str(self.endowment) +
', alpha=' + str(self.alpha) +
', rho=' + str(self.rho))
def demand(self, p):
endowment = self.endowment
alpha = self.alpha
sigma = self.sigma
p = array(p)
m = dot(endowment, p)
x1 = ((alpha / p[0]) ** sigma * m /
(alpha ** sigma * p[0] ** (1 - sigma) +
(1 - alpha) ** sigma * p[1] ** (1 - sigma)))
x2 = (((1.0 - alpha) / p[1]) ** sigma * m /
(alpha ** sigma * p[0] ** (1 - sigma) +
(1 - alpha) ** sigma * p[1] ** (1 - sigma)))
return array([x1, x2])
def utility(self, x):
if self.rho != 0:
return ((self.alpha * x[0] ** self.rho +
(1.0 - self.alpha) * x[1] ** self.rho) **
(1.0 / self.rho))
return x[0] ** self.alpha * x[1] ** (1.0 - self.alpha)
class Economy:
"""
Consists of consumers
"""
def __init__(self, consumers):
"""
Consumers should be a list of consumers
"""
self.consumers = consumers
def excessDemand(self, p):
result = zeros(2)
for consumer in self.consumers:
result = result + consumer.excessDemand(p)
return result
def demand(self, p):
result = zeros(2)
for consumer in self.consumers:
result = result + consumer.demand(p)
return result
def excessDemandGood0(self, p0):
p = array([p0, 1.0 - p0])
result = 0
for consumer in self.consumers:
result = result + consumer.excessDemand(p)[0]
return result
def __add__(self,other):
try:
return Economy(self.consumers + other.consumers)
except:
return Economy(self.consumers + [other])
def numEquilibria(self, n=100):
# p = array([p0, 1 - p0])
q = linspace(0, 1, n)
result = empty(len(q))
#print result
for i, p0 in enumerate(q):
a = self.excessDemandGood0(p0)
#print a
result[i] = a
index = zeros(len(q))
for i in range(1, 2):
if result[i] <= 0:
index[i - 1] = 1
else:
index[i - 1] = 0
for i in range(2, n - 1):
test=result[i - 1] * result[i]
#print test
if test <= 0:
index[i - 1] = 1
else:
index[i - 1] = 0
for i in range(n - 2, n - 1):
if result[i] > 0:
index[i - 1] = 1
else:
index[i - 1] = 0
count = sum(index)
# print "The number of equilibria is"
return count
# print "Excess Demand funciton on the grid:"
# print result
# print "Index when excess demand goes from possitive to negative"
# print index
def __rmul__(self, other):
economy = Economy(other * self.consumers)
return economy
def equilibrium(self, startbracket=None):
def g(x):
return self.excessDemandGood0(x)
if startbracket == None:
startbracket = [1e-10, 1-1e-10]
eqPrice1 = brentq(g, startbracket[0], startbracket[1])
return array([eqPrice1, 1 - eqPrice1])
def __len__(self):
return len(self.consumers)
def __str__(self):
resultString = 'Economy with ' + str(len(self)) + ' consumers.\n'
for consumer in self.consumers:
resultString = resultString + str(consumer) + '\n'
return resultString
I get the error when implementing the following stats() function which calls on randomEconEq():
def randomEcon(e1=[1, 0], e2=[0, 1], iterate_max=100):
rho1 = random.uniform(-8, -1)
rho2 = random.uniform(-8, -1)
alpha1 = random.uniform(0, 1)
alpha2 = random.uniform(0, 1)
x = Consumer(endowment=e1, alpha=alpha1, rho=rho1)
y = Consumer(endowment=e2, alpha=alpha2, rho=rho2)
econ = Economy([x, y])
return econ
def randomEconEq(iterate_max=100):
iterate = 0
eq_vec = []
start = time()
while iterate < iterate_max:
iterate += 1
econ = randomEcon()
equilibria = econ.numEquilibria()
eq_vec.append(equilibria)
# print eq_vec
if (econ.numEquilibria() > 1):
print "Number of multiple equilibria is " + \
str(econ.numEquilibria())
print str(econ)
print str(eq_vec)
end = time()
totaltime = end - start
#print('Total Time is ' + str(totaltime))
return eq_vec
def stats(eq_vec, iterate_max):
one_eq = zeros(len(eq_vec))
three_eq = zeros(len(eq_vec))
five_eq = zeros(len(eq_vec))
more_eq = zeros(len(eq_vec))
# print (eq_vec)
for i in range(len(eq_vec)):
if eq_vec[i] == 1:
one_eq[i] = 1
if eq_vec[i] == 3:
three_eq[i] = 1
if eq_vec[i] == 5:
five_eq[i] = 1
if eq_vec[i] > 5:
more_eq[i] = 1
Eq1 = sum(one_eq)
Eq3 = sum(three_eq)
Eq5 = sum(five_eq)
EqMore = sum(more_eq)
prob1 = float((Eq1 / iterate_max) * 100)
prob3 = float((Eq3 / iterate_max) * 100)
prob5 = float((Eq5 / iterate_max) * 100)
probMore = float((EqMore/iterate_max) * 100)
print ('The Vector of the number of equililbria is:' + str(eq_vec))
print ('Probability of 1 equilibrium is (percent) ' + str(prob1))
print ('Probability of 3 equilibria is (percent) ' + str(prob3))
print ('Probability of 5 equilibria is (percent) ' + str(prob5))
print ('Probability of 1 equilibria is (percent) ' + str(probMore))
eq_vec = randomEconEq(100)
stats(eq_vec, 100)
The error appears in the last two lines of code when implementing the function stats().
An example which creates the error is:
stats(randomEconEq(100), 100)
and the complete traceback is:
>>> stats(randomEconEq(100), 100)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not callable