Python STAR & HASH ODD DIAMOND print with recursion - python

I want to make a pattern as shown below:
I write this program which is given below. But I couldn't take ODD numbers. Could anybody please explain what the mistake is and what the solution is? Thanks.
*
def printPartten(n, k):
if (n < 0): # Base condition
return;
# Recursive call
printPartten(n - 1, k + 1);
for i in range(0, k): # it makes spaces
print(" ", end="");
for i in range(0, n): # for print *
print("* ", end = "");
print("\n", end=""); # for next line
def printPatternReverse(n, k):
if (n < 0): # Base condition
return;
for i in range(0, k): # it makes spaces
print(" ", end = "")
for i in range(0, n): # for print *
print("#", end = " ")
print("\n", end = "") # for next line
# Recursive calls
printPatternReverse(n - 1, k + 1);
# Call to printPartten function
n = int(input("Please enter the desire value for N: "))
printPartten(n, 0);
print("\n",end="")
printPatternReverse(n,0)
print("Thank You!!!")
*
My Output like this:

You example shows that it skips the even rows, so you could add a check for even rows using a modulus:
if (k % 2 == 0):
Applied to your code:
def printPartten(n, k):
if (n < 0): # Base condition
return;
# Recursive call
printPartten(n - 1, k + 1);
if (k % 2 == 0):
for i in range(0, k): # it makes spaces
print(" ", end="");
for i in range(0, n): # for print *
print("* ", end = "");
if (k > 0):
print("\n", end=""); # for next line
def printPatternReverse(n, k):
if (n < 0): # Base condition
return;
if (k % 2 == 0):
for i in range(0, k): # it makes spaces
print(" ", end = "")
for i in range(0, n): # for print *
print("#", end = " ")
print("\n", end=""); # for next line
# Recursive calls
printPatternReverse(n - 1, k + 1);
# Call to printPartten function
n = int(input("Please enter the desire value for N: "))
printPartten(n, 0);
print("\n",end="")
printPatternReverse(n,0)
print("Thank You!!!")
Output:
Please enter the desire value for N: 9
*
* * *
* * * * *
* * * * * * *
* * * * * * * * *
# # # # # # # # #
# # # # # # #
# # # # #
# # #
#
Thank You!!!

Related

How can I make a triangle of hashes upside-down in python

I have to do a hash triangle using this function:
def line(num=int, word=str):
if word == "":
print("*" * num)
else:
print(word[0] * num)
Here is the code i have:
def line(num=int, word=str):
if word == "":
print("*" * num)
else:
print(word[0] * num)
def triangle(size):
# You should call function line here with proper parameters
while size > 0:
line(size, "#")
size -= 1
the output is this:
######
#####
####
###
##
#
but it should be this:
#
##
###
####
#####
######
how can i modify it so it prints that?
You are starting from size and going to 1 you should do the opposite:
i = 0
while i <= size:
i += 1
...
Also for i in range(1, size + 1) would be more pythonic ;)
Slightly adjusted your code
def line(num=int, word=str):
if word == "":
print("*" * num)
else:
print(word[0] * num)
def triangle(size):
# You should call function line here with proper parameters
charPerLine = 1
while charPerLine <= size:
line(charPerLine, "#")
charPerLine += 1
triangle(5)

my decoration sometimes appears just outside the triangle

It seems that my decoration sometimes appears just outside the triangle... How can I fix this?
import random
n = int(input('enter n: '))
x = 1
for i in range(n):
if i == 0:
count = 0
else:
count = random.randint(0, x)
print(' ' * (n - i), '*' * count, end = '')
if i == 0:
print('&', end = '')
else:
print('o', end = '')
print('*' * (x - count - 1))
x += 2
What do I get for value n = 10:
&
***o
*o***
o******
******o**
*********o*
*************o
*****o*********
*************o***
******************o
The random number you generate may return x as randint includes the second value in the set of possible values. So pass x - 1 to randint:
count = random.randint(0, x - 1)
It is also a pity that you have a check for i == 0 in your loop. In that case, why not deal with that first case outside of the loop, and start the loop at 1? It will make your code a bit more elegant.
def tree(n):
from random import sample
body = ["&"] + ["".join(sample("o" + "*" * (k:=x*2+1), k=k)) for x in range(1, n)]
spaces = [" " * (x-2) for x in range(n, 1, -1)]
return "\n".join("".join(tpl) for tpl in zip(spaces, body))
print(tree(10))
Output:
&
o**
****o
o******
*******o*
********o**
*******o*****
**************o
o****************
I love christmas tress! This is my take on the question :-)
import random
n = int(input('Enter tree height: '))
print(" " * (n-1) + "&")
for i in range(2, n+1):
decoration = random.randint(1, (i-1)*2 -1)
print(" " * (n - i) + "*" * decoration + "o" + "*" * ((i-1)*2 - decoration))
Enter tree height: 12
&
*o*
**o**
*o*****
*o*******
********o**
*******o*****
***********o***
********o********
****************o**
***o*****************
*********o*************

How do I make the code shorter and more efficent?

import time
start_time = time.time()
a = [2]
inp = 2
while inp < 60000:
div = 2
inp += 1
while div <= (inp / 2 + 1):
prime = inp / div
if prime.is_integer() == True:
break
else:
if div >= (inp / 2):
a.append(str(inp))
break
else:
div += 1
print(a)
print(len(a))
print("Process finished --- %s seconds ---" % (time.time()-start_time))
I wrote my first own program to calculate every prime number between 0 and 60000. I am searching for tips how to format it better or improve it.
import math
n = 60000
primes = []
for k in range(2,n):
if k % 2 == 0 and k > 2:
pass
elif all(k % i for i in range(3, int(math.sqrt(k)) + 1, 2)):
print(k)
EDIT
Since even number are not prime except 2, i have modified the anwer again
import math
primes2 = [2]
for k in range(3,n,2):
if all(k % i for i in range(3, int(math.sqrt(k)) + 1, 2)):
primes2.append(k)
Or Liner (It will helps in perforamce as well)
from math import sqrt # Most efficient way to use external libraries
primes = [k for k in range(3,n+1,2) if all(k % i for i in range(3, int(sqrt(k)) + 1, 2))]
primes.insert(0, 2)
# To print
print(*[k for k in range(3,n+1,2) if all(k % i for i in range(3, int(sqrt(k)) + 1, 2))],sep='\n')
this is how i would have done it
def isPrime(n) :
if (n <= 1) :
return False
if (n <= 3) :
return True
if (n % 2 == 0 or n % 3 == 0) :
return False
i = 5
while(i * i <= n) :
if (n % i == 0 or n % (i + 2) == 0) :
return False
i = i + 6
return True
def printPrime(n):
for i in range(2, n + 1):
if isPrime(i):
print (i, end =" ")
n = 60000 <--- you can change n by any value you want
printPrime(n)

how to print text in stars box with loop

How to print text in stars box with loop
Example I want:
input1: input text
input2: high of stars
ex:
input1 = Your Name
input2 = 3
output:
***********
*Your Name*
***********
this my code i have now
def function(text):
"""start"""
name = len(text)
num = int(input())
for i in range(num):
for j in range(name + 2):
if i == 0 or j == 0 or i == num - 1:
print("*", end="")
print()
function(input())
output is
***********
*
***********
What should I do next.
You can multiply a string. "*" * 10 == '**********' - you don't need the inner for loop then.
Also, you need to print the thing as it should be, not make a border first - you can't just type onto what's already printed.
def function(text):
"""start"""
name_length = len(text) #renamed your variable, the name was confusing
num = int(input())
for i in range(num):
if i == 0 or i == num - 1: #removed inner loop
print("*" * (name_length+2))
else:
print("*{}*".format(text) #added printing the text and right border
function(input())
You didn't say what should happen for a higher number. I assumed the name should be repeated.
def function(text):
"""start"""
name = len(text)
num = int(input())
text_num = int((num - 1) / 2)
for i in range(num):
for j in range(name + 2):
if i == 0 or i == num - 1:
print("*", end="")
elif i == text_num:
if j == 0 or j == name + 1:
print("*", end="")
else:
print(text[j-1], end="")
print()
function(input())
Another option is to format by line as opposed to character.
Something like this could work:
def function(text):
"""start"""
name = len(text)
num = int(input())
for i in range(num):
if i == 0 or i == num - 1:
print('*' * (name + 2))
elif i == int(num / 2):
print('*' + text + '*')
else:
print('*' + ' ' * name + '*')
function(input())
With num = 3 outputs:
***********
*your name*
***********
With num = 5 outputs:
***********
* *
*your name*
* *
***********
You can build the box in a list and then substitute the name at the middle line:
name = "your name"
num = 3
box = ["*"+(" "*len(name))+"*"]*num
box[0] = box[-1] = "*" * (len(name)+2)
box[num//2] = f"*{name}*"
print("\n".join(box))
***********
*your name*
***********

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....")

Categories

Resources