Specific Character Pattern Python - python

I am trying to achieve the following;
Write a program that produces the following output giving an integer input n.
The result should be the following;
n=1 n=2 n=3 n=4
+ A+B AA+BB AAA+BBB
+E+ A+E+B AA+E+BB
C+D +EEE+ A+EEE+B
C+E+D +EEEEE+
CC+DD C+EEE+D
CC+E+DD
CCC+DDD
I am having issues solving this problem.
When I enter 2 I am currently getting the following but unable how to make it look like the above.
Current result;
A+
B+
E+
C+
D
Here is my code;
def specific_pattern(n):
addition = "+"
alp = "A, B, E, C, D"
# myList = ["A, B, C, D, E"]
newList = []
for j in range(0, n):
for i in range(0, j):
if n == 1:
print(addition)
else:
letters = alp.split(", ")
for letter in range(len(letters)):
newList.append(letters[letter]*j+addition)
newchar = "".join(newList)
print(newchar[:-1])
n = int(input("Enter a number: "))
specific_pattern(n)

You can use simple iteration to create both the top and bottom of the desired diamond:
def sequence(d):
c, l = 0, 1
while c < d - 1:
if l%2:
yield l
c += 1
l += 1
def make_pattern(d):
t, b, r = f'{"A"*(d-1)}+{"B"*(d-1)}', f'{"C"*(d-1)}+{"D"*(d-1)}', list(sequence(d))
body = '\n'.join(f'{"A"*((r[-1]-i)//2)}+{"E"*i}+{"B"*((r[-1]-i)//2)}' for i in r[:-1]) + \
f'\n+{"E"*r[-1]}+\n'+'\n'.join(f'{"C"*((r[-1]-i)//2)}+{"E"*i}+{"D"*((r[-1]-i)//2)}' for i in r[:-1][::-1])
return f'{t}\n{body}\n{b}'
def diamond(d):
return {1:lambda _:'+', 2:lambda _:'A+B\n+E+\nC+D'}.get(d, make_pattern)(d)
print(diamond(3))
print('-'*5)
print(diamond(4))
Output:
AA+BB
A+E+B
+EEE+
C+E+D
CC+DD
-----
AAA+BBB
AA+E+BB
A+EEE+B
+EEEEE+
C+EEE+D
CC+E+DD
CCC+DDD

Related

Equation solving using bisection method using python

I wrote a python code to find root of 2*x-4 using bisection method
def func(x):
return 2*x-4
def bisection(a,b):
if (func(a) * func(b) >= 0):
print("You have not assumed right a and b\n")
return
c = a
while ((b-a) >= 0.01):
c = (a+b)/2
if (func(c) == 0.0):
break
if (func(c)*func(a) < 0):
b = c
else:
a = c
print("The value of root is : ","%.0f"%c)
a =-2
b = 4
bisection(a, b)
Now i want that the function input should be given by the user in the form of mx+n where m and n are integers. Can anyone help how can i do that ?
m, n = list(map(int, input("Please enter the value of [m] [n] for f(x) = mx +n: ").split()))
def Input():
a, b = list(map(int, input("Enter values of [a] [b]: ").split()))
if f(a)*f(b)<0:
Bisection(a, b)
else:
print("Oops! The root of function doesn't belong to the above domain\nPlease try to again:")
Input()
def f(x):
return m*x + n
def Bisection(a, b):
c = (a+b)/2
if f(c)*f(b)<0:
Bisection(c, b)
elif f(c)*f(a)<0:
Bisection(c, a)
elif f(c)==0:
print(c)
Input()
See we know that Bisection, Newton-Raphson, or most of all Numerical methods are the iteration processes so better we use function inside of function: f(f(f(f.....) Of course! by checking the conditions.
Here, I have used elif f(c)==0 this is something which we can't use for quadratic/cubic or higher-order polynomials because getting the exact root will not be possible for all the types of equations say like f(x) = mx^2 - n where m, n > 0 However, we can define the iterations to be performed.
By asking like Please enter the number of iterations to be performed:

Why can't I run this fibonacci sequence?

extremely new to python, whenever I try to run this code
def fib(n):
"""Print a Fibonacci series up to n."""
a, b = 0, 1
while a < n:
print(a, end = ' ')
a, b = b, a+b
print()
I get an error message saying either
print(a, end=' ') SyntaxError: invalid syntax
or
fib() not defined.
how can I solve this?
Because you didn't take value of n from the user.
def fib(n):
"""Print a Fibonacci series up to n."""
a, b = 0, 1
while a < n:
print(a, end = ' ')
a, b = b, a+b
print()
fib(10)
Your code has no issue if you were to use Python 3 so consider using that instead.
If you like python2 a lot then modify your code to the following:
def fib(n):
"""Print a Fibonacci series up to n."""
a, b = 0, 1
while a < n:
print(str(a) + ' ')
a, b = b, a+b
This is because python2 doesn't allow the use of
print(a, end = ' ')
It is a python3 feature

print the ratio of Fibonacci numbers until a specific condition

I will print to screen first 70 Fibonacci numbers. And then in the same script I also want to print F(i+1)/F(i) ratio until a defined F(i+1)-F(i)<=536 condition is met.
My script prints first 70 Fibonacci numbers but it doesn't print the ratio F(i+1)/F(i).
It gives the following error:
Traceback (most recent call last):
File "fib.py", line 13, in
while b-a > 536:
NameError: name 'b' is not defined
In my code a and b represent F(i) and F(i+1), respectively. How can I fix my code?
#!/usr/bin/python
def F(n):
a, b = 0, 1
for i in range(0, n):
a, b = b, a+b
return a
for c in range(0, 70):
print(F(c))
while b-a > 536:
print 'Ratio:', b/a
Try this:
a,b = 0,1
l = []
def F(n):
global a
global b
a,b = 0,1
for i in range(0, n):
a, b = b, a+b
return a
for c in range(0, 70):
num = F(c)
print(num)
l.append(num)
for i in range(0, len(l)-2):
if l[i+1]-l[i] <= 536:
#print b
#print a
print 'Ratio:', float(b)/a
def F(n):
a, b = 0, 1
for i in range(0, n):
a, b = b, a+b
return a
factorials = []
for c in range(0, 70):
factorials.append((F(c)))
for i in xrange(1,len(factorials)-1):
if factorials[i+1] - (factorials[i]) > 536:
print "ratio :"+str(factorials[i+1]/float(factorials[i]))
The output mainly consists of integers starting with 1.61803, Is that what you were trying to achieve ?
def FR(n):
a, b = 0, 1
for i in range(0, n):
a, b = b, a+b
return a , b/float(a) if b-a > 536 else None
for c in range(0, 70):
fb , ra = FR(c)
print fb if ra is None else fb,' Ratio:', ra
b is not definied in your while (as a).
In fact a and b are only define in the F(n) function and they are local variables.
You should read some documentation about Programming and python first. But the following code should works:
(I suppose that you want while a/b <= 536 as this is not clear in your question)
def F(n):
a, b = 0, 1
for i in range(0, n):
a, b = b, a+b
return a, b
for c in range(0, 70):
a,b = F(c)
print(a)
while a/b <= 536:
print('Ratio:{}/{}'.format(b,a))
a, b = F(a)
An other solution is to totaly rewrite your code:
def F(a, b):
c = a + b
return c,a
a, b = 0, 1
for c in range (0,70):
a, b = F(a,b)
print (a)
while a/b <=536:
print(a/b)
a,b = F(a, b)

How to implement base b expansion in Python?

I have to implement this pseudo-code (from a discrete math book):
procedure base b expansion(n,b: positive integers with b>1
q :=n
k :=0
while q does not equal 0
a_k := q mod b
q = q div b
k = k + 1
return (a_k-1, .... a_1, a_0) {(a_k-1... a_1a_0)_b is the base expansion of n}
Here is my code thus far:
def expansion(n,b):
q = n
k = 0
a = []
i = len(str(n))
for x in range(0,1000):
a.append(0)
while q != 0:
a[k] = q % b
q = q / b
return a[k]
print expansion(444,2)
I just cant figure out what I am doing wrong, it usually says the index is out of bounds or it doesn't print enough numbers.
In your code you are not updating k,
while q != 0:
a[k] = q % b
q = q / b
# You need to update k
k += 1
Also, you need to return only a, not a[k].
Also, understand that for the current argument (444,2) you need at least 1085 places in the array before q becomes zero. You do not need to assign based on an index, but rather append the values to the list as they are computed.
So,
def expansion(n,b):
q = n
k = 0
a = []
i = len(str(n))
while q != 0:
a.append(q % b)
q = q / b
k += 1
return a
This way you avoid having to allocate places before hand.
Rather than using a list to accumulate digits, try a string. As you get a digit, concatenate it to the front of the string. Like so:
>>> def n_as_base_b(n, b):
... output = ""
... while n >0:
... output = str(n%b) + output
... n /= b
... return output
...
>>> n_as_base_b(15,2)
'1111'
>>> n_as_base_b(11,2)
'1011'

RSA encryption in python

I decided to write a simple RSA encryption implementation in Python, but every time I run it it prints the error IndexError: list out of range when it's decrypting and in find_key.
Here's the error:
p 937
q 353
n 330761
phi 329472
e 5
d 264609
Traceback (most recent call last):
File "rsa.py", line 94, in
print dec_rsa(b, d, n)
File "rsa.py", line 88, in dec_rsa
char_array.append(decrypt_byte(i, d, n))
File "rsa.py", line 77, in decrypt_byte
return find_key(alpha, (c**d)%n)
File "rsa.py", line 67, in find_key
return [k for k, v in dic.iteritems() if v == val][0]
IndexError: list index out of range
The code:
import fractions, sys, random, math
def isPrime( no ):
if no < 2: return False
if no == 2: return True
if not no&1: return False
for x in range(3, int(no**0.5)+1, 2):
if no%x == 0:
return False
return True
def primes_range(low, high):
primes = []
for i in range(high-low):
if isPrime(i+low):
primes.append(i+low)
return primes
let = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789~!##$%^&*()_+'";:[]/<>,."
a, alpha = 2, {}
for i in let:
alpha[i] = a
a+=1
Low = 29
High = 1000
p = random.choice(primes_range(Low, High))
q = random.choice(primes_range(Low, High))
while p == q:
q = random.choice(primes_range(Low, High))
print "p ",p
print "q ",q
#p = 104729
#q = 3
p, q = int(p), int(q)
n = p*q
phi = (p-1)*(q-1)
print "n ",n
print "phi ",phi
for i in range(2, q if q>p else p):
if fractions.gcd(i, phi) == 1:
e = i
break
print "e ",e
def egcd(a,b):
u, u1 = 1, 0
v, v1 = 0, 1
while b:
q = a // b
u, u1 = u1, u - q * u1
v, v1 = v1, v - q * v1
a, b = b, a - q * b
return u, v, a
def modInverse(e, phi):
return egcd(e, phi)[0]%n
d = modInverse(e, n)
print "d ",d
def find_key(dic, val):
#print "val ",val
#print "dic ",list(dic.iteritems())
return [k for k, v in dic.iteritems() if v == val][0]
def encrypt_byte(byte, e, n):
try:
m = alpha[byte]
except:
m = int(byte)
return (m**e)%n
def decrypt_byte(c, d, n):
return find_key(alpha, (c**d)%n)
def enc_rsa(string, e, n):
char_array = []
for i in range(len(string)):
char_array.append(encrypt_byte(alpha[string[i]], e, n))
return char_array
def dec_rsa(enc_arr, d, n):
char_array = []
for i in enc_arr:
char_array.append(decrypt_byte(i, d, n))
return ''.join(char_array)
a = "hello, world"
b = enc_rsa(a, e, n)
#print b
print dec_rsa(b, d, n)
I hope you're enjoying learning Python!
A couple of things:
(1) Your isPrime is broken: it thinks 1 is prime, 2 and 3 aren't, but all of 25, 35, 121, 143, 289, 323, 529, 841, 899 are. Getting a composite will lead to problems.
(2) You also don't check to see that p != q.
(3) Your alpha[str(byte)] should be alpha[byte] (otherwise you'll get "96llo, worl5").
(4) You're taking the wrong multiplicative modular inverse. You want modInverse(e, phi(n)), not modInverse(e, n); see this worked example.
After fixing those, it seems to work for me.
The following aren't bugs, but suggestions: you should probably use pow(c,d,n) rather than (c**d)%n; for large numbers the former will be much faster. As well, if you want to turn a letter into a number, and you don't really care what number, you could use the "ord"/"chr" functions, and not even need a dictionary. In any case, you might want to swap the keys and values in your dictionary: right now your find_key might as well be using a list, as you're simply searching over all the k,v pairs until you find a match.
Hope that helps!
The implementation of RSA can be further simplified as follows:
1.Choose two different large primes, here for the sake of simplicity let's choose p=937, q=353, as done in the example
2.Compute n = p*q
3.Compute Euler Totient φ(n) ≡ (p-1)*(q-1)
4.Choose the public key e as coprime with φ(n), for simplicity, let's choose e=5, which is a prime
5.Compute the private key d, s.t. d*e ≡ 1 (mod φ(n)), using the multiplicative inverse algorithm (extended Euclidean) from here:
Compute multiplicative inverse of a modulo n
# solution t to a*t ≡ 1 (mod n)
def multiplicative_inverse(a, n):
t, newt = 0, 1
r, newr = n, a
while newr != 0:
q = r // newr
t, newt = newt, t - q * newt
r, newr = newr, r - q * newr
if t < 0:
t = t + n
return t
Python code for steps 1-5:
p, q = 937, 353 # use large primes here
n = p*q
φ = (p-1)*(q-1)
e = 5 # choose public key e as a prime, s.t., gcd(φ, e) = 1
d = multiplicative_inverse(e, φ) # private key d
print(d)
# 131789
6.Encrypt the message (plaintext) with the receiver's public key (e) at sender's end
7.Decrypt the ciphertext received at the receiver end with his private key (d)
The following code shows how the encryption / decryption can be done:
def rsa_encrypt(plain_text, e, n):
# ideally we should convert the plain text to byte array and
# then to a big integer which should be encrypted, but here for the sake of
# simplicity character-by-character encryption is done, which will be slow in practice
cipher_text = [ord(x)**e % n for x in plain_text]
return cipher_text
def rsa_decrypt(cipher_text, d, n):
decoded_text = ''.join([chr(x**d % n) for x in cipher_text])
return decoded_text
Now, let's use the above functions for encryption / decryption:
plain_text = 'Hello world'
cipher_text = rsa_encrypt(plain_text, e, n)
print(cipher_text)
# [296543, 169726, 215626, 215626, 293167, 147571, 122732, 293167, 217253, 215626, 102687]
decoded_text = rsa_decrypt(cipher_text, d, n)
decoded_text
# Hello world

Categories