I'm coming from a background in Google's App Inventor. I'm taking an online class.
Task: Make a triangle out of asterisks with a nested while loop. The triangle has a base of 19 asterisks and a height of 10 asterisks.
Here's where I am.
Num = 1
while Num <= 19:
print '*'
Num = Num * '*' + 2
print Num
what you are doing with
Num = Num * '*' + 2
is the following:
you create a string (Num-times '*') this is what you want
then you try to add two, you'll probably see an error like cannot concatenate 'str' and 'int' objects, because there is no way to add a string to an int (at least in python). Instead you probably want to add two only to Num.
Here's a cool trick - in Python, you can multiply a string by a number with *, and it will become that many copies of the string concatenated together.
>>> "X "*10
'X X X X X X X X X X '
And you can concatenate two strings together with +:
>>> " "*3 + "X "*10
' X X X X X X X X X X '
So your Python code can be a simple for loop:
for i in range(10):
s = ""
# concatenate to s how many spaces to align the left side of the pyramid?
# concatenate to s how many asterisks separated by spaces?
print s
n = 0
w = 19
h = 10
rows = []
while n < h:
rows.append(' '*n+'*'*(w-2*n)+' '*n)
n += 1
print('\n'.join(reversed(rows)))
Produces
*
***
*****
*******
*********
***********
************* #etc...
*************** #2 space on both sides withd-4 *
***************** #1 space on both sides, width-2 *
******************* #0 spaces
>>> len(rows[-1])
19
>>> len(rows)
10
you can use the 'center'-method from string-objects:
width = 19
for num in range(1, width + 1, 2):
print(('*' * num).center(width))
*
***
*****
*******
*********
***********
*************
***************
*****************
*******************
Usually you wouldn't use a nested while loop for this problem, but here's one way
rows = 10
while rows:
rows -=1
cols = 20
line = ""
while cols:
cols -=1
if rows < cols < 20-rows:
line += '*'
else:
line += ' '
print line
(count - 1) * 2 + 1 calculates the number of asterisks in each row.
count = 1
while count <= 10:
print('*' * ((count - 1) * 2 + 1))
count += 1
You can go the easy way of course.
count = 1
while count <= 20:
print('*' * count)
count += 2
Related
I have to print a hollow inverted pyramid:
******
* *
* *
* *
**
*
Following is my code:
n = int(input())
for i in range(n,0,-1):
if i == n:
print(n*'*', end = '')
if i > 1 and i <n:
print('*'+(i-2)*' '+'*')
else:
print('*')
print()
For input as 6 I am not sure why my code is printing 7 stars.
If anyone could help explain what I am doing wrong or missing would be really great!
There are two problems here:
There is no need for the , end=''. You still want a newline to print after this line of stars.
You used if not elif for the second condition, so the third block of code in the else will still run even if the first condition is true.
Here is the corrected code:
n = int(input())
for i in range(n, 0, -1):
if i == n:
print(n * "*")
elif 1 < i < n:
print("*" + (i - 2) * ' ' + '*')
else:
print('*')
If the first iteration of the loop, there are two print calls executing: the first one and the last, so that makes a total of 7 stars in that first line of output.
As the first and last case are different from the other cases, it is easier to just deal with those outside of the loop:
n = int(input())
print(n*'*')
for i in range(n - 3, -1, -1):
print('*' + i*' ' + '*')
if n > 1:
print('*')
There is still one if here to ensure it still works correctly for n equal to 1 or even 0.
To do it without that if, you could do this:
n = int(input())
print(n*'*')
s = '*' + n*' '
for i in range(n - 2, -1, -1):
print(s[:i] + '*')
another type of inverted hollow matrix:
54321
4 1
3 1
2 1
1
Answers:
Hollow Right-angled triangle!!!
n=int(input())
for i in range(n,0,-1):
for k in range(n,0,-1):
if i==n or i==k or k==n-(n-1):
print(k,end=" ")
else:
print(end=" ")
print()
Trying to make a program that asks the user for a height and a character, and then outputs a hollow triangle to that height using that character. Was trying to firstly make a solid triangle, then solve it from there, but so far have only managed to make a half triangle.
Also, using only for loops and no '*' operator
H = int(input("Enter height of triangle: "))
C = str(input("Character: "))
if C == "":
C = "*"
rows = 1
count = 0
while rows <= H:
spaces = 0
while spaces <= (H - rows):
print(" ", end="")
spaces += 1
count = 0
while count < rows:
print(C, end="")
count += 1
print()
rows += 1
this results in this:
*
**
***
****
*****
my goal is this:
*
* *
* *
* *
*********
any help would be appreciated!
Slightly changed your script:
H = int(input("Enter height of triangle: "))
C = str(input("Character: "))
if C == "":
C = "*"
rows = 1
count = 0
while rows <= H:
spaces = 0
while spaces <= (H - rows):
print(" ", end="")
spaces += 1
count = 0
while count < 2*rows-1:
count += 1
if count == 1 or count == 2*rows-1 or rows == H:
print(C, end="")
else:
print(" ", end="")
print()
rows += 1
H = int(input("Enter height of triangle: "))
C = str(input("Character: "))
for i in range(H):
for j in range(H - i):
print(' ', end='')
for j in range(2 * i + 1):
if j == 0 or j == 2 * i or i == H - 1:
print(C, end='')
else:
print(' ', end='')
print()
There's already an answer, but considering that I had fun doing this little program, and that our solution are not the same :
H = int(input("Enter height of triangle: "))
C = str(input("Character: "))
if C == "":
C = "*"
rows = 0
while rows <= H:
cols = 0
if rows == H:
while cols <= H*2:
print(C, end="")
cols += 1
else:
while cols <= H*2:
if rows + cols == H or cols - rows == H:
print(C, end="")
else:
print(" ", end="")
cols += 1
print()
rows += 1
Note that I did this with for loops, and just swapped to while loops to paste it here.
The way to get a hollow triangle is to print spaces in a loop.
If you observe the output you need, you'll see that except for the top and bottom lines, every line has only 2 asterisks (*). That means you need a logic that handles spaces.
There are several ways to write the logic, such as treating each vertical halves as blocks of fixed length and just varying the position of the star or actually counting the spaces for each line. You can explore the different ways to achieve what you need at your convenience. I'll present one soln.
H = int(input("Enter height of triangle: "))
C = str(input("Character: "))
if len(C) != 1:
C = "*"
rows = 1
count = 0
while rows < H:
str = ""
for i in range(H - rows):
str += " "
str += C
if rows > 1:
for i in range(2 * rows - 3):
str += " "
str += C
print(str)
rows += 1
str = ""
for i in range(2 * H - 1):
str += C
print(str)
I have made a change about checking the character. You should not allow characters of more than length 1. Otherwise, the spacing will get messed up
These exercises are meant for you to understand the logic and get comfortable with manipulating code, so do try different variations
This is probably not the most optimized solution but, remember that printing is in general slow as it has to interact with a peripheral (monitor), so try to print in bulk whenever possible. This improves the speed
Can you help to simplify this code and make it more efficient? Mine seems like it's not the best version; what can I improve?
1
232
34543
4567654
567898765
678901109876
This is the code I made:
c = -1
for y in range(1, 7):
print()
print((6-y) * " ", end="")
c += 1
for x in range(1, y+1):
print(y%10, end="")
y += 1
while y - c > 2:
print(y-2, end="")
y -= 1
First of all, I'm guessing that you didn't really want to print that y value of 10; that you really wanted the base-10 reduction to 0. Note that you have an extra character in the pyramid base.
Do not change the value of a loop parameter while you're inside the loop. Specifically, don't change y within the for y loop.
Get rid of c; you can derive it from the other values.
For flexibility, make your upper limit a parameter: you have two constants (6 and 7) that depend on one concept (row limit).
Here's my version:
row_limit = 7
for y in range(1, row_limit):
print()
print((row_limit-y-1) * " ", end="")
for x in range(y, 2*y):
print(x%10, end="")
for x in range(2*(y-1), y-1, -1):
print(x%10, end="")
print()
Output:
1
232
34543
4567654
567898765
67890109876
If you really want to push things, you can shorten the loops with string concatenation and comprehension, but it's likely harder to read for you.
for y in range(1, row_limit):
print()
print((row_limit-y-1) * " " + ''.join([str(x%10) for x in range(y, 2*y)]) + \
''.join([str(x%10) for x in range(2*(y-1), y-1, -1)]), end="")
print()
Each of the loops is turned into a list comprehension, such as:
[str(x%10) for x in range(y, 2*y)]
Then, this list of characters is joined with no interstitial character; this forms half of the row. The second half of the row is the other loop (counting down). In front of all this, I concatenate the proper number of spaces.
Frankly, I prefer my first form.
Here's my implementation.
Python 2:
def print_triangle(n):
for row_num in xrange(1, n + 1):
numbers = [str(num % 10) for num in xrange(row_num, 2 * row_num)]
num_string = ''.join(numbers + list(reversed(numbers))[1:])
print '{}{}'.format(' ' * (n - row_num), num_string)
Python 3:
def print_triangle(n):
for row_num in range(1, n + 1):
numbers = [str(num % 10) for num in range(row_num, 2 * row_num)]
num_string = ''.join(numbers + list(reversed(numbers))[1:])
print('{}{}'.format(' ' * (n - row_num), num_string))
Input:
print_triangle(5)
print_triangle(6)
print_triangle(7)
Output:
1
232
34543
4567654
567898765
1
232
34543
4567654
567898765
67890109876
1
232
34543
4567654
567898765
67890109876
7890123210987
n = int(input())
i = 1
while i <= n:
j = 1
spaces = 1
p = i
while spaces <= n - i:
print (" ", end ="")
spaces += 1
while j <= i:
print(p, end = "")
j += 1
p += 1
p -= 2
while p >= i:
print(p, end = "")
p -= 1
print()
i += 1
so I've been trying to create a program where you prompt the user for the number of rows, and then the program prints out a diamond with input number of rows.
This is what the program is supposed to do:(image)
This is what my code looks like
def main():
ROWS = get_input()
draw_pattern(ROWS)
def get_input():
return int(input("Enter the number of rows (or -1 or -99 to quit): "))
def draw_pattern(ROWS):
if ROWS == -1 or ROWS == -99:
quit
else:
for x in range(0,(int)((ROWS/2)+1),1):
print ((int)((ROWS/2)-(2*x+1)/2)*" " + (2*x+1) * '*')
for t in range((int)(x),0,-1):
print((int)((ROWS/2)-(2*t-1)/2)*" " + (2*t-1) * '*')
main()
This is what it ends up doing:
Enter the number of rows (or -1 or -99 to quit): 7
*
***
*
*****
***
*
*******
*****
***
*
So what am I doing wrong? I assume it's something in my for loop that makes the rows not line up correctly. Can anyone give me a little help? Thanks.
I got it to work like this. (< 3 mins) (DO NOT use even numbers its going to look odd)
def main():
ROWS = get_input()
draw_pattern(ROWS)
def get_input():
return int(input("Enter the number of rows (or -1 or -99 to quit): "))
def draw_pattern(ROWS):
if ROWS == -1 or ROWS == -99:
return
else:
for x in range(1, ROWS, 2):
print(' ' * int(ROWS / 2.0 - x / 2.0) + ("*" * x))
for x in range(ROWS, 1, -2):
print(' ' * int(ROWS / 2.0 - x / 2.0) + ("*" * x))
if x != 1:
print(' ' * int(ROWS / 2.0 - 1 / 2.0) + ("*" * 1))
main()
There are many ways to do this, you can generate all the strings then print them out using formatting to center the diamond, e.g.:
>>> row = 5
>>> d = ('*' * (n if n <= row else 2*row-n) for n in range(1, 2*row, 2))
>>> for i in d:
... print('{:^{w}}'.format(i, w=row))
*
***
*****
***
*
For row = 4:
*
***
***
*
Points for obfuscation?
star = lambda rows:'\n'.join(('*'*(2*(i if i<rows//2 else rows-i-1)+1)).center(rows) for i in range(rows))
Odd
print(star(5))
*
***
*****
***
*
Even
print(star(4))
*
***
***
*
This question already has answers here:
How to print without a newline or space
(26 answers)
Closed 3 years ago.
I'm not able to remove the spacing in a for-loop as numbers are not coming in the same for making the pattern.
My code:
for i in range(1,5):
for j in range(1,i):
print(j)
Produces the following result:
1
1
2
1
2
3
But my desired output is:
1
12
123
1234
Try this:
print(j, end='')
end by default is \n (see print()). Also, be sure to print a newline at the end of each outer loop iteration:
for i in range(1,6): # notice that I changed this to 6
for j in range(1,i):
print(j, end='') # added end=''
print() # printing newline here
1
12
123
1234
EDIT I just noticed you were using Python 2.7. Since that's the case, you can use print j, instead of print(j, end='') and print instead of print(). Note that print j, will leave spaces between the js. If you don't want this, you can import sys and use sys.stdout.write(j) instead (see sys).
Furthermore, if you want to use the Python 3 print function as shown above, you can always
from __future__ import print_function
One line solution, if you're interested:
print('\n'.join([''.join(['{}'.format(i) for i in range(1,j)]) for j in range(2,6)]))
1
12
123
1234
for r in range(1,5):
for c in range (1,r+1):
print c,
print
here, the print without argument causes printing in the next line
In order to get all of the numbers on one line, you'll have to use one print statement per line you want. One way you could do this is:
for i in range(1, 5):
print(''.join([str(n) for i in range(1, i)]))
Keeping the nested for loops you could do:
for i in range(1, 5):
temp = ''
for j in range(1, i):
temp += str(j)
print(temp)
Try:
def RTN():
x = 1
num = int(input('Type any integer besides 0: '))
if num == 0:
return 'Try again!'
while x < num + 2:
print('')
for y in range(1, x):
print(str(y) + ' ', end = '')
x += 1
def pentagon(num):
j = num
for i in range(0, num + 1):
print('{}{}'.format(' ' * j, ' *' * i))
j -= 1
pentagon(2)
output
*
* *
num = int(input())
for i in range (1,num+1):
for j in range(i):
print(j+1,end = '')
print("")
I thought the idea of #Shiva was really nice and made a slightly more general pyramid function, maybe someone can use/enjoy it it:
def pyramid(n_rows, s, upside_down=False, offset=0):
whites = ' ' * len(s)
offset = ' ' * offset
indices = np.arange(n_rows)
if upside_down:
indices = zip(indices[::-1]+1, indices)
else:
indices = zip(indices+1, indices[::-1])
for i, j in indices:
print(f"{offset + whites * j}{(s + whites) * i}")
pyramid(4, 'SO')
# SO
# SO SO
# SO SO SO
# SO SO SO SO
pyramid(4, '*', upside_down=True, offset=3)
# * * * *
# * * *
# * *
# *
x=input('enter some numerical value')
s=''
for i in range(0,x):
for j in range(0,i+1):
s=s+str(j+1)
print s
s=''