I'm implementing A5/1 algorithm, I have the following function:
def to_binary(plain):
print(plain)
binary = str(''.join(format(ord(x), 'b') for x in plain))
j = len(binary)
binary_values = []
k = 0
while(k < j):
binary_values.insert(k,int(binary[k]))
k = k + 1
return(binary_values)
then I'm reading the input as the following:
plainText = input("Please enter your plaintext : ")
print ("You entered : "+ plainText)
plainText = to_binary(plainText)
After that I generate a keyStream and I store it in a list, then I obtain the ciphered text as the following:
while(i < len(plainText)):
cipherText = cipherText + str(plainText[i] ^ keyStream[i])
i = i + 1
Now I can decrypt the ciphered text using the following function:
def decrypt(cipher,keystream):
s = ""
binary = []
i = 0
while(i<len(cipher)):
binary.insert(i,int(cipher[i]))
s = s + str(binary[i]^keystream[i])
i = i +1
print(s)
return convert_binary_to_str(s)
and the convert_binary_to_str function is:
def convert_binary_to_str(bin_data):
str_data =' '
for i in range(0, len(bin_data), 7):
temp_data = bin_data[i:i + 7]
decimal_data = BinaryToDecimal(temp_data)
str_data = str_data + chr(decimal_data)
return str_data
Everything is working fine if the input was a sentence with no white spaces, but if the sentence was for example "Hello There", the decryption is corrupted because the white space representation in binary this way is taking "6 bits" while the other alphabetical characters are "7-bits" long, what can I do to solve this?? I need to store the plain text in a list to apply the algorithm.
I am trying to implement bitonic with the python multiprocessing library and a shared resource array that will be sorted at the end of the program.
The problem I am running into is that when I run the program, I get an prompt that asks "Your program is still running! Are you sure you want to cancel it?" and then when I click cancel N - 1 times (where N is the amount of processes I am trying to spawn) then it just hangs.
When this is run from the command line, it just outputs the unsorted array. Of course, I expect it to be sorted at the program's finish.
I've been using this resource to try and get a firm grasp on how I can mitigate my errors but I haven't had any luck, and now I am here.
ANY help would be appreciated, as I really don't have anywhere else to turn to.
I wrote this using Python 3.6 and here is the program in its entirety:
from multiprocessing import Process, Array
import sys
from random import randint
# remember to move this to separate file
def createInputFile(n):
input_file = open("input.txt","w+")
input_file.write(str(n)+ "\n")
for i in range(n):
input_file.write(str(randint(0, 1000000)) + "\n")
def main():
# createInputFile(1024) # uncomment this to create 'input.txt'
fp = open("input.txt","r") # remember to read from sys.argv
length = int(fp.readline()) # guaranteed to be power of 2 by instructor
arr = Array('i', range(length))
nums = fp.read().split()
for i in range(len(nums)):
arr[i]= int(nums[i]) # overwrite shared resource values
num_processes = 8 # remember to read from sys.argv
process_dict = dict()
change_in_bounds = len(arr)//num_processes
low_b = 0 # lower bound
upp_b = change_in_bounds # upper bound
for i in range(num_processes):
print("Process num: " + str(i)) # are all processes being generated?
process_dict[i] = Process(target=bitonic_sort, args=(True, arr[low_b:upp_b]) )
process_dict[i].start()
low_b += change_in_bounds
upp_b += change_in_bounds
for i in range(num_processes):
process_arr[i].join()
print(arr[:]) # Print our sorted array (hopefully)
def bitonic_sort(up, x):
if len(x) <= 1:
return x
else:
first = bitonic_sort(True, x[:len(x) // 2])
second = bitonic_sort(False, x[len(x) // 2:])
return bitonic_merge(up, first + second)
def bitonic_merge(up, x):
# assume input x is bitonic, and sorted list is returned
if len(x) == 1:
return x
else:
bitonic_compare(up, x)
first = bitonic_merge(up, x[:len(x) // 2])
second = bitonic_merge(up, x[len(x) // 2:])
return first + second
def bitonic_compare(up, x):
dist = len(x) // 2
for i in range(dist):
if (x[i] > x[i + dist]) == up:
x[i], x[i + dist] = x[i + dist], x[i] #swap
main()
I won't go into all the syntax errors in your code since I am sure your IDE tells you about those. The problem that you have is that you are missing an if name==main. I changed your def main() to def sort() and wrote this:
if __name__ == '__main__':
sort()
And it worked (after solving all the syntax errors)
Here is the full code, it is for a basic random alphabetical shift encryption. For some reason, the .write() don't seem to be working.
from random import randint
import time
import os
sentence = input('What do you want to encrypt? ').lower()
namefile = input('What do you want to call the encrypted file? ')
alphabet = {'a':0,'b':1,'c':2,'d':3,'e':4,'f':5,'g':6,'h':7,'i':8,'j':9,'k':10,'l':11,'m':12,'n':13,'o':14,'p':15,'q':16,'r':17,'s':18,'t':19,'u':20,'v':21,'w':22,'x':23,'y':24,'x':25,' ':26,'.':27}
alphabet1 = {0:'a',1:'b',2:'c',3:'d',4:'e',5:'f',6:'g',7:'h',8:'i',9:'j',10:'k',11:'l',12:'m',13:'n',14:'o',15:'p',16:'q',17:'r',18:'s',19:'t',20:'u',21:'v',22:'w',23:'x',24:'y',25:'x',26:' ',27:'.'}
shift = randint(1,27)
x = len(sentence)
y = 0
encrypted_file = open(namefile + '.txt', 'wt')
while y < x:
letter = sentence[y]
position = alphabet[letter]
position = position + shift
if position > 27:
position = position - 27
letter = alphabet1[position]
Here is the first .write(). This one is inside a loop.
encrypted_file.write(letter)
y = y + 1
This is the second .write(). This is a single use one
encrypted_file.write('\nEncryption Shift = ' + str(shift))
encrypted_file.close
time.sleep(2)
print('Done')
time.sleep(1)
print('Here is your encrypted file.')
time.sleep(2)
os.startfile('C:/Users/Jedidiah/Documents/' + namefile + '.txt')
The mode key "wt" doesn't exist.
check here! for all proper mode keys
UPDATE: try this
from random import randint
import time
import os
sentence = input('What do you want to encrypt? ').lower()
namefile = input('What do you want to call the encrypted file? ')
alphabet = {'a':0,'b':1,'c':2,'d':3,'e':4,'f':5,'g':6,'h':7,'i':8,'j':9,'k':10,'l':11,'m':12,'n':13,'o':14,'p':15,'q':16,'r':17,'s':18,'t':19,'u':20,'v':21,'w':22,'x':23,'y':24,'x':25,' ':26,'.':27}
alphabet1 = {0:'a',1:'b',2:'c',3:'d',4:'e',5:'f',6:'g',7:'h',8:'i',9:'j',10:'k',11:'l',12:'m',13:'n',14:'o',15:'p',16:'q',17:'r',18:'s',19:'t',20:'u',21:'v',22:'w',23:'x',24:'y',25:'x',26:' ',27:'.'}
shift = randint(1,27)
x = len(sentence)
y = 0
encrypted_file = open(namefile + '.txt', 'a')
while y < x:
letter = sentence[y]
position = alphabet[letter]
position = position + shift
if position > 27:
position = position - 27
letter = alphabet1[position]
encrypted_file.write(letter)
y = y + 1
encrypted_file.write('\nEncryption Shift = ' + str(shift))
encrypted_file.close
time.sleep(2)
print('Done')
time.sleep(1)
print('Here is your encrypted file.')
time.sleep(2)
os.startfile('C:/Users/Jedidiah/Documents/' + namefile + '.txt')
if you want to overwrite the file use "w" for the mode key
import random
def diceRoll(number):
roll = random.randint(1,number)
print("Rolling a ",number," sided die.")
return roll
def newAccount(playername):
print("Greetings ", playername,"! We'll generate your charecter's attributes by rolling some die")
skillroll = 10 + (int(round((diceRoll(12)/diceRoll(4)))))
strengthroll = 10 + (int(round((diceRoll(12)/diceRoll(4)))))
print("You have ",skillroll," skillpoints and ",strengthroll," strength!")
class newplayer:
name = playername
skill = skillroll
strength = strengthroll
save(newplayer)
def save(newplayer):
"""Saves all details"""
file = open("accounts.txt","a")
file.write("CharacterName = '" + newplayer.name + "'\n")
file.write("Strength = " + str(newplayer.strength) + '\n')
file.write("Skill = " + str(newplayer.skill) + '\n')
file.write("\n")
print("Saved account")
def newPlayer():
try:
player1 = input("What is your 1st player's name? ")
newAccount(player1)
except:
print("Please only enter letters for your character name ")
newPlayer()
newPlayer()
print(" ")
player2 = input("What is your 2nd player's name? ")
newAccount(player2)
The part in bold is the part of the code I have attempted to alter to add some sort of error handling. Someone help me out here please, I know it's probably simple but I can't find an answer to this question anywhere.
Pythons RegEx would be a quite easy solution:
import re
if not re.match("[a-z]+$",inputString):
#your exception handling
I have a problem, when in Hangman game there is a word like happy, it only append 1 'p' in the list...run my code and please tell me what to do?
check my loops.
import random
import time
File=open("Dict.txt",'r')
Data = File.read()
Word = Data.split("\n")
A = random.randint(0,len(Word)-1)
Dict = Word[A]
print(Dict)
Dash = []
print("\n\n\t\t\t","_ "*len(Dict),"\n\n")
i = 0
while i < len(Dict):
letter = str(input("\n\nEnter an alphabet: "))
if letter == "" or letter not in 'abcdefghijklmnopqrstuvwxyz' or len(letter) != 1:
print("\n\n\t\tPlease Enter Some valid thing\n\n")
time.sleep(2)
i = i - 1
if letter in Dict:
Dash.append(letter)
else:
print("This is not in the word")
i = i - 1
for item in Dict:
if item in Dash:
print(item, end = " ")
else:
print("_", end = " ")
i = i + 1
The error is with the "break" on Line 25: once you have filled in one space with the letter "p", the loop breaks and will not fill in the second space with "p".
You need to have a flag variable to remember whether any space has been successfully filled in, like this:
success = False
for c in range(len(Dict)):
if x == Dict[c]:
Dash[c] = x
success = True
if not success:
Lives -= 1
P.S. There's something wrong with the indentation of the code you have posted.