Binary Search Tree Algorithm (BST) currentNode = self - oop

class BST:
def init(self, value):
self.value = value
self.left = None
self.right = None
def insert(self, value):
currentNode = self
print(currentNode)
while True:
if value < currentNode.value:
if currentNode.left is None:
currentNode.left = BST(value)
break
else:
currentNode = currentNode.left
else:
if currentNode.right is None:
currentNode.right = BST(value)
break
else:
currentNode = currentNode.right
return self
I am confused about currentNode = self. What value is this referring to? I am assuming that the 'value' is referring to the value from the parameter but where would currentNode.value come from, the init constructor?

Related

how to solve vector-based variable/constraints in python pyomo

enter image description here
I am solving this problem, i write code. but getting error at last line ' results'
please anyone know how to deal vector based dynamic optimization please let me know.
model = ConcreteModel()
model.num_itter = Param(initialize = 0)
global p_
p_ = model.num_itter
# print(value(p_))
torq = np.zeros((14,6))
# global p_
def M_func(model,i):
return np.array(Mqn( *value(model.q[i]) ))
def sai_func(model, i):
return np.array(sain( *value(model.q[i]) ))
def sai_func_T(model, i):
return np.array(sain( *value(model.q[i]) )).T
def c_func(model, i):
return np.array(cqn(*np.append(value(model.q[0]),value(model.u[0])) ))
def dsai_dt_func(model, i):
return np.array(saidn(*np.append(value(model.q[0]),value(model.u[0])) ))
def first_eq(model,i):
return value(model.M[i])#value(model.q[i])-\
value(model.sai[i]).T#value(model.lm[i])+\
torq#value(model.tu[i])
def second_eq(model,i):
return value(model.sai[i])#value(model.a[i])
def third_eq(model,i):
return (-value(model.dsai_dt[i])#value(model.u[i])).reshape(10,1)
def solu_f(model,i):
global p_
s_ = solu10[int(p_/2),:]
# time.sleep(2)
p_= p_+1
print('p',p_)
return s_
def init_q(model,i):
return solu10[i,:]
def init_u(model,i):
return np.zeros((14,))
def init_tu(model,i):
return np.zeros((6,))
def init_lm(model,i):
return np.zeros((10,))
def init_a(model,i):
return np.zeros((14,))
# Define the time horizon
t0 =0 ;tf =40
model.t = ContinuousSet(bounds=(t0,tf))
# measurements = {_: solu10[_,:] for _ in range(len(solu10))}
# Define the state variables, control inputs, and other variables
model.time_points = Set(initialize=range(200))
model.q = Var(model.t,initialize=init_q)
model.u = Var(model.t,initialize=init_u)
model.a = Var(model.t,initialize=init_a)
model.tu =Var(model.t,initialize=init_tu)
model.lm = Var(model.t,initialize=init_lm)
model.dqdt = DerivativeVar(model.q,wrt=model.t)
model.dudt = DerivativeVar(model.u,wrt=model.t)
# Define the parameters
model.M = Param(model.t,mutable=True, initialize=M_func,within=Any)
model.sai = Param(model.t,mutable=True, initialize=sai_func,within=Any)
model.c = Param(model.t,mutable=True, initialize=c_func,within=Any)
model.dsai_dt = Param(model.t,mutable=True, initialize=dsai_dt_func,within=Any)
model.first_meq = Param(model.t,mutable =True, initialize = first_eq,within = Any)
model.solu = Param(model.t,mutable = True,initialize = solu_f, within =Any)
model.second_meq = Param(model.t,mutable =True, initialize = second_eq,within = Any)
model.third_meq = Param(model.t,mutable =True, initialize = third_eq,within = Any)
# print(value(p_))
# Define the Constraint equations
def dyn_eq_1(model,i):
return model.first_meq[i]==-model.c[i]
def dyn_eq_2(model,i):
return model.second_meq[i]==model.third_meq[i]
def vel_constraint(model,i):
return model.dqdt[i]==model.u[i]
def acc_constraint(model,i):
return model.dudt[i]==model.a[i]
def path_constraint(model, i):
return model.q[i] == model.solu[i]
model.dyn_eq_1s= Constraint(model.t, rule=dyn_eq_1)
model.dyn_eq_2s= Constraint(model.t, rule=dyn_eq_2)
model.vel_constraints = Constraint(model.t, rule= vel_constraint)
model.acc_constraints = Constraint(model.t, rule= acc_constraint)
model.path_constraints = Constraint(model.t, rule=path_constraint)
# Define the bounds
u_lb = -np.array([2,2,0.5,0.34,float('inf'),float('inf'),0.20,28,float('inf'),float('inf'),0.20,28,0.25,0.25])
u_ub = [2,2,0.5,0.34,None,None,0.20,28,None,None,0.20,28,0.25,0.25]
a_lb = -np.array([1.5,1.5,0.2,0.10,float('inf'),float('inf'),0.10,5,float('inf'),float('inf'),0.10,5,0.10,0.10])
a_ub = [1.5,1.5,0.2,0.10,None,None,0.10,5,None,None,0.10,5,0.10,0.10]
tu_lb = -np.array([4,0.5,4,0.5,4,4])
tu_ub = [4,4,4,4,4,4]
model.u.setlb(u_lb)
model.u.setub(u_ub)
model.a.setlb(a_lb)
model.a.setub(a_ub)
model.tu.setlb(tu_lb)
model.tu.setub(tu_ub)
def u_nes_fn(model,i):
u_nes = np.array([])
for _ in [6,7,10,11,12,13]:
u_nes = np.append(u_nes,value(model.u[i])[_])
return u_nes.astype('float64')
model.u_nes = Param(model.t,initialize= u_nes_fn,within = Any)
# Define the objective function
def tu_u_(model,i):
return np.linalg.norm(value( model.u_nes[i]*model.tu[i]*model.u_nes[i]*model.tu[i]))
model.tu_u = Integral(model.t,wrt=model.t,rule = tu_u_)
def objfun(model):
return model.tu_u
model.obj = Objective(rule = objfun)
# Define the solver and solve the problem
solver = SolverFactory('ipopt')
results = solver.solve(model)
ValueError Traceback (most recent call last)
c:\Users\pyomo_opti.ipynb Cell 16 in <cell line: 11>()
9 # Define the solver and solve the problem
10 solver = SolverFactory('ipopt')
---> 11 results = solver.solve(model)
File c:\Users\AppData\Local\Programs\Python\Python310\lib\site-packages\pyomo\opt\base\solvers.py:570, in OptSolver.solve(self, *args, **kwds)
565 try:
566
...
File pyomo\repn\plugins\ampl\ampl_.pyx:410, in pyomo.repn.plugins.ampl.ampl_.ProblemWriter_nl.call()
File pyomo\repn\plugins\ampl\ampl_.pyx:1072, in pyomo.repn.plugins.ampl.ampl_.ProblemWriter_nl._print_model_NL()
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Colliderect function not working in Pygame

So I am making a pong game in pygame while implementing oop. My problem is the colliderect function is giving me the error " ball_hitter object has no attribute 'colliderect'". I've used the colliderect function before but it's not working for me this time.
Code:
import pygame
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((500,500))
pygame.display.set_caption("Pong With Classes!")
#Variables
red = (255,0,0)
blue = (0,0,255)
black = (0,0,0)
clock = pygame.time.Clock()
#End of Variables
class ball_hitter:
def __init__(self,x,y,length,width,color):
self.x = x
self.y = y
self.length = length
self.width = width
self.color = color
self.left = False
self.right = False
def draw_ball_hitter(self):
screen.fill(black)
pygame.draw.rect(screen,self.color,(self.x,self.y,self.length,self.width))
#Paddle creation
paddle = ball_hitter(250,400,130,20,red)
#End of Paddle Creation
class thing_thats_being_hit:
def __init__(self,x,y,color):
self.x = x
self.y = y
self.radius = 27
self.color = color
self.speed_x = -4
self.speed_y = 4
def draw_googlyball(self):
pygame.draw.circle(screen,self.color,(self.x,self.y),self.radius)
def move(self):
self.x += self.speed_x
self.y += self.speed_y
#Ball Creation
ball = thing_thats_being_hit(200,50,blue)
#End of Ball Creation
#Paddle Collision
if paddle.colliderect(ball):
print("It Worked!")
#End Of Paddle Collision
ball.move()
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
paddle.left = True
if event.key == pygame.K_RIGHT:
paddle.right = True
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
paddle.left = False
if event.type == pygame.KEYUP:
if event.key == pygame.K_RIGHT:
paddle.right = False
paddle.draw_ball_hitter()
ball.draw_googlyball()
if paddle.left == True:
paddle.x = paddle.x - 2
if paddle.right == True:
paddle.x = paddle.x + 2
if ball.x <= 0:
ball.speed_x*=-1
if ball.x >= 500:
ball.speed_x *= -1
if ball.y >= 500:
pygame.quit()
ball.move()
pygame.display.update()
clock.tick(100)
I would appreciate it if someone could give me a fixed code and explain is to me.
See How do I detect collision in pygame?. colliderect is a method of pygame.Rect. Therefore you need to create pygame.Rect objects. Also you have to do the collision test in the application loop instead of before the application loop:
while True:
# [...]
paddle_rect = pygame.Rect(paddle.x, paddle.y, paddle.width, paddle. length)
ball_rect = pygame.Rect(ball.x - ball.radius, ball.y - ball.radius,
ball.radius * 2, ball.radius * 2)
if paddle_rect.colliderect(ball_rect):
print("It Worked!")

How to extract entity from Microsoft LUIS using python?

Following the example code in this link, I can extract the intent using "intent_result.intent_id", but how can I extract the entity/entities of the utterance?
'''
import azure.cognitiveservices.speech as speechsdk
print("Say something...")
intent_config = speechsdk.SpeechConfig(subscription="YourLanguageUnderstandingSubscriptionKey", region="YourLanguageUnderstandingServiceRegion")
intent_recognizer = speechsdk.intent.IntentRecognizer(speech_config=intent_config)
model = speechsdk.intent.LanguageUnderstandingModel(app_id="YourLanguageUnderstandingAppId")
intents = [
(model, "HomeAutomation.TurnOn"),
(model, "HomeAutomation.TurnOff")
]
intent_recognizer.add_intents(intents)
start_continuous_recognition() instead.
intent_result = intent_recognizer.recognize_once()
if intent_result.reason == speechsdk.ResultReason.RecognizedIntent:
print("Recognized: \"{}\" with intent id `{}`".format(intent_result.text, intent_result.intent_id))
elif intent_result.reason == speechsdk.ResultReason.RecognizedSpeech:
print("Recognized: {}".format(intent_result.text))
elif intent_result.reason == speechsdk.ResultReason.NoMatch:
print("No speech could be recognized: {}".format(intent_result.no_match_details))
elif intent_result.reason == speechsdk.ResultReason.Canceled:
print("Intent recognition canceled: {}".format(intent_result.cancellation_details.reason))
if intent_result.cancellation_details.reason == speechsdk.CancellationReason.Error:
print("Error details: {}".format(intent_result.cancellation_details.error_details))
# </IntentRecognitionOnceWithMic>
'''
from azure.cognitiveservices.language.luis.runtime import LUISRuntimeClient
from msrest.authentication import CognitiveServicesCredentials
from azure.cognitiveservices.language.luis.runtime.models import EntityModel
from collections import OrderedDict
from typing import Union
class LuisPredictionClass():
def __init__(self, endpoint, appIdLUIS, predictionResourcePrimaryKey):
self.endpoint = endpoint
self.appIdLUIS = appIdLUIS
self.predictionResourcePrimaryKey = predictionResourcePrimaryKey
self.client = LUISRuntimeClient(self.endpoint, CognitiveServicesCredentials(self.predictionResourcePrimaryKey))
def find_LUIS_result(self,Text):
luis_result = self.client.prediction.resolve(self.appIdLUIS,Text)
return luis_result
def extract_entity_value(self,entity: EntityModel) -> object:
if (entity.additional_properties is None or "resolution" not in entity.additional_properties ):
return entity.entity
resolution = entity.additional_properties["resolution"]
if entity.type.startswith("builtin.datetime."):
return resolution
if entity.type.startswith("builtin.datetimeV2."):
if not resolution["values"]:
return resolution
resolution_values = resolution["values"]
val_type = resolution["values"][0]["type"]
timexes = [val["timex"] for val in resolution_values]
distinct_timexes = list(OrderedDict.fromkeys(timexes))
return {"type": val_type, "timex": distinct_timexes}
if entity.type in {"builtin.number", "builtin.ordinal"}:
return self.number(resolution["value"])
if entity.type == "builtin.percentage":
svalue = str(resolution["value"])
if svalue.endswith("%"):
svalue = svalue[:-1]
return self.number(svalue)
if entity.type in {
"builtin.age",
"builtin.dimension",
"builtin.currency",
"builtin.temperature",
}:
units = resolution["unit"]
val = self.number(resolution["value"])
obj = {}
if val is not None:
obj["number"] = val
obj["units"] = units
return obj
value = resolution.get("value")
return value if value is not None else resolution.get("values")
def extract_normalized_entity_name(self,entity: EntityModel) -> str:
# Type::Role -> Role
type = entity.type.split(":")[-1]
if type.startswith("builtin.datetimeV2."):
type = "datetime"
if type.startswith("builtin.currency"):
type = "money"
if type.startswith("builtin."):
type = type[8:]
role = (
entity.additional_properties["role"]
if entity.additional_properties is not None
and "role" in entity.additional_properties
else ""
)
if role and not role.isspace():
type = role
return type.replace(".", "_").replace(" ", "_")
Now you can run it as:
LuisPrediction = LuisPredictionClass("<<endpoint>>", "<<appIdLUIS>>", "<<predictionResourcePrimaryKey>>")
luis_result = LuisPrediction.find_LUIS_result("<<YOUR STRING HERE>>")
if len(luis_result.entities) > 0:
for i in luis_result.entities:
print(LuisPrediction.extract_normalized_entity_name(i),' : ',LuisPrediction.extract_entity_value(i))

What's more elegant way to check for anagram?

I can't imagine better way to check for anagram than my solution:
def anagram(self,s,t):
if len(s) != len(t):
return False
else:
for elem1 in s:
current_looking = elem1
if current_looking in t:
current_index = t.index(current_looking)
t = t[:current_index] + t[current_index+1:]
else:
return False
return True
Or this:
def anagram(s1,s2):
return sorted(s1) == sorted(s2)
Or maybe there is another one?
collections.Counter is as succinct and faster than the sorting approach (O(n) < O(n log(n))):
from collections import Counter
def anagram(a, b):
return Counter(a) == Counter(b)
You can boost performance at the expense of terseness:
def anagram(a, b):
return len(a) == len(b) and Counter(a) == Counter(b)

How to resize rows in a QTreeView and a QStandardItemModel?

I'd like to set my rows to a fixed height. I've found an example using QAbstractItemModel, but I'm using QStandardItemModel. When I run the app, the QTreeView is blank. Any thoughts on how I could get this working for a QStandardItemModel?
import sys
from PySide import QtCore, QtGui
class TreeItem(object):
def __init__(self, data, parent=None):
self.parentItem = parent
self.data = data
self.childItems = []
def appendChild(self, item):
self.childItems.append(item)
def row(self):
if self.parentItem:
return self.parentItem.childItems.index(self)
return 0
class TreeModel(QtCore.QAbstractItemModel):
def __init__(self, parent=None):
super(TreeModel, self).__init__(parent)
self.rootItem = TreeItem(None)
for i, c in enumerate("abcdefg"):
child = TreeItem([i, c], self.rootItem)
self.rootItem.appendChild(child)
parent = self.rootItem.childItems[1]
child = TreeItem(["down", "down"], parent)
parent.appendChild(child)
def columnCount(self, parent):
return 2
def data(self, index, role):
if not index.isValid():
return None
if role == QtCore.Qt.DisplayRole:
item = index.internalPointer()
return item.data[index.column()]
elif role == QtCore.Qt.SizeHintRole:
print "giving size hint"
return QtCore.QSize(10, 10)
return None
def flags(self, index):
if not index.isValid():
return QtCore.Qt.NoItemFlags
return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable
def headerData(self, section, orientation, role):
if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
return ["A", "B"][section]
return None
def index(self, row, column, parent):
if not self.hasIndex(row, column, parent):
return QtCore.QModelIndex()
if not parent.isValid():
parentItem = self.rootItem
else:
parentItem = parent.internalPointer()
childItem = parentItem.childItems[row]
if childItem:
return self.createIndex(row, column, childItem)
else:
return QtCore.QModelIndex()
def parent(self, index):
if not index.isValid():
return QtCore.QModelIndex()
parentItem = index.internalPointer().parentItem
if parentItem == self.rootItem:
return QtCore.QModelIndex()
return self.createIndex(parentItem.row(), 0, parentItem)
def rowCount(self, parent):
if parent.column() > 0:
return 0
if not parent.isValid():
parentItem = self.rootItem
else:
parentItem = parent.internalPointer()
return len(parentItem.childItems)
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
model = TreeModel()
view = QtGui.QTreeView()
view.setModel(model)
view.setWindowTitle("Simple Tree Model")
view.show()
sys.exit(app.exec_())
Also, I've been looking around for the meaning of the term delegate in Qt, but the concept still isn't clicking in my head yet. Any insight into that would be appreciated as well!
You generally do this using QItemDelegates (or QStyledItemDelegate if you want stylesheet styling to work) by overriding the sizeHint method and always returning a size of a fixed height.
class MyDelegate(QtGui.QStyledItemDelegate):
def sizeHint(self, option, index):
my_fixed_height = 30
size = super(MyDelegate, self).sizeHint(option, index)
size.setHeight(my_fixed_height)
return size
view = QtGui.QTreeView()
delegate = MyDelegate()
view.setItemDelegate(delegate)