RC4 decryption with key in Python - python

I pulled this code from here for asp http://bytes.com/topic/access/insights/906671-rc4-encryption-algorithm-vba-vbscript, which i then run thru base64.
I am wonder if anyone can help me figure out how to write the decryption piece but in Python. As the decryption will happen on my Python Server Page.
Found this http://www.id-snippet.com/20801/python-rc4-cipher/, but it doesn't decrypt the RC4 asp from the first link.
-Jim
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
ASP page
'Base64
Function Base64Encode(inData)
Const Base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
Dim cOut, sOut, I
'For each group of 3 bytes
For I = 1 To Len(inData) Step 3
Dim nGroup, pOut, sGroup
'Create one long from this 3 bytes.
nGroup = &H10000 * Asc(Mid(inData, I, 1)) + _
&H100 * MyASC(Mid(inData, I + 1, 1)) + MyASC(Mid(inData, I + 2, 1))
'Oct splits the long To 8 groups with 3 bits
nGroup = Oct(nGroup)
'Add leading zeros
nGroup = String(8 - Len(nGroup), "0") & nGroup
'Convert To base64
pOut = Mid(Base64, CLng("&o" & Mid(nGroup, 1, 2)) + 1, 1) + _
Mid(Base64, CLng("&o" & Mid(nGroup, 3, 2)) + 1, 1) + _
Mid(Base64, CLng("&o" & Mid(nGroup, 5, 2)) + 1, 1) + _
Mid(Base64, CLng("&o" & Mid(nGroup, 7, 2)) + 1, 1)
'Add the part To OutPut string
sOut = sOut + pOut
'Add a new line For Each 76 chars In dest (76*3/4 = 57)
'If (I + 2) Mod 57 = 0 Then sOut = sOut + vbCrLf
Next
Select Case Len(inData) Mod 3
Case 1: '8 bit final
sOut = Left(sOut, Len(sOut) - 2) + "=="
Case 2: '16 bit final
sOut = Left(sOut, Len(sOut) - 1) + "="
End Select
Base64Encode = sOut
End Function
Function MyASC(OneChar)
If OneChar = "" Then MyASC = 0 Else MyASC = Asc(OneChar)
End Function
'RC4
Function RunRC4(sMessage, strKey)
Dim kLen, x, y, i, j, temp
Dim s(256), k(256)
'Init keystream
klen = Len(strKey)
For i = 0 To 255
s(i) = i
k(i) = Asc(Mid(strKey, (i Mod klen) + 1, 1))
Next
j = 0
For i = 0 To 255
j = (j + k(i) + s(i)) Mod 255
temp = s(i)
s(i) = s(j)
s(j) = temp
Next
'Drop n bytes from keystream
x = 0
y = 0
For i = 1 To 3072
x = (x + 1) Mod 255
y = (y + s(x)) Mod 255
temp = s(x)
s(x) = s(y)
s(y) = temp
Next
'Encode/Decode
For i = 1 To Len(sMessage)
x = (x + 1) Mod 255
y = (y + s(x)) Mod 255
temp = s(x)
s(x) = s(y)
s(y) = temp
RunRC4 = RunRC4 & Chr(s((s(x) + s(y)) Mod 255) Xor Asc(Mid(sMessage, i, 1)))
Next
End Function
encStr = Base64Encode(RunRC4(username,"1234"))
Python Server Page
def decode64(in_str):
import base64
decodedStr = base64.b64decode(in_str)
return decodedStr
def rc4crypt(data, key):
x = 0
box = range(256)
for i in range(256):
x = (x + box[i] + ord(key[i % len(key)])) % 256
box[i], box[x] = box[x], box[i]
x,y = 0, 0
out = []
for char in data:
x = (x + 1) % 256
y = (y + box[x]) % 256
box[x], box[y] = box[y], box[x]
out.append(chr(ord(char) ^ box[(box[x] + box[y]) % 256]))
return ''.join(out)
decStr = rc4crypt(decode64(encStr), "1234")
Can't figure out why python decrypt doesn't render the original string when using the same key "1234"

Related

Is there a shorter way to increment bd_address in python?

I wrote a python's function to increment BT device BD_ADDR by any value but my function can only work up to xx:xx:xx:xx:FE:FF. For example, original BD_ADDR = AA:BB:CC:DD:EE:FF --> incremented by 1 BD_ADDR = AA:BB:CC:DD:EF:00. Also is there a shorter way to do this without all if statements? any suggestions will be appreciated.
Below is the script:
def ba_incr(mac,incr):
old_bytes = mac[12:].split(":")
if (old_bytes[0] != "00"):
if (old_bytes[0] != "01" and old_bytes[0] != "0F"):
old_hex = str(old_bytes[0] + old_bytes[1])
incr_hex = hex(int(str(int(old_hex, base=16) + incr)))[2:]
new_bytes = str(incr_hex[:2]) + ":" + str(incr_hex[2:])
elif (old_bytes[0] == "0F" and old_bytes[1] == "FF") :
old_hex = str(old_bytes[0] + old_bytes[1])
incr_hex = hex(int(str(int(old_hex, base=16) + incr)))[2:]
new_bytes = str(incr_hex[:2]) + ":" + str(incr_hex[2:])
else:
old_hex = str(old_bytes[0] + old_bytes[1])
incr_hex = hex(int(str(int(old_hex, base=16) + incr)))[2:]
#print ("incremented hex",incr_hex)
new_bytes = "0" + str(incr_hex[:1]) + ":" + str(incr_hex[1:])
elif (old_bytes[0] == "00" and old_bytes[1] == "FF"):
old_hex = old_bytes[1]
#print ("old hex:",old_hex)
incr_hex = hex(int(str(int(old_hex, base=16) + incr)))[2:]
#print ("incremented hex:",incr_hex)
new_bytes = "01" + ":" + str(incr_hex[1:])
elif (old_bytes[0] == "00" and old_bytes[1][:1] == "0") and old_bytes[1][1:] != "F":
old_hex = old_bytes[1]
#print ("old hex:",old_hex)
incr_hex = hex(int(str(int(old_hex, base=16) + incr)))[2:]
#print ("incremented hex:",incr_hex)
new_bytes = old_bytes[0] + ":0" + str(incr_hex)
elif (old_bytes[0] == "00" and old_bytes[1] != "FF"):
old_hex = old_bytes[1]
#print ("old hex:",old_hex)
incr_hex = hex(int(str(int(old_hex, base=16) + incr)))[2:]
#print ("incremented hex:",incr_hex)
new_bytes = old_bytes[0] + ":" + str(incr_hex)[:2]
print ("mac after:", mac[:12] + new_bytes.upper())
You can probably try something like this:
Remove the ':' from the mac address
Convert the mac address to integer
Increment the integer value
Convert the integer to hex string
Insert back the ':' at the appropriate positions
Sample code that worked for me (for simplicity I am incrementing by 1). You may need to modify it to handle corner cases.
s = 'AA:BB:CC:DD:EE:FF'
s = s.replace(':', '')
val = int(s, 16)
val = val + 1
incr_s = hex(val)
incr_s = incr_s[2:].upper()
incr_s = ':'.join(incr_s[i:i+2] for i in range(0, len(incr_s), 2))
print(s)
print(incr_s)
Output:
AABBCCDDEEFF
AA:BB:CC:DD:EF:00

Error , Infeasible No value for uninitialized NumericValue object

I'm trying to optmize a problem of clients/facility allocation and I'm using pyomo to do so. I have the following problem that appear and cannot solve it even if I initialize all the values of Model.z to 0; the problems is still infeasible
from __future__ import division
import pyomo.environ as pyo
#from pyomo.environ import *
from pyomo.opt import SolverFactory
import sys
import numpy as np
import sys
import os
from time import perf_counter
from pulp import *
from pyomo.util.infeasible import log_infeasible_constraints
#print(sys.path)
opt = pyo.SolverFactory('glpk')
opt.options['threads'] =4
#import instance
model = pyo.ConcreteModel()
# n is the number of facility related to J
# m is the number of clients related to I
# t is the number of periods relatdd to T
# H is the maximum number of clients that can be served
[m,n,t,H] = np.genfromtxt(fname = r'./Instances/data-100-10-4-3-0.txt', dtype = None, max_rows = 1)
f_values = np.genfromtxt(fname = r'./Instances/data-100-10-4-3-0.txt', dtype = None, max_rows = 4,skip_header=1)
c_values = np.genfromtxt(fname = r'./Instances/data-100-10-4-3-0.txt', dtype = None, skip_footer = 1,skip_header=5)
p_values = np.genfromtxt(fname = r'./Instances/data-100-10-4-3-0.txt', dtype = None, skip_header=405)
model.J = pyo.Set(initialize=[int(i)+1 for i in range(n)])
model.T= pyo.Set(initialize=[int(i)+1 for i in range(t)])
model.T.pprint()
model.I = pyo.Set(initialize=[int(i)+1 for i in range(m)])
model.H = pyo.Set(initialize=[int(i)+1 for i in range(H)])
# Generation of Subsets of all clients
client_list = [int(i)+1 for i in range(100)]
list_H = [int(i)+1 for i in range(H)]
possible_groups_of_clients=[]
for i in list_H:
possible_groups_of_clients += [list(elem) for elem in itertools.combinations(client_list,i)]
possible_groups_of_clients = possible_groups_of_clients[0:5] #Only select the first 5 subsets
model.K = pyo.Set(initialize=[int(i)+1 for i in range(len(possible_groups_of_clients))])
p_val = np.zeros((len(model.K),len(model.J),len(model.T)))
for t in model.T:
t=t-1 #Pyomo starts at 1
for j in model.J:
j=j-1
count = 0
for k in possible_groups_of_clients:
#k=k+1
c_sum=0;
for p in k:
if t==0:
c_sum = c_sum +c_values[p][j]
elif t==1:
c_sum = c_sum +c_values[p+100][j]
elif t==2:
c_sum = c_sum +c_values[p+200][j]
elif t==3:
c_sum = c_sum +c_values[p+300][j]
#print(f_values[t][j])
p_val[count][j][t] = f_values[t][j]+ c_sum
count=count+1
model.p_val = pyo.Param(model.K,model.J,model.T, initialize = lambda model,k,j,t: p_val[k-1][j-1][t-1])
#Matrice Aik
A = [[0 for k in range(len(possible_groups_of_clients))] for i in range(100)]
#model.p_val = pyo.Param(model.T,model.J,model.K, initialize = lambda model,t,j,k: A[t-1][j-1][k-1])
model.A = pyo.Param(model.I, model.K, mutable= True,initialize= lambda model,i,k: A[i-1][k-1])
count=1
for i in possible_groups_of_clients:
for k in range(100):
k=k+1
#print(k)
if k in i:
model.A[k,count]=1
else:
model.A[k,count]=0
count=count+1
model.z = pyo.Var(model.K,model.J,model.T,initialize= 0,within=pyo.NonNegativeReals,bounds=(0,1))
a=range(len(possible_groups_of_clients))
print(p_values)
# Minization of objective functions
# Constraint unique client
model.uniq_client = pyo.Constraint(
model.I,
rule=lambda model, i: sum(model.A[i,k]*model.z[k,j,t] for t in model.T for j in model.J for k in model.K) == 1
)
model.unique_service_groupclients = pyo.Constraint(
model.J, model.T,
rule=lambda model,j,t: sum(model.z[k,j,t] for k in model.K)<=1
)
model.min_factory_perperiod = pyo.Constraint(
model.T,
rule=lambda model, t: sum(model.z[k,j,t] for j in model.J for k in model.K )>=p_values[t-1]
)
model.obj = pyo.Objective(rule= lambda model:sum(model.p_val[k,j,t]*model.z[k,j,t] for t in model.T for j in model.J for k in model.K ), sense= pyo.minimize)
model.pprint()
Constraint Group Client
sol = pyo.SolverFactory('glpk',).solve(model).write()
log_infeasible_constraints(model)
# ==========================================================
# = Solver Results =
# ==========================================================
# ----------------------------------------------------------
# Problem Information
# ----------------------------------------------------------
Problem:
- Name: unknown
Lower bound: -inf
Upper bound: inf
Number of objectives: 1
Number of constraints: 145
Number of variables: 201
Number of nonzeros: 601
Sense: minimize
# ----------------------------------------------------------
# Solver Information
# ----------------------------------------------------------
Solver:
- Status: ok
Termination condition: infeasible
Statistics:
Branch and bound:
Number of bounded subproblems: 0
Number of created subproblems: 0
Error rc: 0
Time: 0.008042335510253906
ERROR: evaluating object as numeric value: z[1,1,1]
(object: <class 'pyomo.core.base.var._GeneralVarData'>)
No value for uninitialized NumericValue object z[1,1,1]
ERROR: evaluating object as numeric value: 1.0 - (A[1,1]*z[1,1,1] +
A[1,2]*z[2,1,1] + A[1,3]*z[3,1,1] + A[1,4]*z[4,1,1] + A[1,5]*z[5,1,1] +
A[1,1]*z[1,2,1] + A[1,2]*z[2,2,1] + A[1,3]*z[3,2,1] + A[1,4]*z[4,2,1] +
A[1,5]*z[5,2,1] + A[1,1]*z[1,3,1] + A[1,2]*z[2,3,1] + A[1,3]*z[3,3,1] +
A[1,4]*z[4,3,1] + A[1,5]*z[5,3,1] + A[1,1]*z[1,4,1] + A[1,2]*z[2,4,1] +
A[1,3]*z[3,4,1] + A[1,4]*z[4,4,1] + A[1,5]*z[5,4,1] + A[1,1]*z[1,5,1] +
A[1,2]*z[2,5,1] + A[1,3]*z[3,5,1] + A[1,4]*z[4,5,1] + A[1,5]*z[5,5,1] +
A[1,1]*z[1,6,1] + A[1,2]*z[2,6,1] + A[1,3]*z[3,6,1] + A[1,4]*z[4,6,1] +
A[1,5]*z[5,6,1] + A[1,1]*z[1,7,1] + A[1,2]*z[2,7,1] + A[1,3]*z[3,7,1] +
A[1,4]*z[4,7,1] + A[1,5]*z[5,7,1] + A[1,1]*z[1,8,1] + A[1,2]*z[2,8,1] +
A[1,3]*z[3,8,1] + A[1,4]*z[4,8,1] + A[1,5]*z[5,8,1] + A[1,1]*z[1,9,1] +
A[1,2]*z[2,9,1] + A[1,3]*z[3,9,1] + A[1,4]*z[4,9,1] + A[1,5]*z[5,9,1] +
A[1,1]*z[1,10,1] + A[1,2]*z[2,10,1] + A[1,3]*z[3,10,1] + A[1,4]*z[4,10,1]
+ A[1,5]*z[5,10,1] + A[1,1]*z[1,1,2] + A[1,2]*z[2,1,2] + A[1,3]*z[3,1,2] +
A[1,4]*z[4,1,2] + A[1,5]*z[5,1,2] + A[1,1]*z[1,2,2] + A[1,2]*z[2,2,2] +
A[1,3]*z[3,2,2] + A[1,4]*z[4,2,2] + A[1,5]*z[5,2,2] + A[1,1]*z[1,3,2] +
A[1,2]*z[2,3,2] + A[1,3]*z[3,3,2] + A[1,4]*z[4,3,2] + A[1,5]*z[5,3,2] +
A[1,1]*z[1,4,2] + A[1,2]*z[2,4,2] + A[1,3]*z[3,4,2] + A[1,4]*z[4,4,2] +
A[1,5]*z[5,4,2] + A[1,1]*z[1,5,2] + A[1,2]*z[2,5,2] + A[1,3]*z[3,5,2] +
A[1,4]*z[4,5,2] + A[1,5]*z[5,5,2] + A[1,1]*z[1,6,2] + A[1,2]*z[2,6,2] +
A[1,3]*z[3,6,2] + A[1,4]*z[4,6,2] + A[1,5]*z[5,6,2] + A[1,1]*z[1,7,2] +
A[1,2]*z[2,7,2] + A[1,3]*z[3,7,2] + A[1,4]*z[4,7,2] + A[1,5]*z[5,7,2] +
A[1,1]*z[1,8,2] + A[1,2]*z[2,8,2] + A[1,3]*z[3,8,2] + A[1,4]*z[4,8,2] +
A[1,5]*z[5,8,2] + A[1,1]*z[1,9,2] + A[1,2]*z[2,9,2] + A[1,3]*z[3,9,2] +
A[1,4]*z[4,9,2] + A[1,5]*z[5,9,2] + A[1,1]*z[1,10,2] + A[1,2]*z[2,10,2] +
A[1,3]*z[3,10,2] + A[1,4]*z[4,10,2] + A[1,5]*z[5,10,2] + A[1,1]*z[1,1,3] +
A[1,2]*z[2,1,3] + A[1,3]*z[3,1,3] + A[1,4]*z[4,1,3] + A[1,5]*z[5,1,3] +
A[1,1]*z[1,2,3] + A[1,2]*z[2,2,3] + A[1,3]*z[3,2,3] + A[1,4]*z[4,2,3] +
A[1,5]*z[5,2,3] + A[1,1]*z[1,3,3] + A[1,2]*z[2,3,3] + A[1,3]*z[3,3,3] +
A[1,4]*z[4,3,3] + A[1,5]*z[5,3,3] + A[1,1]*z[1,4,3] + A[1,2]*z[2,4,3] +
A[1,3]*z[3,4,3] + A[1,4]*z[4,4,3] + A[1,5]*z[5,4,3] + A[1,1]*z[1,5,3] +
A[1,2]*z[2,5,3] + A[1,3]*z[3,5,3] + A[1,4]*z[4,5,3] + A[1,5]*z[5,5,3] +
A[1,1]*z[1,6,3] + A[1,2]*z[2,6,3] + A[1,3]*z[3,6,3] + A[1,4]*z[4,6,3] +
A[1,5]*z[5,6,3] + A[1,1]*z[1,7,3] + A[1,2]*z[2,7,3] + A[1,3]*z[3,7,3] +
A[1,4]*z[4,7,3] + A[1,5]*z[5,7,3] + A[1,1]*z[1,8,3] + A[1,2]*z[2,8,3] +
A[1,3]*z[3,8,3] + A[1,4]*z[4,8,3] + A[1,5]*z[5,8,3] + A[1,1]*z[1,9,3] +
A[1,2]*z[2,9,3] + A[1,3]*z[3,9,3] + A[1,4]*z[4,9,3] + A[1,5]*z[5,9,3] +
A[1,1]*z[1,10,3] + A[1,2]*z[2,10,3] + A[1,3]*z[3,10,3] + A[1,4]*z[4,10,3]
+ A[1,5]*z[5,10,3] + A[1,1]*z[1,1,4] + A[1,2]*z[2,1,4] + A[1,3]*z[3,1,4] +
A[1,4]*z[4,1,4] + A[1,5]*z[5,1,4] + A[1,1]*z[1,2,4] + A[1,2]*z[2,2,4] +
A[1,3]*z[3,2,4] + A[1,4]*z[4,2,4] + A[1,5]*z[5,2,4] + A[1,1]*z[1,3,4] +
A[1,2]*z[2,3,4] + A[1,3]*z[3,3,4] + A[1,4]*z[4,3,4] + A[1,5]*z[5,3,4] +
A[1,1]*z[1,4,4] + A[1,2]*z[2,4,4] + A[1,3]*z[3,4,4] + A[1,4]*z[4,4,4] +
A[1,5]*z[5,4,4] + A[1,1]*z[1,5,4] + A[1,2]*z[2,5,4] + A[1,3]*z[3,5,4] +
A[1,4]*z[4,5,4] + A[1,5]*z[5,5,4] + A[1,1]*z[1,6,4] + A[1,2]*z[2,6,4] +
A[1,3]*z[3,6,4] + A[1,4]*z[4,6,4] + A[1,5]*z[5,6,4] + A[1,1]*z[1,7,4] +
A[1,2]*z[2,7,4] + A[1,3]*z[3,7,4] + A[1,4]*z[4,7,4] + A[1,5]*z[5,7,4] +
A[1,1]*z[1,8,4] + A[1,2]*z[2,8,4] + A[1,3]*z[3,8,4] + A[1,4]*z[4,8,4] +
A[1,5]*z[5,8,4] + A[1,1]*z[1,9,4] + A[1,2]*z[2,9,4] + A[1,3]*z[3,9,4] +
A[1,4]*z[4,9,4] + A[1,5]*z[5,9,4] + A[1,1]*z[1,10,4] + A[1,2]*z[2,10,4] +
A[1,3]*z[3,10,4] + A[1,4]*z[4,10,4] + A[1,5]*z[5,10,4])
(object: <class 'pyomo.core.expr.numeric_expr.SumExpression'>)
No value for uninitialized NumericValue object z[1,1,1]
Traceback (most recent call last):
File "main.py", line 246, in <module>
log_infeasible_constraints(model)
File "/home/john/.local/lib/python3.6/site-packages/pyomo /util/infeasible.py", line 25, in log_infeasible_constraints
if constr.equality and fabs(value(constr.lower - constr.body)) >= tol:
File "/home/john/.local/lib/python3.6/site-packages/pyomo/core/expr/numvalue.py", line 226, in value
tmp = obj(exception=True)
File "/home/john/.local/lib/python3.6/site-packages/pyomo/core/expr/numeric_expr.py", line 222, in __call__
return evaluate_expression(self, exception)
File "/home/john/.local/lib/python3.6/site-packages/pyomo/core/expr/visitor.py", line 973, in evaluate_expression
return visitor.dfs_postorder_stack(exp)
File "/home/john/.local/lib/python3.6/site-packages/pyomo/core/expr/visitor.py", line 518, in dfs_postorder_stack
flag, value = self.visiting_potential_leaf(_sub)
File "/home/john/.local/lib/python3.6/site-packages/pyomo/core/expr/visitor.py", line 893, in visiting_potential_leaf
return True, value(node)
File "/home/john/.local/lib/python3.6/site-packages/pyomo/core/expr/numvalue.py", line 230, in value
% (obj.name,))
ValueError: No value for uninitialized NumericValue object z[1,1,1]
I got this error whatever I try and I don't understand why Z should be initialized as it is the variable I'm trying to minimize

naive bayes classifier not working, prefers spam

I'm newer to Python and I've been trying to build a Naive Bayes classifier, but it seems to be prioritizing Spam over Ham. I know it's a lot to ask, but I was hoping someone who was familiar with Naive Bayes could point out what I've done wrong. As a side note: I skipped the denominator portion of the Naive Bayes equation; a common denominator shouldn't make a difference, right?
Here's a link to the guide I followed: https://towardsdatascience.com/unfolding-na%C3%AFve-bayes-from-scratch-2e86dcae4b01
And here's my code:
import csv
ham = 0
spam = 0
dictionarySpam = {}
dictionaryHam = {}
dictionaryTotal = {}
userString = input("Enter your string")
userString = userString.replace('.', ' ')
a = "!##$%^&*()_+=-?,><':;[]/"
userStringList = userString.split()
print(userStringList)
totalNumHam = 0
with open('spam.csv') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
for row in csv_reader:
if "ham" in row[0]:
ham += 1
elif "spam" in row[0]:
spam += 1
words = row[1].split()
for word in words:
word = word.replace('.', ' ')
for char in a:
word = word.replace(char, '')
dictionaryTotal[word.lower()] = dictionaryTotal.get(word.lower(), 0) + 1
if "ham" in row[0].lower():
dictionaryHam[word.lower()] = dictionaryHam.get(word.lower(), 0) + 1
elif "spam" in row[0].lower():
dictionarySpam[word.lower()] = dictionarySpam.get(word.lower(), 0) + 1
probHam = 1;
probSpam = 1;
print("HAM cases: ", ham)
print("SPAM cases: ", spam)
print(dictionaryHam)
print(dictionarySpam)
for item in userStringList:
if item in dictionaryHam:
probHam = probHam * ((dictionaryHam[item] + 1) / (sum(dictionaryHam.values()) + len(dictionaryTotal) + 1))
elif item not in dictionaryHam:
probHam = probHam * (1 / (sum(dictionaryHam.values()) + len(dictionaryTotal) + 1))
if item in dictionarySpam:
probSpam = probSpam * ((dictionarySpam[item] + 1) / (sum(dictionarySpam.values()) + len(dictionaryTotal) + 1))
elif item not in dictionaryHam:
probHam = probSpam * (1 / (sum(dictionarySpam.values()) + len(dictionaryTotal) + 1))
print("OUT: ", probHam)
probHam = probHam * (ham / (ham + spam))
probSpam = probSpam * (spam / (ham + spam))
print(probHam)
print(probSpam)
if probHam > probSpam:
print("This message is HAM")
else:
print("This message is SPAM")
I think you have messed up with your brackes in line:
probHam = probHam * ((dictionaryHam[item] + 1) / (sum(dictionaryHam.values()) + len(dictionaryTotal) + 1))

python files - who to open corectly

We have file with some math problems like: 46 + 19 (only + or - and it built up this way: number, space, sign, space, number) and we need to transform it into a new file and solve them (46 + 19 = 65). We don't know how many exercises there will be or the number of digits in every number. Here is my code:
enter code here
input_file = open(r'C:\try\bla.txt', 'r')
nums = input_file.read()
y = 0
dig1 = ''
dig2 = ''
sign = ''
x1 = nums.find(' ')
x2 = x1 + 1
def one(dig1, dig2, y):
for i in xrange(x1):
dig1 += nums[y]
y += 1
for m in xrange(abs(-x2)):
dig2 += nums[y + 1]
y += 1
sign = nums[x2]
if sign == '+':
sum = int(dig1) + int(dig2)
if sign == '-':
sum = int(dig1) - int(dig2)
print dig1, dig2, '=', sum
for a in xrange(0):
one(dig1, dig2, y)
one(dig1, dig2, y)
print 'f', nums[21]
#print dig1, dig2, '=', sum
Maybe you are want to get this(python3):
test.txt:
10 + 15
22 - 71
33 + 64
code:
import operator
op = {'+': operator.add, '-': operator.sub}
with open('test.txt', 'r') as f:
lines = f.readlines()
for i in lines:
args = i.split()
val = op[args[1]](int(args[0]), int(args[-1]))
r = f'{i.strip()} = {val}'
print(r)

Error in python replace. (AttributeError: 'tuple' object has no attribute 'replace')

Environment
I am using Python 3 and my OS is Windows 7.
I understand that some commands have changed from the transition from python 2.7 to 3 (What I have used).
Problem
The variable is temporary but is this:
(((((0, 7), 7), 8), 4), 5)
Here is the code to get rid of the brackets:
randy = randy.replace(")", "")
randy = randy.replace("(", "")
randy = randy.replace(" ", "")
When it tries to execute the replace function, I get thrown an error:
Traceback (most recent call last):
File "<string>", line 248, in run_nodebug
File "Criptic.py", line 134, in <module>
randy = randy.replace(")", "")
AttributeError: 'tuple' object has no attribute 'replace'
Edit:
Here is all of the code:
#Import string
import string
import random
#Input user data
text = input("Enter your text to be converted: ")
#Test Print
print("-------------------------")
print("Your text is: ",text)
#Break up all the data
data = list(text)
#Lowercase
count = text.count("a")
count1 = text.count("b")
count2 = text.count("c")
count3 = text.count("d")
count4 = text.count("e")
count5 = text.count("f")
count6 = text.count("g")
count7 = text.count("h")
count8 = text.count("i")
count9 = text.count("j")
count10 = text.count("k")
count11 = text.count("l")
count12 = text.count("m")
count13 = text.count("n")
count14 = text.count("o")
count15 = text.count("p")
count16 = text.count("q")
count17 = text.count("r")
count18 = text.count("s")
count19 = text.count("t")
count20 = text.count("u")
count21 = text.count("v")
count22 = text.count("w")
count23 = text.count("x")
count24 = text.count("y")
count25 = text.count("z")
count26 = text.count("A")
#Uppercase
count27 = text.count("B")
count28 = text.count("C")
count29 = text.count("D")
count30 = text.count("E")
count31 = text.count("F")
count32 = text.count("G")
count33 = text.count("H")
count34 = text.count("I")
count35 = text.count("J")
count36 = text.count("K")
count37 = text.count("L")
count38 = text.count("M")
count39 = text.count("N")
count40 = text.count("O")
count41 = text.count("P")
count42 = text.count("Q")
count43 = text.count("R")
count44 = text.count("S")
count45 = text.count("T")
count46 = text.count("U")
count47 = text.count("V")
count48 = text.count("W")
count49 = text.count("X")
count50 = text.count("Y")
count51 = text.count("Z")
#Other Characters
count52 = text.count(" ")
count53 = text.count("?")
count54 = text.count("#")
count55 = text.count("(")
count56 = text.count(")")
count57 = text.count(".")
#Numbers
count58 = text.count("1")
count59 = text.count("2")
count60 = text.count("3")
count61 = text.count("4")
count62 = text.count("5")
count63 = text.count("6")
count64 = text.count("7")
count65 = text.count("8")
count66 = text.count("9")
count67 = text.count("0")
#Counting how many characters in the sentence
finalcount = count + count1 + count2 + count3 + count4 + count5 + count6 + count7 + count8 + count9 + count10 + count11 + count12 + count13 + count14 + count15 + count16 + count17 + count18 + count19 + count20 + count21 + count22 + count23 + count24 + count25 + count26 + count27 + count28 + count29 + count31 + count32 + count33 + count34 + count35 + count36 + count37 + count38 + count39 + count40 + count41 + count42 + count43 + count44 + count45 + count46 + count47 + count48 + count49 + count50 + count51 + count52 + count53 + count54 + count55 + count56 + count57 + count58 + count59 + count60 + count61 + count62 + count63 + count64 + count65 + count66 + count67
#Final count of Characters
print(" Chars: ",finalcount)
print("-------------------------")
char = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!##$%^&*()?_+-=1234567890 "
charnum = 74 + 11
list(char)
randy = 0
num = 0
while num < finalcount:
rand = random.randrange(1,9)
randy = randy,rand
finalcount = finalcount - 1
if rand == 1:
print(text[finalcount],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],",")
if rand == 2:
print(char[random.randrange(0,charnum)],text[finalcount],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],",")
if rand == 3:
print(char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],text[finalcount],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],",")
if rand == 4:
print(char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],text[finalcount],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],",")
if rand == 5:
print(char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],text[finalcount],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],",")
if rand == 6:
print(char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],text[finalcount],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],",")
if rand == 7:
print(char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],text[finalcount],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],",")
if rand == 8:
print(char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],text[finalcount],char[random.randrange(0,charnum)],",")
if rand == 9:
print(char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],text[finalcount],",")
randy = randy.replace(")", "")
randy = randy.replace("(", "")
randy = randy.replace(" ", "")
print("-------------------------")
print("::::::::Completed::::::::")
print("-------------------------")
print(randy)
print("-This is your code unlock key. Without this code it will not decript!!!! ")
print("-------------------------")
You have a tuple (a sort of list) of numbers, and you want to make that a string. You can't replace the brackets, they aren't a part of the variable, they are just a part of its representation.
Instead you should use join() and str()
result = " ".join(str(x) for x in randy)
However, this probably will not give the right result either, as it is a nested list of tuples. You probably mean: randy = randy + (rand,) instead if randy = randy,rand.
randy = randy,rand
This notation creates a tuple of two elements, tuples do not have a method called replace.
If you just want to concatenate the numbers into a list representation separated by commas, you could do this in your loop:
randy = []
num = 0
while num < finalcount:
rand = random.randrange(1,9)
randy.append(rand)
Then you remove the replace lines, and instead do this
randy = ",".join(randy)
to get a string that has the values separated by commas.
You should maybe add the output that you would like to get to your question, because at the moment it's not quite clear what you want to do exactly.
exam_st_date = (11, 12, 2014)
# Sample Output : The examination will start from : 11 / 12 / 2014
newtup = str(exam_st_date).replace(',', ' /')
print(newtup)
look at mine example should give you some results
To delete a list of characters, you could use the string's translate method:
import string
name = "(((((0, 7), 7), 8), 4), 5)"
table = string.maketrans( '', '', )
print name.translate(table,"()")

Categories