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()
Related
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)
long = int(input("longueur : "))
larg = int(input("largeur : "))
for i in range(larg):
if i == 0 or i == larg - 1:
for j in range(long):
print("* ", end="")
print()
else:
for j in range(long):
if j == 0 or j == long - 1:
print("* ", end="")
else:
print(end=" ")
print()
I was trying to achieve a rectangle shape through symbols .
I started learning Python recently and I'm searching for a faster/cleaner way to do this .
the output requested is:
* * * *
* *
* * * *
Here is a clean and simple approach...
length = int(input("length: "))
width = int(input("width: "))
for i in range(length):
print("* " * width)
Well, you could use multiply with your multiplication signs:
rows = 3
columns = 5
print(('* ' * columns + '\n') * rows, end = '')
Output:
* * * * *
* * * * *
* * * * *
If you want to print a hollow rectangle, it's a little more complicated as you need different rows in the middle. For example:
for r in range(rows):
if r == 0 or r == rows - 1:
print('* ' * columns)
else:
print('* ' + ' ' * (columns - 2) + '* ')
Output:
* * * * *
* *
* * * * *
You need to use a loop to iterate through each row. If the row is first or last then fill it with column * '*'. If the row is the middle one then add an '*', fill with appropriate spaces and finally add an '*'.
Here's how you can do it:
long = int(input("longueur : "))
larg = int(input("largeur : "))
for i in range(long):
if (i == 0) or (i == long - 1): # Checking if it is first or last row
print('* ' * larg) # Printing entire row without gap
else: # For middle rows
print('* ' + ' ' *(larg - 2) + '*') # Printing middle rows with gap in between.
Output:
longueur : 3
largeur : 4
* * * *
* *
* * * *
longueur : 4
largeur : 7
* * * * * * *
* *
* *
* * * * * * *
You can try the good old basic for loop
rows = 3
columns = 3
for i in range(rows):
for j in range(columns):
print('*', end=' ')
print()
will give
* * *
* * *
* * *
as per your updated question for hollow
for i in range(1, rows + 1):
for j in range(1, columns + 1):
if i == 1 or i == rows or j == 1 or j == columns:
print("*", end=" ")
else:
print(" ", end=" ")
print()
will give
* * *
* *
* * *
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I am new to Python and Stackoverflow in general, so sorry if my formatting sucks and I'm not good at English. But I am stuck with this code.
test = True
a = True
total = 0
t = 0
while test:
n = int(input('Width (7-10): '))
if n<7 or n>10:
print('Invalid Number!')
total += 1
if n>=7 and n<=10:
break
while a:
c = int(input('Border (1-3): '))
if c<1 or c>3:
print('Invalid Number!')
t += 1
if c>=1 and c<=3:
break
This is the result.
Width (7-10): 5
Invalid Number!
Width (7-10): 10
Border (1-3): 0
Invalid Number!
Border (1-3): 2
And this is the result that I want.
Width (7-10): 5
Invalid Number!
Width (7-10): 10
Border (1-3): 0
Invalid Number!
Border (1-3): 2
**********
**********
** **
** **
** **
** **
** **
** **
**********
**********
I don't know how to make the square.
Firstly, you can simply write
while True:
Instead of
a = True
while a:
Secondly, you don't use total or t anywhere. You can delete them.
Thirdly, if x has to belong to [a, b], you can write
if a <= x <= b:
Fourthly, you can use else statement instead of negation of if. Also, when you have break in if statement, the code below won't be executed if statement is true (it will break), so you even don't have to use any else here.
The last part you can make by simple iteration in for loop and multiplying or adding strings (e.g. 5*'a' = 'aaaaa')
while True:
width = int(input('Width (7-10): '))
if 7 <= width <= 10:
break
print('Invalid Number!')
while True:
border = int(input('Border (1-3): '))
if 1 <= border <= 3:
break
print('Invalid Number!')
for _ in range(border):
print(width*'*')
for _ in range (width - 2*border):
print(border*'*' + (width-2*border)*' ' + border*'*')
for _ in range(border):
print(width*'*')
This can be achieved by the following code:
for i in range(n):
if i < c or i >= n-c:
print("*"*n)
else:
print("*"*c + " "*(n-(c*c)) + "*"*c)
This iterates through a for loop with the range being the width entered earlier (n in this case). By testing if you are at the first/last few iterations (as determined by the border, or c in this case), you can print the border. If not, you can print the necessary stars with the required spacing.
You print the required amount of stars by multiplying the string as necessary.
ok, i am totally lost, i don't know how u expect
**********
**********
** **
** **
** **
** **
** **
** **
**********
**********
that when u haven't written any code that will output that result, but what u could do is that before u break in the last while loop paste this
dummy = ''
for line in range(1, n + 1):
if line <= c or line > n - c:
dummy = ''.join(['*'] * n)
print(dummy)
dummy = ''
else:
dummy = ''.join(['*'] * c)
dummy = dummy + ''.join([' '] * (n - 2*c))
dummy = dummy + ''.join(['*'] * c)
print(dummy)
please respond if it helped i spent some time on this, and here is ur final code
a = True
total = 0
t = 0
while test:
n = int(input('Width (7-10): '))
if n<7 or n>10:
print('Invalid Number!')
total += 1
if n>=7 and n<=10:
break
while a:
c = int(input('Border (1-3): '))
if c<1 or c>3:
print('Invalid Number!')
t += 1
if c>=1 and c<=3:
for line in range(1, n + 1):
if line <= c or line > n - c:
dummy = ''.join(['*'] * n)
print(dummy)
dummy = ''
else:
dummy = ''.join(['*'] * c)
dummy = dummy + ''.join([' '] * (n - 2*c))
dummy = dummy + ''.join(['*'] * c)
print(dummy)
break
I need to make a nested triangle of hash symbols. But I can't get it to rotate 180 degrees like I need it to, I am also not getting the 12 rows like I need to.
This is my code.
n = int(input("Enter a number: "))
for i in range (0, n):
for j in range(0, i + 1):
print("#", end='')
print("")
for i in range (n, 0, -1):
for j in range(0, i -1):
print("#", end='')
print("")
The Input value is 6.
Enter a number:6
#
##
###
####
#####
######
######
#####
####
###
##
#
But I keep getting this:
Enter a number: 6
#
##
###
####
#####
######
#####
####
###
##
#
How do I fix this?
You can use the str.rjust method to align a string to the right:
n = int(input("Enter a number: "))
for i in range(2 * n):
print(('#' * (n - int(abs(n - i - 0.5)))).rjust(n))
Demo: https://ideone.com/27AM7a
A bit late
def absp1(x):
if (x < 0):
return -x - 1
return x
n = int(input("Enter a number: "))
for i in range(-n, n):
for j in range(absp1(i)):
print(' ', end='')
for k in range(n-absp1(i)):
print('#',end='')
print()
You can use this (manually calculating number of spaces and hashtags):
n = int(input("Enter a number: "))
for i in range (1, n + 1):
print(" "*(n - i) + "#"*i)
for i in range (n, 0, -1):
print(" "*(n - i) + "#"*i)
Or use rjust:
n = int(input("Enter a number: "))
for i in range (1, n + 1):
print(("#"*i).rjust(n))
for i in range (n, 0, -1):
print(("#"*i).rjust(n))
Also this works fine
num = 6
sing = "#"
for i in range(1, num * 2):
if i > num:
spaces = " " * (i - num)
signs = sign * (2 * num - i)
line = "{0}{1}".format(spaces, signs)
elif i == num:
spaces = " " * (num - i)
signs = sign * i
line = "{0}{1}\n{0}{1}".format(spaces, signs)
else:
spaces = " " * (num - i)
signs = sign * i
line = "{0}{1}".format(spaces, signs)
print(line)
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)