Joel Pearce
Joel Pearce

Reputation: 47

Creating a snowflake in Python

I am trying to create a program in Python that creates a snowflake based on the input of a number. Below is my code:

n = int(input())
a = [["."] * n] * n

temp = n/2
start_point = 0
mid_point = int(temp)
end_point = n - 1

for i in range(n):
    if i > mid_point + 1:
        start_point -= 1
        end_point += 1

    for j in range(n):
        
        if (j == start_point) or (j == mid_point) or (j == end_point) or (i == mid_point):
            a[i][j] = "*"
        else:
            a[i][j] = "."
    
    
    if i < mid_point - 1:
        start_point += 1
        end_point -= 1


for row in a:
    print(' '.join([str(elem) for elem in row]))

For example, if the input is '5' the output should look like:

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

However, my output looks like:

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

I was sure that my code was correct so I rewrote it in Java as:

public class Snowflake {
    
    public static void createSnowflake(int n) {
        String[][] array = new String[n][n];

        float temp = (float) (n/2);
        System.out.println(temp);
        int start_point = 0;
        int mid_point = (int) (temp);
        System.out.println(mid_point);
        int end_point = n - 1;

        for(int i = 0; i < n; i++) {
            if(i > mid_point+1) {
                start_point--;
                end_point++;
            }
            for(int j = 0; j < n; j++) {
                if((j == start_point) || (j == mid_point) || (j == end_point) || (i == mid_point)) {
                    array[i][j] = "*";
                }
                else {
                    array[i][j] = ".";
                }
            }
            
            if(i < mid_point-1) {
                start_point++;
                end_point--;
            }
        }
        
        for(int i = 0; i < n; i++) {
            for(int j = 0; j < n; j++) {
                System.out.print(array[i][j]);
            }
            System.out.print("\n");
        }
    }

    public static void main(String[] args) {
        createSnowflake(5);
    }
}

And it worked as expected. To my eyes the underlying logic is exactly the same, and yet the Java code works and the Python code doesn't. Could someone help me find where I've made a mistake in the Python syntax or how my Java code somehow differs from it?

Upvotes: 2

Views: 287

Answers (1)

willcrack
willcrack

Reputation: 1852

If you change the creation of a to:

 a= [["." for j in range(n)] for i in range(n)]

it should fix it.
This has to do with the way python copies lists.
Check the question linked on the comments to your question.

Enjoyed this question, I feel like it could only be here during this time of the year.

Upvotes: 2

Related Questions