Python Hw, bisection Method - python

Part A - Bisection Method
Write a function called bisection(n, p) that asks the user to enter a mathematical function f(x)
and two boundary points in order to solve for r such that f(r) = 0 using bisection method.
The function terminates when the solution r is found or when the maximum number of iterations
n is reached (default n = 100), whichever occurs first.
def bisection(n = 100, p = 0.0001):
# code goes below
fx = input("f(x) = ")
a = float(input("Boundary A: "))
x = a
fa = eval(fx)
b = float(input("Boundary B: "))
x = b
fb = eval(fx)
i = 0
if (fa * fb >= 0):
print("Bisection method fails")
return
while(i < n):
m = a + b / 2
x = m
fm = eval(fx)
if(fm * fa < 0):
a = a
b = m
if (fm * fb < 0):
a = m
b = b
i = i + 1
if (fm == 0):
return m
pass
When I input: f(x) = x - 1
Boundary A: 0
Boundary B: 3
No answer is printed so I'm very confused?!

There are lots of problems with this code. For some reason you defined p and never passed it again, I assume it stands for epsilon. You defined midpoint as
a+b/2
which is equivalent to
a+(b/2)
but you need
(a+b)/2
.
Statement
if (fm == 0):
this statement would probably never run because it is hard to get that close to a root for a few iterations.
Instead, use
if (abs(fm<p)):
Modified code
def bisection(n = 250, p = 10**-6):
# code goes below
fx = input("f(x) = ")
a = float(input("Boundary A: "))
x = a
fa = eval(fx)
b = float(input("Boundary B: "))
x = b
fb = eval(fx)
for i in range(1, n+1):
m = (a + b)/2
x = m
fm = eval(fx)
if(fm * fa < 0):
a = a
b = m
elif (fm * fa > 0):
a = m
b = b
elif (abs(fm<p)):
return m
print(bisection())
Output:
f(x) = x - 1
Boundary A: 0
Boundary B: 3
1.0

Related

Brute force attack for discrete log problem (Python)

I'm still learning Python and trying to wrap my mind around brute force attacks using for loops in Python. I made this for loop to try every number from 0 to 999999 and store it in the variable n. Instead of letting my for look run forever, I want it to stop at a specific scalarmult(n,P) value. For example, let's say I want the for loop to end when print(scalarmult(n,P)) prints, (111111,2334897).
p = 1000003
class Fp:
def __init__(self,x):
self.int = x % p
def __str__(self):
return str(self.int)
__repr__ = __str__
Fp.__eq__ = \
lambda a,b: a.int == b.int
Fp.__add__ = \
lambda a,b: Fp(a.int + b.int)
Fp.__sub__ = \
lambda a,b: Fp(a.int - b.int)
Fp.__mul__ = \
lambda a,b: Fp(a.int * b.int)
def clockadd(P1, P2):
x1,y1 = P1
x2,y2 = P2
x3 = x1*y2+y1*x2
y3 = y1*y2-x1*x2
return x3,y3
P = (Fp(1000),Fp(2))
def scalarmult(n,P):
if n == 0: return (Fp(0), Fp(1))
if n == 1: return P
Q = scalarmult(n//2,P)
Q = clockadd(Q,Q)
if n % 2: Q=clockadd(P,Q)
return Q
#(947472, 736284)
for n in range(0,10):
i = scalarmult(n,P)
print(n, i) #i.e. 6 (780000, 1351)
if n == 780000 and P == 1351: #should stop the for loop at iteration 7 which is 6 (780000, 1351)
break
Add an if statement inside the loop, after the print
if n == 111111 and p == 2334897:
break

How to encrypt and decrypt message RSA in python?

I am trying to write RSA encryption and decryption in python without Crypto library and in short I have generated public(e,N) and private(d,N) keys to exchange with message and I don't know how to that.The message I want to send is also key:b'gAAAAABenIFsZD5Oa7GPNKPV7yBHSKasuzpMzYPPoXbEqX3cbxO_9-3eP9UdKOXsrQmLSesKkaeKk9VZXI6Qx-iWS8tglsxbRwjgdAWPZKQa8NLyH1ICKJgEihrc-9ybO6WgV_jASgHH0zg4mdEP8XhxQmg6-S96HA=='
Does someone know how to encrypt message with my public key and decrypt it with private ?
import random
def gcd(a, b): # gdc to find proper e
if (b == 0):
return a
else:
return gcd(b, a % b)
def isPrime(num):
if num > 1:
for i in range(2, num):
if (num % i) == 0:
return False;
break
else:
return True
else:
return False;
def pGenerator():
p = 0
while p == 0:
pn = random.randint(0, 40)
if (isPrime(pn)):
p = pn
break
return p
def qGenerator(p):
q = 0
while q == 0:
pn = random.randint(0, 40)
if (isPrime(pn) and pn != p and pn <p):
q = pn
break
return q
def eGenerator( fiN):
e = 0
while e == 0:
pn = random.randint(0, fiN)
if (gcd(pn, fiN) == 1):
e = pn
break
return e
def start():
p = pGenerator()
print(p)
q = qGenerator(p)
print(q)
N = p * q
fiN = (p - 1) * (q - 1)
print(fiN)
e = eGenerator(fiN)
d=multiplicative_inverse(e,fiN)
c=encrypt(e, N, "d")
decrypt(d,N,c)
print(c)
def encrypt(e,n, plaintext):
#Unpack the key into it's components
key=e
#Convert each letter in the plaintext to numbers based on the character using a^b mod m
cipher = [(ord(char) ** key) % n for char in plaintext]
#Return the array of bytes
return cipher
def multiplicative_inverse(e, phi):
d = 0
x1 = 0
x2 = 1
y1 = 1
temp_phi = phi
while e > 0:
temp1 = temp_phi / e
temp2 = temp_phi - temp1 * e
temp_phi = e
e = temp2
x = x2 - temp1 * x1
y = d - temp1 * y1
x2 = x1
x1 = x
d = y1
y1 = y
if temp_phi == 1:
return d + phi
start()
Have you tried rsapy?
Just read its docs on its PyPI page.
Example:
import rsapy
pub, pri = rsapy.genkey(2**512)
print(rsapy.encode("message", pub))
# This also works with b"message"

Is my math or my variables wrong in my RSA example?

I was reading up on cryptography, specifically RSA(https://www.khanacademy.org/computing/computer-science/cryptography/modern-crypt/v/rsa-encryption-part-4), and decided to make an example for myself. However, even though I'm pretty sure I got my variables right, I think I got my math wrong. Can someone help me find the error? I tried to put comments everywhere I thought needed an explanation. Written in Python 3.5.2
#m^phi(n) mod n == 1 where m & n dont share a common factor
#since 1^k = 1, m^(k * phi(n)) mod n == 1, too.
#since 1*m = m, m* (m^(k * phi(n)) mod n) == m
#^^^^simplifies to m^(k * phi(n) + 1) mod n == m
#b/c m^(e*d) mod n = m
#m^(e*d) mod n == m^(k * phi(n) + 1) mod n
#e*d = k * phi(n) + 1
#d = (k * phi(n) + 1)/e
from fractions import gcd
import random
i = 1
j = 1
t = 1
def is_prime(a):
return all(a % i for i in range(2, a))
while True:
p1 = random.randrange(10.00000)#gens the 1st random prime
if is_prime(p1):
if p1 == 0 or p1 == 1:
i+=1
continue
else:
print("First Random Prime Found on attempt "+str(i)+": "+str(p1))
break
i+=1
while True:
p2 = random.randrange(10.00000)#gens the 1st random prime
if is_prime(p2):
if p2 == 0 or p2 == 1:
j+=1
continue
else:
print("First Random Prime Found on attempt "+str(j)+": "+str(p2))
break
j+=1
n = p1 * p2
print("n = p1 * p2 = "+str(n))
phi_n = (p1 - 1) * (p2 - 1)#phi(n) = how many numbers below n share no factors w/ n. Given Definition of a prime, phi(any_prime_num) is always any_prime_num - 1.
print("phi_n = (p1 - 1) * (p2 - 1) = "+str(phi_n))
while True:
e = random.randrange(10)#gens the 3rd random prime
if e % 2 != 0:
if phi_n % e == 0:
k+=1
continue
else:
print("Public Random Prime(is e)Found on attempt "+str(t)+": "+str(e))
break
k = random.randrange(e)
print("num used to find d(is k): "+str(k))
d = (k * phi_n + 1)/e
print("PRIVATE key(is d): "+str(d))
#pub_key = [n, e]
#priv_key = [d, k, p1, p2, phi_n]
m = input("Type an int: ")
if gcd(int(m), n) != 1:
quit() #b/c m & n must not share a common factor(apparently)
c = (int(m)**e) % n #cipher text(nums)
print("Encrypted: "+str(c))
u = (c**d) % n #SHOULD be decrypted text(more nums)
print("Decrypted: "+str(u))
if int(m) == int(u):
print("Successful!!")
else:
print("Unsuccessful....")

Minimum spanning tree using Kruskal in Python, recursion enters a infinite loop

The purpose of this code is to create the shortest path that connect each point. I've tried to implement the Kruskals algorithm in Python, but there is a problem and it occurs when the function findSet(x) is called. It seems like the program enters a infinite loop. I've tried to print x, x.dad and x.dad.dad and x in the crucial moment returns the initial x. I really don't know where is the problem.
class Point:
def __init__(self,x = None, y = None):
self.x = x
self.y = y
self.dad = None
self.rank = None
class Edge:
def __init__(self, firstPoint = None, secondPoint = None, value = None):
self.firstPoint = firstPoint
self.secondPoint = secondPoint
if self.firstPoint != None and self.secondPoint != None:
self.value = abs(firstPoint.x-secondPoint.x) + abs(firstPoint.y - secondPoint.y)
else:
self.value = float("inf")
def makeSet(node):
node.dad = node
node.rank = 0
def findSet(x):
print x, x.dad,x.dad.dad
if x == x.dad:
return x
x.dad = findSet(x.dad)
return x.dad
def unionSet(node1,node2):
root1 = findSet(node1)
root2 = findSet(node2)
if root1.rank < root2.rank:
root1.dad = root2
if root1.rank > root2.rank:
root2.dad = root1
else:
root2.dad = root1
root1.rank += 1
def merge(A, p, q, r):
L = A[p:q+1]
R = A[q+1:r+1]
infinite = Edge()
L.append(infinite)
R.append(infinite)
temp = []
i = 0
j = 0
for k in range(p,r+1):
if L[i].value <= R[j].value:
temp.append(L[i])
i += 1
else:
temp.append(R[j])
j += 1
A[p:r+1] = temp
def mergeSort(A,p,r):
A2 = A
if p < r:
q = int((p+r)/2)
mergeSort(A2, p, q)
mergeSort(A2, q+1, r)
merge(A2, p, q, r)
def readPoint(A):
temp = []
for i in range(0,len(A), 2):
tempPoint = Point(A[i],A[i+1])
makeSet(tempPoint)
temp.append(tempPoint)
return temp
def calculateEdges(A):
tempArray = []
for i in range(0,len(A)):
for j in range(i+1,len(A)):
edge = Edge(A[i], A[j])
tempArray.append(edge)
return tempArray
def Kruskal(N, E):
mergeSort(E,0,len(E)-1)
j = 0
i = 0
total = 0
while j < N:
if findSet(E[i].firstPoint) != findSet(E[i].secondPoint):
unionSet(E[i].firstPoint,E[i].secondPoint)
j += 1
total += E[i].value
if i < len(E) - 1:
i += 1
return total
Ar = readPoint([18, 2, 99, 68])
E = calculateEdges(Ar)
print Kruskal(len(Ar),E)

Converting string using list in python

I've been trying to rearrange the string by reversing a particular strings consecutively from the given string input and the limit is given as input.
for example
limit is 3
if input is Hellothegamestarts
output must be Heltolhegemastastr
and it is saved in separate array
The code is:
while True:
t = int(input())
if t == 0:
break
string = raw_input()
string = string.encode('utf-8')
leng = len(string)
r = t/leng
m = []
leng = 0
for i in range(r):
if r % 2 == 0:
l = 0
l = leng + t
for i in range(t):
temp = string[l]
m.append(temp)
l = l - 1
r = r + 1
leng = leng + t
else:
l = 0
l = leng
for i in range(t):
temp = string[l]
m.append(temp)
l = l + 1
r = r + 1
leng = leng + t
print m
the output i got is [] and asks for next input for t.
Any help is appreciated.
Take the blocks in chunks of 3s, and reverse the odd ones, eg:
import re
s = 'Hellothegamestarts'
r = ''.join(
el if idx % 2 == 0 else el[::-1]
for idx, el in enumerate(re.findall('.{,3}', s))
)
# Heltolhegemastastr
Maybe you can try -
t = int(input())
if t == 0:
break;
string = raw_input()
m = ''
leng = len(string)
i = 0
while i < leng:
if (i/t) % 2 != 0:
m = m + string[i+t-1:i-1:-1]
else:
m = m + string[i:i+t]
i = i + t
print(m)
Alternatively you can try this
def myfunc(s, count):
return [''.join(x) for x in zip(*[list(s[z::count]) for z in range(count)])]
a='Hellothegamestarts'
lst=myfunc(a,3)
print "".join([i if lst.index(i) in range(0,len(lst),2) else i[::-1] for i in lst])
myfun i didn't write it.It's from here

Categories

Resources