I am trying to remove the multiplicative properties that are in my loops as it complicates things up and makes the code more of a hassle on my end. Can anybody help me out and try to remove the multiplicative properties but still retain the same output
space = '\t'
star = '*'
while 1:
size = int(input("Enter the height of the pattern (must be greater than 0): "))
if size > 0:
break
print("Invalid Entry!")
i = 0
while i < size:
star_count = 2 * i - 1
line = space * (size - i - 1)
if i == 0 :
line += "1"
else :
line += str(2 * i) + space
line += (star + space) * star_count
if i > 0 :
line += str(2 * i + 1)
i += 1
print(line)
Output should be this if user input is 5
1
2 * 3
4 * * * 5
6 * * * * * 7
8 * * * * * * * 9
Perhaps something like this for the last section?
n = 5 # This is the user input
lead_tabs = n - 1
for i in range(n):
text = '1' if i == 0 else str(2 * i) + '\t*' * (2 * i - 1) + '\t' + str(2 * i + 1)
print('\t' * lead_tabs + text)
lead_tabs -= 1
1
2 * 3
4 * * * 5
6 * * * * * 7
8 * * * * * * * 9
Related
I have a program that "rolls" 2 dice 100 times and adds the values of each roll to a list. I then count the number of times 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, and 12 appear in that list, and that is how many times the combination appeared in the rolls. Right now, I am displaying my data by concatenating a string with the number, the number of times it appears, and then a newline for the next number.(see the image)
https://i.stack.imgur.com/qxUGr.png
However, I wish to display my "graph" vertically, like the second image attached: https://i.stack.imgur.com/5KvzU.png
I've tried multiple things such as putting everything including the stars in one mega list and then zipping them, however that was unsuccessful. I also tried to write a loop that prints stars in rows however I can't seem to make sense of it.
def q6():
c = 0
c1 = 0
results = []
for x in range(100):
c = random.randint(1, 6)
c1 = random.randint(1, 6)
sum = c + c1
results.append(sum)
num2 = results.count(2)
num3 = results.count(3)
num4 = results.count(4)
num5 = results.count(5)
num6 = results.count(6)
num7 = results.count(7)
num8 = results.count(8)
num9 = results.count(9)
num10 = results.count(10)
num11 = results.count(11)
num12 = results.count(12)
display = "2: " + (num2 * "*") + "\n" + "3: " + (num3 * "*") + "\n"+ "4: " + (num4 * "*") + "\n"+ "5: " + (num5 * "*") + "\n"+ "6: " + (num6 * "*") + "\n"+ "7: " + (num7 * "*") + "\n"+ "8: " + (num8 * "*") + "\n"+ "9: " + (num9 * "*") + "\n"+ "10: " + (num10 * "*") + "\n"+ "11: " + (num11 * "*") + "\n"+ "12: " + (num12 * "*")
return display
#below is a loop I tried to do by printing the stars in a row and printing a space if the value was 0. the variable called "big" is the largest number in the list of values, variable "layers" was the layer the loop was printing at the time. "string" is of course the display.
"""while layers < big:
for x in counts[x]:
y = 0
if x > 0:
string += " * "
counts[y] = counts[y] - 1
if x == 0:
string += " "
y += 1
string += "\n"
layers += 1
return string"""
This is my code so far.
Try the following:
import random
def q6():
d = {k: 0 for k in range(2, 13)}
for _ in range(100):
d[random.randint(1, 6) + random.randint(1, 6)] += 1 # random draw
output = ' '.join(f'{k:2}' for k in d) # header
while any(d.values()): # while there are any remaining stars to be drawn
line = '' # begin with an empty string
line = ' '.join(' *' if v else ' ' for v in d.values())
for k in d: # loop over d to reduce the number of remaining stars
if d[k] > 0:
d[k] -= 1
output += '\n' + line # append the line to the output
return output
print(q6())
As you can note, the idea is to reduce the number of stars by 1 at each step, until the numbers are depleted.
Note that the number of stars, i.e., the dict d, will not be kept intact. In case you want to keep that, use something like d_copy = d.copy() before the while loop.
Also this approach uses the fact that dict preserves the order of the items (based on insertion) since python 3.7.
Output:
2 3 4 5 6 7 8 9 10 11 12
* * * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * *
* * * * * * * *
* * * * * * *
* * * * * * *
* * * * * *
* * * * * *
* * * * *
* * * *
* *
* *
*
*
*
*
*
*
*
*
*
*
*
As per OP's request,
line = ' '.join(' *' if v else ' ' for v in d.values())
uses conditional expression. For example, output = 'a' if x else 'b' sets output as 'a' if x is True, and 'b' if x is False.
In this case, python sees v. If v is non-zero, it is "truthy", so ' *' if v else ' ' for v equals to ' *'. If v is zero, then v is "falsy", so it equals to ' '. In other words, the line is equivalent to
temp = []
for v in d.values():
if v != 0:
temp.append(' *')
else:
temp.append(' ')
line = ' '.join(temp)
To make it vertical you need to check each number separately, make a for loop that counts from 1 to 100 (which are the minimum and the maximum prospects) to check in each number if that number reaches this value and a nested for loop to check each num if it reaches it....something like:
list = [num2, num3, num4, num5, num6, num7, num8, num9, num10, num11, num12]
for i in range(1,100):
line = []
for x in list:
if x >= i:
line.append("*")
else:
line.append(" ")
for element in line:
print(element, end="")
Python newbie here.
I Got an exercise to write a function that receives 2 parameters, the first is a single note string, and the other is the max length(int) of the middle row. (i.e arrow(my_char, max_length)
Basically the function is supposed to return an "arrow formation".
I'm supposed to use a for loop for this.
for ex. the print for print(arrow("*", 5)) is supposed to be:
*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*
What I've done so far:
for i in range(1, max_length + 1):
print (my_char * i)
for i in range(max_length, 1, -1):
print (my_char * i)
I got the formation right, but the formation is not returned and I need to add spaces between the asterisks.
Following your question description and what you did, it appears that to works properly the argument of print() in your second for loop must be my_char*(i-1) instead of my_char*i. Then you can add spaces between asterisks, and tie all into a function taking 2 parameters as follows:
def arrow(my_char, max_length):
for i in range(1, max_length + 1):
print(" ".join(my_char * i))
for i in range(max_length, 1, -1):
print(" ".join(my_char * (i-1)))
Example: If you take my_char = "*" and max_length = 5, the function arrow(my_char, max_length) will output:
*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*
One of many answers would be like this:
def arrow(char, length):
for i in range(length):
for j in range(i):
print(char + ' ', end='')
print ()
for i in range(length,0,-1):
for j in range(i,0,-1):
print(char + ' ', end='')
print ()
I am trying to draw the following pattern in Python:
# #
## ##
### ###
########
I can get the two right triangles separately but cannot figure out how to make them into one. Would anone be able to help me?
My code for the left triangle is:
rows = 4
for i in range(0, rows):
for j in range(0, i+1):
print('#', end='')
print()
My code for the right triangle is:
for i in range(0,rows):
for j in range(0, rows-i):
print(' ',end='')
for k in range(0, i+1):
print('#',end='')
print()
I'm trying to combine them somehow but haven't been successful.
Here's one way to go about it. '#' * x prints a increasing number of '#'s and space [(2*x):] slices the eight spaces in the string space.
space = ' '
for x in range (1, 5) :
print ('#' * x + space [(2*x):] + '#' * x)
And here is a version without slicing.
y = 6
for x in range (1, 5) :
print ('#' * x, end = '')
if y > 0 : print (' ' * y, end = '')
print ('#' * x)
y = y - 2
This is a pattern program
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * *
* * * * *
* * * *
* * *
* *
*
the code for this program will be:
for i in range(0,7):
for j in range(0,i+1):
print("*",end=" ")
print("\r")
for m in range(5,-1,-1):
for n in range(0,m+1):
print("*",end=" ")
print("\r")
try using string formatting with spacers like so:
>>>print("{:<4}{:>4}".format('#','#'))
# #
>>>print("{:x^7}".format('#'))
xxx#xxx
#f-strings
x = '#'
>>>print(f'{x:>5}')
#
The formatting spacers add padding, to the left right, or both sides of a string
I ended up doing:
col=8
x=2
y=col-1
for i in range(1, col//2+1):
for j in range(1, col+1):
if(j>=x and j<=y):
print(' ', end='')
else:
print('#', end='')
x=x+1
y=y-1
print()
Here assuming no.of lines l = 4
The min space starts with s = 2.
No.of hashes to print based on lines end = l * 2.
l = 4
space = 2
end = l * 2
for i in range(1, l + 1):
print('#'*i, end='')
print(' '*(end - space), end='')
print('#'*i)
space = space + 2
I want to make a function to print triangle like the following picture. User can insert the row number of the triangle. The total lenght of first row is must an odd.
I try to use below code :
def triangle(n):
k = 2*n - 2
for i in range(0, n):
for j in range(0, k):
print(end=" ")
k = k - 1
for j in range(0, i+1):
print("* ", end="")
print("\r")
n = 5
triangle(n)
Here is the expected output image :
and here is my actual output image :
but I can't remove the star middle star. And it's not Upside - Down Triangle
You could try a different way.
def triangle(n) :
for i in range(1,n+1) :
for j in range(1,i) :
print (" ",end="")
for j in range(1,(n * 2 - (2 * i - 1))
+1) :
if (i == 1 or j == 1 or
j == (n * 2 - (2 * i - 1))) :
print ("*", end="")
else :
print(" ", end="")
print ("")
n = 5
triangle(n)
Not sure how cool implementation is this but it gives results:
def triangle(n):
print(' '.join(['*']*(n+2)))
s = int((n/2)+1)
for i in range(s):
star_list = [' ']*(n+2)
star_list[-i-2] = ' *'
star_list[i+1] = '*'
print(''.join(star_list))
n = 5
triangle(n)
Output:
* * * * * * *
* *
* *
*
for n = 7:
* * * * * * * * *
* *
* *
* *
*
I would try a recursive solution where you call the printTriangle() function. This way, it will print the point first and move it's way down the call stack.
I want to write a program that prints this output:
*
* *
* *
* *
*
But it prints this instead:
*
* *
* * *
* * * *
* * * * *
Suppose n = 5 is the input from the user, then the first star should be in the centre, and the ending star as well, so I can divide the input number by 2 to get the position of the first and the last star.
For the rest of the stars I am not understanding how to make it so that if one star is above then the next star should not be below it.
def Empty_triangle(n):
k = 2*n - 2
for i in range(0, n):
for j in range(0, k):
print(end=" ")
k = k - 1
for j in range(0, i+1):
# printing stars
print("* ", end="")
# ending line after each row
print("\r")
# Driver Code
n = 5
Empty_triangle(n)
How about this sort of thing?
print("\n".join([" "*(n-2-i)+"*"+" "*(2*i-1)+("*"if i>0 else"") for i in list(range(n-1))+[0]]))
Which, for example, for n=5, gives this output:
*
* *
* *
* *
*
Is this the kind of thing you had in mind?
Here's a less code-golfish version
def Empty_triangle(n):
for i in list(range(n-1))+[0]: #i.e. [0,1,2,3,4,0] so the last line is the same as the first
line = ""
leadingSpaces = n-2-i
line += " "*leadingSpaces
line += "*"
if i != 0:
middleSpaces = 2*i-1
line += " "*middleSpaces
line += "*"
print(line)
# Driver Code
n = 5
Empty_triangle(n)