Alright, so I've been staring at my screen for the past few hours trying to solve this problem. I have to create a diagonal line that which could have any character.
Needs to look like something like this:
*
*
*
This is my code that I have right now.
# Draw a Diagonal
row = 1
while row <= size:
# Output a single row
col = 1
while col <= row:
# Output the drawing character
print()
# The next column number
col = col + 1
# Output a newline to end the row
print(end=drawingChar)
# The next row number
row = row + 1
print()
and it doesn't come out close to anything like a diagonal line! Could use some insight, thank you for the help. I have to use nested loops. I saw a couple other questions like this on the search, but they don't work for my assignment.
you can do this with a simple for loop:
>>> for i in range(5):
print(' '*i, end = '*\n')
*
*
*
*
*
Related
Here's the picture of the program/ how it should work, it should display 1*1 then 12$3 < 3 is the sum of 1+2.. we only got to for loop.
I have tried a lot of solutions and this is what i got to at the end, for some reason i can't copy and paste it here without the code deleting whatever i had here..
also the output currently is:
please help and thanks a lot
I would implement this idea this way:
def func(n: int):
for i in range(1, n + 1):
nsum = 0 # Sum of numbers in nested loop.
last = 0 # Last number added to 'nsum'.
string = '' # Final string which is then printed.
for j in range(1, i + 1):
nsum += j # Add to total sum.
string += str(j) # Add to final string.
last = j # Set last number to current.
# Decide if either asterisk (*) or dollar ($) should be included
# in final message, after it append total sum.
string += ('*' if last % 2 else '$') + str(nsum)
print(string)
func(6)
I've started learning programming and I need to create program, where user can enter amount of rows wanted and then program has to print two different shapes according to the info given by user. Shapes have to be like
Blockquote
# # # # # *
# # * *
# # AND * * *
# # * * * *
# # # # # * * * * *
I managed to do the triangle, but I can't figure out, how to create square that is empty inside. I have only done it filled inside.
Can anyone help me to modify my code?
userInput = input("Enter amount of row's wanted: ")
def shape(userInput, drawCharacter):
n = 0
while n < int(userInput):
n += 1
if drawCharacter == "*":
print(n*drawCharacter.rjust(3))
elif drawCharacter == "#":
print(int(userInput)*drawCharacter.rjust(3))
shape(userInput, "*")
print("|__________________|\n")
shape(userInput, "#")
A method using numpy array to avoid loops when generating the matrix:
import numpy
n = 5 # or userinput, has to be >= 2
mat = np.full((n,n), '#') # a matrix of #s
mat[1:-1, 1:-1] = np.full((n-2, n-2), ' ') # make the center of the matrix ' '
print('\n'.join([' '.join(e) for e in mat]))
result:
# # # # #
# #
# #
# #
# # # # #
Your box consists of basically following parts:
Top and bottom rows: print (width * '#')
And center rows: print ('#{}#'.format(' ' * (width - 2)))
And as an exercise you just need to figure out the loop.. ;)
If this is your first encounter with programming(any language), what I would recommend you to do is to try to implement this problem with nested for loops (which will simulate a 2d-array, or basically a matrix), try to figure out what index-es of the matrix not to print out and print out only the edges.
By doing this approach you will get a much better in-depth understanding of the problem that this task presents and how to solve it. Good luck!
I am working on a basic shapes program in Python and can't seem to work out my code. I need to keep it simple using while loops and the variables given, nested loops are usable.
Here is my code for a square:
def drawSquare(size, drawingChar):
print('Square: ')
row = 1
while row <= size:
# Output a single row
drawRow(size, drawingChar)
# Output a newline to end the row
print()
# The next row number
row = row + 1
print()
It is supposed to print like:
x
x
x
x
based on a size and character entered by the user.
drawRow is another function similar to drawSquare:
def drawRow(size, drawingChar):
col = 1
while col <= size:
print(drawingChar, end=' ')
col = col + 1
It would make more sense with a for loop:
def drawSquare(size, drawingChar):
for i in range(size):
print(" "*i + drawingChar)
Example:
drawSquare(4, "p")
Output:
p
p
p
p
Please show your work for drawDiagonal (or anything) when asking a question.
Diagonal is probably the easier case here:
def drawDiagonal(size, drawingChar):
for y in range(size):
s = ' '* y + drawingChar
print(s)
drawDiagonal(4,"X")
X
X
X
X
(Maybe pick a fixed font)
The solution I came up with is:
def drawDiagonal(size, drawingChar):
print('Diagonal: ')
row = 1
while row <= size:
# Output a single row
drawRow(row - 1, ' ')
print(drawingChar)
# Output a newline to end the row
print()
# The next row number
row = row + 1
print()
Note: drawRow is defined separately (above, in question)
& drawDiagonal was called separately as well:
drawDiagonal(userSize, userChar)
where
userSize = input('Size: ')
userChar = input('Character: ')
I have a coding assignment to input row and column length, and create a power table. THe example below is for 5 rows, 5 columns.
The code I have so far prints the correct number of rows and columns, but I haven't been able to get the calculations to work. It just shows a table of 1's, five by five.
rows = int(input("Enter a number of rows: "))
cols = int(input("Enter a number of columns: "))
x = 1
y = 1
z = 1
line = ""
while x <= cols :
line = line + format(y**cols, "4d")
x = x + 1
while z <= rows :
print(line)
z = z + 1
The basic problem is that you need to nest your loops. Your second problem is that you never change y. What you do at the moment is to compute the power sequence for 1 into five different lines -- and then you print that last line only five times. Try two changes:
Compute a line, then print it immediately. Then you go to the next line.
Use the correct variable.
After changes:
while z <= rows:
while x <= cols:
line = line + format(x**cols, "4d") # Note the variable change
x = x + 1
print(line)
z = z + 1
Also, look up the for statement, as this will simplify things. After that, look up list comprehension for even more compression.
Here is a way to do it that preserves padding no matter what:
def grid(rows, cols, padding):
max_num_len = len(str(rows**cols))
return '\n'.join([
''.join(['{{:>{}}}'.format(max_num_len+padding).format((row+1)**(col+1))
for col in range(cols)])
for row in range(rows)
])
print(grid(5, 5, 3))
Instead, try creating a 2D array in Python such as a 2D list.
Matrix = [[0 for x in range(5)] for y in range(5)]
for i in range(5):
for j in range(5):
Matrix[i][j]=j^i
Then, print the data you need using nested for loops.
for i in range (5):
for j in range(5):
print(Matrix[j][i])
I am trying to write code that will display a shape with an odd width. Once the shape is completed it is placed inside an outer shape. The user will be able to input the characters used for the shape and the number of rows.
I am hoping to produce a shape and, with a for loop, produce an outer shape.
***** .
*** ...
* .....
.*****.
...***...
.....*.....
this is my current code. I only know how to create a shape.
char = (input("Enter first charactrer"))
rows = int(input("enter the number of rows"))
for m in range(rows, 0, -1):
for n in range(0, rows-m):
print(end=" ")
for n in range(0,m):
print(char,end=" ")
print()
There is no need for some of the for-loops:
A useful feature in python is the way you can multiply a char by an int to get a string of that repeated char.
For example, if you do:
'c' * 10
you get:
'cccccccccc'
The reason this will be useful in your case is that you can use it to print the spaces and chars. This will be neater than for-loops as instead of printing a single chars over and over with no line breaks, you can instead print the full number of spaces as a string with one call.
To see what I mean, I wrote your original code using this:
char = input("enter the char ")
rows = int(input("enter the number of inner rows "))
for r in range(rows, 0, -1):
print(' ' * 2 * (rows-r), end='')
print((char+' ') * (2*r+1))
see how much neater it is? Also, you can notice that in the second print of each row for the chars, I used the calculation: 2*r +1. This is what you need to convert this pattern:
3. * * * *
2. * * *
1. * *
0. *
to this one (as you requested):
3. *******
2. *****
1. ***
0. *
you can see that for each row of the second one, the number of chars is 2 * the row +1. So row 3 has 7 chars, row 2 has 5 etc.
If you wanted to, as you have gotten rid of the unnecessary for-loops now, you could put both of the prints in one statement:
print(' ' * 2 * (rows-r) + (char+' ') * (2*r+1))
however, the first may be considered neater and clearer so you might want to stick with the separate statements.
Embedding the inner triangle in an outer one
First off for this, we will need to input two different chars for the inner and outer triangles. This will allow us to differentiate which is which.
I think that the best way to do this would be to keep the print statement which creates the spaces before the triangles as before, but modify how we draw the chars and their pattern.
This is what we want for an input of 4 rows:
0. .
1. ...
2. .....
3. .......
4. .*******.
5. ...*****...
6. .....***.....
7. .......*.......
notice how it would be simplest to split the printing process in half. So for the top half just print a regular triangle, but for the bottom print one regular, one flipped and another regular.
To do this, we want to loop through each of the 8 rows and check when we are half way through. If past halfway, we want the calculations for each smaller triangle to think they are at the top of the triangle, i.e. reset the row count for them so when printing row 4, we calculate as if printing on row 0. To achieve this, once past halfway, we need to modulo the row variable by half of the total rows (the total rows now being not what is entered, but double the entered amount as you can see we have a triangle with 8 rows but an inputted row value of 4). This will give the intended effect of the triangles being half size of the total triangle.
Finally, one last thing to consider is that the center/inner triangle needs to be flipped as we have done before. As our row count is now going from 0 at the top downwards rather than the other way around, we need to change the calculation for that row to be rows - r so it is flipped.
Taking all this into account, the final code may look something like:
innerChar = input("enter the inner char ")
outerChar = input("enter the outer char ")
rows = int(input("enter the number of inner rows "))
for r in range(2 * rows):
#print the white space on the left
print(' ' * 2 * (2 * rows-r), end='')
if r < rows:
#top triangle
print((outerChar+' ') * (2*r + 1))
else:
#working with the row modulo 2
r %= rows
#bottom three triangles
print((outerChar+' ') * (2*r + 1), end='')
print((innerChar+' ') * (2*(rows-r) - 1), end='')
print((outerChar+' ') * (2*r + 1))
One way to make this easier is to not worry about the spaces at first. Just generate the non-space symbols of each row, and save them into a list. Then at the end, determine the width of the biggest row, and use the str.center method to print each row with the correct amount of space.
def tri(n, chars='*.'):
ic, oc = chars
outer = range(1, 2*n, 2)
# top triangle chars
rows = []
for w in outer:
rows.append(w * oc)
# lower triangles chars
inner = reversed(outer)
for u, v in zip(outer, inner):
a, b = u * oc, v * ic
rows.append(a + b + a)
# Get maximum row size
width = len(rows[-1])
#Print all the rows
for row in rows:
print(row.center(width))
# test
tri(5)
output
.
...
.....
.......
.*******.
...*****...
.....***.....
.......*.......
The characters to use are passed to tri as a two character string, with a default of '*' for the inner char (ic) and '.' for the outer char (oc). But if you want to use other chars you can pass them, like this:
tri(4, '#o')