How to convert int to hex in python - python

I try to run spritz encryption code in python . which it have to convert in to hex. The same code is
result = self.s.int_to_hex(self.s.hash(256, self.s.int_string("ABC"), 32))
print(result)
It have no error but I want to reduce permutation array from 256 to 16. So I change the code like this.
result = self.s.int_to_hex(self.s.hash(16, self.s.int_string("ABC"), 32))
print(result)
Then it show error like this.
.E
======================================================================
ERROR: test_hash (__main__.TestSpritz)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:/Python34/test.py", line 9, in test_hash
result = self.s.int_to_hex(self.s.hash(16, self.s.int_string("ABC"), 32))
File "C:/Python34\spritz.py", line 130, in hash
self.absorb(M)
File "C:/Python34\spritz.py", line 73, in absorb
self.absorb_byte(byte)
File "C:/Python34\spritz.py", line 68, in absorb_byte
self.absorb_nibble(self.high(b))
File "C:/Python34\spritz.py", line 63, in absorb_nibble
self.S[self.a], self.S[int(math.floor(self.N/2)+x)] = self.S[int(math.floor(self.N/2)+x)], self.S[self.a]
IndexError: list index out of range
----------------------------------------------------------------------
Ran 2 tests in 0.031s
FAILED (errors=1)
I don't know how to use function int_to_hex please help me.
This is my code.
test.py
import unittest
from spritz import Spritz
class TestSpritz(unittest.TestCase):
def setUp(self):
self.s = Spritz()
def test_hash(self):
result = self.s.int_to_hex(self.s.hash(16, self.s.int_string("ABC"), 32))
print(result)
self.assertEqual(result[0:16], '028FA2B48B934A18')
result = self.s.int_to_hex(self.s.hash(256, self.s.int_string("spam"), 32))
self.assertEqual(result[0:16], 'ACBBA0813F300D3A')
result = self.s.int_to_hex(self.s.hash(256, self.s.int_string("arcfour"), 32))
self.assertEqual(result[0:16], 'FF8CF268094C87B9')
def test_encryption(self):
result = self.s.array_to_string(self.s.encrypt(self.s.int_string("ABC"), [0]*8))
self.assertEqual(result, '779A8E01F9E9CBC0')
result = self.s.array_to_string(self.s.encrypt(self.s.int_string("spam"), [0]*8))
self.assertEqual(result, 'F0609A1DF143CEBF')
result = self.s.array_to_string(self.s.encrypt(self.s.int_string("arcfour"), [0]*8))
self.assertEqual(result, '1AFA8B5EE337DBC7')
if __name__ == '__main__':
unittest.main()
spritz.py
import math
from fractions import gcd
class Spritz():
alt = False
def initialize_state(self, N_input):
self.i = 0
self.j = 0
self.k = 0
self.z = 0
self.a = 0
self.w = 1
self.N = N_input
self.D = int(math.ceil(math.sqrt(self.N)))
self.S = list(range(self.N))
def low(self, b):
return b % self.D
def high(self, b):
return int(math.floor(b/self.D))
def update(self):
self.i = (self.i + self.w) % self.N
self.j = (self.k + self.S[(self.j + self.S[self.i]) % self.N]) % self.N
self.k = (self.i + self.k + self.S[self.j]) % self.N
self.S[self.i], self.S[self.j] = self.S[self.j], self.S[self.i]
def whip(self, r):
for v in list(range(r)):
self.update()
self.w = (self.w + 1) % self.N
while gcd(self.w, self.N) != 1:
self.w = (self.w + 1) % self.N
def crush(self):
for v in list(range(int(math.floor(self.N/2)))):
if self.S[v] > self.S[self.N-1-v]:
self.S[v], self.S[self.N-1-v] = self.S[self.N-1-v], self.S[v]
def alt_crush(self):
for v in list(range(int(math.floor(self.N/2)))):
x = self.S[v]
y = self.S[N-1-v]
if x > y:
self.S[v] = y
self.S[N-1-v] = x
else:
self.S[v] = x
self.S[N-1-v] = y
def shuffle(self):
self.whip(2*self.N)
self.alt_crush() if self.alt else self.crush()
self.whip(2*self.N)
self.alt_crush() if self.alt else self.crush()
self.whip(2*self.N)
self.a = 0
def absorb_nibble(self, x):
if self.a == int(math.floor(self.N/2)):
self.shuffle()
self.S[self.a], self.S[int(math.floor(self.N/2)+x)] = self.S[int(math.floor(self.N/2)+x)], self.S[self.a]
self.a = (self.a + 1) % self.N
def absorb_byte(self, b):
self.absorb_nibble(self.low(b))
self.absorb_nibble(self.high(b))
def absorb(self, I):
for v in list(range(0, len(I), 3)):
byte = int(I[v:v+3])
self.absorb_byte(byte)
def absorb_stop(self):
if self.a == int(math.floor(self.N/2)):
self.shuffle()
self.a = (self.a + 1) % self.N
def output(self):
self.z = self.S[(self.j + self.S[(self.i + self.S[(self.z + self.k) % self.N]) % self.N]) % self.N]
return self.z
def drip(self):
if self.a > 0:
self.shuffle()
self.update()
return self.output()
def squeeze(self, r):
if self.a > 0:
self.shuffle()
P = ""
for v in list(range(r)):
#P.append("%0.2X" % self.drip())
P += "%03d" % self.drip()
return P
def print_variables(self):
print ("i: " + hex(self.i))
print ("j: " + hex(self.j))
print ("k: " + hex(self.k))
print ("z: " + hex(self.z))
print ("a: " + hex(self.a))
print ("w: " + hex(self.w))
print ("D: " + hex(self.D))
print ("S: " + self.array_to_string(self.S))
#print "S: " + str(self.S)
def int_string(self, string):
key = ""
for char in string:
key += "%03d" % ord(char)
return key
def int_to_hex(self, int_string):
result = ""
for i in list(range(0, len(int_string), 3)):
result += "%0.2X" % int(int_string[i:i+3])
return result
def array_to_string(self, array):
result = ""
for i in array:
result += "%0.2X" % i
return result
def hash(self, N, M, r):
self.initialize_state(N)
self.absorb(M)
self.absorb_stop()
self.absorb_byte(r)
return self.squeeze(r)
def key_setup(self, K):
self.initialize_state(256)
self.absorb(K)
def encrypt(self, K, M):
self.key_setup(K)
Z_string = self.squeeze(len(M))
Z = [int(Z_string[i:i+3]) for i in list(range(0, len(Z_string), 3))]
C = [i + j for i, j in zip(M, Z)]
return C

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 .

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

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