linked list ==> Which one is correct implementation of linked list - linked-list

I have two set of codes :
class node :
def __init__(self,data=None):
self.data = data # Assign data
self.next = None # Initialize
class linked_list :
def __init__(self):
self.head = node()
def append(self,data):
new_node = node(data)
cur = self.head
while cur.next!= None :
cur = cur.next
cur.next = new_node
def display(self):
elements = []
cur_node = self.head
while cur_node.next !=None:
cur_node = cur_node.next
elements.append(cur_node.data)
print(elements)
upon calling it
mylist = linked_list() #initialize linked list
mylist.append(3) #appending elements
mylist.append(4) #appending elements
mylist.append(5) #appending elements
mylist.append(6) #appending elements
mylist.display() #calling display
it Returns [3,4,5,6]
And
class linkedListNode :
def __init__(self,data= None):
self.data = data
self.nextNode = None
class linkedList:
def __init__(self):
self.head = linkedListNode()
def addNode(self,data):
newNode = linkedListNode(data)
if not self.head :
self.head = newNode
else :
newNode.nextNode = self.head
self.head = newNode
def displayList(self):
elements = []
cursor = self.head
while cursor.nextNode!=None:
elements.append(cursor.data)
cursor = cursor.nextNode
return elements
Upon running returning :
mylist = linkedList()
mylist.addNode(3)
mylist.addNode(4)
mylist.addNode(5)
mylist.addNode(6)
myLinkedListElements = mylist.displayList()
print(myLinkedListElements)
it Returns [6,5,4,3]
Which is right ?
This should be like this as per my understanding :
Head/first node -> 2nd node ->last node -> null
Pointers pointing towards one another. last node pointing to null.
So I think 6 should be the new head node

Related

Spawning an Object with State TTS

I would like to combine two and more objects in the TabletopSimulator. Wenn I spawn the objects I can combine like this page https://kb.tabletopsimulator.com/host-guides/creating-states/. I would like this create with Lua. So I need help... I spawn the objects like here, but I didn`t get two objects with 2 states.
function SpawnLevel1(Obj1, ID)
CID = ID
spawnparamslvl = {
type = 'Custom_Assetbundle',
position = Obj1.getPosition(),
rotation = Obj1.getRotation(),
scale = {x=1, y=1, z=1},
}
paramslvl = {
assetbundle = data[CID].assetbundle,
type = 1,
material = 0,
}
Obj2 = spawnObject(spawnparamslvl)
obj_name = data[CID].display_name
Obj2.setDescription(obj_name)
Obj2.setName(obj_name)
Obj2.setCustomObject(paramslvl)
Obj1.addAttachment(Obj2).SetState(1)
end
function deploy(PID)
display_name = data[PID].display_name
spawnparams = {
type = 'Custom_Assetbundle',
position = self.getPosition(),
rotation = self.getRotation(),
scale = {x=1, y=1, z=1},
}
params = {
assetbundle = data[PID].assetbundle,
type = 0,
material = 0,
}
Spawning(spawnparams, params, display_name, PID)
end
function Spawning(spawnparams, params, display_name, PID)
Obj1 = spawnObject(spawnparamsmain)
ID = PID
Level1 = SpawnLevel1(Obj1, ID)
Obj1.setCustomObject(paramsmain)
Obj1.setName(display_name)
end
Thank you for your help
Radoan
You have to use spawnObjectData or spawnObjectJSON. The format of the "object data" follows the format of the save file.
Rather than hardcoding the large data structures needed to build an object, I'll use existing objects as templates. This is a common practice that's also reflected by the following common idiom for modifying an existing object:
local data = obj.getData()
-- Modify `data` here --
obj.destruct()
obj = spawnObjectData({ data = data })
The following are the relevant bits of "object data" for states:
{ -- Object data (current state)
-- ...
States = {
["1"] = { -- Object data (state 1)
--- ...
},
["3"] = { -- Object data (state 3)
-- ...
},
["4"] = { -- Object data (state 4)
-- ...
}
},
-- ...
}
So you could use this:
function combine_objects(base_obj, objs_to_add)
if not objs[1] then
return base_obj
end
local data = base_obj.getData()
if not data.States then
data.States = { }
end
local i = 1
while data.States[tostring(i)] do i = i + 1 end
i = i + 1 -- Skip current state.
while data.States[tostring(i)] do i = i + 1 end
for _, obj in ipairs(objs_to_add) do
data.States[tostring(i)] = obj.getData()
obj.destruct()
i = i + 1
end
base_obj.destruct()
return spawnObjectData({ data = data })
end

Update each element in linked list with the data of the previous element

Given a one-way linked list, I want to update each element's value with the value of the previous node, for instance, if I have list 1 -> 2 -> 3 -> null, so after the run it'll be new_value -> 1 -> 2 -> null where new_value is given in each iteration.
What I've tried to do (pseudo-code) is:
list_head = head
for i = length-1 to 0:
current = head
do i times:
prev_data = current.data
current = current.next
current.data = prev_data
It doesn't seem to work properly, though...what am I missing? is there another way to do it?
EDIT: assume that new_value is already assigned to head at this point
Thanks in advance
You can implement list with arrays as well. Here is an implementation in javascript. Hope it helps.
var array = [1,2,3]; // list with array
var newValue = 4;
function push(value){
array.pop(); // to remove the last element
array.unshift(value); // to add the new element
console.log(array);
}
push(newValue);
I do not see a reason why you would need to use two loops - I suspect your issue has to do with the "do i times". Instead I would suggest to simply push the values through the list until the tail has been reached (and the last value is dropped). The following is an implementation of that idea using a very simple Node class:
function Node(data,next=null) {
this.data = data;
this.next = next;
this.toString = function() {
if(this.next) return this.data + " -> " + this.next.toString();
else return this.data + " -> null";
}
}
var head = new Node(1,new Node(2,new Node(3)));
console.log(head.toString())
var new_value = 0;
var curr = head;
do{
var old_value = curr.data;
curr.data = new_value;
new_value = old_value;
curr = curr.next;
} while(curr)
console.log(head.toString());

Calculate no of attachments and show it in tree view in openerp 7.0

I am using the following code to add a new column in stock.picking.in object and update the no of attachments to it (to show in tree view the count of attachments).
class stock_picking(osv.osv):
_inherit = "stock.picking.in"
_name = 'stock.picking.in'
def count_attachments(self, cr, uid, ids, fields, arg, context):
obj_attachment = self.pool.get('ir.attachment')
for record in self:
_logger.info("record now in tree view:"+record)
record.attachment_count =0
attachment_ids = obj_attachment.search([('res_model','=','stock.picking.in'),('res_id','=',record.id)]).ids
if attachment_ids:
record.attachment_count =len(attachment_ids)
return record
_columns = {
'attachment_count' :fields.function(count_attachments,method=True,string="Attachment Count" ,type='integer')
}
stock_picking()
Then I have added the following line to the tree view.
<field name="attachment_count">
to show the count in tree view.
However the values are not getting updated and the count_attachments is not getting called.
Any help is appreciated. Thanks in advance!
Try following,
class stock_picking(osv.osv):
_inherit = "stock.picking.in"
_name = 'stock.picking.in'
def count_attachments(self, cr, uid, ids, fields, arg, context=None):
obj_attachment = self.pool.get('ir.attachment')
res = {}
for record in self:
res[record.id] = 0
_logger.info("record now in tree view:"+record)
attachment_ids = obj_attachment.search([('res_model','=','stock.picking.in'),('res_id','=',record.id)]).ids
if attachment_ids:
res[record.id] = len(attachment_ids)
return res
_columns = {
'attachment_count' :fields.function(count_attachments,method=True,string="Attachment Count" ,type='integer')
}

Copy Object Properties to a Map by Value not by Reference

I'm not sure where i'm going wrong, but it seems that I'm not able to copy properties from an object instance and assign them to a map without the values being changed after saving the instance.
This is a sample class:
class Product {
String productName
String proudctDescription
int quantityOnHand
}
Once the form is submitted and it's sent to my controller, I can access the values and manipulate them from the productInstance.properties map that is available from the instance. I want to copy the properties to another map to preserve the values before committing them during an edit. So let's say we are editing a record and these are the values stored in the db: productName = "My Product", productDescription = "My Product Description" and quantityOnHand = 100.
I want to copy them to:
def propertiesBefore = productInstance.properties
This did not work, because when I save the productInstance, the values in propertiesBefore change to whatever the instance had.
So I tried this:
productInstance.properties.each { k,v -> propertiesBefore[k] = v }
Same thing happened again. I am not sure how to copy by value, it seems no matter what I try it copies by reference instead.
EDIT
As per the request of Pawel P., this is the code that I tested:
class Product {
String productName
String productDescription
int quantityOnHand
}
def productInstance = new Product(productName: "Some name", productDescription: "Desciption", quantityOnHand: 10)
def propertiesBefore = [:]
productInstance.properties.each { k,v -> propertiesBefore[k] = (v instanceof Cloneable) ? v.clone() : v }
productInstance.productName = "x"
productInstance.productDescription = "y"
productInstance.quantityOnHand = 9
println propertiesBefore.quantityOnHand // this will print the same as the one after the save()
productInstance.save(flush:true)
println propertiesBefore.quantityOnHand // this will print the same as the one above the save()
Without cloning, copying hash-map [:]'s values to a new hash-map [:]'s space can also be done by "pushing" the first one over, which would achieve the same result that you desired (copy by value)!
def APE = [:]
APE= [tail: 1, body: "hairy", hungry: "VERY!!!"]
def CAVEMAN = [:]
CAVEMAN << APE //push APE to CAVEMAN's space
//modify APE's values for CAVEMAN
CAVEMAN.tail = 0
CAVEMAN.body = "need clothes"
println "'APE': ${APE}"
println "'CAVEMAN': ${CAVEMAN}"
Output ==>
'APE': [tail:1, body:hairy, hungry:VERY!!!]
'CAVEMAN': [tail:0, body:need clothes, hungry:VERY!!!]
The problem is that you actually copy references to variables. To obtain copy of variable you should use clone(). Take a look:
class Product {
String productName
String productDescription
int quantityOnHand
}
def productInstance = new Product(productName: "Some name", productDescription: "Desciption", quantityOnHand: 10)
def propertiesBefore = [:]
productInstance.properties.each { k,v -> propertiesBefore[k] = (v instanceof Cloneable) ? v.clone() : v }
productInstance.productName = "x"
productInstance.productDescription = "y"
productInstance.quantityOnHand = 9
println productInstance.properties
println propertiesBefore
It prints:
[quantityOnHand:9, class:class Product, productName:x, productDescription:y]
[quantityOnHand:10, class:class Product, productName:Some name, productDescription:Desciption]
A simpler example for groovy using Hash-Map [:] can be like this:
def APE = [:]
APE= [tail: 1, body: "hairy", hungry: "VERY!!!"]
def CloneMe = APE //*APE as clone*
def CAVEMAN = [:] //*copy APE's values over thru mapping the clone*
CloneMe.each { key,value -> CAVEMAN[key] = (value instanceof Cloneable) ? value.clone() : value }
println "'CloneMe': ${CloneMe}"
//change some of the clone's values for CAVEMAN
CAVEMAN.tail = 0
CAVEMAN.body = "need clothes"
println "'APE': ${APE}"
println "'CAVEMAN': ${CAVEMAN}"
Output ==>
'CloneMe': [tail:1, body:hairy, hungry:VERY!!!]
'APE': [tail:1, body:hairy, hungry:VERY!!!]
'CAVEMAN': [tail:0, body:need clothes, hungry:VERY!!!]

Force-directed graphing algorithm having strange results

I've been trying to create a force-directed graphing algorithm with RBX::Lua. So far, everything seems to be working absolutely fine mathematically, but there are a couple of things that make absolutely no sense at all.
My problem is, the nodes experience an unexpected attraction to one another, whether connected or not. What the program does is, all of the unconnected nodes repel each other like a magnet, and all of the connected nodes attract each other like a spring.
I don't see anything in my code that could be causing this.
-- Creating an icon to represent each node
local n = Instance.new("Part", Instance.new("Humanoid", Instance.new("Model")).Parent)
n.Name = "Head"
local tor = Instance.new("Part", n.Parent)
tor.Name = "Torso"
tor.Anchored = true
tor.FormFactor = "Custom"
tor.Transparency = 1
local h = n.Parent.Humanoid
h.Health = 0
h.MaxHealth = 0
h.Parent.Name = "Node"
n.FormFactor = "Symmetric"
n.Shape = "Ball"
n.TopSurface, n.BottomSurface = "Smooth", "Smooth"
n.Size = Vector3.new(2,2,2)
n.BrickColor = BrickColor.new("Institutional white")
n.Anchored = true
Instance.new("Vector3Value", n).Name = "velocity"
-- List of connections and nodes
local t = {
["Metals"]={"Gold", "Silver", "Steel", "Brass", "Mercury"},
["Alloys"]={"Steel", "Brass"},
["Noble Gasses"]={"Helium", "Argon", "Krypton", "Xenon"},
["Water"]={"Hydrogen", "Oxygen"},
["Liquids"]={"Water", "Mercury"},
["Alone"]={}
}
--[[ -- Separate list for testing, commented out
local t = {
["A"]={"B"},
["B"]={"C"},
["C"]={"D"},
["D"]={"E"},
["E"]={"F"}
}]]
-- Add all of the nodes to the workspace, position them randomly
for _, v in pairs(t) do
local p1 = workspace:findFirstChild(_) or n.Parent:clone()
p1.Name = _
p1.Parent = workspace
p1.Head.CFrame = CFrame.new(Vector3.new(math.random(-100000,100000)/1000,0,math.random(-100000,100000)/1000))
for a, b in ipairs(v) do
if v ~= b then
local p2 = workspace:findFirstChild(b) or n.Parent:clone()
p2.Name = b
p2.Parent = workspace
p2.Head.CFrame = CFrame.new(Vector3.new(math.random(-100000,100000)/1000,0,math.random(-100000,100000)/1000))
local at = p1:findFirstChild(b) or Instance.new("ObjectValue", p1)
at.Name = b
local at2 = at:clone()
at2.Parent = p2
at2.Name = _
local lasso = Instance.new("SelectionPartLasso", p2.Head)
lasso.Name = "Link"
lasso.Humanoid = p2.Humanoid
lasso.Part = p1.Head
lasso.Color = BrickColor.new("Institutional white")
end
end
end
local parts = {} -- List of all of the nodes themselves
-- Add all of the nodes to the list
for _, v in ipairs(workspace:GetChildren()) do
if v.ClassName == "Model" then
table.insert(parts, v.Head)
end
end
while wait() do -- Repeat forever waiting one frame between loops
for _, v in ipairs(parts) do
for a, b in ipairs(parts) do
if v ~= b then
local dif = b.Position-v.Position
local force = 0
if b.Parent:findFirstChild(v.Name) then -- if b is conneted to v
force = (dif.magnitude-30)/100
else
force = force - 1/dif.magnitude^2
end
local add = dif/dif.magnitude*force
add = add - v.Position/v.Position.magnitude/100
v.velocity.Value = v.velocity.Value + add
end
end
v.CFrame = v.CFrame + v.velocity.Value -- Postion the node
v.velocity.Value = v.velocity.Value*.2 -- Damping
v.CFrame = v.CFrame-v.CFrame.p*Vector3.new(0,1,0) -- Force 2D (optional)
v.Parent.Torso.CFrame = v.CFrame -- To display links connecting nodes
end
end
I found the problem. "b.Parent:findFirstChild(v.Name)" should have been "b.Parent:findFirstChild(v.Parent.Name)," otherwise it will just return true every time. This is just because of how I have the display of the nodes set up.

Resources