How to convert an object to iterable (list)? - python

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

Related

Calling a method within other method definitions and 'object has no attribute'

So I've been solving problems utilizing classes for the sake of practicing, but I've been having troubles with calling a method defined in a class, within a method definition of the same class
class Hive:
def __init__(self, arr):
self._arr = arr
self._index = ['Re','Pt','Cc','Ea','Tb','Cm','Ex']
self._number = [0] * 7
self._ratio = []
self._len = len(self._arr)
def number(self):
for i in range(7):
for j in range(self._len):
if self._index[i] == self._arr[j]:
self._number[i] += 1
return self._number
def rate(self):
population = self._arr.number()
for x in range(7):
self._ratio.append(population[x] / self._len)
return self._ratio
def prnt(self):
population2= self._arr.number()
rate2 = self._arr.rate()
for k in range(7):
print("%s %d %.2f" % (self._index[k], population2[k], rate2[k]))
print("Total", str(self._len), "1.00")
arr = input().split()
Colony = Hive(arr)
Colony.prnt()
This ends up with an error that states the following:
Traceback (most recent call last):
File "inee.py", line 33, in <module>
Colony.prnt()
File "inee.py", line 25, in prnt
population2= self._arr.number()
AttributeError: 'list' object has no attribute 'number'
So the only way I could remedy this with my current knowledge was to take care of list assignments outside the method definitions:
class Hive:
def __init__(self, arr):
self._arr = arr
self._index = ['Re','Pt','Cc','Ea','Tb','Cm','Ex']
self._number = [0] * 7
self._ratio = []
self._len = len(self._arr)
def number(self):
for i in range(7):
for j in range(self._len):
if self._index[i] == self._arr[j]:
self._number[i] += 1
return self._number
def rate(self, array):
for x in range(7):
self._ratio.append(array[x] / self._len)
return self._ratio
def prnt(self, array2, array3):
for k in range(7):
print("%s %d %.2f" % (self._index[k], array2[k], array3[k]))
print("Total", str(self._len), "1.00")
arr = input().split()
initial = Hive(arr)
population = initial.number()
rateList = initial.rate(population)
initial.prnt(population, rateList)
This yielded results I wanted, but what's wrong with the first one? Is that not a correct way of calling methods within a method definition within a class?
By callint prnt()-method, you are referring to self._arr. This is not your Hive-object which has the number()-method. It's simply a list. A list does not have a number() attribute. The way you wrote your script you can only call number()-method on the Hive-object itself: self.number(), instead of self._arr.number().
This counts for rate()-method and prnt()-method:
def rate(self):
population = self.number() # <-- here
for x in range(7):
self._ratio.append(population[x] / self._len)
return self._ratio
def prnt(self):
population2 = self.number() # <-- here
rate2 = self.rate() # <-- and here
for k in range(7):
print("%s %d %.2f" % (self._index[k], population2[k], rate2[k]))
print("Total", str(self._len), "1.00")
The second variant you provided cannot work, because you're using number()-method on Hive-object which has no longer a defined attribute number(), because you outsourced it. But you can use it now as a function like this:
>>> arr = ["This", "is", "a", "test", "Re", "Cc", "Tb"]
>>> initial = Hive(arr)
>>> population = number(initial)
>>> print(population)
[1, 0, 1, 0, 1, 0, 0]

Why does passing a dictionary as a parameter take more time?

I tried to a leetcode problem. I find one of the following code throws a time limit exceeded error. I created the following testing code. I found the first one pass dictionary as a parameter takes more time the the other one. 0.94s vs 0.84s.
Can anyone explain this ?
class Solution(object):
def longestPalindromeSubseq(self, x):
"""
:type s: str
:rtype: int
"""
#dic = {}
def helper(s, dic):
if len(s) == 0:
return 0
if len(s) == 1:
return 1
if s in dic:
return dic[s]
if s[0] == s[-1]:
res = helper(s[1:-1], dic)+2
else:
l1 = helper(s[:-1], dic)
l2 = helper(s[1:], dic)
res = max(l1,l2)
dic[s] = res
#print (id(dic), dic)
return res
d = {}
ans = helper(x, d)
#print (id(d), d)
return ans
class Solution1(object):
def longestPalindromeSubseq(self, x):
"""
:type s: str
:rtype: int
"""
dic = {}
def helper(s):
if len(s) == 0:
return 0
if len(s) == 1:
return 1
if s in dic:
return dic[s]
if s[0] == s[-1]:
res = helper(s[1:-1])+2
else:
l1 = helper(s[:-1])
l2 = helper(s[1:])
res = max(l1,l2)
dic[s] = res
#print (id(dic), dic)
return res
ans = helper(x)
#print (id(dic), dic)
return ans
import time
if __name__ == "__main__":
x = "gphyvqruxjmwhonjjrgumxjhfyupajxbjgthzdvrdqmdouuukeaxhjumkmmhdglqrrohydrmbvtuwstgkobyzjjtdtjroqpyusfsbjlusekghtfbdctvgmqzeybnwzlhdnhwzptgkzmujfldoiejmvxnorvbiubfflygrkedyirienybosqzrkbpcfidvkkafftgzwrcitqizelhfsruwmtrgaocjcyxdkovtdennrkmxwpdsxpxuarhgusizmwakrmhdwcgvfljhzcskclgrvvbrkesojyhofwqiwhiupujmkcvlywjtmbncurxxmpdskupyvvweuhbsnanzfioirecfxvmgcpwrpmbhmkdtckhvbxnsbcifhqwjjczfokovpqyjmbywtpaqcfjowxnmtirdsfeujyogbzjnjcmqyzciwjqxxgrxblvqbutqittroqadqlsdzihngpfpjovbkpeveidjpfjktavvwurqrgqdomiibfgqxwybcyovysydxyyymmiuwovnevzsjisdwgkcbsookbarezbhnwyqthcvzyodbcwjptvigcphawzxouixhbpezzirbhvomqhxkfdbokblqmrhhioyqubpyqhjrnwhjxsrodtblqxkhezubprqftrqcyrzwywqrgockioqdmzuqjkpmsyohtlcnesbgzqhkalwixfcgyeqdzhnnlzawrdgskurcxfbekbspupbduxqxjeczpmdvssikbivjhinaopbabrmvscthvoqqbkgekcgyrelxkwoawpbrcbszelnxlyikbulgmlwyffurimlfxurjsbzgddxbgqpcdsuutfiivjbyqzhprdqhahpgenjkbiukurvdwapuewrbehczrtswubthodv"
print (x)
t0 = time.time()
sol = Solution()
print (sol.longestPalindromeSubseq(x))
t1 = time.time()
print(t1- t0)
sol1 = Solution1()
print (sol1.longestPalindromeSubseq(x))
t2 = time.time()
print(t2-t1)
Python uses something that is called call by sharing. The function gets only the alias on the parameter. With that in mind, it does't matter what you pass to the function.
But the script may take different time to execute. It is not constant. Using recursion makes it even harder to predict

Print dict with custom class as values wont call their string method?

I was messing around with classes in python and wrote 2 little ones:
class ClaElement:
start = None
end = None
basesLeft = None
orientation = None
contig = None
size = None
def __init__(self, contig, start, end, orientation, basesLeft=None):
self.contig = contig
self.start = start
self.end = end
self.orientation = orientation
self.basesLeft = basesLeft
self.size = self.end - self.start
def __str__(self):
return "{ClaElement: "+str(self.contig)+"_"+str(self.start)+"_"+str(self.end)+"_"+str(self.orientation)+"}"
def getSize(self):
return self.size
class ClaCluster:
contig = None
clusterElements = []
def __init__(self, contig, firstElement):
self.contig = contig
self.addElement(firstElement)
def addElement(self, claElement):
self.clusterElements.append(claElement)
def getFirst(self):
return self.clusterElements[0]
def getLast(self):
return self.clusterElements[-1]
def getElements(self):
return self.clusterElements
def getContig(self):
return self.contig
def __str__(self):
return "{ClaCluster: "+str(self.contig)+" "+str(len(self.clusterElements))+" elements}"
And my test-main:
from ClaElement import ClaElement
from ClaCluster import ClaCluster
if __name__ == '__main__':
ele = ClaElement("x",1,2,"left")
claDict = dict()
cluster = ClaCluster("x", ele)
claDict["hello"] = cluster
print(claDict)
print(claDict["hello"])
print(ele)
This leads to the following output:
{'hello': <ClaCluster.ClaCluster object at 0x7fe8ee04c5f8>}
{ClaCluster: x 1 elements}
{ClaElement: x_1_2_left}
Now my question is why is the output of my first print the memory address even though I provided a functioning string-method for my class ClaCluster? Is there a way to get the method invoked when I am printing the dictionary or do I have to iterate by hand?
The __str__() method of the built-in dict type uses the __repr__() method of your class, not __str__(). Simply rename your method, and all should work fine.

AttributeError: AS Instance has no attribute 'toString'

Writing code in Python for an Astar program to find the shortest path between cities. Getting the above error, and I'm at a complete loss. Pulling between a few .py files, here are the relevant sections:
from asdriver.py - added full asdriver
import adata # Map data
import astar # A* class
import sys
# Default start, goal cities
defaultcities = ('Yakima, WA', 'Tampa, FL')
def printnode(n):
print n.toString()
adata.input()
startcity = raw_input("Start city [{0}]: ".format(defaultcities[0])).strip()
if startcity == '': startcity = defaultcities[0]
if startcity not in adata.cities:
print "City not recognized"
sys.exit(0)
goalcity = raw_input("Goal city [{0}]: ".format(defaultcities[1])).strip()
if goalcity == '': goalcity = defaultcities[1]
if goalcity not in adata.cities:
print "City not recognized"
sys.exit(0)
dbg = raw_input("Debug Options: [none]").strip()
findpath = astar.AS(startcity, goalcity, printnode)
ans = findpath.astar_run(printnode, dbg)
if not ans:
print "No answer"
else:
print "Final Path:"
print ans.toString()
From astar.py
import adata
class AS:
def __init__(self, startcity, goalcity, tracefunc):
self.startcity = startcity
self.goalcity = goalcity
self.tracefunc = tracefunc
self.openlist = [Node([startcity])]
self.closedlist = []
def heuristic(self, printnode, start, end):
raise NotImplementedError
def astar_run(self, startcity, endcity, dbg = ""):
while self.openlist:
citystep = min(self.openlist, key = lambda o:o.g + o.h)
if citystep == self.goalcity:
path = []
while citystep.parent:
path.append(citystep)
citystep = citystep.parent
path.append(citystep)
return path[::-1]
self.openlist.remove(citystep)
self.closedlist.append(citystep)
for printnode in self.openlist: #was self.tracefunc
if printnode in self.closedset:
continue
elif printnode in self.openset:
newG = citystep.g + citystep.cost(printnode)
if printnode.g > newG:
printnode.g = newG
printnode.parent = citystep
else:
printnode.g = citystep.g + citystep.cost(printnode)
printnode.h = self.heuristic(printnode, start, end)
printnode.parent = citystep
self.openset.add(printnode)
return self
class Node:
def __init__(self, path=[], f=0, g=0, h=0):
self.path = path[:]
self.f = f
self.g = g
self.h = h
self.parent = None
def toString(self):
s = 'f=%d g=%d h=%d ' % (self.f, self.g, self.h)
for city in self.path:
s = s + ' ' + city
return s
def cost(self):
raise NotImplementedError
'
Complete beginner, so any help would be appreciated.
Thanks in advance!!!
Your def astar_run() method returns self (see last line of your method), or it returns a list by slicing the path[::-1], neither has a toString() method so you are getting this exception. If you want to print the representation of your class then it is normal to declare this method __repr__() and then you can just print ans. If you want to be able to convert to a string then the method is usually called __str__().
What do you expect to be return from astar_run()? It is usually poor practice to return two different types from the same function.

Python -- TypeError on string format from binary output

I'm getting a getting a TypeError for unbound method (at the bottom). I'm teaching myself Python so this may be some simple mistake. The issue is with outFormat(), which didn't give me problems when I test it by itself but is not working within the class. Here's the class:
class gf2poly:
#binary arithemtic on polynomials
def __init__(self,expr):
self.expr = expr
def id(self):
return [self.expr[i]%2 for i in range(len(self.expr))]
def listToInt(self):
result = gf2poly.id(self)
return int(''.join(map(str,result)))
def prepBinary(a,b):
a = gf2poly.listToInt(a); b = gf2poly.listToInt(b)
bina = int(str(a),2); binb = int(str(b),2)
a = min(bina,binb); b = max(bina,binb);
return a,b
def outFormat(raw):
raw = str(raw); g = []
[g.append(i) for i,c in enumerate(raw) if c == '1']
processed = "x**"+' + x**'.join(map(str, g[::-1]))
#print "processed ",processed
return processed
def divide(a,b): #a,b are lists like (1,0,1,0,0,1,....)
a,b = gf2poly.prepBinary(a,b)
bitsa = "{0:b}".format(a); bitsb = "{0:b}".format(b)
difflen = len(str(bitsb)) - len(str(bitsa))
c = a<<difflen; q=0
while difflen >= 0 and b != 0:
q+=1<<difflen; b = b^c
lendif = abs(len(str(bin(b))) - len(str(bin(c))))
c = c>>lendif; difflen -= lendif
r = "{0:b}".format(b); q = "{0:b}".format(q)
#print "r,q ",type(r),type(q)
return r,q #returns r remainder and q quotient in gf2 division
def remainder(a,b): #separate function for clarity when calling
r = gf2poly.divide(a,b)[0]; r = int(str(r),2)
return "{0:b}".format(r)
def quotient(a,b): #separate function for clarity when calling
q = gf2poly.divide(a,b)[1]; q = int(str(q),2)
return "{0:b}".format(q)
This is how I'm calling it:
testp = gf2poly.quotient(f4,f2)
testr = gf2poly.remainder(f4,f2)
print "quotient: ",testp
print "remainder: ",testr
print "***********************************"
print "types ",type(testp),type(testr),testp,testr
testp = str(testp)
print "outFormat testp: ",gf2poly.outFormat(testp)
#print "outFormat testr: ",gf2poly.outFormat(testr)
This is the error:
TypeError: unbound method outFormat() must be called with gf2poly instance as first argument (got str instance instead)
Where you have this:
def outFormat(raw):
You probably want either this:
def outFormat(self, raw):
Or this:
#staticmethod
def outFormat(raw):
The former if you eventually need access to self in outFormat(), or the latter if you do not (as currently is the case in the posted code).

Categories

Resources