Here is my code
def gen_code(codeLength):
symbols = ('ABCDEF')
code = random.sample(symbols, k=codeLength)
return str(code)
def print_code(code):
i = 0
while i < len(code):
print(code[i])
i += 1
code = gen_code(codeLength)
print("The code is " + code)
convCode = code[0] + code[1] + code[2] + code[3]
print(convCode)
So I basically want to generate a random string from the letters I have provided and then check if the user guesses a correct entry in that string (I'm trying to make mastermind). The issue I have is checking to see if the user's guess is in the code which is generated.
This is what my code outputs:
Why is my convCode variable printing ['E' and not EAFB?
If the code is returned as a list instead of a string, you can access the individual letters of the code in the manner you want to.
import random
codeLength=4
def gen_code(codeLength):
symbols = ('ABCDEF')
code = random.sample(symbols, k=codeLength)
return code
def print_code(code):
i = 0
while i < len(code):
print(code[i])
i += 1
code = gen_code(codeLength)
print("The code is " + str(code))
convCode = code[0] + code[1] + code[2] + code[3]
print(convCode)
In your gen_code function you convert the list to a string before you return it:
def gen_code(codeLength):
symbols = ('ABCDEF')
code = random.sample(symbols, k=codeLength)
# This converts it to a string, rather than leaving it as a list
# which is presumably what you want.
return str(code)
So later in your code:
convCode = code[0] + code[1] + code[2] + code[3]
Gives you the first four characters of that string which are exactly ['E'
Try changing gen_code to this:
def gen_code(codeLength):
symbols = ('ABCDEF')
code = random.sample(symbols, k=codeLength)
return code
code is a list use slicing to get the required result which will give you flexibility as you need not write hardcoded list indices each time.
import random
def gen_code(codeLength):
symbols = ('ABCDEF')
code = random.sample(symbols, k=codeLength)
return code
def print_code(code):
i = 0
while i < len(code):
print(code[i])
i += 1
code = gen_code(5)
print("The code is " + str(code))
convCode =code[:4]
print(convCode)
Related
I am trying to convert units within an excel file. The code below was working until I added the unitval.replace statements, after which the unit conversion doesn't occur. These are to replace , to . in the data and " " to no space. Is it possible to write something like this and still get the unit conversion code below it to work? Thanks!
def unitConversion(ssheet,scollist,units,c):
if (units != None):
unitval = str(ssheet.cell_value(units,c))
factor = 1
if "," in unitval:
unitval = unitval.replace(",",".")
if " " in unitval:
unitval = unitval.replace(" ", "")
try:
factor = REF.conversions[unitval]
for i in range(0,len(scollist),1):
try:
scollist[i] = float(scollist[i]) * factor
except:
if (scollist[i] == ""):
scollist[i] = ""
elif ((scollist[i][0] == "<") or (scollist[i][0] == ">")):
temp = float(scollist[i][1:])
scollist[i] = "-" + str(temp/1000)
Here is my code:
import turtle
def first_index(s):
for i in range(len(s)):
if not (s[i].isdigit()):
return i
return None
def go_to(s):
if s[0] == 'G':
comma_ind = first_index(s)
first_arg = int(s[1:comma_ind])
second_arg = int(s[comma_ind + 1:comma_ind + first_index(s[comma_ind + 1:])])
turtle.goto(first_arg, second_arg)
go_to('G10,10')
Does anyone know why this error occurs? Your help would be much appreciated, thank you!
Two issue:
first_index should return the last index if a a non-digit character is not found
When getting the second parameter, you're sending a partial string to the index function so you need to add the starting index of the string you passed
Try this code:
import turtle
#This gets the
def first_index(s):
for i in range(1,len(s)):
if not (s[i].isdigit()):
return i
return len(s)-1 # reached end of string
def go_to(s):
if s[0] == 'G':
comma_ind = first_index(s)
first_arg = int(s[1:comma_ind])
second_arg = int(s[comma_ind + 1:comma_ind + first_index(s[comma_ind + 1:])+comma_ind]) # add comma index to returned index
turtle.goto(first_arg, second_arg)
go_to('G99,99')
input()
Output
I'm currently making an encryption program for an assignment however I cannot decrypt. The cause of this is that the key is a string made from a randomly generated bitstring however when turning the key back into a bitstring I get a different bitstring. I realized this after checking and finding out that the bitstring after turning the key back to binary is shorter than the bitstring used to make the key.
##imports##################################################
from socket import *
import random
##functions################################################
def CCipher(message, k):
output = ""
for x in message:
i = ord(x)
i = (i+k)%128
output += chr(i)
return output
def toBinary(message):
output = ""
for x in message:
i = bin(ord(x))[2:]
output += i
return output
def XOR(bitstring1, bitstring2):
output = ""
if(len(bitstring1) != len(bitstring2)):
print("Use bitstrings of the same length")
return None
for x in range(len(bitstring1)):
if(bitstring1[x] == "1" and bitstring2[x] == "0"):
output += "1"
elif(bitstring1[x] == "0" and bitstring2[x] == "1"):
output += "1"
else:
output += "0"
return output
def randomBinary(k):
output = ""
for x in range(k):
i = random.randint(0,1)
output = output + str(i)
return output
def toString(message):
output = ""
i = ""
n = 0
for x in message:
n += 1
i += x
if(n == 7):
output += chr(int(i,2))
n = 0
i = ""
return output
##server stuff#########################################
serverName = "OmariPC"
serverPort = 12347
clientSocket = socket(AF_INET,SOCK_STREAM)
clientSocket.connect((serverName,serverPort))
##files################################################
nowar = open("NoWar.dat",'r')
trump = open("Trump.dat","w")
##encryption###########################################
message = nowar.read()
mesBin = toBinary(message)
bkey = randomBinary(len(mesBin))
encrypted = XOR(mesBin, bkey)
encrypted = toString(encrypted)
key = toString(bkey)
trump.write(encrypted)
trump.close()
enKey = CCipher(key, 4)
##sending###############################################
clientSocket.send(enKey.encode())
print(len(enKey))
clientSocket.send(encrypted.encode())
print(len(encrypted))
##testing###############################################
if key == toString(bkey):
print(True)
else:
print(False)
if len(toBinary(key)) == len(bkey):
print(True)
else:
print(False)
output:
168
168
True
False
def toBinary(message):
output = ""
for x in message:
i = bin(ord(x))[2:]
output += i
return output
bin(ord(x)) generates strings of variable length. For example:
>>> bin(ord(' '))
0b100000
>>> bin(ord('a'))
0b1100001
You concatenate all of the results of bin() together, so there's no way to separate them later. Meanwhile, your toString() function reads exactly 7 "bits" at a time.
You could make bin() append chunks of a fixed-size instead:
# Pad the left with 0s to always generate a string of length 7.
# (Assumes that all input characters are ASCII.)
assert(ord(x) < 128)
bin(ord(x))[2:].rjust(7, '0')
I have the following code which helps to bruteforce hashes
The first if statement will run, the values are hash=wordlist.txt, args=abtfg, values=[0, "0,1", 0, wordlist.txt, true]
def bruteforce(hash, args, values):
if "." in hash:
files = open(values[args.find("f")]) # Open wordlist.txt
for xhsd in files.readlines():
hash = xhsd
alphabet = "abcdefghijklmnopqrstuvwxyz"
alphabet += alphabet.upper() + "0123456789!$%^&*(){}~#][;:'#/?.>,<"
if "b" in args: # It is
m = args.find("b")
m = values[m]
else:
m = "0,16"
# m is 0,10
start_time = strftime("%Y-%m-%d %H:%M:%S", gmtime())
l = 0
print("Cracking...")
attempts = 0
while l == 0:
password = ""
for x in range(random.randrange(int(m.split(",")[0])+1,int(m.split(",")[1])+1)): # range(random.randrange(0,10))
password += alphabet[random.randrange(0,len(alphabet)-1)]
num = hash_types[int(values[args.find("t")])] # num="md5"
htype = "hash2 = hashlib."+num+"(password).hexdigest()"
exec(htype) # hash2 = md5(password)
print hash2 + ":" + hash # Compares the hashes
if hash == hash2:
print password
l = 1
else:
print "Trying..."
The first item it tries, it cracks it almost instantly, printing:
0cc175b9c0f1b6a831c399e269772661:0cc175b9c0f1b6a831c399e269772661
(this is hash2 and hash). So we now know these two variables are equal. However, the if statement directly below it, doesn't run. This is the weirdest thing I've seen in Python, could anyone explain why this is? I've printed both variables and they're clearly the same...
Removing whitespace could help:
if hash.strip() == hash2.strip():
import sys
import string
import re
keywords = []
task = "*"
while task not in "ed":
task = raw_input("Encrypt or Decrypt: \nType ‘e’ to Encrypt\nType ‘d’ to Decrypt\n").lower()
keyword = "*"
keyphrase = "*"
while not(re.match('[a-z ]+$',keyword)):
keyword = raw_input("enter your first keyword:-").lower()
while not(re.match('[a-z ]+$',keyphrase)):
keyphrase = raw_input("enter a key phrase:-").lower()
loop = 0
repeated_keyword = ""
if len(keyword) < len(keyphrase):
while len(repeated_keyword) < len(keyphrase):
repeated_keyword = repeated_keyword + keyword[loop]
loop += 1
if loop >= len(keyword):
loop = 0
elif len(keyword) == len(keyphrase):
repeated_keyword = keyword
last_charecter_in_keyword = keyword[-1]
elif len(keyword) > len(keyphrase):
repeated_keyword = keyword
last_charecter_in_keyword = keyword[-1]
while len(repeated_keyword) > len(keyphrase):
repeated_keyword = repeated_keyword[:-1]
repeated_keyword_letter_positions = []
keyphrase_letter_positions = []
for character in repeated_keyword:
position_of_char_in_repeated_keyword = (string.ascii_lowercase + " ").find(character) +1
repeated_keyword_letter_positions.append(position_of_char_in_repeated_keyword)
for character in keyphrase:
position_of_char_in_keyphrase = (string.ascii_lowercase + " ").find(character)
keyphrase_letter_positions.append(position_of_char_in_keyphrase)
if task == "e":
final_positions_of_letters = [a + b for a, b in zip(keyphrase_letter_positions,repeated_keyword_letter_positions)]
elif task == "d":
final_positions_of_letters = [a - b for a, b in zip(keyphrase_letter_positions,repeated_keyword_letter_positions)]
new_letter = ""
final_cipher = []
loop = 0
alphabet = string.ascii_lowercase + " " + string.ascii_lowercase + " "
while loop < len(final_positions_of_letters):
new_letter =alphabet[final_positions_of_letters[loop]]
final_cipher = str(final_cipher) + str(new_letter)
loop += 1
print final_cipher
This is a encryption/ decryption programme in python 2.7. However at the end of the programme when the final_cipher list is printed to the shell a pair of [] brackets are printed prior to the contents of the list
You have some options here:
• Loop through the array, and print each element on the same row without delimiter.
• Use 'join' to join all the parts of the array in a single string. You can find more information about the join statement here.
Personally I do think 'join' is the best option here.
I guess you are trying to output a string. And you are making a mistake by setting the initial declaration to an empty list.
For fixing this just use :
final_cipher = "" instead of final_cipher = []
This should get you the output in string format.
Seeing:
final_cipher = []
loop = 0
alphabet = string.ascii_lowercase + " " + string.ascii_lowercase + " "
while loop < len(final_positions_of_letters):
new_letter =alphabet[final_positions_of_letters[loop]]
final_cipher = str(final_cipher) + str(new_letter)
loop += 1
print final_cipher
I see that you are working with final_cipher like a string, then you should initialize like:
final_cipher = ""
And:
final_cipher = str(final_cipher) + str(new_letter)
Should be:
final_cipher = final_cipher + str(new_letter)
Or better:
final_cipher += str(new_letter)
final_cipher is a list, so yes, printing it will print it as a string, i.e. the result of calling str(final_cipher).
If you want to just print the elements seperated by a comma, you can use .join:
print ", ".join(final_cipher)
You create final_cipher as a list but then change your mind and do string concatenation instead. On the first iteration of the loop, str(final_cipher) creates the string representation of an empty list "[]". Look familiar? Keep a list and build the string at the end.
final_cipher = []
loop = 0
alphabet = string.ascii_lowercase + " " + string.ascii_lowercase + " "
while loop < len(final_positions_of_letters):
new_letter =alphabet[final_positions_of_letters[loop]]
final_cipher.append(str(new_letter))
loop += 1
final_cipher = ''.join(final_cipher)
print final_cipher