I'm trying to have a class (dprObject) that is a container for several dprVariables
each variable has a list with integers (for now)
but when I change something to one variable, it changes to all the other variables
in this case, the output I get is
score: 5, 6, 3, 4,
position: 5, 6, 3, 4,
but I want to see
score: 5, 6,
position: 3, 4,
#!/usr/bin/python3
import pprint
def main():
d = dprObject() #new dpr object
score = dprVariable(d, "score") #new dpr variable
score.set(5) #set value
score.set(6)
position = dprVariable(d, "position")
position.set(3)
position.set(4)
print(d)
print("done")
class dprObject:
var = []
t = 0
def __init__(self):
pass
def __str__(self):
toReturn = ""
for v in self.var:
toReturn += v.toString()
return toReturn
def tick(self):
self.t += 1
def addVariable(self,v):
self.var.append(v)
class dprVariable:
name = ""
value = None
val = []
def __init__(self,d,name):
self.name = name
d.addVariable(self)
def __str__(self):
return self.toString()
def toString(self):
toReturn = self.name + ": "
for v in self.val:
toReturn += str(v) + ", "
return toReturn
def set (self, value):
self.value = value
self.val.append(value)
#class DprValue:
if __name__ == "__main__":
main()
any help would be appreciated
thanks
This code:
class dprVariable:
...
val = []
makes val a class variable, shared between all instances of dprVariable. To have one val per instance, you need to do this:
class dprVariable:
def __init__(self, ...):
self.val = []
(dprObject has the same problem.)
Related
This is the python code which uses A* algorithm for finding solution for 8 puzzle problems, I got some error messages, how can I fix it?(The error message is under the code)
There are several object-oriented programming concepts for Problems class, Node class that are implemented to express the problem solution search that you need to understand in order to make the Python program complete. The priority queue is to make the nodes to be explored to be sorted according to their f-evaluation function score and return the min one as the first node to be searched next.
There is also a memorize function to memorize the heuristic value of state as a look-up table so that you don’t need to calculate the redundant computing of heuristic estimation value, so you can ignore it at this point if you don’t understand.
The components you need to implement is to make the abstract part of the program realizable for 8 -puzzle with the successor methods attached to a problem class which consists of initial state and goal state. Make sure the program can run correctly to generate the solution sequence that move the empty tile so that the 8-puzzle can move "Up", "Down", "Left", "Right", from initial state to goal state.
import math
infinity = math.inf
from itertools import chain
import numpy as np
import bisect
class memoize:
def __init__(self, f, memo={}):
self.f = f
self.memo = {}
def __call__(self, *args):
if not str(args) in self.memo:
self.memo[str(args)] = self.f(*args)
return self.memo[str(args)]
def coordinate(state):
index_state = {}
index = [[0,0], [0,1], [0,2], [1,0], [1,1], [1,2], [2,0], [2,1], [2,2]]
for i in range(len(state)):
index_state[state[i]] = index[i]
return index_state
def getInvCount(arr):
inv_count = 0
empty_value = -1
for i in range(0, 9):
for j in range(i + 1, 9):
if arr[j] != empty_value and arr[i] != empty_value and arr[i] > arr[j]:
inv_count += 1
return inv_count
def isSolvable(puzzle) :
inv_count = getInvCount([j for sub in puzzle for j in sub])
return (inv_count % 2 == 0)
def linear(state):
return sum([1 if state[i] != goal[i] else 0 for i in range(9)])
#memoize
def manhattan(state):
index_goal = coordinate(goal)
index_state = coordinate(state)
mhd = 0
for i in range(9):
for j in range(2):
mhd = abs(index_goal[i][j] - index_state[i][j]) + mhd
return mhd
#memoize
def sqrt_manhattan(state):
index_goal = coordinate(goal)
index_state = coordinate(state)
mhd = 0
for i in range(9):
for j in range(2):
mhd = (index_goal[i][j] - index_state[i][j])**2 + mhd
return math.sqrt(mhd)
#memoize
def max_heuristic(state):
score1 = manhattan(state)
score2 = linear(state)
return max(score1, score2)
class PriorityQueueElmt:
def __init__(self,val,e):
self.val = val
self.e = e
def __lt__(self,other):
return self.val < other.val
def value(self):
return self.val
def elem(self):
return self.e
class Queue:
def __init__(self):
pass
def extend(self, items):
for item in items: self.append(item)
class PriorityQueue(Queue):
def __init__(self, order=min, f=None):
self.A=[]
self.order=order
self.f=f
def append(self, item):
queueElmt = PriorityQueueElmt(self.f(item),item)
bisect.insort(self.A, queueElmt)
def __len__(self):
return len(self.A)
def pop(self):
if self.order == min:
return self.A.pop(0).elem()
else:
return self.A.pop().elem()
# Heuristics for 8 Puzzle Problem
class Problem:
def __init__(self, initial, goal=None):
self.initial = initial; self.goal = goal
def successor(self, state):
reachable = []
def get_key(val):
for key, value in index_state.items():
if val == value:
return key
return -1
def candidate(state, Position):
state = state.copy()
zero_index = state.index(0)
swap_index = state.index(get_key(Position))
state[zero_index], state[swap_index] = state[swap_index], state[zero_index]
return state
index_state = coordinate(state)
zero_position = index_state[0]
move_pair = {"left":[zero_position[0], zero_position[1] - 1],
"right":[zero_position[0], zero_position[1] + 1],
"up":[zero_position[0] - 1, zero_position[1]],
"down":[zero_position[0] + 1, zero_position[1]]
}
for action, position in move_pair.items():
#print(action, position)
if get_key(position) != -1:
reachable.append((action, candidate(state, position)))
#print(reachable)
return reachable
def goal_test(self, state):
return state == self.goal
def path_cost(self, c, state1, action, state2):
return c + 1
def value(self):
abstract
class Node:
def __init__(self, state, parent=None, action=None, path_cost=0, depth =0):
self.parent = parent
if parent:
self.depth = parent.depth + 1
else:
self.depth = 0
self.path_cost = path_cost
self.state = state
if action:
self.action = action
else: self.action = "init"
def __repr__(self):
return "Node state:\n " + str(np.array(self.state).reshape(3,3)) +"\n -> action: " + self.action + "\n -> depth: " + str(self.depth)
def path(self):
x, result = self, [self]
while x.parent:
result.append(x.parent)
x = x.parent
return result
def expand(self, problem):
for (act,n) in problem.successor(self.state):
if n not in [node.state for node in self.path()]:
yield Node(n, self, act,
problem.path_cost(self.path_cost, self.state, act, n))
def graph_search(problem, fringe):
closed = {}
fringe.append(Node(problem.initial,depth=0))
while fringe:
node = fringe.pop()
if problem.goal_test(node.state):
return node
if str(node.state) not in closed:
closed[str(node.state)] = True
fringe.extend(node.expand(problem))
return None
def best_first_graph_search(problem, f):
return graph_search(problem, PriorityQueue(min, f))
def astar_search(problem, h = None):
h = h or problem.h
def f(n):
return max(getattr(n, 'f', -infinity), n.path_cost + h(n.state))
return best_first_graph_search(problem, f)
def print_path(path, method):
print("*" * 30)
print("\nPath: (%s distance)" % method)
for i in range(len(path)-1, -1, -1):
print("-" * 15)
print(path[i])
goal = [1, 2, 3, 4, 5, 6, 7, 8, 0]
# Solving the puzzle
puzzle = [7, 2, 4, 5, 0, 6, 8, 3, 1]
if(isSolvable(np.array(puzzle).reshape(3,3))): # even true
# checks whether the initialized configuration is solvable or not
print("Solvable!")
problem = Problem(puzzle,goal)
path = astar_search(problem, manhattan).path()
print_path(path, "manhattan")
path = astar_search(problem, linear).path()
print_path(path, "linear")
path = astar_search(problem, sqrt_manhattan).path()
print_path(path, "sqrt_manhattan")
path = astar_search(problem, max_heuristic).path()
print_path(path, "max_heuristic")
else :
print("Not Solvable!") # non-even false
TypeError Traceback (most recent call last)
<ipython-input-124-2a60ddc8c009> in <module>
9 problem = Problem(puzzle,goal)
10
---> 11 path = astar_search(problem, manhattan).path()
12 print_path(path, "manhattan")
13
<ipython-input-123-caa97275712e> in astar_search(problem, h)
18 def f(n):
19 return max(getattr(n, 'f', -infinity), n.path_cost + h(n.state))
---> 20 return best_first_graph_search(problem, f)
21
22 def print_path(path, method):
<ipython-input-123-caa97275712e> in best_first_graph_search(problem, f)
12
13 def best_first_graph_search(problem, f):
---> 14 return graph_search(problem, PriorityQueue(min, f))
15
16 def astar_search(problem, h = None):
<ipython-input-123-caa97275712e> in graph_search(problem, fringe)
8 if str(node.state) not in closed:
9 closed[str(node.state)] = True
---> 10 fringe.extend(node.expand(problem))
11 return None
12
<ipython-input-121-e5a968bd54f0> in extend(self, items)
18
19 def extend(self, items):
---> 20 for item in items: self.append(item)
21
22 class PriorityQueue(Queue):
<ipython-input-122-db21613469b9> in expand(self, problem)
69
70 def expand(self, problem):
---> 71 for (act,n) in problem.successor(self.state):
72 if n not in [node.state for node in self.path()]:
73 yield Node(n, self, act,
TypeError: cannot unpack non-iterable int object
I got some error messages, how can I fix it?
There is one error message, The pieces of codes you get in the error message are the stack trace, which might help you to know how the execution got at the final point where the error occurred. In this case that is not so important. The essence of the error is this:
for (act,n) in problem.successor(self.state)
TypeError: cannot unpack non-iterable int object
So this means that the successor method returned an int instead of a list.
Looking at the code for successor, I notice that it intends to return a list called reachable, but there is a return statement right in the middle of the code, leaving the largest part of that code unexecuted (so-called "dead code"):
return state
This statement makes no sense where it is positioned. It seems to be an indentation problem: that return belongs inside the function just above it, like this:
def candidate(state, Position):
state = state.copy()
zero_index = state.index(0)
swap_index = state.index(get_key(Position))
state[zero_index], state[swap_index] = state[swap_index], state[zero_index]
return state # <-- indentation!
I wrote a simple Proxy class in python3, but I have a problem with "was_called" function
class Proxy:
last_invoked = ""
calls = {}
def __init__(self, obj):
self._obj = obj
def __getattr__(self, item):
attrs = dir(self._obj)
if item in attrs:
Proxy.last_invoked = item
if item in Proxy.calls.keys():
Proxy.calls[item] += 1
else:
Proxy.calls[item] = 1
if item in Proxy.calls.keys():
Proxy.calls[item] += 1
else:
Proxy.calls[item] = 1
return getattr(self._obj, item)
else:
raise Exception('No Such Method')
def last_invoked_method(self):
if Proxy.last_invoked == "":
raise Exception('No Method Is Invoked')
else:
return Proxy.last_invoked
def count_of_calls(self, method_name):
if method_name in Proxy.calls.keys():
return Proxy.calls[method_name]
return 0
def was_called(self, method_name):
if method_name in Proxy.calls.keys():
if Proxy.calls[method_name] > 0: return True
return False
class Radio():
def __init__(self):
self._channel = None
self.is_on = False
self.volume = 0
def get_channel(self):
return self._channel
def set_channel(self, value):
self._channel = value
def power(self):
self.is_on = not self.is_on
radio = Radio()
radio_proxy = Proxy(radio)
radio.number = 3
radio_proxy.number = 3
radio_proxy.power()
print(radio_proxy.was_called("number"))
print(radio_proxy.was_called("power"))
"was_called" function is work for functions and attributes that is in radio at first such as "power", but it's not work for new attributes that we add such as "number".
I expect for both print "True", because both of "power" and "number" is called. but first print return False!
What do you suggest?
def Proxy(class_type):
class ProxyClass(class_type):
def __init__(self, *args, **kwargs):
# Set your _calls and _last_invoked here, so that they are not class attributes (and are instead instance attributes).
self._calls = {}
self._last_invoked = ""
# Pass the arguments back to the class_type (in our case Radio) to initialize the class.
super().__init__(*args, **kwargs)
def __getattribute__(self, item):
# We must do this prelimary check before continuing on to the elif statement.
# This is since _calls and _last_invoked is grabbed when self._last_invoked/self._calls is called below.
if item in ("_calls", "_last_invoked"):
return super(ProxyClass, self).__getattribute__(item)
elif not item.startswith("_"):
self._last_invoked = item
self._calls[item] = 1 if item not in self._calls.keys() else self._calls[item] + 1
return super(ProxyClass, self).__getattribute__(item)
def __setattr__(self, item, val):
# Wait until _calls is initialized before trying to set anything.
# Only set items that do not start with _
if not item == "_calls" and not item.startswith("_"):
self._calls[item] = 0
super(ProxyClass, self).__setattr__(item, val)
def last_invoked_method(self):
if self._last_invoked == "":
raise Exception('No Method Is Invoked')
else:
return self._last_invoked
def count_of_calls(self, method_name):
return self._calls[method_name] if method_name in self._calls.keys() else 0
def was_called(self, method_name):
return True if method_name in self._calls.keys() and self._calls[method_name] > 0 else False
return ProxyClass
#Proxy
class Radio():
def __init__(self):
self._channel = None
self.is_on = False
self.volume = 0
def get_channel(self):
return self._channel
def set_channel(self, value):
self._channel = value
def power(self):
self.is_on = not self.is_on
radio = Proxy(Radio)()
radio.number = 3 # Notice that we are only setting the digit here.
radio.power()
print(radio._calls)
print(radio.number) # Notice that this when we are actually calling it.
print(radio._calls)
outputs:
{'is_on': 0, 'volume': 0, 'number': 0, 'power': 1}
3
{'is_on': 0, 'volume': 0, 'number': 1, 'power': 1}
A few modifications here and there, but you should be able to see the bigger idea by reading through the code. From here you should be able to modify the code to your liking. Also note that any variable that starts with _ is automatically removed from the _calls dictionary.
If you rather not use the decorator #Proxy, you may initialize your Radio class (as a proxy) like so:
# Second parentheses is where your Radio args go in.
# Since Radio does not take any args, we leave it empty.
radio_proxy = Proxy(Radio)()
Also, make sure to understand the difference between class attributes, and instance attributes.
Edit:
class Test:
def __init__(self, var):
self.var = var
self.dictionary = {}
def __getattribute__(self, item):
print("we are GETTING the following item:", item)
# If we don't do this, you end up in an infinite loop in which Python is
# trying to get the `dictionary` class to do `self.dictionary['dictionary'] = ...`
if item == "dictionary":
super(Test, self).__getattribute__(item)
else:
self.dictionary[item] = "Now we can use this!"
return super(Test, self).__getattribute__(item)
def __setattr__(self, item, key):
print("we are SETTING the following item:", item)
super(Test, self).__setattr__(item, key)
Notice:
test = Test(4)
outputs:
we are SETTING the following item: var
we are SETTING the following item: dictionary
then following it:
test.var
outputs:
we are GETTING the following item: var
we are GETTING the following item: dictionary
I want to implements a-star algorithm and the function (from Route_Algorithm.py) extends the nodes to get the next layor of f_value in the tree . The node can be regard as the station. And the self.settings.station_matrix is the numpy.matrix.
def voluation_station(self, successor, dest_location,bus_stations):
'''initilize all the f(g+h) to the specific nodes'''
length = len(self.settings.station_matrix[successor])
for end_element in range(length):
for station in bus_stations:
if int(station.name) == end_element:
station.get_g(self.settings.station_matrix[successor][end_element])
length_station = len(self.settings.station_matrix[end_element])
for element_station in range(length_station):
if element_station == dest_location:
station.get_h(self.settings.station_matrix[end_element][dest_location])
for element in bus_stations:
element.result_f()
return bus_stations
However, when I run the part of code. It reports the error like this:
Traceback (most recent call last):
File "/home/surface/Final-Year-Project/FYP/Main.py", line 4, in <module>
class main():
File "/home/surface/Final-Year-Project/FYP/Main.py", line 13, in main
new_route.busy_route_matrix()
File "/home/surface/Final-Year-Project/FYP/oop_objects/Route.py", line 87, in busy_route_matrix
self.route_algorithm.A_STAR_Algorithm(start_location,dest_location,self.bus_stations)
File "/home/surface/Final-Year-Project/FYP/Util/Route_Algorithm.py", line 40, in A_STAR_Algorithm
self.voluation_station(successor, dest_location,bus_stations)
File "/home/surface/Final-Year-Project/FYP/Util/Route_Algorithm.py", line 73, in voluation_station
station.get_g(self.settings.station_matrix[successor][end_element])
TypeError: 'int' object is not callable
I search the solution in the Internet, I think the problem may be in the end_element, maybe some inherient problem but I'm not sure. Can some one help me! Please!
Additional codes for other classes:
These classes are Util classes, which helps for handle oop_objects!
The class is for the Route_Algorithm:
from Util.Mergesort_algorithm import mergesort_algorithm
class route_algorithm():
'''generate the route to optimise the profiles'''
def __init__(self,settings):
# a* algorithm
self.open_list = []
self.close_list = []
self.route = []
self.settings = settings
self.flag_find = False
self.lines = []
# merge_sort algorithm
self.mergesort_algorithm = mergesort_algorithm()
def A_STAR_Algorithm(self, start_location, dest_location,bus_stations):
'''search the best route for each passenger to the destination'''
#self.clean_f(bus_stations)
# initial the value of f in start_location
for item in bus_stations:
if int(item.name) == start_location:
item.get_g = 0
for key, value in item.adjacent_station.items():
if int(key.name) == dest_location:
item.get_h = value
self.open_list.append(start_location)
#start_location is the name of station
while self.flag_find == False:
successor = self.open_list[0]
self.open_list.remove(successor)
self.route.append(successor)
self.voluation_station(successor, dest_location,bus_stations)
self.a_brain_judge_1(dest_location,bus_stations)
print(self.flag_find)
if self.flag_find == True:
#end the location
self.route.append(dest_location)
#add the line to the self.line
self.print_lines()
self.flag_find = False
self.open_list = []
else:
#continue to search the minimize
list = self.sort(bus_stations)
for item in list:
print(item.name)
print(item.f)
#疑问如果前两个的预估值一样该如何处理
self.open_list.append(int(list[0].name))
def voluation_station(self, successor, dest_location,bus_stations):
'''initilize all the f(g+h) to the specific nodes'''
length = len(self.settings.station_matrix[successor])
for end_element in range(length):
for station in bus_stations:
if int(station.name) == end_element:
station.get_g(self.settings.station_matrix[successor][end_element])
length_station = len(self.settings.station_matrix[end_element])
for element_station in range(length_station):
if element_station == dest_location:
station.get_h(self.settings.station_matrix[end_element][dest_location])
for element in bus_stations:
element.result_f()
return bus_stations
def a_brain_judge_1(self, dest_location,bus_stations):
'''whether the direct_line is the optimize'''
tmp_dest = bus_stations[0]
self.tmp_nodes = []
self.flag_find = True
for element in bus_stations:
if int(element.name) == dest_location:
tmp_dest = element
for element in bus_stations:
if element == tmp_dest:
pass
else:
if element.f < tmp_dest.f:
self.tmp_nodes.append(element)
self.flag_find = False
if self.flag_find == True:
self.route.append(tmp_dest.name)
return None
else:
return self.tmp_nodes
def sort(self,bus_stations):
'''sort all the f in the next stations'''
return self.mergesort_algorithm.Merge_Sort(bus_stations)
def print_lines(self):
#print(len(self.route))
for item in self.route:
print(item)
print("NEXT PASSENGER!---------")
def clean_f(self,stations):
for item in stations:
item.clean_data()
The class is Random_Algorithm, which helps for generate the random passengers.
import random
from Data.Settings import settings
from oop_objects.Bus_Station import bus_station
from oop_objects.Passenger import passenger
class random_algorithm():
'''generate the random bus-stations and passengers'''
def __init__(self):
self.setting = settings()
def random_passenger(self,number):
'''generate random passengers for bus-station,
and assumes there are 6 stations now. Furthermore, the data will be crawled by the creeper'''
passengers = []
for i in range(number):
new_passenger = passenger()
random.seed(self.setting.seed)
new_passenger.Change_Name(random.randint(1,self.setting.bus_station_number))
# generate the start-location
self.setting.seed +=1
end_location = random.randint(1,self.setting.bus_station_number)
# generate the end-location
while new_passenger.name == end_location:
self.setting.seed += 1
end_location = random.randint(1,self.setting.bus_station_number)
#judge whether the start-location same as the end-location
new_passenger.change_end_location(end_location)
passengers.append(new_passenger)
return passengers
def random_station(self,number):
'''generate the name of random stations '''
bus_stations = []
for i in range(number):
new_bus_station = bus_station()
new_bus_station.Name(str(i))
bus_stations.append(new_bus_station)
return bus_stations
def random_edge(self,bus_stations):
'''generate the edge information for the stations'''
for location1 in bus_stations:
#print("The information add in "+location1.name)
for location2 in bus_stations:
if location1 != location2:
#print("the "+location2.name+" was added in the "+location1.name)
if location2 not in location1.adjacent_station and location1 not in location2.adjacent_station:
random.seed(self.setting.seed)
edge = random.randint(1,self.setting.edge_distance)
location1.add_adjacent_station(location2,edge)
#print("the edge is "+str(edge))
self.setting.seed += 1
return bus_stations
The class is the mergesort_algorithm, which compare the f for different stations
class mergesort_algorithm():
def Merge_Sort(self,stations):
length = len(stations)
middle = int(length/2)
if length<=1:
return stations
else:
list1 = self.Merge_Sort(stations[:middle])
list2 = self.Merge_Sort(stations[middle:])
return self.Merge(list1,list2)
def Merge(self,list1,list2):
list3 = []
length1 = len(list1)
length2 = len(list2)
point1 = 0
point2 = 0
while point1<=length1-1 and point2<=length2-1:
if list1[point1].f<list2[point2].f:
list3.append(list1[point1])
point1 += 1
else:
list3.append(list2[point2])
point2 += 1
if point1>=length1:
for i in range(length2):
if i>=point2:
list3.append(list2[point2])
if point2>=length2:
for i in range(length1):
if i>=point1:
list3.append(list1[point1])
return list3
#def print_sort_result(self):
The following class are oop.classes
The class is for the Route:
from Util.Random_Algorithm import random_algorithm
from Data.Settings import settings
from Util.Route_Algorithm import route_algorithm
import numpy as np
class route():
def __init__(self):
self.bus_stations = []
self.passengers = []
self.settings = settings()
#random algorithm
self.random_algorithm = random_algorithm()
#route_algorithm
self.route_algorithm = route_algorithm(self.settings)
def start_route(self):
'''The raw route Information(TEXT) for bus_stations '''
stations = self.random_algorithm.random_station(self.settings.bus_station_number)
finsih_edge_stations = self.random_algorithm.random_edge(stations)
'''
for item in finsih_edge_stations:
print("\nthe information for " + item.name + " is: \t")
for key, value in item.adjacent_station.items():
print("the station is " + key.name)
print(" the distace is " + str(value))
'''
self.bus_stations = finsih_edge_stations
'''The raw route Information(Text) for passengers'''
self.passengers = self.random_algorithm.random_passenger(self.settings.passengers_number)
def bus_stations_matrix(self):
'''trasfer the raw text to the matrix'''
#create zero_matrix
length = len(self.bus_stations)
tmp_matrix = np.zeros(length*length)
station_matrix = tmp_matrix.reshape(length,length)
for item in self.bus_stations:
for key,value in item.adjacent_station.items():
station_matrix[int(item.name)][int(key.name)] = value
station_matrix[int(key.name)][int(item.name)] = value
print(station_matrix)
self.settings.station_matrix = station_matrix
def passengers_matrix(self):
'''trasfer the raw text to the matrix'''
length = len(self.bus_stations)
tmp_matrix = np.zeros(length*length)
passenger_matrix = tmp_matrix.reshape(length,length)
for item in self.passengers:
#print("the start location of passenger is "+str(item.name))
#print("the end location of passenger is "+str(item.end_location))
#print(" ")
passenger_matrix[item.name-1][item.end_location-1]+=1;
print(passenger_matrix)
self.settings.passenger_matrix = passenger_matrix
def busy_route_matrix(self):
'''generate the bus_busy_route matrix'''
#read the requirements of passengers
length = self.settings.bus_station_number
for start_location in range(length):
for dest_location in range(length):
if self.settings.passenger_matrix[start_location][dest_location] == 0:
pass
else:
magnitude = self.settings.passenger_matrix[start_location][dest_location]
#运行a*算法去寻找最短路径/run the a* algorithm to search the path
self.route_algorithm.A_STAR_Algorithm(start_location,dest_location,self.bus_stations)
print("------------------------------------")
def practice(self):
'''practice some programming'''
for element in self.bus_stations:
print((element.f))
The class is for the Passenger
class passenger():
def __init__(self):
self.name = 0
self.end_location = "null"
def Change_Name(self,name):
'''change the name of passenger'''
self.name = name
def change_end_location(self,location):
'''generate the end_location'''
self.end_location = location
The class for the bus_station
class bus_station():
'''the class represents the bus station'''
def __init__(self):
'''the attribute of name means the name of bus-station
the attribute of passenger means the passenger now in the bus-station'''
self.name = "null"
self.passenger = []
self.adjacent_station = {}
#A* algorithm
self.g = 0
self.h = 0
self.f = 0
def Name(self,name):
'''change the name of the station'''
self.name = name
def add_passengers(self,*passenger):
'''add the passenger in the bus-station'''
self.passenger.append(passenger)
def add_adjacent_station(self,station,edge):
'''add the adjacent station in the this station'''
self.adjacent_station[station] = edge
def get_g(self,value):
'''get the value of g (线路值)'''
self.g =self.g+ value
def get_h(self,value):
'''get the value of f (预估值)'''
self.h = value
def result_f(self):
'''print the value of f (实际值)'''
self.f = self.g+self.h
def add_self_cost(self):
self.add_adjacent_station()
The following class is storing the data.
The class is for the setting:
class settings():
def __init__(self):
self.seed = 5
self.bus_station_number = 10
self.passengers_number = 10
self.edge_distance = 50
self.station_matrix = None
self.passenger_matrix = None
And the main class to run the whole project:
from oop_objects.Route import route
class main():
new_route = route()
new_route.start_route()
print("The distance between different bus station :")
new_route.bus_stations_matrix()
print("The location information for passengers :")
new_route.passengers_matrix()
new_route.busy_route_matrix()
#new_route.practice()practice
#new_route.sort()bus_stations
You should avoid the station of successor because you have assigned the value by using the get_g
The result should be:
def voluation_station(self, successor, dest_location,bus_stations):
'''initilize all the f(g+h) to the specific nodes'''
length = len(self.settings.station_matrix[successor])
for end_element in range(length):
if end_element == successor:
pass
else:
for station in bus_stations:
if int(station.name) == end_element:
station.get_g(self.settings.station_matrix[successor][end_element])
length_station = len(self.settings.station_matrix[end_element])
for element_station in range(length_station):
if element_station == dest_location:
station.get_h(self.settings.station_matrix[end_element][dest_location])
for element in bus_stations:
element.result_f()
return bus_stations
I want to convert an object to an iterable.
I have the output of the format
>>>result[0]
<Particle [0.015270307267929021, -0.0009933688866323714, -0.004208897534490854, -0.011275132115610775, 0.0029132053067140572, 0.005608170262839968, 0.0005401367846572976, -0.013393458586919493, 0.0003998091070805884, 0.0002900137732599478]>
The full code of the problem is
from fstpso import FuzzyPSO
def example_fitness( particle ):
return sum(map(lambda x: x**2, particle))
if __name__ == '__main__':
dims = 10
FP = FuzzyPSO()
FP.set_search_space( [[-10, 10]]*dims )
FP.set_fitness(example_fitness)
result = FP.solve_with_fstpso()
print "Best solution:", result[0]
print "Whose fitness is:", result[1]
I want to use result[0] as the list.
Source
According to your comment which states it's fstpso.pso.Particle, if you just call the following, you'll be able to use it as iterator without changing the original source code.
variable = result[0].X
for i in variable:
print(i)
The original source code indicates the __repr__() function is just printing the self.X value, which is a list.
def __repr__(self):
return "<Particle %s>" % str(self.X)
The fstpso.pso.Particle object is as follows:
class Particle(object):
def __init__(self):
self.X = []
self.V = []
self.B = []
self.MarkedForRestart = False
self.CalculatedFitness = sys.float_info.max
self.FitnessDevStandard = sys.float_info.max
self.CalculatedBestFitness = sys.float_info.max
self.SinceLastLocalUpdate = 0
self.DerivativeFitness = 0
self.MagnitudeMovement = 0
self.DistanceFromBest = sys.float_info.max
self.CognitiveFactor = 2.
self.SocialFactor = 2.
self.Inertia = 0.5
# support for PPSO
self.MaxSpeedMultiplier = .25
self.MinSpeedMultiplier = 0
def __repr__(self):
return "<Particle %s>" % str(self.X)
def __str__(self):
return "\t".join(map(str, self.X))
From https://github.com/aresio/fst-pso/blob/master/fstpso/pso.py
What you want can be got with:
result[0].X
Alright so I have a dict with keys that point to an array of 5 values. These 5 values I pass to a class to sort out and feed me info etc.
Main
So, this works, but my querstion is is there a better way of exytracting the array to pass to the 'weapon' class, or do i just need to 'wepstats[0],wepstats[1]' etc? Or is there a better way of going about this? I'm all ears as Im only learning to do this stuff.
class Main():
def weaponDamage(self):
#print 15 * 2.22
wdb = WeaponDB()
wepstats = wdb.getWeaponStats('Sword')
wep = Weapon(wepstats[0],wepstats[1],wepstats[2],wepstats[3],wepstats[4])
wep2 = Weapon("Sword", 5, 55, 1.55, 2.1)
print wep
print wep2
s = sayThings()
greet = s.Say()
self.crit = wep.getDamageCrtRND()
self.scrit = wep.getDamageSCrtRND()
self.avg = wep.getDamageAvg()
self.high = wep.getDamageHigh()
self.low = wep.getDamageLow()
self.mod = wep.getDamageMod()
self.norm = wep.getDamageNrmRND()
self.name = wep.getWeaponName()
print greet
print "-----------"
print "Name: " + self.name
print "-----------"
print "High: %s" % self.high
print "Low : %s" % self.low
print "Avg : %s" % self.avg
print "Crit: %s" % self.crit
print "--------------------"
Dict
EDIT: Should I be making a DB of items in this manner in the first place? Is there a more logic method of doing this?
class WeaponDB():
"""Here be thine weapons of thy holy might"""
def __init__(self):
self.script = {
'None': "Error: No Weapon stats to get selected.",
'Sword': ("Sword", 5, 55, 1.55, 2.1),
}
def getWeaponStats(self, key = 'None'):
try:
return self.script[key]
except KeyError:
return self.script['None']
Class useing the values as parameters
class Weapon():
def __init__(self, name = "Stick", high = 1, low = 0, critMod = 1, scritMod = 2):
self.rng = randNum()
self.name = name
self.high = high
self.low = low
self.critMod = critMod
self.scritMod = scritMod
def getWeaponName(self):
return self.name
def getDamageHigh(self):
return self.high
def getDamageLow(self):
return self.low
def getDamageMod(self):
return self.critMod
def getDamageSMod(self):
return self.scritMod
etc...
If I understand well you can do something like this:
class Weapon:
def __init__( self, name = 'Stick', high = 1, low = 0 ):
self.name = name
self.high = high
self.low = low
wepstats = ( 'Sword', 5, 55 )
sword = Weapon( *wepstats )
Then if you check your attributes you get:
>>> sword.name
'Sword'
>>> sword.high
5
>>> sword.low
55
Using *wepstats you pass the entire tuple as arguments for your constructor.