Squishy
Squishy

Reputation: 96

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)

Upvotes: 2

Views: 1042

Answers (2)

Arty
Arty

Reputation: 16747

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:

*...*...*
.*..*..*.
..*.*.*..
...***...
*********
...***...
..*.*.*..
.*..*..*.
*...*...*

Upvotes: 1

Squishy
Squishy

Reputation: 96

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()

Upvotes: 1

Related Questions