Defining a function within a class in Python 2.7 - python

I tried to add a pgdc function in the Fraction class in order to calculate the biggest common divided or a number pgdc ... The function should be recursive. However, I keep getting the following error:
Traceback (most recent call last):
File "C:/Users/jf/Desktop/Python-jEdit_v2/23_fraction.py", line 60, in <module>
p = a.plus(b)
File "C:/Users/jf/Desktop/Python-jEdit_v2/23_fraction.py", line 35, in plus
return resultat.simplifier()
File "C:/Users/jf/Desktop/Python-jEdit_v2/23_fraction.py", line 27, in simplifier
p = pgcd(self.num, self.den)
NameError: global name 'pgcd' is not defined
In addition,
I also got the following error for the simplifier : AttributeError: Fraction instance has no attribute 'simplifier'
Which, leave me puzzle, as I tried to add self.pgcd=pgcd and self.simplifier=simplifier
at various places and it still did not work well...
# -*- coding: utf-8 -*-
class Fraction():
# constructeur et attributs
def __init__(self, num = 0, den = 1):
self.num = num
if (den == 0):
erreur("Dénominateur nul") #fonction d'erreur
self.den = den
def __str__(self):
return str(self.num) + "/" + str(self.den)
def erreur(message):
print "Erreur: " + message
from sys import exit
exit()
def pgcd(a, b):
if a == b:
return a
if a > b:
return pgcd(a-b, b)
else:
return pgcd(a, b-a)
def simplifier(self):
p = pgcd(self.num, self.den)
self.num = self.num / p
self.den = self.den / p
return self
def plus(self, f):
resultat = Fraction(self.num * f.den + self.den * f.num, \
self.den * f.den)
return resultat.simplifier()
def moins(self, f):
resultat = Fraction(self.num * f.den - self.den * f.num, \
self.den * f.den)
if (resultat.num < 0):
# changer de signe avant de simplifier
resultat.num = - resultat.num
resultat = resultat.simplifier()
resultat.num = - resultat.num
return resultat
else:
return resultat.simplifier()
def fois(self, f):
resultat = Fraction(self.num * f.num, self.den * f.den)
return resultat.simplifier()
def div(self, f):
resultat = Fraction(self.num * f.den, self.den * f.num)
return resultat.simplifier()
#### CONSOLE ####
a = Fraction(5, 11)
b = Fraction(3, 7)
p = a.plus(b)

You need to declare self as a parameter of your function and use it when you want to recursively call pgcd:
def pgcd(self,a, b):
if a == b:
return a
if a > b:
return self.pgcd(a-b, b)
else:
return self.pgcd(a, b-a)
Also, call pgcd with self. on this line:
p = self.pgcd(self.num, self.den) #from pgcd(self.num, self.den)

Related

pso algorithm on test function. But I'm stuck with python code

So I have to classes Swarm and Particles, and a class for Sphere function.
But when I'm trying to run the optimization, I get error on iteretation and I don't understand why:
TypeError: '<' not supported between instances of 'NoneType' and 'NoneType'
Eventually, if you can give me some tipf for shifted sphere function.
from abc import ABCMeta, abstractmethod
import numpy
import numpy.random
from particle import Particle
class Swarm (object):
__metaclass__ = ABCMeta
def __init__ (self,
swarmsize,
minvalues,
maxvalues,
currentVelocityRatio,
localVelocityRatio,
globalVelocityRatio):
self.__swarmsize = swarmsize
assert len (minvalues) == len (maxvalues)
assert (localVelocityRatio + globalVelocityRatio) > 4
self.__minvalues = numpy.array (minvalues[:])
self.__maxvalues = numpy.array (maxvalues[:])
self.__currentVelocityRatio = currentVelocityRatio
self.__localVelocityRatio = localVelocityRatio
self.__globalVelocityRatio = globalVelocityRatio
self.__globalBestFinalFunc = None
self.__globalBestPosition = None
self.__swarm = self.__createSwarm ()
def __getitem__ (self, index):
"""
Возвращает частицу с заданным номером
"""
return self.__swarm[index]
def __createSwarm (self):
return [Particle (self) for _ in range (self.__swarmsize) ]
def nextIteration (self):
for particle in self.__swarm:
return particle.nextIteration (self)
#property
def minvalues (self):
return self.__minvalues
#property
def maxvalues (self):
return self.__maxvalues
#property
def currentVelocityRatio (self):
return self.__currentVelocityRatio
#property
def localVelocityRatio (self):
return self.__localVelocityRatio
#property
def globalVelocityRatio (self):
return self.__globalVelocityRatio
#property
def globalBestPosition (self):
return self.__globalBestPosition
#property
def globalBestFinalFunc (self):
return self.__globalBestFinalFunc
def getFinalFunc (self, position):
assert len (position) == len (self.minvalues)
finalFunc = self._finalFunc (position)
if (self.__globalBestFinalFunc == None or
finalFunc < self.__globalBestFinalFunc):
self.__globalBestFinalFunc = finalFunc
self.__globalBestPosition = position[:]
#abstractmethod
def _finalFunc (self, position):
pass
#property
def dimension (self):
return len (self.minvalues)
def _getPenalty (self, position, ratio):
penalty1 = sum ([ratio * abs (coord - minval)
for coord, minval in zip (position, self.minvalues)
if coord < minval ] )
penalty2 = sum ([ratio * abs (coord - maxval)
for coord, maxval in zip (position, self.maxvalues)
if coord > maxval ] )
return penalty1 + penalty2
class Particle (object):
def __init__ (self, swarm):
self.__currentPosition = self.__getInitPosition (swarm)
self.__localBestPosition = self.__currentPosition[:]
self.__localBestFinalFunc = swarm.getFinalFunc (self.__currentPosition)
self.__velocity = self.__getInitVelocity (swarm)
#property
def position (self):
return self.__currentPosition
#property
def velocity (self):
return self.__velocity
def __getInitPosition (self, swarm):
return numpy.random.rand (swarm.dimension) * (swarm.maxvalues - swarm.minvalues) + swarm.minvalues
def __getInitVelocity (self, swarm):
assert len (swarm.minvalues) == len (self.__currentPosition)
assert len (swarm.maxvalues) == len (self.__currentPosition)
minval = -(swarm.maxvalues - swarm.minvalues)
maxval = (swarm.maxvalues - swarm.minvalues)
return numpy.random.rand (swarm.dimension) * (maxval - minval) + minval
def nextIteration (self, swarm):
rnd_currentBestPosition = numpy.random.rand (swarm.dimension)
rnd_globalBestPosition = numpy.random.rand (swarm.dimension)
veloRatio = swarm.localVelocityRatio + swarm.globalVelocityRatio
commonRatio = (2.0 * swarm.currentVelocityRatio /
(numpy.abs (2.0 - veloRatio - numpy.sqrt (veloRatio ** 2 - 4.0 * veloRatio) ) ) )
newVelocity_part1 = commonRatio * self.__velocity
newVelocity_part2 = (commonRatio *
swarm.localVelocityRatio *
rnd_currentBestPosition *
(self.__localBestPosition - self.__currentPosition) )
newVelocity_part3 = (commonRatio *
swarm.globalVelocityRatio *
rnd_globalBestPosition *
(swarm.globalBestPosition - self.__currentPosition) )
self.__velocity = newVelocity_part1 + newVelocity_part2 + newVelocity_part3
self.__currentPosition += self.__velocity
finalFunc = swarm.getFinalFunc (self.__currentPosition)
if finalFunc < self.__localBestFinalFunc:
self.__localBestPosition = self.__currentPosition[:]
self.__localBestFinalFunc = finalFunc
class Swarm_X2 (Swarm):
def init (self,
swarmsize,
minvalues,
maxvalues,
currentVelocityRatio,
localVelocityRatio,
globalVelocityRatio):
Swarm.init (self,
swarmsize,
minvalues,
maxvalues,
currentVelocityRatio,
localVelocityRatio,
globalVelocityRatio)
def _finalFunc (self, position):
penalty = self._getPenalty (position, 10000.0)
finalfunc = sum (position * position)
return finalfunc + penalty
from swarm_x2 import Swarm_X2
from utils import printResult
if name == "main":
iterCount = 300
dimension = 5
swarmsize = 200
minvalues = numpy.array ([-100] * dimension)
maxvalues = numpy.array ([100] * dimension)
currentVelocityRatio = 0.1
localVelocityRatio = 1.0
globalVelocityRatio = 5.0
swarm = Swarm_X2 (swarmsize,
minvalues,
maxvalues,
currentVelocityRatio,
localVelocityRatio,
globalVelocityRatio
)
for n in range (iterCount):
print "Position", swarm[0].position
print "Velocity", swarm[0].velocity
print printResult (swarm, n)
swarm.nextIteration()

How to add a function to take data from a .txt list?

I need to change the code in line # 39
I have approximately seen scripts that use with open ("file.txt", "r") as f: take data from a text document.
I have a list of "Point.txt"
g = Point(250,127)
g = Point(330,224)
g = Point(557,186)
g = Point(370,197)
g = Point(222,107)
Need to add a function so that the script takes data from the list of the document "Point.txt"
and the whole result was saved in one document "Save.txt"
class Point(object):
def __init__(self, _x, _y, _order = None): self.x, self.y, self.order = _x, _y, _order
def calc(self, top, bottom, other_x):
l = (top * inverse_mod(bottom)) % p
x3 = (l * l - self.x - other_x) % p
return Point(x3, (l * (self.x - x3) - self.y) % p)
def double(self):
if self == INFINITY: return INFINITY
return self.calc(3 * self.x * self.x, 2 * self.y, self.x)
def __add__(self, other):
if other == INFINITY: return self
if self == INFINITY: return other
if self.x == other.x:
if (self.y + other.y) % p == 0: return INFINITY
return self.double()
return self.calc(other.y - self.y, other.x - self.x, other.x)
def __mul__(self, e):
if self.order: e %= self.order
if e == 0 or self == INFINITY: return INFINITY
result, q = INFINITY, self
while e:
if e&1: result += q
e, q = e >> 1, q.double()
return result
def __str__(self):
if self == INFINITY: return "infinity"
return " %x %x" % (self.x, self.y)
def inverse_mod(a):
if a < 0 or a >= p: a = a % p
c, d, uc, vc, ud, vd = a, p, 1, 0, 0, 1
while c:
q, c, d = divmod(d, c) + (c,)
uc, vc, ud, vd = ud - q*uc, vd - q*vc, uc, vc
if ud > 0: return ud
return ud + p
p, INFINITY = 1693, Point(None, None)
g = Point(250,127)
wave = 78
result = ' ID: %x\n getID: %s' % (wave, g*wave)
f = open('Save.txt', 'a')
f.write(result)
f.close()
I have used regex to extract the parameters that you have to pass for Point creation :
import re
f = open('Save.txt', 'a')
with open('Point.txt', 'rb') as points_txt_file:
for line in points_txt_file:
found_points = re.search(r'Point\((\s*\d+\s*),(\s*\d+\s*)\)', f'{line}')
print(found_points.groups())
param1 = int(found_points.group(1))
param2 = int(found_points.group(2))
g = Point(param1, param2)
result = ' ID: %x\n getID: %s' % (wave, g*wave)
f.write(result)
f.close()
Remove your code from line #38 and use this code .

How to use __mul__ in a class named Fraction

How do I make multiplication work with my class Fraction?
class Fraction(object):
def __init__(self, num, den):
self.num = num
self.den = den
def resolve(self):
#a = 2
#b = 6
#c = 2
#d = 5
self.num = self.num / other.num
self.den = self.den / other.den
return self
def __str__(self):
return "%d/%d" %(self.num, self.den)
def __mul__(self, other):
den = self.den * other.num
num = self.num * other.den
return (Fraction(self.num * other.num, self.den * other.den))
print('Multiplication:', Fraction.__mul__(2, 6))
This is the output:
Traceback (most recent call last):
File "app.py", line 43, in <module>
print('Multiplication:', Fraction.__mul__(2, 6))
File "app.py", line 27, in __mul__
den = self.den * other.num
AttributeError: 'int' object has no attribute 'den'
Try this
f1 = Fraction(1, 2)
f2 = Fraction(2, 3)
print(f1 * f2)
Here I'm
Creating an object f1 of class Fraction this is 1/2
Similarly f2 which is 2/3
Now f1 * f2 automatically calls the dunder method __mul__ of f1 with f2 as the other argument
So you should see the expected Fraction object getting printed
PS: The reason why you're getting the AttributeError is because, __mul__ expects Fraction objects to be passed - while you are passing ints

AttributeError: 'Rsa' object has no attribute 'n'

I am getting this error:
Traceback (most recent call last):
File "/Users/aditya/Desktop/Pycharm /Fire_Tech_Camp/Rsa/RsaMainFrame.py", line 7, in <module>
rsa = RsaEncryptionAndDecryption.Rsa()
File "/Users/aditya/Desktop/Pycharm /Fire_Tech_Camp/Rsa/RsaEncryptionAndDecryption.py", line 8, in __init__
self.p, self.q = self.findingPandQ()
File "/Users/aditya/Desktop/Pycharm /Fire_Tech_Camp/Rsa/RsaEncryptionAndDecryption.py", line 80, in findingPandQ
while not self.isPrime(self.a):
File "/Users/aditya/Desktop/Pycharm /Fire_Tech_Camp/Rsa/RsaEncryptionAndDecryption.py", line 14, in isPrime
for i in range(2,int(self.n**0.5)+1):
AttributeError: 'Rsa' object has no attribute 'n'
What I am trying to do is create a class with a function (isPrime()) to check primes.
Then in a seperate function I check if it is prime (generate_keys()). The class is being called in a seperate file.
Code:
Main File where I call the class:
from Rsa import RsaEncryptionAndDecryption
from appJar import gui
app = gui()
rsa = RsaEncryptionAndDecryption.Rsa()
def encode(name):
msg = app.getEntry('Input to Encode Here')
if msg != '':
p, q = rsa.findingPandQ()
while p == q:
p, q = rsa.findingPandQ()
n, e, d = rsa.generate_keys(p, q)
print(n, e, d)
I run this function in this
app.addButton('Encode', encode, 3, 3)
The class code is here:
import random
from math import gcd
class Rsa:
def __init__(self):
self.p, self.q = self.findingPandQ()
self.n = self.p * self.q
self.phi = (self.p - 1) * (self.q - 1)
self.e = 0
def isPrime(self, n):
for i in range(2,int(self.n**0.5)+1):
if self.n%i == 0:
return False
return True
def modReverse(self, phi, e):
self.pos00 = self.phi
self.pos01 = self.phi
self.pos10 = self.e
self.pos11 = 1
self.newpos10 = 0
while self.newpos10 != 1:
self.pos00pos10int = self.pos00 // self.pos10
self.inttimespos10 = self.pos00pos10int * self.pos10
self.inttimespos11 = self.pos00pos10int * self.pos11
self.newpos10 = self.pos00 - self.inttimespos10
if self.newpos10 < 0:
self.newpos10 %= phi
self.newpos11 = self.pos01 - self.inttimespos11
if self.newpos11 < 0:
self.newpos11 %= phi
self.pos00 = self.pos10
self.pos01 = self.pos11
self.pos10 = self.newpos10
self.pos11 = self.newpos11
return self.newpos11
def coprime(self, a, b):
return gcd(self.a, self.b) == 1
def findingPandQ(self):
self.a = random.randint(10,100)
while not self.isPrime(self.a):
self.a = random.randint(10,100)
self.b = random.randint(10,100)
while not self.isPrime(self.b):
self.b = random.randint(10,100)
return self.a, self.b
def generate_keys(self, p, q):
for i in range(self.phi):
if self.isPrime(i):
if self.coprime(i, self.phi):
self.e = i
self.d = self.modReverse(self.phi, self.e)
while self.e == self.d:
self.p, self.q = self.findingPandQ(self.p, self.q)
while self.p == self.q:
self.p, self.q = self.findingPandQ(self.p, self.q)
self.n, self.e, self.d = self.generate_keys(self.p, self.q)
return self.n, self.e, self.d
You are calling your functions before you have set self.n:
def __init__(self):
self.p, self.q = self.findingPandQ()
self.n = self.p * self.q
self.n is set only after you called findingPandQ(). Because you call isPrime() from findingPandQ(), and isPrime() assumes that self.n exists, that fails.
You probably made a simple error; you should be using n (the argument passed to isPrime(), and not self.n:
def isPrime(self, n):
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True

AttributeError: 'tuple' object has no attribute 'times_scalar'

This is my Linear System code. The times_scalar function is defined in the Vector object. When executing the multiply_coefficient_and_row function, I get AttributeError: 'tuple' object has no attribute 'times_scalar'. I tried different things including converting the tuple into a list and back to a tuple but had no success.
from decimal import Decimal, getcontext
from copy import deepcopy
from Vector import Vector
from Plane import Plane
getcontext().prec = 30
class LinearSystem(object):
ALL_PLANES_MUST_BE_IN_SAME_DIM_MSG = 'All planes in the system should live in the same dimension'
NO_SOLUTIONS_MSG = 'No solutions'
INF_SOLUTIONS_MSG = 'Infinitely many solutions'
def __init__(self, planes):
try:
d = planes[0].dimension
for p in planes:
assert p.dimension == d
self.planes = planes
self.dimension = d
except AssertionError:
raise Exception(self.ALL_PLANES_MUST_BE_IN_SAME_DIM_MSG)
def swap_rows(self, row1, row2):
self[row1], self[row2] = self[row2], self[row1]
def multiply_coefficient_and_row(self, coefficient, row):
n = self[row].normal_vector.coordinates
k = self[row].constant_term
new_normal_vector = n.times_scalar(coefficient)
new_constant_term = k * coefficient
self[row] = Plane(normal_vector = new_normal_vector, constant_term = new_constant_term)
def add_multiple_times_row_to_row(self, coefficient, row_to_add, row_to_be_added_to):
n1 = self[row_to_add].normal_vector.coordinates
n2 = self[row_to_be_added_to].normal_vector.coordinates
k1 = self[row_to_add].constant_term
k2 = self[row_to_be_added_to].constant_term
new_normal_vector = n1.times_scalar(coefficient).plus(n2)
new_constant_term = (k1 * coefficient) + k2
self[row_to_be_added_to] = Plane(normal_vector = new_normal_vector, constant_term = new_constant_term)
def indices_of_first_nonzero_terms_in_each_row(self):
num_equations = len(self)
num_variables = self.dimension
indices = [-1] * num_equations
for i,p in enumerate(self.planes):
try:
indices[i] = p.first_nonzero_index(p.normal_vector.coordinates)
except Exception as e:
if str(e) == Plane.NO_NONZERO_ELTS_FOUND_MSG:
continue
else:
raise e
return indices
def __len__(self):
return len(self.planes)
def __getitem__(self, i):
return self.planes[i]
def __setitem__(self, i, x):
try:
assert x.dimension == self.dimension
self.planes[i] = x
except AssertionError:
raise Exception(self.ALL_PLANES_MUST_BE_IN_SAME_DIM_MSG)
def __str__(self):
ret = 'Linear System:\n'
temp = ['Equation {}: {}'.format(i+1,p) for i,p in enumerate(self.planes)]
ret += '\n'.join(temp)
return ret
class MyDecimal(Decimal):
def is_near_zero(self, eps=1e-10):
return abs(self) < eps
and from the Vector class this times_scalar function:
def times_scalar(self, c):
new_coordinates = [Decimal(c) * x for x in self.coordinates]
return Vector(new_coordinates)

Categories