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.
Related
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.
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()
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]
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 :)
Right now I am attempting to code the knapsack problem in Python 3.2. I am trying to do this dynamically with a matrix. The algorithm that I am trying to use is as follows
Implements the memoryfunction method for the knapsack problem
Input: A nonnegative integer i indicating the number of the first
items being considered and a nonnegative integer j indicating the knapsack's capacity
Output: The value of an optimal feasible subset of the first i items
Note: Uses as global variables input arrays Weights[1..n], Values[1...n]
and table V[0...n, 0...W] whose entries are initialized with -1's except for
row 0 and column 0 initialized with 0's
if V[i, j] < 0
if j < Weights[i]
value <-- MFKnapsack(i - 1, j)
else
value <-- max(MFKnapsack(i -1, j),
Values[i] + MFKnapsack(i -1, j - Weights[i]))
V[i, j} <-- value
return V[i, j]
If you run the code below that I have you can see that it tries to insert the weight into the the list. Since this is using the recursion I am having a hard time spotting the problem. Also I get the error: can not add an integer with a list using the '+'. I have the matrix initialized to start with all 0's for the first row and first column everything else is initialized to -1. Any help will be much appreciated.
#Knapsack Problem
def knapsack(weight,value,capacity):
weight.insert(0,0)
value.insert(0,0)
print("Weights: ",weight)
print("Values: ",value)
capacityJ = capacity+1
## ------ initialize matrix F ---- ##
dimension = len(weight)+1
F = [[-1]*capacityJ]*dimension
#first column zeroed
for i in range(dimension):
F[i][0] = 0
#first row zeroed
F[0] = [0]*capacityJ
#-------------------------------- ##
d_index = dimension-2
print(matrixFormat(F))
return recKnap(F,weight,value,d_index,capacity)
def recKnap(matrix, weight,value,index, capacity):
print("index:",index,"capacity:",capacity)
if matrix[index][capacity] < 0:
if capacity < weight[index]:
value = recKnap(matrix,weight,value,index-1,capacity)
else:
value = max(recKnap(matrix,weight,value,index-1,capacity),
value[index] +
recKnap(matrix,weight,value,index-1,capacity-(weight[index]))
matrix[index][capacity] = value
print("matrix:",matrix)
return matrix[index][capacity]
def matrixFormat(*doubleLst):
matrix = str(list(doubleLst)[0])
length = len(matrix)-1
temp = '|'
currChar = ''
nextChar = ''
i = 0
while i < length:
if matrix[i] == ']':
temp = temp + '|\n|'
#double digit
elif matrix[i].isdigit() and matrix[i+1].isdigit():
temp = temp + (matrix[i]+matrix[i+1]).center(4)
i = i+2
continue
#negative double digit
elif matrix[i] == '-' and matrix[i+1].isdigit() and matrix[i+2].isdigit():
temp = temp + (matrix[i]+matrix[i+1]+matrix[i+2]).center(4)
i = i + 2
continue
#negative single digit
elif matrix[i] == '-' and matrix[i+1].isdigit():
temp = temp + (matrix[i]+matrix[i+1]).center(4)
i = i + 2
continue
elif matrix[i].isdigit():
temp = temp + matrix[i].center(4)
#updates next round
currChar = matrix[i]
nextChar = matrix[i+1]
i = i + 1
return temp[:-1]
def main():
print("Knapsack Program")
#num = input("Enter the weights you have for objects you would like to have:")
#weightlst = []
#valuelst = []
## for i in range(int(num)):
## value , weight = eval(input("What is the " + str(i) + " object value, weight you wish to put in the knapsack? ex. 2,3: "))
## weightlst.append(weight)
## valuelst.append(value)
weightLst = [2,1,3,2]
valueLst = [12,10,20,15]
capacity = 5
value = knapsack(weightLst,valueLst,5)
print("\n Max Matrix")
print(matrixFormat(value))
main()
F = [[-1]*capacityJ]*dimension
does not properly initialize the matrix. [-1]*capacityJ is fine, but [...]*dimension creates dimension references to the exact same list. So modifying one list modifies them all.
Try instead
F = [[-1]*capacityJ for _ in range(dimension)]
This is a common Python pitfall. See this post for more explanation.
for the purpose of cache illustration, I generally use a default dict as follows:
from collections import defaultdict
CS = defaultdict(lambda: defaultdict(int)) #if i want to make default vals as 0
###or
CACHE_1 = defaultdict(lambda: defaultdict(lambda: int(-1))) #if i want to make default vals as -1 (or something else)
This keeps me from making the 2d arrays in python on the fly...
To see an answer to z1knapsack using this approach:
http://ideone.com/fUKZmq
def zeroes(n,m):
v=[['-' for i in range(0,n)]for j in range(0,m)]
return v
value=[0,12,10,20,15]
w=[0,2,1,3,2]
v=zeroes(6,5)
def knap(i,j):
global v
if i==0 or j==0:
v[i][j]= 0
elif j<w[i] :
v[i][j]=knap(i-1,j)
else:
v[i][j]=max(knap(i-1,j),value[i]+knap(i-1,j-w[i]))
return v[i][j]
x=knap(4,5)
print (x)
for i in range (0,len(v)):
for j in range(0,len(v[0])):
print(v[i][j],end="\t\t")
print()
print()
#now these calls are for filling all the boxes in the matrix as in the above call only few v[i][j]were called and returned
knap(4,1)
knap(4,2)
knap(4,3)
knap(4,4)
for i in range (0,len(v)):
for j in range(0,len(v[0])):
print(v[i][j],end="\t\t")
print()
print()