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?
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.
Related
I've implemented a 6k+-1 primality test function both in a C extension and pure Python code but seems pure Python code is much faster! is there something wrong with my C code or something else?
I also compiled a similar test in pure C with the is_prime function, and its execution time was the same as the C extension (almost 2sec)
primemodule.c
#define PY_SSIZE_T_CLEAN
#include "Python.h"
int is_prime(int n)
{
int i;
if (n <= 3)
return (n > 1);
if (n % 2 == 0 || n % 3 == 0)
return (0);
i = 5;
while ((i * i) <= n)
{
if (n % i == 0 || n % (i + 2) == 0)
return (0);
i += 6;
}
return (1);
}
static PyObject *prime_isprime(PyObject *self, PyObject *args)
{
int n;
if (!PyArg_ParseTuple(args, "i", &n))
return (NULL);
if (is_prime(n))
Py_RETURN_TRUE;
Py_RETURN_FALSE;
}
static PyMethodDef prime_methods[] = {
{"is_prime", prime_isprime, METH_VARARGS, "Check if a number is prime"},
{NULL, NULL, 0, NULL}};
static struct PyModuleDef prime_module = {
PyModuleDef_HEAD_INIT,
"prime",
NULL,
-1,
prime_methods};
PyMODINIT_FUNC PyInit_prime(void)
{
return (PyModule_Create(&prime_module));
}
py_test.py
import time
MAX_INT = 2147483647
def is_prime(n: int) -> bool:
if n <= 3:
return n > 1
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i ** 2 <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
t1 = time.process_time()
for i in range(MAX_INT - 100, MAX_INT):
is_prime(i)
print(time.process_time() - t1, "seconds")
c_test.py
import time
import prime
MAX_INT = 2147483647
t1 = time.process_time()
for i in range(MAX_INT - 100, MAX_INT):
prime.is_prime(i)
print(time.process_time() - t1, "seconds")
python c_test.py
2.078125 seconds
python py_test.py
0.03125 seconds
timecmd.bat a.exe
2.13 seconds
I think your C implementation is buggy regarding integer overflows and signedness and ends up in a bigger loop than the Python version.
Changing the parameter type to unsigned int (and i too, since otherwise that's a compiler warning):
static int is_prime(unsigned int n)
{
unsigned int i;
if (n <= 3)
return (n > 1);
if (n == 2 || n == 3)
return (1);
if (n % 2 == 0 || n % 3 == 0)
return (0);
i = 5;
while ((i * i) <= n)
{
if (n % i == 0 || n % (i + 2) == 0)
return (0);
i += 6;
}
return (1);
}
makes it (anecdotally, on my machine, approximately) 37 times faster than the Python implementation.
I have a string with characters and a number for the rows and columns that will be in the pattern:
char_str1 = 'abc'
char_str1 = '31452'
num = 5
I would like the output to be:
abcab 31452
bcabc 14523
cabca 45231
abcab 52314
bcabc 23145
I have tried doing:
for i in range(num):
for j in range(num):
print(char_str1, end='')
print()
output:
abcabcabcabcabc
abcabcabcabcabc
abcabcabcabcabc
abcabcabcabcabc
abcabcabcabcabc
If you replicate the strings at least num times, simple slicing works. The original strings need to be at least length 1 of course:
char_str1 = 'abc'
char_str2 = '31452' # You had a typo here st1 instead of str2
num = 5
a = char_str1 * num
b = char_str2 * num
for i in range(num):
print(a[i:i+num], b[i:i+num])
Output:
abcab 31452
bcabc 14523
cabca 45231
abcab 52314
bcabc 23145
Please use the below code in java for your pattern!!
JAVA
public class Main {
public static void printPattern(String s, int n) {
for (int i = 0; i < n; i++) {
for (int j = i; j < n + i; j++) {
System.out.print(s.charAt(j % s.length()));
}
System.out.println();
}
}
public static void main(String[] args) {
printPattern("abc", 5);
printPattern("31452", 5);
}
}
EDIT:
Python
def printPattern(s, n):
for i in range(n):
for j in range(i, n + i):
print(s[j % len(s)], end='')
print()
printPattern("abc", 5);
printPattern("31452", 5);
I'm trying to write a very basic box drawing program using pyprocessing,
but a condition to check if the mouse is within a box fails, when the logic looks ok:
#!/usr/bin/env python
from pyprocessing import *
S = 20
W = 5
H = 5
data = [[0] * W] * H
def setup():
size(W*(S+5),H*(S+5))
def draw():
background(0)
for y in xrange(H):
for x in xrange(W):
fill(data[x][y] * 255)
rect(x*S,y*S,S,S)
def mouseDragged():
for y in xrange(H):
for x in xrange(W):
xs = x * S
ys = y * S
# this doesn't behave as expected: it should draw a single box if the condition is met, not the whole row
if (mouse.x >= xs) and (mouse.x <= (xs+S)) and (mouse.y >= ys and mouse.y <= (ys+S)):
if key.pressed:
data[x][y] = 0
else:
data[x][y] = 1
run()
I've tried the same approach using the Java version of Processing and it works as expected:
int S = 20;
int W = 5;
int H = 5;
int[][] data = new int[W][H];
void setup(){
size(100,100);
noStroke();
}
void draw(){
background(0);
for (int y = 0 ; y < H; y++){
for (int x = 0 ; x < W; x++){
fill(data[x][y] * 255);
rect(x*S,y*S,S,S);
}
}
}
void mouseDragged(){
for (int y = 0 ; y < H; y++){
for (int x = 0 ; x < W; x++){
int xs = x * S;
int ys = y * S;
if ((mouseX > xs) && (mouseX < (xs+S)) && (mouseY >= ys && mouseY <= (ys+S))){
data[x][y] = 1;
}
}
}
}
Similar behaviour in JS:
var S = 20;
var W = 5;
var H = 5;
var data = new Array(W);
function setup(){
createCanvas(100,100);
noStroke();
for (var i = 0 ; i < H; i++) data[i] = [0,0,0,0,0];
}
function draw(){
background(0);
for (var y = 0 ; y < H; y++){
for (var x = 0 ; x < W; x++){
fill(data[x][y] * 255);
rect(x*S,y*S,S,S);
}
}
}
function mouseDragged(){
for (var y = 0 ; y < H; y++){
for (var x = 0 ; x < W; x++){
var xs = x * S;
var ys = y * S;
if ((mouseX > xs) && (mouseX < (xs+S)) && (mouseY >= ys && mouseY <= (ys+S))){
data[x][y] = 1;
}
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.4.23/p5.min.js"></script>
Am I writing the box bounds condition correctly in Python ? If so, is there a bug with pyprocessing ? How can I get past it ?
I'm using pyprocessing.version '0.1.3.22'
Trying to be lazy is the issue:
data = [[0] * W] * H
This doesn't simply create a nested array, it copies the references of the first array ([0]), so when I modify one value in one row, the whole row is modified.
Since I'm super experienced with python, I've initialised the array in a probably a non-pythonic way:
data = []
for y in xrange(H):
data.append([])
for x in xrange(W):
data[y].append(0)
So the full working code is:
#!/usr/bin/env python
from pyprocessing import *
S = 20
W = 5
H = 5
# data = [[0] * W] * H #trouble
data = []
for y in xrange(H):
data.append([])
for x in xrange(W):
data[y].append(0)
def setup():
size(W*(S),H*(S))
def draw():
background(0)
for y in xrange(H):
for x in xrange(W):
fill(data[x][y] * 255)
rect(x*S,y*S,S,S)
def mouseDragged():
for y in xrange(H):
for x in xrange(W):
xs = x * S
ys = y * S
if (mouse.x >= xs) and (mouse.x <= (xs+S)) and (mouse.y >= ys and mouse.y <= (ys+S)):
if key.pressed:
data[x][y] = 0
else:
data[x][y] = 1
run()
I'm trying to test the speed of generating numbers from normal distribution by using Box–Muller transform against Marsaglia polar method. It is said that Marsaglia polar method is suppose to be faster than Box–Muller transform because it does not need to compute sin and cos. However, when I code this in Python, this is not true. Can someone verify this or explain to me why this is happening?
def marsaglia_polar():
while True:
x = (random.random() * 2) - 1
y = (random.random() * 2) - 1
s = x * x + y * y
if s < 1:
t = math.sqrt((-2) * math.log(s)/s)
return x * t, y * t
def box_muller():
u1 = random.random()
u2 = random.random()
t = math.sqrt((-2) * math.log(u1))
v = 2 * math.pi * u2
return t * math.cos(v), t * math.sin(v)
For "fun", I wrote it up in go. The box_muller function is faster there as well. Also, it's about 10 times faster than the python version.
package main
import (
"fmt"
"math"
"math/rand"
"time"
)
func main() {
rand.Seed(time.Now().UnixNano())
now := time.Now()
for i := 0; i < 1000000; i++ {
marsaglia_polar()
}
fmt.Println("marsaglia_polar duration = ", time.Since(now))
now = time.Now()
for i := 0; i < 1000000; i++ {
box_muller()
}
fmt.Println("box_muller duration = ", time.Since(now))
}
func marsaglia_polar() (float64, float64) {
for {
x := random() * 2 - 1;
y := random() * 2 - 1;
s := x * x + y * y;
if s < 1 {
t := math.Sqrt((-2) * math.Log(s)/s);
return x * t, y * t
}
}
}
func box_muller() (float64, float64) {
u1 := random()
u2 := random()
t := math.Sqrt((-2) * math.Log(u1))
v := 2 * math.Pi * u2
return t * math.Cos(v), t * math.Sin(v)
}
func random() float64 {
return rand.Float64()
}
Output:
marsaglia_polar duration = 104.308126ms
box_muller duration = 88.365933ms
I'm learning Cython and came across this snippit of code:
import numpy as np
cimport numpy as np
def mean(np.ndarray[np.double_t] input):
cdef np.double_t cur
# Py_ssize_t is numpy's index type
cdef Py_ssize_t i
cdef Py_ssize_t N = len(input)
for i from 0 <= i < N:
cur += input[i]
return cur / N
a=np.array([1,2,3,4], dtype=np.double)
Obviously, this returns the mean of a which is 2.5. My question is this:
Is the for loop a Python loop, Cython, or C?
Compile it and see: the C code that Cython produces is nicely annotated.
/* "cyexample.pyx":11
* cdef Py_ssize_t N = len(input)
*
* for i from 0 <= i < N: # <<<<<<<<<<<<<<
* cur += input[i]
*
*/
__pyx_t_1 = __pyx_v_N;
for (__pyx_v_i = 0; __pyx_v_i < __pyx_t_1; __pyx_v_i++) {
/* "cyexample.pyx":12
*
* for i from 0 <= i < N:
* cur += input[i] # <<<<<<<<<<<<<<
*
* return cur / N
*/
__pyx_t_2 = __pyx_v_i;
__pyx_t_3 = -1;
if (__pyx_t_2 < 0) {
__pyx_t_2 += __pyx_bshape_0_input;
if (unlikely(__pyx_t_2 < 0)) __pyx_t_3 = 0;
} else if (unlikely(__pyx_t_2 >= __pyx_bshape_0_input)) __pyx_t_3 = 0;
if (unlikely(__pyx_t_3 != -1)) {
__Pyx_RaiseBufferIndexError(__pyx_t_3);
{__pyx_filename = __pyx_f[0]; __pyx_lineno = 12; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
}
__pyx_v_cur = (__pyx_v_cur + (*__Pyx_BufPtrStrided1d(__pyx_t_5numpy_double_t *, __pyx_bstruct_input.buf, __pyx_t_2, __pyx_bstride_0_input)));
}
And so the loop itself is successfully turned into C. Note that these days Cython can handle range naturally, so the older "from 0 <= i < N" style isn't necessary. The point of introducing the (non-Python) "for/from" syntax was to signify which loops should be C-ified.
for..from seems to be a Pyrex / Cython loop: http://docs.cython.org/src/userguide/language_basics.html#integer-for-loops