Instance has no attribute _pi - python

I'm trying to make a Python module like this:
class square:
def _init_(self):
self._length = 0
self._perimeter = 0
self._area = 0
def setLength(self, length):
self._length = float(length)
self._perimeter = 0
self._area = 0
def getLength(self):
return self._length
def getPerimeter(self):
if self._perimeter == 0:
self._perimeter = float(self._length * 4)
return self._perimeter
def getArea(self):
if self._area == 0:
self._area = float(self._length * self._length)
return self._area
class rectangle:
def _init_(self):
self._length = 0
self._width = 0
self._perimeter = 0
self._area = 0
def setLength(self, length):
self._length = float(length)
self._perimeter = 0
self._area = 0
def getLength(self):
return self._length
def setWidth(self, width):
self._width = float(width)
self._perimeter = 0
self._area = 0
def getWidth(self):
return self._width
def getPerimeter(self):
if self._perimeter == 0:
perim1 = float(self._length * 2)
perim2 = float(self._width * 2)
self._perimeter = float(perim1 + perim2)
return self._perimeter
def getArea(self):
if self._area == 0:
self._area = float(self._length * self._width)
return self._area
class circle:
def _init_(self):
self._radius = 0
self._diameter = 0
self._circumference = 0
self._pi = 3.14159265
def setRadius(self, radius):
self._radius = float(radius)
self._diameter = float(self._radius * 2)
self._circumference = 0
def setDiameter(self, diameter):
self._diameter = float(diameter)
self._radius = float(self._diameter / 2)
self._circumference = 0
def getRadius(self):
return self._radius
def getDiameter(self):
return self._diameter
def getPi(self):
return self._pi
def getCircumference(self):
if self._circumference == 0:
self._circumference = float(self._diameter * self._pi)
return self._circumference
class triangle:
def _init_(self):
self._side = []
self._side[0] = 0
self._side[1] = 0
self._side[2] = 0
self._side[3] = 0
self._angle = []
self._angle[0] = 0
self._angle[1] = 0
self._angle[2] = 0
self._angle[3] = 0
self._perimeter = 0
self._area = 0
def setSide(self, side, length):
self._side[side] = float(length)
def getSide(self, side):
return self._side[side]
def getPerimeter(self):
if self._perimeter == 0:
self._perimeter = side[1] + side[2] + side[3]
return self._perimeter
def setAngle(self, angle, measure):
self._angle[angle] = float(measure)
def getAngle(self, angle):
if self._angle[angle] == 0:
if angle == 1:
angle1 = self._angle[2]
angle2 = self._angle[3]
elif angle == 2:
angle1 = self._angle[1]
angle2 = self._angle[3]
elif angle == 3:
angle1 = self._angle[1]
angle2 = self._angle[2]
anglet = angle1 + angle2
angler = float(180) - anglet
self._angle[angle] = angler
return self.angle[angle]
It's part of a package named Mathworks. The calling code is this:
import mathworks as mw
mycircle = mw.shapes.circle()
mycircle.setDiameter(5)
circum = mycircle.getCircumference()
print circim
When I try two run the second module, I get this:
Traceback (most recent call last):
File "<string>", line 254, in run_nodebug
File "<module1>", line 21, in <module>
File "<module1>", line 17, in main
File "C:\Python27\lib\site-packages\mathworks\shapes.py", line 70, in getCircumference
self._circumference = float(self._diameter * self._pi)
AttributeError: circle instance has no attribute '_pi'
What's wrong? It works if I replace self._pi with 3.14159265, but I need it to work the other way.

You didn't name your initializers correctly, it needs double underscores on either end:
def __init__(self):
You need to correct that for all your classes.
Because you didn't name them correctly, they are not being run when you create an instance of your classes.
Next problem you'll run into is your triangle initializer; you cannot address indexes in an empty list. Create the whole list in one go instead:
def __init__(self):
self._side = [0, 0, 0, 0]
self._angle = [0, 0, 0, 0]
self._perimeter = 0
self._area = 0

You have the constructor written incorrectly. It should be __init__, not _init_, i.e. double underscores.
Because you wrote it wrong, it's not being called, so those attributes aren't being created when you instantiate your objects.

Related

How to solve class inheritance in Python?

I have 2 almost identical classes. How can they be solved by inheritance?
1 class (maybe parent):
class Heart():
""" třída zdraví """
def __init__(self):
self.x = []
self.y = []
self.s = []
self.h = 0
def vykresli(self):
#vykreslení srdce
heart_big = pygame.image.load(os.path.join(DIR, "images/heart_big.png"))
heart_small = pygame.image.load(os.path.join(DIR, "images/heart_small.png"))
if random.randrange(0, 500) == 1 and len(self.x) <= 0:
self.x.append(random.randrange(50, 970))
self.y.append(0)
self.s.append(random.randrange(1, 4))
for x in range(len(self.x)):
if self.h % 9 == 0:
SCREEN.blit(heart_big, (self.x[x], self.y[x]))
else:
SCREEN.blit(heart_small, (self.x[x], self.y[x]))
self.y[x] += self.s[x]
self.h += 1
if self.h > 100: self.h = 0
for y in range(len(self.x)):
if self.y[y] > OKNO_Y:
del self.y[y]
del self.x[y]
del self.s[y]
break
2 class (maybe child)
class MissileStack():
"""definuje třídu nabití zásobníku střelami"""
def __init__(self):
self.x = []
self.y = []
self.s = []
self.h = 0
self.rotate = 0
def vykresli(self):
#vykreslení dodávky zásoby střel
misilestack = pygame.image.load(os.path.join(DIR, "images/misilestack.png"))
if random.randrange(0, 50) == 1 and len(self.x) <= 0:
self.x.append(random.randrange(50, 970))
self.y.append(0)
self.s.append(random.randrange(1, 4))
#self.missile = pygame.transform.rotate(pygame.image.load(os.path.join(DIR, "images/missile.png")),180)
for x in range(len(self.x)):
misilestackrotate = pygame.transform.rotate(misilestack, self.rotate)
SCREEN.blit(misilestackrotate, (self.x[x], self.y[x]))
self.y[x] += self.s[x]
self.h += 1
self.rotate += 1
if self.rotate >= 360: self.rotate = 0
if self.h > 100: self.h = 0
for y in range(len(self.x)):
if self.y[y] > OKNO_Y:
del self.y[y]
del self.x[y]
del self.s[y]
break
Both classes do practically the same thing. They just use a different image and a different random generation. I've read a lot of tutorials on class inheritance, but I can't use inheritance in practice.
Ignoring the fact that your code is doing a bunch of questionable things, You can create a base class that factors out the common operations.
All the class and method names are completely made up here, since I don't know what you are really trying to do and my command of your native language is non-existent:
class Sprite:
def __init__(self, r):
self.x = []
self.y = []
self.s = []
self.r = r
def vykresli(self):
if random.randrange(0, self.r) == 1 and len(self.x) <= 0:
self.x.append(random.randrange(50, 970))
self.y.append(0)
self.s.append(random.randrange(1, 4))
self.pre_loop()
for x in range(len(self.x)):
self.do_blit((self.x[x], self.y[x]))
self.y[x] += self.s[x]
self.post_loop()
for y in range(len(self.x)):
if self.y[y] > OKNO_Y:
del self.y[y]
del self.x[y]
del self.s[y]
break
def pre_loop(self):
pass
def post_loop(self):
pass
The deltas now make for two small specific classes:
class Heart(Sprite):
def __init__(self):
super().__init__(500)
self.h = 0
#vykreslení srdce
self.heart_big = pygame.image.load(os.path.join(DIR, "images/heart_big.png"))
self.heart_small = pygame.image.load(os.path.join(DIR, "images/heart_small.png"))
def do_blit(self, coord):
if self.h % 9 == 0:
SCREEN.blit(self.heart_big, coord)
else:
SCREEN.blit(self.heart_small, coord)
def post_loop(self):
super().post_loop()
self.h += 1
if self.h > 100:
self.h = 0
and
class Missiles(Sprite):
def __init__(self):
super().__init__(50)
#vykreslení dodávky zásoby střel
misilestack = pygame.image.load(os.path.join(DIR, "images/misilestack.png"))
def pre_loop(self):
super().pre_loop()
self.misilestackrotate = pygame.transform.rotate(misilestack, self.rotate)
def do_blit(self, coord):
SCREEN.blit(self.misilestackrotate, coord)
def post_loop(self):
super().post_loop()
self.rotate += 1
if self.rotate >= 360:
self.rotate = 0
I've added hooks called pre_loop, do_blit and post_loop to allow you to do class-specific operations for each type of Sprite. You can experiment with abstract base classes if you want to do things like enforce an implementation of do_blit.

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()

AttributeError: 'list' object has no attribute 'row'

Following Code From the book deep learning and the game of go
Not Sure Why I am getting this error
full error:
Traceback (most recent call last): File "bot_v_bot.py", line 25, in
main() File "bot_v_bot.py", line 20, in main
bot_move = bots[game.next_player].select_move(game) File "C:\Users\Max\Desktop\books\pdf\code\Go ML\dlgo\agent\naive.py", line
14, in select_move
if game_state.is_valid_move(Move.play(canidate)) and not is_point_an_eye(game_state.board, canidate, game_state.next_player):
File "C:\Users\Max\Desktop\books\pdf\code\Go
ML\dlgo\agent\helpers.py", line 20, in is_point_an_eye
if board.is_on_grid(corners): File "C:\Users\Max\Desktop\books\pdf\code\Go ML\dlgo\goboard_slow.py", line
71, in is_on_grid
return 1 <= point.row <= self.num_rows and 1 <= point.col <=
self.num_cols AttributeError: 'list' object has no attribute 'row'
My Directory looks like
GO ML
-bot_v_bot.py
-dlgo
---__pychache__
---agent
----__init__.py
----base.py
----helpers.py
----naive.py
---__init__.py
---goboard_slow.py
---gotypes.py
---utils.py
Bot_V_Bot code
from dlgo.agent import naive
from dlgo import goboard_slow
from dlgo import gotypes
from dlgo.utils import print_board, print_move
import time
def main():
board_size = 9
game = goboard_slow.GameState.new_game(board_size)
bots = {
gotypes.Player.black: naive.RandomBot(),
gotypes.Player.white: naive.RandomBot(),
}
while not game.is_over():
time.sleep(0.3)
print(chr(27) + "[2j")
print_board(game.board)
bot_move = bots[game.next_player].select_move(game)
print_move(game.next_player, bot_move)
game = game.apply_move(bot_move)
if __name__ == '__main__':
main()
goboard_slow code
import copy
from dlgo.gotypes import Player
from dlgo.gotypes import Point
class GoString():
def __init__(self, color, stones, liberties):
self.color = color
self.stones = set(stones)
self.liberties = set(liberties)
def remove_liberty(self, point):
self.liberties.remove(point)
def add_liberty(self, point):
self.liberties.add(point)
def merged_with(self, go_string):
assert go_string.color == self.color
combined_stones = self.stones | go_string.stones
return GoString(
self.color,
combined_stones,
(self.liberties | go_string.liberties) - combined_stones)
#property
def num_liberties(self):
return len(self.liberties)
def __eq__(self, other):
return isinstance(other, GoString) and \
self.color == other.color and \
self.stones == other.stones and \
self.liberties == other.liberties
class Board():
def __init__(self, num_rows, num_cols):
self.num_rows = num_rows
self.num_cols = num_cols
self._grid = {}
def place_stone(self, player, point):
assert self.is_on_grid(point)
assert self._grid.get(point) is None
adjacent_same_color = []
adjacent_opposite_color = []
liberties = []
for neighbor in point.neighbors():
if not self.is_on_grid(neighbor):
continue
neighbor_string = self._grid.get(neighbor)
if neighbor_string is None:
liberties.append(neighbor)
elif neighbor_string.color == player:
if neighbor_string not in adjacent_same_color:
adjacent_same_color.append(neighbor_string)
else:
if neighbor_string not in adjacent_opposite_color:
adjacent_opposite_color.append(neighbor_string)
new_string = GoString(player, [point], liberties)
for same_color_string in adjacent_same_color:
new_string = new_string.merged_with(same_color_string)
for new_string_point in new_string.stones:
self._grid[new_string_point] = new_string
for other_color_string in adjacent_opposite_color:
other_color_string.remove_liberty(point)
for other_color_string in adjacent_same_color:
if other_color_string.num_liberties == 0:
self._remove_string(other_color_string)
def is_on_grid(self, point):
return 1 <= point.row <= self.num_rows and 1 <= point.col <= self.num_cols
def get(self, point):
string = self._grid.get(point)
if string is None:
return None
return string.color
def get_go_string(self, point):
string = self._grid.get(point)
if string is None:
return None
return string
def _remove_string(self, string):
for point in string.stones:
for neighbor in point.neighbors():
neighbor_string = self._grid.get(neighbor)
if neighbor_string is None:
continue
if neighbor_string is not string:
neighbor_string.add_liberty(point)
self._grid[point] = None
class Move():
def __init__(self, point=None, is_pass=False, is_resign=False):
assert (point is not None) ^ is_pass ^ is_resign
self.point = point
self.is_play = (self.point is not None)
self.is_pass = is_pass
self.is_resign = is_resign
#classmethod
def play(cls, point):
return Move(point=point)
#classmethod
def pass_turn(cls):
return Move(is_pass=True)
#classmethod
def resign(cls):
return Move(is_resign=True)
class GameState():
def __init__(self, board, next_player, previous, move):
self.board = board
self.next_player = next_player
self.previous_state = previous
self.last_move = move
def apply_move(self, move):
if move.is_play:
next_board = copy.deepcopy(self.board)
next_board.place_stone(self.next_player, move.point)
else:
next_board = self.board
return GameState(next_board, self.next_player.other, self, move)
#classmethod
def new_game(cls, board_size):
if isinstance(board_size, int):
board_size = (board_size, board_size)
board = Board(*board_size)
return GameState(board, Player.black, None, None)
def is_over(self):
if self.last_move is None:
return False
if self.last_move.is_resign:
return True
second_last_move = self.previous_state.last_move
if second_last_move is None:
return False
return self.last_move.is_pass and second_last_move.is_pass
def is_move_self_capture(self, Player, move):
if not move.is_play:
return False
next_board = copy.deepcopy(self.board)
next_board.place_stone(Player, move.point)
new_string = next_board.get_go_string(move.point)
return new_string.num_liberties == 0
#property
def situation(self):
return (self.next_player, self.board)
def does_move_validate_ko(self, player, move):
if not move.is_play:
return False
next_board = copy.deepcopy(self.board)
next_board.place_stone(player, move.point)
next_situation = (Player.other, next_board)
past_state = self.previous_state
while past_state is not None:
if past_state.situation == next_situation:
return True
past_state = past_state.previous_state
return False
def is_valid_move(self, move):
if self.is_over():
return False
if move.is_pass or move.is_resign:
return True
return (
self.board.get(move.point) is None and
not self.is_move_self_capture(self.next_player, move) and
not self.does_move_validate_ko(self.next_player, move))
gotypes code
import enum
from collections import namedtuple
class Player(enum.Enum):
black = 1
white = 2
#property
def other(self):
return Player.black if self == Player.white else Player.white
class Point(namedtuple('Point', 'row col')):
def neighbors(self):
return [
Point(self.row - 1, self.col),
Point(self.row + 1, self.col),
Point(self.row, self.col - 1),
Point(self.row, self.col + 1),
]
utils code
import random
from dlgo.agent.base import Agent
from dlgo.agent.helpers import is_point_an_eye
from dlgo.goboard_slow import Move
from dlgo.gotypes import Point
class RandomBot(Agent):
def select_move(self, game_state):
""""Choose a random valid move that preserves our own eyes."""
canidates = []
for r in range(1, game_state.board.num_rows + 1):
for c in range(1, game_state.board.num_cols +1):
canidate = Point(row=r, col=c)
if game_state.is_valid_move(Move.play(canidate)) and not is_point_an_eye(game_state.board, canidate, game_state.next_player):
canidates.append(canidate)
if not canidates:
return Move.pass_turn()
return Move.play(random.choice(canidates))
from dlgo import gotypes
COLS = 'ABCDEFGHIJKLMNOPQRST'
STONE_TO_CHAR = {
None: ' . ',
gotypes.Player.black: ' x ',
gotypes.Player.white: ' o ',
}
def print_move(player, move):
if move.is_pass:
move_str = 'passes'
elif move.is_resign:
move_str = 'resigns'
else:
move_str = '%s%d' % (COLS[move.point.col - 1], move.point.row)
print('%s %s' % (player, move_str))
def print_board(board):
for row in range(board.num_rows, 0, -1):
bump = " " if row <= 9 else ""
line = []
for col in range(1, board.num_cols + 1):
stone = board.get(gotypes.Point(row = row, col = col))
line.append(STONE_TO_CHAR[stone])
print('%s%d %s' % (bump, row, ''.join(line)))
print(' ' + ' '.join(COLS[:board.num_cols]))
Helpers Code
from dlgo.gotypes import Point
def is_point_an_eye(board, point, color):
if board.get(point) is not None:
return False
for neighbor in point.neighbors():
if board.is_on_grid(neighbor):
neighbor_color= board.get(neighbor)
if neighbor_color != color:
return False
friendly_corners = 0
off_board_corners = 0
corners = [
Point(point.row - 1, point.col - 1),
Point(point.row - 1, point.col + 1),
Point(point.row + 1, point.col - 1),
Point(point.row + 1, point.col + 1),
]
for corner in corners:
if board.is_on_grid(corners):
corner_color = board.get(corner)
if corner_color == olor:
friendly_corners += 1
else:
off_board_corners += 1
if off_board_corners > 0:
return off_board_corners + friendly_corners == 4
return friendly_corners >= 3
Base Code
class Agent:
def __init(self):
pass
def selec_move(self, game_state):
raise NotImplementedError()
Both Inits are empty
corners is the list of all corner points, corner is
the current element in the for loop.
Barmar
I think it's just a typo: board.is_on_grid(corners)
should be board.is_on_grid(corner)
Barmar
These worked and fixed it

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

Python binary search tree height function wont work

I've been trying the recursive approach but been stuck for too long. I cant tell if it's my BST code that's wrong or my recursion.
Regardless of how many elements I put in my tree I still get the value 2 from my height function.
class Treenode:
def __init__(self, value = None, rchild = None, lchild = None):
self.value = value
self.rchild = rchild
self.lchild = lchild
class bin_tree:
def __init__(self):
self.root = None
def put(self, x):
if self.root is None:
self.root = Treenode(x)
return True
if self.exists(x) == True:
return False
p = self.root
while True:
if x < p.value:
if p.lchild is None:
p.lchild = Treenode(x)
return True
else:
p = p.lchild
elif x > p.value:
if p.rchild is None:
p.rchild = Treenode(x)
return True
else:
p = p.rchild
return
def exists(self, x):
p = self.root
while True and p != None:
if p.value == x:
return True
elif p.value > x and p.lchild != None:
p = p.lchild
elif p.value < x and p.rchild != None:
p = p.rchild
else:
return False
def isempty(self):
return self.root == None
def height(self):
def gh(enrot):
if enrot == None:
return 0
else:
return 1 + max(gh(enrot.lchild), gh(enrot.rchild))
return gh(self.root)
Example code:
from Bintree import *
p = bin_tree()
x = input()
for word in x.split():
p.put(word)
a = input()
if p.exists(a) is True:
print('Exists!')
else:
print('Does not exist!')
print(p.isempty())
print(p.height())
The height method is fine. In your put method, you stop without actually adding the element, so the height doesn't actually grow beyond 2:
def put(self, x):
...
while True:
if x < p.value:
...
elif x > p.value:
if p.rchild is None:
...
else:
p = p.rchild
return
# ^^^^^^ This shouldn't be here.

Categories