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*************
Related
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)
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!!!
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*
***********
I have a code that is ridiculously long and I need to use it in many methods. I think there's definitely a better way to write it. But I'm struggling to find it. What the code does is that it:
Takes 12 numbers
It inputs them in a list(let us call it count)
Creates 12 stars variables
It needs to create some sort of matrix that looks like this:
******* count1
******** count2
********** maxcount (could be any count from count1 to 12, as long as it is the maximum
***** count5
etc..
So to explain that, we have 12 count variables, I needed to take the largest variable of them, so I put them in a list. After putting them in a list, I selected the max(count) in order to build my astericks representation.
The maximum number of astericks possible is 10. THerefore, the maximum amongst the 12 counts should have 10 stars next to it, and all the others will have their stars relatively.
This is my code, but it doesn't seem optimal at all to me, lots of variables created and initialized as well as it takes some time.
count = list()
count.append(count1)
count.append(count2)
count.append(count3)
count.append(count4)
count.append(count5)
count.append(count6)
count.append(count7)
count.append(count8)
count.append(count9)
count.append(count10)
count.append(count11)
count.append(count12)
stars1 = 0
stars2 = 0
stars3 = 0
stars4 = 0
stars5 = 0
stars6 = 0
stars7 = 0
stars8 = 0
stars9 = 0
stars10 = 0
stars11 = 0
stars12 = 0
stars1 = int((count1 * 10) / max(count))
stars2 = int((count2 * 10) / max(count))
stars3 = int(count3 * 10 / max(count))
stars4 = int(count4 * 10 / max(count))
stars5 = int(count5 * 10 / max(count))
stars6 = int(count6 * 10 / max(count))
stars7 = int(count7 * 10 / max(count))
stars8 = int(count8 * 10 / max(count))
stars9 = int(count9 * 10 / max(count))
stars10 = int(count10 * 10 / max(count))
stars11 = int(count11 * 10 / max(count))
stars12 = int(count12 * 10 / max(count))
astericks1 = ""
astericks2 = ""
astericks3 = ""
astericks4 = ""
astericks5 = ""
astericks6 = ""
astericks7 = ""
astericks8 = ""
astericks9 = ""
astericks10 = ""
astericks11 = ""
astericks12 = ""
for i in range(1, 11):
if (i <= stars1):
astericks1 += "*"
else:
astericks1 += " "
if (i <= stars2):
astericks2 += "*"
astericks2 += " "
if (i <= stars3):
astericks3 += "*"
else:
astericks3 += " "
if (i <= stars4):
astericks4 += "*"
else:
astericks4 += " "
if (i <= stars5):
astericks5 += "*"
else:
astericks5 += " "
if (i <= stars6):
astericks6 += "*"
else:
astericks6 += " "
if (i <= stars7):
astericks7 += "*"
else:
astericks7 += " "
if (i <= stars8):
astericks8 += "*"
else:
astericks8 += " "
if (i <= stars9):
astericks9 += "*"
else:
astericks9 += " "
if (i <= stars10):
astericks10 += "*"
else:
astericks10 += " "
if (i <= stars11):
astericks11 += "*"
else:
astericks11 += " "
if (i <= stars12):
astericks12 += "*"
else:
astericks12 += " "
First of all this kind of if,elif statements and variable creations are generally bad coding practice. Secondly, as a little advice you should always think that I can create same functionality with the list instead of two different variables for the same reason (count1,count2, etc.).
As I understand from your code you print maximum 10 stars for max value. So the code below should produce same behavior with yours using list comprehensions. Also I should mention that it can be written more efficiently but I wanted to be clear and simple for you.
variable_num = 12
count = [int(input()) for i in range(variable_num)]
max_num = max(count)
count = [(i*10)//max_num for i in count]
for ind,i in enumerate(count):
print("{} count {}".format(int(i)*"*",ind))
As simple as:
# Get 12 numbers as input
s = input("Input 12 numbers separated by a white space")
# Save them in a list and calculate the maximum
nums = [int(item) for item in s.split()]
max_num = max(nums)
for idx, item in enumerate(nums):
# Calcuate number of stars, ensuring number of stars are never more then 10
num_stars = int(item * 10 / max_num)
# print the stars
print('*' * num_stars, 'count{}'.format(idx))
Sample output will be
Input 12 numbers separated by a white space1 2 3 4 5 6 1 2 3 4 5 6
* count0
*** count1
***** count2
****** count3
******** count4
********** count5
* count6
*** count7
***** count8
****** count9
******** count10
********** count11
my answer for finding the number of combinations given drawing 3 cards out of 52 is off by a spot. Like 0 cards from 52 should = 1, 1 should = 52, 2 = 1326 and so on. but I have 0 = 1, 1 = 1, 2 = 52 and so on. What would I modify to reach the desired result? I think the error is in def factorial() but I can not seem to fix/ find the issue, no matter what I try.
def factorial(num):
i = 2
if num == 0:
num = 1
print(num)
elif num > 1:
for i in range(i, num):
num = num * i
return num
def combinations(n,r):
l = n-r
nn = factorial(n)
rn = factorial(r)
ln = factorial(l)
result = nn / (rn * ln)
print(result)
return result
def main():
h = 52
a = 0
while a<4:
combinations(h,a)
a = a + 1
You're printing extra stuff in factorial which may lead to the confusion. I suggest you print out your final result with comparison to your a variable at the end of the combinations function like so:
print("For a=" + str(r) + ", result=" + str(result))
Here is the overall edited code:
def factorial(num):
if num == 0:
num = 1
elif num > 1:
for i in range(2, num): # Setting i=2 at the start is redundant
num = num * i
return num
def combinations(n,r):
l = n-r
nn = factorial(n)
rn = factorial(r)
ln = factorial(l)
result = nn / (rn*ln)
print("For a=" + str(r) + ", result=" + str(result))
return
h = 52
a = 0
while a<4:
combinations(h,a)
a = a + 1