Python Shape Printing - python

Hi everyone, I have an assignment to acquire this shape in Python. I am a beginner, I tried to use nested loops to create this shape but I couldn't. Could someone help? Thanks a lot. (I couldn't copy the output exactly I'm sorry)
I used nested for loops, if and else statements in various ways (for example, I've tried to write stars at the end of a row) but I couldn't get the shape. I am editing the post in order to show you my effort. I am really sorry that my output is really different from the wanted one.
len = int(input("enter an odd number: "))
if len % 2 == 0:
print("enter an odd number")
else:
row = int((len+1) / 2)
for i in range (0,len):
print("#",end="")
print()
for i in range(0,row):
print("*")
print("*", end=" ")
for j in range(1,len):
print("*",end="")
for i in range(0,len):
print("#",end="")
for n = 5
#####
* *
* *
* *
* *
* *
* *
#####

This could be one way of solving it:
if we define n as the sample input, the shape can be divided into 3 steps of length (n//2) each.
Initialization: print('#'*n)
Step 1: for i in range(n//2): print('*'+' '*(n-2)+'*')
Step 2a: create a print_list: print_list = [k*' ' + '*'+ (n-2-2*k)*' ' + '*' + k*' ' for k in range(n//2)]
Step 2b: Now print each line in print_list
Step 3: Then print each line in print_list[::-1]
End: print('#'*n)
Implemented Code:
n = int(input("enter an odd number: "))
if n % 2 == 0:
print("enter an odd number")
else:
print("#"*n)
for i in range(n//2):
print('*'+' '*(n-2)+'*')
print_list = [k * ' ' + '*' + (n - 2 - 2*k) * ' ' + '*' + k * ' 'for k in range(n//2)]
for p in print_list: print(p)
for p in print_list[::-1]: print(p)
print("#"*n)

Related

Create a 2d array that prints out a snowflake PYTHON

I am trying to create a piece of code that will accept a odd number as a input and create a snowflake using this graph of n * n
Enter Integer: 5
* . * . *
. * * * .
* * * * *
. * * * .
* . * . *
Im pretty sure Im on the the right track
n = int(input("Enter odd input: "))
while n % 2 == 0:
print("Invalid Input. Input must be odd")
n = int(input("Enter odd input: "))
snowflake = [["."] * n for i in range(n)]
middle = int((n-1) / 2)
for i in range(n):
snowflake[i][2] = "*"
snowflake[2][i] = "*"
snowflake[i][i] = "*"
diagnol = 5-i
snowflake[i][diagnol] = "*"
for i in snowflake:
for j in i:
print(j, end=' ')
print()
print()
But I keep getting this error
snowflake[i][diagnol] = "*"
IndexError: list assignment index out of range
Can someone help edit my code or give me a tip?(This is a homework assignment)
I decided not to fix your algorithm, but as a working example to provide my own algorithm:
Try it online!
n = 9
a = [['.'] * n for i in range(n)]
for i in range(n):
a[n // 2][i], a[i][n // 2], a[i][i], a[i][n - 1 - i] = ['*'] * 4
print('\n'.join([''.join(a[i]) for i in range(n)]))
Output:
*...*...*
.*..*..*.
..*.*.*..
...***...
*********
...***...
..*.*.*..
.*..*..*.
*...*...*
After debugging it I found that 5 was too big and that some of the code would only work if the input was 5
n = int(input("Enter odd input: "))
while n % 2 == 0:
print("Invalid Input. Input must be odd")
n = int(input("Enter odd input: "))
snowflake = [["."] * n for i in range(n)]
middle = int((n-1) / 2)
for i in range(n):
snowflake[i][middle] = "*"
snowflake[middle][i] = "*"
snowflake[i][i] = "*"
diagnol = n -1 -i
snowflake[i][diagnol] = "*"
for i in snowflake:
for j in i:
print(j, end=' ')
print()
print()

How to fix code for octagon of asterisk in python?

The problem is my code runs but that it does not create an octagon shape. The shape the stars make is similar to an octagon but I need code that creates a regular shaped octagon and I am confused on what's wrong with the code.
length = int(input("What is the length of one side? "))
for i in range(length):
print(' ' * (length - i-1) + '*' * (length + i*2))
for i in range(length-1):
print('*' * ((length * 2)))
for i in range(length):
print(' ' * (i+1) + '*' * ((length-i)*2))
No error messages but code does not produce desired outcome of an octagon shape when user inputs a number.
This should work
length = int(input("What is the length of one side? "))
for i in range(length - 1):
print(' ' * (length - i-1) + '*' * (length + i*2))
for i in range(length):
print('*' * ((length + 2 * (length - 1))))
for i in range(length - 2, -1, -1):
print(' ' * (length - i-1) + '*' * (length + i*2))
The formula for the second step was wrong, and for the last section you can reuse the logic for the first section but running it backwards, hope this help you :)
Edit
I realized that the count of the vertical sides doesn't match with the length, so this would be the correction for that code, but for the case where the length is 1 it displays a single point, and if you think about it it may have sense to be like that because for this apparent solution
*
***
*
There's no side for the diagonals, so I think that this edited version is better, and a single asterisk for case 1 makes sense.

Print Letter "A" depending on the input size

I am working on a program for school, and my homework is to create Letter "A" and the size depends on persons input.
I only worked with loops, print, and input, so I work with what I have.
I tried the following code:
v = eval(input("Enter the size of the Letter: "))
for i in range (v):
print(" " * ((v/2)-i) + i * '*' + ((v/2)-i))
..but I get an error.
Using if statements, my code below seems to work. I am not sure if it is possible without them.
v = eval(input("Enter the size of the Letter: "))
for i in range(1, v, 2):
if i == int(v/2):
middle = i * '*'
else:
middle = '*' + (i-2) * ' ' + '*' if i != 1 else '*'
print(" " * int((v/2)-(i/2)) + middle + int((v/2)-(i/2)) * " ")

HackerRank Staircase Python

I am trying to solve a problem in HackerRank and I am having an issue with my submission. My code works in PyCharm but HackerRank is not accepting my submission.
Here is the problem I am trying to solve: https://www.hackerrank.com/challenges/staircase
Here is my code:
def staircase(num_stairs):
n = num_stairs - 1
for stairs in range(num_stairs):
print ' ' * n, '#' * stairs
n -= 1
print '#' * num_stairs
staircase(12)
Any ideas why HackerRank is not accpeting my answer?
Your output is incorrect; you print an empty line before the stairs that should not be there. Your range() loop starts at 0, so you print n spaces and zero # characters on the first line.
Start your range() at 1, and n should start at num_stairs - 2 (as Multiple arguments to print() adds a space:
from __future__ import print_function
def staircase(num_stairs):
n = num_stairs - 2
for stairs in range(1, num_stairs):
print(' ' * n, '#' * stairs)
n -= 1
print('#' * num_stairs)
You can simplify this to one loop:
def staircase(num_stairs):
for stairs in range(1, num_stairs + 1):
print(' ' * (num_stairs - stairs) + '#' * stairs)
Note that I use concatenation now to combine spaces and # characters, so that in the last iteration of the loop zero spaces are printed and num_stairs # characters.
Last but not least, you could use the str.rjust() method (short for “right-justify”) to supply the spaces:
def staircase(num_stairs):
for stairs in range(1, num_stairs + 1):
print(('#' * stairs).rjust(num_stairs))
You can use rjust to justify the string to the right:
def staircase(n):
for i in range(1, n+1):
print(("#" * i).rjust(n))
Another solution
n = int(raw_input())
s = '#'
for i in xrange( 1 , n+1):
print " "*(n-i) + s*i
first, create a list, then print with join \n'
def staircase(n):
print("\n".join([' ' * (n-x) + '#' * x for x in range(1, n+1)]))
def staircase(n):
for i in range(0, n): # n rows
print(' '*(n-i-1) + '#'*(i+1)) # first print n-i-1 spaces followed by i '#'
n = int(input())
staircase(n)
its look like secondary diagonal
def staircase(n):
for i in range(n):
for j in range (n):
if i+j == n-1:
print(" "*j+"#"*(n-j))
output-
#
##
###
####
#####
######
for i in range(n):
result = ' '*(n-i-1) +('#')*(i+1)
print(result)
I was getting an error until I replaced the comma with a plus sign:
print(' ' * (n - i - 1) + '#' * (i + 1))
Understanding the problem is 80% of the solution. The requirement states the min/max total of stairs.
"""
Prints a staircase with a total number of stairs
Note: total number of stairs must be between 1 and 100 inclusive, as per requirements
"""
def staircase(n):
if n < 1 or n > 100:
print("Error: Total number of stairs must be between 1, 100 inclusive!")
else:
for x in range(1, n+1):
print(" " * (n - x) + "#" * x )
#-----------------------
staircase(0)
Error: Total number of stairs must be between 1, 100 inclusive!
staircase(101)
Error: Total number of stairs must be between 1, 100 inclusive!
staircase(4)
#
##
###
####
def staircase(n):
space = n-1
for i in range(n):
x = i + 1
print(" " * space + "#" * x)
space -= 1
one more solution:
def staircase(n):
for i in reversed(range(n)):
print(i*' '+(n-i)*'#')
You can just change the sep argument of print from ' ' to '', and your answer will be correct
def staircase(n):
for i in range(1, n+1):
print(' ' * (n-i), '#' * (i), sep='')
The answer you submitted is not accepted because the default print settings adds an empty space in front of the printouts, and one of the question requirements is for there to have no spaces in the output.
The default sep in print is a space character i.e. ' '.
This might not be the cleanest way to write the code, but it works:
print('\n'.join(' ' * (n - i) + '#' * i for i in range(1, n + 1)))
Another Answer
H = int(input())
for i in range(1,H+1):
H = H - 1
print(' '*(H) + ('#'*(i)))
you can simply use while loop also.
import sys
n1=int(raw_input())-1
n2=1
while n1>=0:
print " "*n1,"#"*n2
n1=n1-1
n2=n2+1
def staircase(n):
for in range(i,n+1):
print str("#"*i).rjust(n)

Asterisks Triangle in Python

I am trying to create a program that allows me to make a "pyramid" or "triangle" using asterisks, in the Python program. I've already started the code, but can't seem to figure it out.
Here's the code I've managed to figure out:
def triangle():
totalRows = int(eval(input("How big? ")))
for currentRows in range(1,totalRows+1):
for currentCol in range (1, currentRows+1):
print("*", end = " ")
triangle()
The end result is supposed to mirror this!
How big? 1
*
------------------------------------------------------
How big? 2
*
* *
------------------------------------------------------
How big? 3
*
* *
* * *
------------------------------------------------------
Slight modification to RParadox's solution to match requirement:
for i in range(totalRows + 1):
numWhite = totalRows - i
print ' ' * numWhite + '* ' * i
n = 10
for i in range(n-1):
numwhite = n-i
print ' '*numwhite + '*'*i + '*'*i
**
****
******
********
**********
************
**************
****************
def build_pyr(depth):
rows = [ (depth-i)*' ' + i*2*'*' + '*' for i in range(depth-1) ]
for i in rows:
print i
This works, however, it adds 2n + 1 asterisks at each depth. Just remove the + 1 asterisks from the list comprehension and add an initial asterisk to the row list before hand.
kiko="*"
empty=" "
def star(n):
for i in range(n):
print((n-i-1)*empty+(i+i+1)*kiko)
star(5)
def xmastree(maxwidth):
for i in xrange(1,maxwidth,2):
print '{0}'.format('*'*i).center(maxwidth)
or:
def xmastree2(maxrows):
for i in xrange(1,maxrows*2,2):
print '{0}'.format('*'*i).center(maxrows*2)
hmm, still no response, maybe not generic enough ? ok try this ;-) :
def triangle(pattern, n):
maxwidth = n*len(pattern)*2
for i in xrange(1,n*2+1,2):
print '{0}'.format(pattern*i).center(maxwidth)
>>> triangle(' ^', 5)
^
^ ^ ^
^ ^ ^ ^ ^
^ ^ ^ ^ ^ ^ ^
^ ^ ^ ^ ^ ^ ^ ^ ^
Woah, guys, you are going at it from a really complicated point of view! why don'y you just use this program? :
asterisknum = int(raw_input('How many asterisks? Input here: '))
base = 0
if asterisknum % 2 == 0:
print ('Added 1 to even number')
asterisknum = asterisknum + 1
while asterisknum != -1 :
print (' ' * base + '*' * asterisknum)
base = base + 1
asterisknum = asterisknum - 2
raw_input('Press <Enter> to exit')
I just made this program to work once, but I used the extremely simple parts of python that everybody should know. It could be tweaked to work again in the same program, or whatever...
def triangle(height):
maxstars = 1+ 2*(height -1)
spaces = int(maxstars/2)
for i in range(0,height):
print(" " * spaces +"*" * (1+ 2*i))
spaces = spaces -1
number = int(input("Please enter height of triangle: "))
triangle(number)
Imagine you have "blocks" of stars and space. Now add them on a canvas.
This is Python.
It glues objects together in this particular case
This code prints a diamond, the first loop is the upper half, the second loop is the lower half.
Note that i had to make new variables(objects) for the second loop.
Hope this helps guys :)
star = "*"
space = "." # dots are for presentation purposes
rows = 10
star_counter = 1
space_counter = rows
for i in range(rows):
print((space * (space_counter - 1 )) + (star * star_counter) +
(star * (star_counter - 1)) + (space * (space_counter - 1)) )
star_counter += 1
space_counter -= 1
star_counter_new = (rows - 1) # one row less for the lower triangle
# the upper triangle takes the base row
# that's why rows - 1
space_counter_new = 1
for j in range(rows - 1): # same goes here
print((space * (space_counter_new)) + (star * (star_counter_new)) +
(star * (star_counter_new - 1)) + (space * (space_counter_new )))
space_counter_new += 1
star_counter_new -= 1
it can be done in just few steps:
def main():
rows = input(" enter the number of rows : ")
for i in range (rows):
print ' '*(rows-i-1) + '*'*(2*i+1)
main()
def pypart2(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
pypart2(n)

Categories