Python: Make Pyramid With Numbers - python

I'm trying to make a pyramid with numbers without reassigning.
I was able to do this with symbols (see below):
def print_pyramid_step_3(heightNum):
ctr = 1
while(ctr <= heightNum):
row_spaces = " " * (heightNum - ctr)
row = (2*ctr-1) * "$"
print(row_spaces + row)
ctr = ctr +1
# Get the input to get the height of the pyramid
heightNum = int(input("Enter the height of the pyramid: "))
print("----"*50)
print("Printing the pyramid by adding spaces to the row")
print("----"*50)
print_pyramid_step_3(heightNum)
Output:
$
$$$
$$$$$
$$$$$$$
$$$$$$$$$
The desired output Im trying to get looks like this when a user types in a pyramid height of 5 and the starting number is 1.
Desired Output:
1
234
56789
10111213141516
171819202122232425

try this:
j = 1
for i in range(height):
for k in range(1,height + i+1):
if (k < height - i):
print(" ", end='')
else:
print(j, end='')
j+=1
print()

Related

how can i generate circles in the Pascal's triangle?

Our assignment task is on recursion to develop the Pascal Triangle and circle the generated numbers in a red font. I managed to generate the Pascal triangle after user input, however how do K proceed to make the numbers have a red font and be circled?
I used recursion to achieve the pascal triangle after user enters no. of rows, but now am stuck on how to make the numbers encircled. Below is the code I used.
rows = int(input("enter number of rows:"))
list1 = [] #empty list
for i in range(rows):
list2 = [] #sublist to print numbers
for col in range(i+1):
if col == 0 or col == i:
list2.append(1)
else:
list2.append(list1[i - 1][col - 1] + list1[i - 1][col])
list1.append(list2)
for col in range(rows-1-i):
print(format("","<2"), end='')
for col in range(i+1):
print(format(list1[i][col],"<3"), end='')
print()
```
In order to make the console text red you can use:
print("\033[31m" + string)
The details on how it works you can find here: https://stackabuse.com/how-to-print-colored-text-in-python/
I don't really understand what is the expecting "circle" output but you can play with this script:
list_of_all_elements = []
for item in list1:
list_of_all_elements.extend(item)
half_length = len(list_of_all_elements) // 2 + 1
symbol = " "
for i in range(half_length):
# Number of symbols in the start of the row.
temp = symbol * (half_length//2 - i if i <= half_length//2 else i - half_length//2)
# First row.
if i == 0:
temp += str(list_of_all_elements[i])
# Both "elifs" - last row.
elif i == half_length - 1 and len(list_of_all_elements) % 2 == 0:
temp += " " + str(list_of_all_elements[half_length-1])
elif i == half_length - 1 and len(list_of_all_elements) % 2 != 0:
temp += str(list_of_all_elements[half_length-1]) + " " + str(list_of_all_elements[half_length])
# Middle rows.
else:
number_of_middle_symbols = symbol*(2*i-1 if i <= half_length//2 else 4*half_length//2 - 2*i - 1)
temp += str(list_of_all_elements[i]) + number_of_middle_symbols + str(list_of_all_elements[-i])
# Printing the current row in red.
print("\033[31m" + temp)
Here list1 is the list generated by your code. I would say it provides the output which looks more like a rombus than a circle, but this script could be a place to start with.

I no longer have an alignment issue, however, when I print out my X's and O's there will be a 0 next to them. Does anyone know a different solution?

This is what I have so far, if you have any ideas please let me know. It would mean a lot to me.
a_list = list(range(1, squared_input + 1))
turn = 0
Symbol_1 = "X"
Symbol_2 = "O"
while turn <= 9:
X = 1
while X < squared_input + 1 :
print(str(a_list[X - 1]).zfill(2), end= "")
if X%board_size == 0 :
print("")
print(("--+" * (board_size - 1)), end="")
print("--")
else:
print("|", end="")
X = X + 1
turn = turn + 1
Symbol_1, Symbol_2 = Symbol_2, Symbol_1
print("You are user " + Symbol_1 + ".")
user_input = input("Please pick a slot on the game board (using numbers 1 - " + str(squared_input) + "): ")
a_list[int(user_input) - 1] = Symbol_1
The zeros come from your call to zfill which explicitly pads a string with 0 to a requested size. You call zfill(2) with a string that contains a single character. So the function pads that to length two by adding a 0.
To pad with blanks you can for example use the format() function or just something like
'%2d' % a_list[X-1]
which will pad each number to length 2 from the left with blanks, or
'%-2d' % a_list[X-1]
which will pad each number to length 2 from the right with blanks.

CS50 Mario More Sentimental Python - Not Printing Rows

I am attempting to write the CS50 Mario More Sentimental (Python) and I am running across some issues. The code is not performing correctly and is generating some issues as listed below:
Results for cs50/problems/2020/x/sentimental/mario/more generated by check50 v3.1.2
:) mario.py exists.
:) rejects a height of -1
:) rejects a height of 0
:( handles a height of 1 correctly
expected ""# #"", not ""
:( handles a height of 2 correctly
expected "" # #"\n"## ...", not ""
:( handles a height of 8 correctly
expected "" # #"\...", not ""
:( rejects a height of 9, and then accepts a height of 2
expected program to reject input, but it did not
:) rejects a non-numeric height of "foo"
:) rejects a non-numeric height of ""
To see the results in your browser go to https://submit.cs50.io/check50/74938be07d19fd3664e32b052c21717012088526
I am not understanding why it will not display the blocks now...
# make sure there is valid input
while True:
try:
# ask for input
height = int(input("Height: "))
# make sure height is greater than 0 and less than or equal to 8
if height >= 1 and height <= 8:
break
# iterate through height
for counter in range(height):
print(" " * (height - 1 - counter), end="")
print("#" * (counter + 1), end="")
print(" " * 2, end="")
print("#" * (counter + 1), end="")
print(end="\n")
# display error message is value entered is below or above 1 and 8
except ValueError:
print("Please enter a number between 1 and 8. ", end="\n")
Not sure why we need while loop at all. Try taking height input from user without while loop and check if h>=1 & h<=8, if yes: run your for loop else: print error message & exit()
height = int(input("Height: "))
if height >= 1 and height <= 8:
for counter in range(height):
print(" " * (height - 1 - counter), end="")
print("#" * (counter + 1), end="")
print(" " * 2, end="")
print("#" * (counter + 1), end="")
print(end="\n")
else:
print("Please enter height between 1 and 8")
exit()

Create multiplication table?

Am a beginner in Programming and am practicing how to use nested for loops to make a multiplication table in python 2.7.5.
Here is my code
x=range(1,11)
y=range(1,11)
for i in x:
for j in y:
print i*j
pass
well,the result is correct but it does not appear in a square matrix form as i wish.Please help me improve the code
You should print without a line break.
x = range(1,11)
y = range(1,11)
for i in x:
for j in y:
print i*j, # will not break the line
print # will break the line
you may add formatting to keep constant cell width
x = range(1,11)
y = range(1,11)
for i in x:
for j in y:
# substitute value for brackets
# force 4 characters, n stands for number
print '{:4n}'.format(i*j), # comma prevents line break
print # print empty line
Python's print statement adds new line character by default to the numbers you wish to have in your output. I guess you would like to have just a trailing spaces for inner loop and a new line character at the end of the outer loop.
You can achieve this by using
print i * j, # note the comma at the end (!)
and adding just a new line at the end of outer loop block:
print ''
To learn more about the trailing coma, and why it works, look here: "How to print in Python without newline or space?". Mind that it works differently in Python 3.
The final code should look like:
x=range(1,11)
y=range(1,11)
for i in x:
for j in y:
print i*j,
print ''
You can also look for '\t' special character which would allow you to get better formatting (even this old resource is good enough: https://docs.python.org/2.0/ref/strings.html)
USE This Code. It works MUCH better. I had to do this for school, and I can tell you that after putting about 4 hours into this it works flawlessly.
def returnValue(int1, int2):
return int1*int2
startingPoint = input("Hello! Please enter an integer: ")
endingPoint = input("Hello! Please enter a second integer: ")
int1 = int(startingPoint)
int2 = int(endingPoint)
spacing = "\t"
print("\n\n\n")
if int1 == int2:
print("Your integers cannot be the same number. Try again. ")
if int1 > int2:
print("The second number you entered has to be greater than the first. Try again. ")
for column in range(int1, int2+1, 1): #list through the rows(top to bottom)
if column == int1:
for y in range(int1-1,int2+1):
if y == int1-1:
print("", end=" \t")
else:
individualSpacing = len(str(returnValue(column, y)))
print(y, " ", end=" \t")
print()
print(column, end=spacing)
for row in range(int1, int2+1, 1): #list through each row's value. (Go through the columns)
#print("second range val: {:}".format(row))
individualMultiple = returnValue(row, column)
print(individualMultiple, " ", end = "\t")
print("")
Have a good day.
#Generate multiplication table by html
import random
from copy import deepcopy
N = 15
colors = ['F','E','D','C','B','A']
i = 0
colorsall = []
while i < N:
colornow = deepcopy(colors)
random.shuffle(colornow)
colornow = "#"+"".join(colornow)
colorsall.append(colornow)
i += 1
t = ""
for i in range(1,N+1):
s = ''
for j in range(1,N+1):
if j >= i:
s += '<td style="background-color:' + colorsall[i-1] + '">'+str(i*j)+'</td>'
else:
s += '<td style="background-color:' + colorsall[j-1] + '">'+str(i*j)+'</td>'
s = "<tr>" + s + "</tr>"
t = t + s + '\n'
print('<table>' + t + '</table>')
Taken from https://todaymylearn.blogspot.com/2022/02/multiplication-table-in-html-with-python.html [Disclosure : my blog]

Draw inverted triangle of asterisk by using nested loops in Python

I've to write a program that get a series of valid inputs from user and then uses the nested loops to draw the inverted triangle.
I've managed to work out the triangle but I struggling on inverted triangle. Can anyone give me some hint on how to draw the inverted triangle by only print a single charater of * and without using * * rowlength?
Global constant
L = 10
Get rows number
rows = int(input ( 'Enter a number of rows: ' ) )
Rows cannot less than 10 or greater than 100
while rows < 10 or rows > 100:
if rows < L:
print( 'The number is too Low.' )
else:
print( 'The number is too high.' )
rows = int(input ( 'Enter the correct value: ' ) )
Display the triangle
for r in range(rows):
for c in range(r + 1):
print('*', end='')
print()
This is very similar to a question I had to do for class once, but we were implementing it in C. Actually, quite cool to go back now, reimplement it in python and look at the difference.
The problem we had in class was very similar. My python code to make this work is:
while True:
rows = input('Enter the number of rows: ')
if 3 <= rows <= 33:
break
else:
continue
padding = ' '*rows
while rows > 0:
print(padding[rows:] + '*'*rows)
rows = rows - 1
-- modified below, to print outline of inverted triangle:
# print the outline of an inverted triangle:
height = rows
# inner padding for min height (3)
inner_buffer = [0, 1, 3]
while len(inner_buffer) <= rows:
inner_buffer.append(inner_buffer[-1]+2)
while height > 0:
outer_padding = ' '*(rows - height)
if height == 1:
print(outer_padding + '*')
else:
inner_padding = ' '*(inner_buffer.pop()-2)
print(outer_padding + '*' + inner_padding + '*')
height = height - 1
There has got to be a more elegant want to code this, but simply a working hack to see if we are on the right track.
New revision below:
-- function that will produce a regular triangle, or inverted triangle as defined
def get_rows():
while True:
rows = input('Enter the number of rows: ')
if 3 <= rows <= 33:
return rows
def triangle(rows, regular=False, invert=True):
if invert:
height = -1 * rows
else:
height = 0
# inner padding for min height (3)
inner_buffer = [0, 1, 3]
while len(inner_buffer) <= rows:
inner_buffer.append(inner_buffer[-1]+2)
level = 0
while level <= rows:
outer_padding = ' '*(rows - abs(height))
if height == 0:
print(outer_padding + '*')
else:
inner_padding = ' '*( inner_buffer[ abs(height) ] )
print(outer_padding + '*' + inner_padding + '*')
height += 1
level += 1
Let me know :)

Categories

Resources