I change this code to work in persian. My code returns:
Key: Text is too short to analyze Text:
and doesn't return key and decrypt text. Is it anything wrong with uppercase or ascii in persian text? What can I do?
# -*- coding: utf-8 -*-
from string import uppercase
from operator import itemgetter
def vigenere_decrypt(target_freqs, input):
nchars = len(uppercase)
ordA = ord(u"ا")
sorted_targets = sorted(target_freqs)
def frequency(input):
result = [[c, 0.0] for c in uppercase]
for c in input:
result[c - ordA][1] += 1
return result
def correlation(input):
result = 0.0
freq = frequency(input)
freq.sort(key=itemgetter(1))
for i, f in enumerate(freq):
result += f[1] * sorted_targets[i]
return result
cleaned = [ord(c) for c in input.upper() if c.isupper()]
best_len = 0
best_corr = -100.0
# Assume that if there are less than 20 characters
# per column, the key's too long to guess
for i in xrange(2, len(cleaned) // 20):
pieces = [[] for _ in xrange(i)]
for j, c in enumerate(cleaned):
pieces[j % i].append(c)
# The correlation seems to increase for smaller
# pieces/longer keys, so weigh against them a little
corr = -0.5 * i + sum(correlation(p) for p in pieces)
if corr > best_corr:
best_len = i
best_corr = corr
if best_len == 0:
return ("Text is too short to analyze", "")
pieces = [[] for _ in xrange(best_len)]
for i, c in enumerate(cleaned):
pieces[i % best_len].append(c)
freqs = [frequency(p) for p in pieces]
key = ""
for fr in freqs:
fr.sort(key=itemgetter(1), reverse=True)
m = 0
max_corr = 0.0
for j in xrange(nchars):
corr = 0.0
c = ordA + j
for frc in fr:
d = (ord(frc[0]) - c + nchars) % nchars
corr += frc[1] * target_freqs[d]
if corr > max_corr:
m = j
max_corr = corr
key += chr(m + ordA)
r = (chr((c - ord(key[i % best_len]) + nchars) % nchars + ordA)
for i, c in enumerate(cleaned))
return (key, "".join(r))
def main():
encoded = " پهيتش غعهدد ذصلدي هزفضر کنهرظ ضذکاح يصتمد "
english_frequences = [
14, 4.2, 0.7, 5.2, 0.1, 1.2, 0.4,
1, 1.4, 7.5, 0.1, 8.5, 2.1, 0.1,
3.3, 2.6, 0.7, 0.3, 0.6, 0.2, 1.5,
0.2, 1.6, 1.2, 3, 1.7, 2.7, 5.7, 7.1, 6, 5.7, 9.1]
(key, decoded) = vigenere_decrypt(english_frequences, encoded)
print "Key:", key
print "\nText:", decoded
main()
Related
I am trying to define the Python function - obtains the mean and variance with given multiple vectors. There are only x-axis and y-axis.
I tried make some functions and created the code but it showed me just an incorrect value.
Below is my code.
def avr(*inn):
hap = 0
cnt = 0
for i in inn:
hap += i
cnt += 1
avrr = hap/cnt
return avrr
def varr(*inn):
jejob = 0
jegobhap = 0
cnt = 0
for i in inn:
cha = (i-avr(*inn))
jegob = cha**2
jegobhap += jegob
cnt += 1
varr_m = jegobhap/cnt
return varr_m
def mean_and_var(*val):
x_axis_avr = avr(*val[0])
y_axis_avr = avr(*val[1])
x_axis_boon = varr(*val[0])
y_axis_boon = varr(*val[1])
return ((x_axis_avr,y_axis_avr),(x_axis_boon,y_axis_boon))
v1=(0,1)
v2=(0.5, 0.5)
v3=(1,0)
v4=(50,30)
m, var = mean_and_var(v1,v2,v3,v4)
print("mean: ", m, "var: " , var)
and it gives me
mean: (0.5, 0.5) var: (0.25, 0.0)
The correct value should be;
mean (12.875, 7.875) var: (459.546875,163.296875)
What is the error?
I think you expect too much for Python.
var[0] gives first vector (0,1), not first values from all vectors (0, 0.5, 1, 50).
var[1] gives second vector (0.5, 0.5), not second values from all vectors (1, 0.5, 0, 30)
And it doesn't use values v3, v4
Try this and you get expected values
v1 = (0, 0.5, 1, 50)
v2 = (1, 0.5, 0, 30)
m, var = mean_and_var(v1, v2)
print("mean: ", m, "var: " , var)
EDIT: using numpy you can do something like this
(I removed all * before variables)
def avr(inn): # * removed
#print('avr:', inn)
hap = 0
cnt = 0
for i in inn:
hap += i
cnt += 1
avrr = hap/cnt
return avrr
def varr(inn): # * removed
#print('varr:', inn)
jejob = 0
jegobhap = 0
cnt = 0
for i in inn:
cha = (i-avr(inn)) # * removed
jegob = cha**2
jegobhap += jegob
cnt += 1
varr_m = jegobhap/cnt
return varr_m
def mean_and_var(val):
x_axis_avr = avr(val[:,0]) # * removed
y_axis_avr = avr(val[:,1]) # * removed
x_axis_boon = varr(val[:,0]) # * removed
y_axis_boon = varr(val[:,1]) # * removed
return (x_axis_avr, y_axis_avr), (x_axis_boon, y_axis_boon)
import numpy as np
v1 = (0, 1)
v2 = (0.5, 0.5)
v3 = (1, 0)
v4 = (50, 30)
matrix = np.array([v1,v2,v3,v4])
#print(matrix)
m, var = mean_and_var(matrix)
print("mean: ", m, "var: " , var)
I am trying to solve a linear programming problem using IBM's Cplex, while calling it from Python.
The problem is to minimize a+c,
subject to the constraint that Ax'=m',
where x=[a,b,c]
A = [[20,0,0],[0,20,30]]
m = [20,30]
with a,b,c between 0 and 1.
One correct solution to the problem is a=1, b=0, and c=1. But Cplex gives solutions, a=1, b=1, and c=0. There is an error in formulating the problem but I cannot figure out where. Code below
import cplex
from cplex.exceptions import CplexError
import sys
my_obj = [1.0, 0.0, 1.0]
my_ub = [1.0] * len(my_obj)
my_lb = [0.0] * len(my_obj)
my_colnames = ["a", "b", "c"]
my_rhs = [20.0, 30.0]
my_rownames = ["c1", "c2"]
my_sense = "E" * len(my_rownames)
def populatebynonzero(prob):
prob.objective.set_sense(prob.objective.sense.minimize)
prob.linear_constraints.add(rhs = my_rhs, senses = my_sense,names = my_rownames)
prob.variables.add(obj = my_obj, ub = my_ub, lb = my_lb ,names = my_colnames)
rows = [0,1]
cols = [0,1]
vals = [20.0,30.0]
prob.linear_constraints.set_coefficients(zip(rows, cols, vals))
def lpex1():
try:
my_prob = cplex.Cplex()
handle = populatebynonzero(my_prob)
my_prob.solve()
except CplexError, exc:
print exc
return
numrows = my_prob.linear_constraints.get_num()
numcols = my_prob.variables.get_num()
print
# solution.get_status() returns an integer code
print "Solution status = " , my_prob.solution.get_status(), ":",
# the following line prints the corresponding string
print my_prob.solution.status[my_prob.solution.get_status()]
print "Solution value = ", my_prob.solution.get_objective_value()
slack = my_prob.solution.get_linear_slacks()
pi = my_prob.solution.get_dual_values()
x = my_prob.solution.get_values()
dj = my_prob.solution.get_reduced_costs()
for i in range(numrows):
print "Row %d: Slack = %10f Pi = %10f" % (i, slack[i], pi[i])
for j in range(numcols):
print "Column %d: Value = %10f Reduced cost = %10f" % (j, x[j], dj[j])
my_prob.write("lpex1.lp")
print x, "SOLUTIONS"
lpex1()
There was an error in definition of rows and columns of the constraint, corrections below, works now
rows = [0,1,1]
cols = [0,1,2]
vals = [20.0,20.0,30.0]
I am trying to solve a linear programming problem using IBM's CPLEX Python API. It involves two sets of equality constraints. The code below works fine when we use either one of the two sets of constraints, but fails to find a solution when both sets of constraints are used.
The constraints are:
First constraint: Wx' = c', where W = [[20,0,0],[0,20,30]], x = [a,b,c], c=[20,30]
Second constraint: Vx' = e', where V = [[1,1,0],[0,0,1]], x = [a,b,c], c=[1,1]
Objective function: minimize a + c
One solution which meets both sets of constrains is a=1, b=0, c=1.
There is an error in the way I am introducing the two sets of constrains in Cplex Python. My code is below. To check that the code works with either set of constraints by itself comment out on of the sets of constraints.
import cplex
from cplex.exceptions import CplexError
import sys
def populatebynonzero(prob):
my_obj = [1.0, 0.0, 1.0]
my_ub = [1.0] * len(my_obj)
my_lb = [0.0] * len(my_obj)
my_colnames = ["a", "b", "c"]
prob.objective.set_sense(prob.objective.sense.minimize)
prob.variables.add(obj = my_obj, ub = my_ub, lb = my_lb ,names = my_colnames)
# first set of equality constraints: Wx' = c', where W = [[20,0,0],[0,20,30]], x = [a,b,c], c=[20,30]
my_rhs = [20.0, 30.0]
my_rownames = ["c1", "c2"]
my_sense = "E" * len(my_rownames)
rows = [0,1,1]
cols = [0,1,2]
vals = [20.0,20.0,30.0]
prob.linear_constraints.add(rhs = my_rhs, senses = my_sense,names = my_rownames)
prob.linear_constraints.set_coefficients(zip(rows, cols, vals))
# second set of equality constraints: Vx' = e', where V = [[1,1,0],[0,0,1]], x = [a,b,c], c=[1,1]
my_rhs = [1.0, 1.0]
my_rownames = ["e1", "e2"]
my_sense = "E" * len(my_rownames)
rows = [0,0,1]
cols = [0,1,2]
vals = [1.0,1.0,1.0]
prob.linear_constraints.add(rhs = my_rhs, senses = my_sense,names = my_rownames)
prob.linear_constraints.set_coefficients(zip(rows, cols, vals))
def lpex1():
try:
my_prob = cplex.Cplex()
handle = populatebynonzero(my_prob)
my_prob.solve()
except CplexError, exc:
print exc
return
numrows = my_prob.linear_constraints.get_num()
numcols = my_prob.variables.get_num()
print
# solution.get_status() returns an integer code
print "Solution status = " , my_prob.solution.get_status(), ":",
# the following line prints the corresponding string
print my_prob.solution.status[my_prob.solution.get_status()]
print "Solution value = ", my_prob.solution.get_objective_value()
slack = my_prob.solution.get_linear_slacks()
pi = my_prob.solution.get_dual_values()
x = my_prob.solution.get_values()
dj = my_prob.solution.get_reduced_costs()
for i in range(numrows):
print "Row %d: Slack = %10f Pi = %10f" % (i, slack[i], pi[i])
for j in range(numcols):
print "Column %d: Value = %10f Reduced cost = %10f" % (j, x[j], dj[j])
my_prob.write("lpex1.lp")
print x, "SOLUTIONS"
lpex1()
It works if the two sets of constraints are combined into one matrix in the following way, though it would be good to find a solution which does not have to do combining
import cplex
from cplex.exceptions import CplexError
import sys
def populatebynonzero(prob):
my_obj = [1.0, 0.0, 1.0]
my_ub = [1.0] * len(my_obj)
my_lb = [0.0] * len(my_obj)
my_colnames = ["a", "b", "c"]
prob.objective.set_sense(prob.objective.sense.minimize)
prob.variables.add(obj = my_obj, ub = my_ub, lb = my_lb ,names = my_colnames)
#combined constraints
my_rhs = [20.0, 30.0, 1.0, 1.0]
my_rownames = ["c1", "c2", "e1", "e2"]
my_sense = "E" * len(my_rownames)
rows = [0,1,1,2,2,3]
cols = [0,1,2,0,1,2]
vals = [20.0,20.0,30.0,1,1,1]
prob.linear_constraints.add(rhs = my_rhs, senses = my_sense,names = my_rownames)
prob.linear_constraints.set_coefficients(zip(rows, cols, vals))
"""
# first set of equality constraints: Wx' = c', where W = [[20,0,0],[0,20,30]], x = [a,b,c], c=[20,30]
my_rhs = [20.0, 30.0]
my_rownames = ["c1", "c2"]
my_sense = "E" * len(my_rownames)
rows = [0,1,1]
cols = [0,1,2]
vals = [20.0,20.0,30.0]
prob.linear_constraints.add(rhs = my_rhs, senses = my_sense,names = my_rownames)
prob.linear_constraints.set_coefficients(zip(rows, cols, vals))
# second set of equality constraints: Vx' = e', where V = [[1,1,0],[0,0,1]], x = [a,b,c], c=[1,1]
my_rhs = [1.0, 1.0]
my_rownames = ["e1", "e2"]
my_sense = "E" * len(my_rownames)
rows = [0,0,1]
cols = [0,1,2]
vals = [1.0,1.0,1.0]
prob.linear_constraints.add(rhs = my_rhs, senses = my_sense,names = my_rownames)
prob.linear_constraints.set_coefficients(zip(rows, cols, vals))
"""
def lpex1():
try:
my_prob = cplex.Cplex()
handle = populatebynonzero(my_prob)
my_prob.solve()
except CplexError, exc:
print exc
return
numrows = my_prob.linear_constraints.get_num()
numcols = my_prob.variables.get_num()
print
# solution.get_status() returns an integer code
print "Solution status = " , my_prob.solution.get_status(), ":",
# the following line prints the corresponding string
print my_prob.solution.status[my_prob.solution.get_status()]
print "Solution value = ", my_prob.solution.get_objective_value()
slack = my_prob.solution.get_linear_slacks()
pi = my_prob.solution.get_dual_values()
x = my_prob.solution.get_values()
dj = my_prob.solution.get_reduced_costs()
for i in range(numrows):
print "Row %d: Slack = %10f Pi = %10f" % (i, slack[i], pi[i])
for j in range(numcols):
print "Column %d: Value = %10f Reduced cost = %10f" % (j, x[j], dj[j])
my_prob.write("lpex1.lp")
print x, "SOLUTIONS"
lpex1()
When you are attempting to create the second set of constraints, you are using the wrong indices for the rows:
# second set of equality constraints: Vx' = e', where V = [[1,1,0],[0,0,1]], x = [a,b,c], c=[1,1]
my_rhs = [1.0, 1.0]
my_rownames = ["e1", "e2"]
my_sense = "E" * len(my_rownames)
rows = [0,0,1] # <- HERE
cols = [0,1,2]
vals = [1.0,1.0,1.0]
That is, you're using the row indices 0 and 1, which were created for the first set of constraints. Instead, you should do something like the following:
# second set of equality constraints: Vx' = e', where V = [[1,1,0],[0,0,1]], x = [a,b,c], c=[1,1]
my_rhs = [1.0, 1.0]
my_rownames = ["e1", "e2"]
my_sense = "E" * len(my_rownames)
cols = [0,1,2]
vals = [1.0,1.0,1.0]
rowindices = list(prob.linear_constraints.add(rhs = my_rhs, senses = my_sense,names = my_rownames))
assert len(rowindices) == 2
rows = [rowindices[0], rowindices[0], rowindices[1]]
prob.linear_constraints.set_coefficients(zip(rowindices, cols, vals))
Above, we get the new row indices from the call to prob.linear_constriants.add. With this change, the script works fine.
In addition, it's a good idea to write out the problem in LP format to make sure that it looks correct, like so:
prob.write("model.lp")
I am relatively new to python and have been asked to write a code where I enter a specific sequence of DNA and get various values for that sequence in return. I made a dictionary and am having trouble making the code recall the dictionary for values. The code is as follows:
import math
def dnaTM(seqobj):
if isinstance(seqobj,SeqRecord):
seq = seqobj.seq.tostring().upper()
elif isinstance(seqobj,Seq):
seq = seqobj.tostring().upper()
elif isinstance(seqobj,str):
seq = seqobj.upper()
C_primer = .000001
C_Monovalent = 1
percentage_annealed = 50
percentage_annealed = percentage_annealed/100.0
R = 1.987
deltaH = dict()
deltaS = dict()
deltaH = { 'AA/TT': -7.9, 'AT/TA': -7.2, 'TA/AT': -7.2, 'CA/GT': -8.5,
'GT/CA': -8.4, 'CT/GA': -7.8, 'GA/CT': -8.2, 'CG/GC': -10.6,
'GC/CG': -9.8, 'GG/CC': -8.0, 'GC_init': 0.1, 'AT_init': 2.3}
deltaS = { 'AA/TT': -22.2, 'AT/TA': -20.4, 'TA/AT': -21.3, 'CA/GT': -22.7,
'GT/CA': -22.4, 'CT/GA': -21.0, 'GA/CT': -22.2, 'CG/GC': -27.2,
'GC/CG': -24.4, 'GG/CC': -19.9, 'GC_init': -2.8, 'AT_init': 4.1,
'sym': -1.4}
seqLength = len(seq)
dH = 0.2 + deltaH[str(seq[0])] + deltaH[str(seq[len(seq)-1])]
dS = -5.7 + deltaS[seq[0]] + deltaS[seq[len(seq)-1]]
for i in range(0, seqLength - 1):
dH += deltaH[str(seq[i:i+2])]
dS += deltaS[seq[i:i+2]]
dS = dS + 0.368 * seqLength * math.log(1)
Tm =(dH * 1000) / (dS + R * (math.log(C_primer*(1- percentage_annealed)/percenta\
ge_annealed)-21.4164))
return Tm
I am trying to build a fuzzy inference system in python. I have 4 variables depending on which output class is decided.
def fuzzInferenceself():
### Input ###
hf_very_poor = fuzz.trimf(hotel_facility, [0, 0.15, 0.3])
hf_poor = fuzz.trimf(hotel_facility, [2.5,0.3,0.45])
hf_average = fuzz.trimf(hotel_facility, [0.4, 0.5, 0.75])
hf_good = fuzz.trimf(hotel_facility, [0.7, 0.85, 0.9])
hf_very_good = fuzz.trimf(hotel_facility, [0.875, 0.92, 1.0])
vc_less = fuzz.trimf(visited_count, [0, 0.05, 0.1])
vc_average = fuzz.trimf(visited_count, [0.05, 0.2, 0.35])
vc_many = fuzz.trapmf(visited_count, [0.3,0.45,0.55,0.7])
vc_a_lot = fuzz.trapmf(visited_count, [0.65,0.8,0.9,1.0])
rm_very_poor = fuzz.trimf(hotel_facility, [0, 0.15, 0.3])
rm_poor = fuzz.trimf(hotel_facility, [2.5,0.3,0.45])
rm_average = fuzz.trimf(hotel_facility, [0.4, 0.5, 0.75])
rm_good = fuzz.trimf(hotel_facility, [0.7, 0.8, 0.9])
rm_very_good = fuzz.trimf(hotel_facility, [0.85, 0.9,1.0])
## output ####
class_very_poor = fuzz.gaussmf(class_score,1,0.5)
class_poor = fuzz.gaussmf(class_score,1.75,0.65)
class_average = fuzz.gaussmf(class_score,2.25,0.75)
class_good = fuzz.gaussmf(class_score,3,0.25)
class_very_good = fuzz.gaussmf(class_score, 3.5, 0.5)
def hotelFaclilityClassification(self,A):
hf_vp= fuzz.interp_membership(hotel_facility, hf_very_poor, A)
hf_p= fuzz.interp_membership(hotel_facility, hf_poor, A)
hf_av= fuzz.interp_membership(hotel_facility, hf_average, A)
hf_gd= fuzz.interp_membership(hotel_facility, hf_good, A)
hf_vg= fuzz.interp_membership(hotel_facility, hf_very_good, A)
return dict(hfVP = hf_vp, hfP = hf_p, hfAV = hf_av,hGD = hf_gd, hVG = hf_vg)
def visitCountClassification(B):
vc_l = fuzz.interp_membership(visited_count,vc_less)
vc_av = fuzz.interp_membership(visited_count,vc_average)
vc_mn = fuzz.interp_membership(visited_count,vc_many)
vc_al = fuzz.interp_membership(visited_count,vc_a_lot)
return dict(vcL = vc_l, vcAV=vc_av, vcMN = vc_mn, vcAL = vc_al )
def roomFacilityClassification(C):
rm_vp = fuzz.interp_membership(room_facility,rm_very_poor)
rm_p = fuzz.interp_membership(room_facility,rm_poor)
rm_av = fuzz.interp_membership(room_facility,rm_average)
rm_gd = fuzz.interp_membership(room_facility,rm_good)
rm_vg = fuzz.interp_membership(room_facility,rm_very_good)
return dict(rmVP = rm_vp, rmP = rm_p, rmAV = rm_av, rmGD = rm_gd, rmVG = rm_vg)
A similar function for price is: def priceClassification(D).
The rules are as follows:
"If Hotel facility score is Very good, visited count is alot, room facility is very good,prices is less then class is very good."
I do not understand how to code the rules. All sources I have seen takes one input and one output variable. But this is not the case in my code.
Can anyone give me a good resource or idea about how to code this rule?