Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Rewrite this program in Python while keeping its functionality equivalent to the C version.
#include <stdio.h> void recurse(unsigned int i) { printf("%d\n", i); recurse(i+1); } int main() { recurse(0); return 0; }
import sys print(sys.getrecursionlimit())
Generate a Python translation of this C snippet without changing its computational steps.
#include <stdio.h> #define mod(n,m) ((((n) % (m)) + (m)) % (m)) int is_prime(unsigned int n) { if (n <= 3) { return n > 1; } else if (!(n % 2) || !(n % 3)) { return 0; } else { unsigned int i; for (i = 5; i*i <= n; i += 6) if (!(n % i) || !(n % (i + 2))) return 0; return 1; } } void carmichael3(int p1) { if (!is_prime(p1)) return; int h3, d, p2, p3; for (h3 = 1; h3 < p1; ++h3) { for (d = 1; d < h3 + p1; ++d) { if ((h3 + p1)*(p1 - 1) % d == 0 && mod(-p1 * p1, h3) == d % h3) { p2 = 1 + ((p1 - 1) * (h3 + p1)/d); if (!is_prime(p2)) continue; p3 = 1 + (p1 * p2 / h3); if (!is_prime(p3) || (p2 * p3) % (p1 - 1) != 1) continue; printf("%d %d %d\n", p1, p2, p3); } } } } int main(void) { int p1; for (p1 = 2; p1 < 62; ++p1) carmichael3(p1); return 0; }
class Isprime(): multiples = {2} primes = [2] nmax = 2 def __init__(self, nmax): if nmax > self.nmax: self.check(nmax) def check(self, n): if type(n) == float: if not n.is_integer(): return False n = int(n) multiples = self.multiples if n <= self.nmax: return n not in multiples else: primes, nmax = self.primes, self.nmax newmax = max(nmax*2, n) for p in primes: multiples.update(range(p*((nmax + p + 1) // p), newmax+1, p)) for i in range(nmax+1, newmax+1): if i not in multiples: primes.append(i) multiples.update(range(i*2, newmax+1, i)) self.nmax = newmax return n not in multiples __call__ = check def carmichael(p1): ans = [] if isprime(p1): for h3 in range(2, p1): g = h3 + p1 for d in range(1, g): if (g * (p1 - 1)) % d == 0 and (-p1 * p1) % h3 == d % h3: p2 = 1 + ((p1 - 1)* g // d) if isprime(p2): p3 = 1 + (p1 * p2 // h3) if isprime(p3): if (p2 * p3) % (p1 - 1) == 1: ans += [tuple(sorted((p1, p2, p3)))] return ans isprime = Isprime(2) ans = sorted(sum((carmichael(n) for n in range(62) if isprime(n)), [])) print(',\n'.join(repr(ans[i:i+5])[1:-1] for i in range(0, len(ans)+1, 5)))
Write the same code in Python as shown below in C.
#include <stdlib.h> #include <stdio.h> #include <time.h> #include <SDL/SDL.h> unsigned int frames = 0; unsigned int t_acc = 0; void print_fps () { static Uint32 last_t = 0; Uint32 t = SDL_GetTicks(); Uint32 dt = t - last_t; t_acc += dt; if (t_acc > 1000) { unsigned int el_time = t_acc / 1000; printf("- fps: %g\n", (float) frames / (float) el_time); t_acc = 0; frames = 0; } last_t = t; } void blit_noise(SDL_Surface *surf) { unsigned int i; long dim = surf->w * surf->h; while (1) { SDL_LockSurface(surf); for (i=0; i < dim; ++i) { ((unsigned char *)surf->pixels)[i] = ((rand() & 1) ? 255 : 0); } SDL_UnlockSurface(surf); SDL_Flip(surf); ++frames; print_fps(); } } int main(void) { SDL_Surface *surf = NULL; srand((unsigned int)time(NULL)); SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO); surf = SDL_SetVideoMode(320, 240, 8, SDL_DOUBLEBUF | SDL_HWSURFACE); blit_noise(surf); }
black = color(0) white = color(255) def setup(): size(320, 240) def draw(): loadPixels() for i in range(len(pixels)): if random(1) < 0.5: pixels[i] = black else: pixels[i] = white updatePixels() fill(0, 128) rect(0, 0, 60, 20) fill(255) text(frameRate, 5, 15)
Translate the given C code snippet into Python without altering its behavior.
#include <stdio.h> #include <termios.h> #include <unistd.h> #include <fcntl.h> #include <sys/time.h> void set_mode(int want_key) { static struct termios old, new; if (!want_key) { tcsetattr(STDIN_FILENO, TCSANOW, &old); return; } tcgetattr(STDIN_FILENO, &old); new = old; new.c_lflag &= ~(ICANON); tcsetattr(STDIN_FILENO, TCSANOW, &new); } int get_key(int no_timeout) { int c = 0; struct timeval tv; fd_set fs; tv.tv_usec = tv.tv_sec = 0; FD_ZERO(&fs); FD_SET(STDIN_FILENO, &fs); select(STDIN_FILENO + 1, &fs, 0, 0, no_timeout ? 0 : &tv); if (FD_ISSET(STDIN_FILENO, &fs)) { c = getchar(); set_mode(0); } return c; } int main() { int c; while(1) { set_mode(1); while (get_key(0)); printf("Prompt again [Y/N]? "); fflush(stdout); c = get_key(1); if (c == 'Y' || c == 'y') { printf("\n"); continue; } if (c == 'N' || c == 'n') { printf("\nDone\n"); break; } printf("\nYes or no?\n"); } return 0; }
try: from msvcrt import getch except ImportError: def getch(): import sys, tty, termios fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch print "Press Y or N to continue" while True: char = getch() if char.lower() in ("y", "n"): print char break
Generate a Python translation of this C snippet without changing its computational steps.
#include <stdio.h> #include <termios.h> #include <unistd.h> #include <fcntl.h> #include <sys/time.h> void set_mode(int want_key) { static struct termios old, new; if (!want_key) { tcsetattr(STDIN_FILENO, TCSANOW, &old); return; } tcgetattr(STDIN_FILENO, &old); new = old; new.c_lflag &= ~(ICANON); tcsetattr(STDIN_FILENO, TCSANOW, &new); } int get_key(int no_timeout) { int c = 0; struct timeval tv; fd_set fs; tv.tv_usec = tv.tv_sec = 0; FD_ZERO(&fs); FD_SET(STDIN_FILENO, &fs); select(STDIN_FILENO + 1, &fs, 0, 0, no_timeout ? 0 : &tv); if (FD_ISSET(STDIN_FILENO, &fs)) { c = getchar(); set_mode(0); } return c; } int main() { int c; while(1) { set_mode(1); while (get_key(0)); printf("Prompt again [Y/N]? "); fflush(stdout); c = get_key(1); if (c == 'Y' || c == 'y') { printf("\n"); continue; } if (c == 'N' || c == 'n') { printf("\nDone\n"); break; } printf("\nYes or no?\n"); } return 0; }
try: from msvcrt import getch except ImportError: def getch(): import sys, tty, termios fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch print "Press Y or N to continue" while True: char = getch() if char.lower() in ("y", "n"): print char break
Maintain the same structure and functionality when rewriting this code in Python.
#include <stdio.h> #include <termios.h> #include <unistd.h> #include <fcntl.h> #include <sys/time.h> void set_mode(int want_key) { static struct termios old, new; if (!want_key) { tcsetattr(STDIN_FILENO, TCSANOW, &old); return; } tcgetattr(STDIN_FILENO, &old); new = old; new.c_lflag &= ~(ICANON); tcsetattr(STDIN_FILENO, TCSANOW, &new); } int get_key(int no_timeout) { int c = 0; struct timeval tv; fd_set fs; tv.tv_usec = tv.tv_sec = 0; FD_ZERO(&fs); FD_SET(STDIN_FILENO, &fs); select(STDIN_FILENO + 1, &fs, 0, 0, no_timeout ? 0 : &tv); if (FD_ISSET(STDIN_FILENO, &fs)) { c = getchar(); set_mode(0); } return c; } int main() { int c; while(1) { set_mode(1); while (get_key(0)); printf("Prompt again [Y/N]? "); fflush(stdout); c = get_key(1); if (c == 'Y' || c == 'y') { printf("\n"); continue; } if (c == 'N' || c == 'n') { printf("\nDone\n"); break; } printf("\nYes or no?\n"); } return 0; }
try: from msvcrt import getch except ImportError: def getch(): import sys, tty, termios fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch print "Press Y or N to continue" while True: char = getch() if char.lower() in ("y", "n"): print char break
Rewrite this program in Python while keeping its functionality equivalent to the C version.
#include "stdio.h" #include "math.h" int perfect(int n) { int max = (int)sqrt((double)n) + 1; int tot = 1; int i; for (i = 2; i < max; i++) if ( (n % i) == 0 ) { tot += i; int q = n / i; if (q > i) tot += q; } return tot == n; } int main() { int n; for (n = 2; n < 33550337; n++) if (perfect(n)) printf("%d\n", n); return 0; }
def perf1(n): sum = 0 for i in range(1, n): if n % i == 0: sum += i return sum == n
Maintain the same structure and functionality when rewriting this code in Python.
#include "stdio.h" #include "math.h" int perfect(int n) { int max = (int)sqrt((double)n) + 1; int tot = 1; int i; for (i = 2; i < max; i++) if ( (n % i) == 0 ) { tot += i; int q = n / i; if (q > i) tot += q; } return tot == n; } int main() { int n; for (n = 2; n < 33550337; n++) if (perfect(n)) printf("%d\n", n); return 0; }
def perf1(n): sum = 0 for i in range(1, n): if n % i == 0: sum += i return sum == n
Rewrite this program in Python while keeping its functionality equivalent to the C version.
#include<stdlib.h> #include<stdio.h> #include<complex.h> typedef struct { int rows, cols; complex **z; } matrix; matrix transpose (matrix a) { int i, j; matrix b; b.rows = a.cols; b.cols = a.rows; b.z = malloc (b.rows * sizeof (complex *)); for (i = 0; i < b.rows; i++) { b.z[i] = malloc (b.cols * sizeof (complex)); for (j = 0; j < b.cols; j++) { b.z[i][j] = conj (a.z[j][i]); } } return b; } int isHermitian (matrix a) { int i, j; matrix b = transpose (a); if (b.rows == a.rows && b.cols == a.cols) { for (i = 0; i < b.rows; i++) { for (j = 0; j < b.cols; j++) { if (b.z[i][j] != a.z[i][j]) return 0; } } } else return 0; return 1; } matrix multiply (matrix a, matrix b) { matrix c; int i, j; if (a.cols == b.rows) { c.rows = a.rows; c.cols = b.cols; c.z = malloc (c.rows * (sizeof (complex *))); for (i = 0; i < c.rows; i++) { c.z[i] = malloc (c.cols * sizeof (complex)); c.z[i][j] = 0 + 0 * I; for (j = 0; j < b.cols; j++) { c.z[i][j] += a.z[i][j] * b.z[j][i]; } } } return c; } int isNormal (matrix a) { int i, j; matrix a_ah, ah_a; if (a.rows != a.cols) return 0; a_ah = multiply (a, transpose (a)); ah_a = multiply (transpose (a), a); for (i = 0; i < a.rows; i++) { for (j = 0; j < a.cols; j++) { if (a_ah.z[i][j] != ah_a.z[i][j]) return 0; } } return 1; } int isUnitary (matrix a) { matrix b; int i, j; if (isNormal (a) == 1) { b = multiply (a, transpose(a)); for (i = 0; i < b.rows; i++) { for (j = 0; j < b.cols; j++) { if ((i == j && b.z[i][j] != 1) || (i != j && b.z[i][j] != 0)) return 0; } } return 1; } return 0; } int main () { complex z = 3 + 4 * I; matrix a, aT; int i, j; printf ("Enter rows and columns :"); scanf ("%d%d", &a.rows, &a.cols); a.z = malloc (a.rows * sizeof (complex *)); printf ("Randomly Generated Complex Matrix A is : "); for (i = 0; i < a.rows; i++) { printf ("\n"); a.z[i] = malloc (a.cols * sizeof (complex)); for (j = 0; j < a.cols; j++) { a.z[i][j] = rand () % 10 + rand () % 10 * I; printf ("\t%f + %fi", creal (a.z[i][j]), cimag (a.z[i][j])); } } aT = transpose (a); printf ("\n\nTranspose of Complex Matrix A is : "); for (i = 0; i < aT.rows; i++) { printf ("\n"); aT.z[i] = malloc (aT.cols * sizeof (complex)); for (j = 0; j < aT.cols; j++) { aT.z[i][j] = rand () % 10 + rand () % 10 * I; printf ("\t%f + %fi", creal (aT.z[i][j]), cimag (aT.z[i][j])); } } printf ("\n\nComplex Matrix A %s hermitian", isHermitian (a) == 1 ? "is" : "is not"); printf ("\n\nComplex Matrix A %s unitary", isUnitary (a) == 1 ? "is" : "is not"); printf ("\n\nComplex Matrix A %s normal", isNormal (a) == 1 ? "is" : "is not"); return 0; }
def conjugate_transpose(m): return tuple(tuple(n.conjugate() for n in row) for row in zip(*m)) def mmul( ma, mb): return tuple(tuple(sum( ea*eb for ea,eb in zip(a,b)) for b in zip(*mb)) for a in ma) def mi(size): 'Complex Identity matrix' sz = range(size) m = [[0 + 0j for i in sz] for j in sz] for i in range(size): m[i][i] = 1 + 0j return tuple(tuple(row) for row in m) def __allsame(vector): first, rest = vector[0], vector[1:] return all(i == first for i in rest) def __allnearsame(vector, eps=1e-14): first, rest = vector[0], vector[1:] return all(abs(first.real - i.real) < eps and abs(first.imag - i.imag) < eps for i in rest) def isequal(matrices, eps=1e-14): 'Check any number of matrices for equality within eps' x = [len(m) for m in matrices] if not __allsame(x): return False y = [len(m[0]) for m in matrices] if not __allsame(y): return False for s in range(x[0]): for t in range(y[0]): if not __allnearsame([m[s][t] for m in matrices], eps): return False return True def ishermitian(m, ct): return isequal([m, ct]) def isnormal(m, ct): return isequal([mmul(m, ct), mmul(ct, m)]) def isunitary(m, ct): mct, ctm = mmul(m, ct), mmul(ct, m) mctx, mcty, cmx, ctmy = len(mct), len(mct[0]), len(ctm), len(ctm[0]) ident = mi(mctx) return isequal([mct, ctm, ident]) def printm(comment, m): print(comment) fields = [['%g%+gj' % (f.real, f.imag) for f in row] for row in m] width = max(max(len(f) for f in row) for row in fields) lines = (', '.join('%*s' % (width, f) for f in row) for row in fields) print('\n'.join(lines)) if __name__ == '__main__': for matrix in [ ((( 3.000+0.000j), (+2.000+1.000j)), (( 2.000-1.000j), (+1.000+0.000j))), ((( 1.000+0.000j), (+1.000+0.000j), (+0.000+0.000j)), (( 0.000+0.000j), (+1.000+0.000j), (+1.000+0.000j)), (( 1.000+0.000j), (+0.000+0.000j), (+1.000+0.000j))), ((( 2**0.5/2+0.000j), (+2**0.5/2+0.000j), (+0.000+0.000j)), (( 0.000+2**0.5/2j), (+0.000-2**0.5/2j), (+0.000+0.000j)), (( 0.000+0.000j), (+0.000+0.000j), (+0.000+1.000j)))]: printm('\nMatrix:', matrix) ct = conjugate_transpose(matrix) printm('Its conjugate transpose:', ct) print('Hermitian? %s.' % ishermitian(matrix, ct)) print('Normal? %s.' % isnormal(matrix, ct)) print('Unitary? %s.' % isunitary(matrix, ct))
Ensure the translated Python code behaves exactly like the original C snippet.
#include<stdlib.h> #include<stdio.h> #include<complex.h> typedef struct { int rows, cols; complex **z; } matrix; matrix transpose (matrix a) { int i, j; matrix b; b.rows = a.cols; b.cols = a.rows; b.z = malloc (b.rows * sizeof (complex *)); for (i = 0; i < b.rows; i++) { b.z[i] = malloc (b.cols * sizeof (complex)); for (j = 0; j < b.cols; j++) { b.z[i][j] = conj (a.z[j][i]); } } return b; } int isHermitian (matrix a) { int i, j; matrix b = transpose (a); if (b.rows == a.rows && b.cols == a.cols) { for (i = 0; i < b.rows; i++) { for (j = 0; j < b.cols; j++) { if (b.z[i][j] != a.z[i][j]) return 0; } } } else return 0; return 1; } matrix multiply (matrix a, matrix b) { matrix c; int i, j; if (a.cols == b.rows) { c.rows = a.rows; c.cols = b.cols; c.z = malloc (c.rows * (sizeof (complex *))); for (i = 0; i < c.rows; i++) { c.z[i] = malloc (c.cols * sizeof (complex)); c.z[i][j] = 0 + 0 * I; for (j = 0; j < b.cols; j++) { c.z[i][j] += a.z[i][j] * b.z[j][i]; } } } return c; } int isNormal (matrix a) { int i, j; matrix a_ah, ah_a; if (a.rows != a.cols) return 0; a_ah = multiply (a, transpose (a)); ah_a = multiply (transpose (a), a); for (i = 0; i < a.rows; i++) { for (j = 0; j < a.cols; j++) { if (a_ah.z[i][j] != ah_a.z[i][j]) return 0; } } return 1; } int isUnitary (matrix a) { matrix b; int i, j; if (isNormal (a) == 1) { b = multiply (a, transpose(a)); for (i = 0; i < b.rows; i++) { for (j = 0; j < b.cols; j++) { if ((i == j && b.z[i][j] != 1) || (i != j && b.z[i][j] != 0)) return 0; } } return 1; } return 0; } int main () { complex z = 3 + 4 * I; matrix a, aT; int i, j; printf ("Enter rows and columns :"); scanf ("%d%d", &a.rows, &a.cols); a.z = malloc (a.rows * sizeof (complex *)); printf ("Randomly Generated Complex Matrix A is : "); for (i = 0; i < a.rows; i++) { printf ("\n"); a.z[i] = malloc (a.cols * sizeof (complex)); for (j = 0; j < a.cols; j++) { a.z[i][j] = rand () % 10 + rand () % 10 * I; printf ("\t%f + %fi", creal (a.z[i][j]), cimag (a.z[i][j])); } } aT = transpose (a); printf ("\n\nTranspose of Complex Matrix A is : "); for (i = 0; i < aT.rows; i++) { printf ("\n"); aT.z[i] = malloc (aT.cols * sizeof (complex)); for (j = 0; j < aT.cols; j++) { aT.z[i][j] = rand () % 10 + rand () % 10 * I; printf ("\t%f + %fi", creal (aT.z[i][j]), cimag (aT.z[i][j])); } } printf ("\n\nComplex Matrix A %s hermitian", isHermitian (a) == 1 ? "is" : "is not"); printf ("\n\nComplex Matrix A %s unitary", isUnitary (a) == 1 ? "is" : "is not"); printf ("\n\nComplex Matrix A %s normal", isNormal (a) == 1 ? "is" : "is not"); return 0; }
def conjugate_transpose(m): return tuple(tuple(n.conjugate() for n in row) for row in zip(*m)) def mmul( ma, mb): return tuple(tuple(sum( ea*eb for ea,eb in zip(a,b)) for b in zip(*mb)) for a in ma) def mi(size): 'Complex Identity matrix' sz = range(size) m = [[0 + 0j for i in sz] for j in sz] for i in range(size): m[i][i] = 1 + 0j return tuple(tuple(row) for row in m) def __allsame(vector): first, rest = vector[0], vector[1:] return all(i == first for i in rest) def __allnearsame(vector, eps=1e-14): first, rest = vector[0], vector[1:] return all(abs(first.real - i.real) < eps and abs(first.imag - i.imag) < eps for i in rest) def isequal(matrices, eps=1e-14): 'Check any number of matrices for equality within eps' x = [len(m) for m in matrices] if not __allsame(x): return False y = [len(m[0]) for m in matrices] if not __allsame(y): return False for s in range(x[0]): for t in range(y[0]): if not __allnearsame([m[s][t] for m in matrices], eps): return False return True def ishermitian(m, ct): return isequal([m, ct]) def isnormal(m, ct): return isequal([mmul(m, ct), mmul(ct, m)]) def isunitary(m, ct): mct, ctm = mmul(m, ct), mmul(ct, m) mctx, mcty, cmx, ctmy = len(mct), len(mct[0]), len(ctm), len(ctm[0]) ident = mi(mctx) return isequal([mct, ctm, ident]) def printm(comment, m): print(comment) fields = [['%g%+gj' % (f.real, f.imag) for f in row] for row in m] width = max(max(len(f) for f in row) for row in fields) lines = (', '.join('%*s' % (width, f) for f in row) for row in fields) print('\n'.join(lines)) if __name__ == '__main__': for matrix in [ ((( 3.000+0.000j), (+2.000+1.000j)), (( 2.000-1.000j), (+1.000+0.000j))), ((( 1.000+0.000j), (+1.000+0.000j), (+0.000+0.000j)), (( 0.000+0.000j), (+1.000+0.000j), (+1.000+0.000j)), (( 1.000+0.000j), (+0.000+0.000j), (+1.000+0.000j))), ((( 2**0.5/2+0.000j), (+2**0.5/2+0.000j), (+0.000+0.000j)), (( 0.000+2**0.5/2j), (+0.000-2**0.5/2j), (+0.000+0.000j)), (( 0.000+0.000j), (+0.000+0.000j), (+0.000+1.000j)))]: printm('\nMatrix:', matrix) ct = conjugate_transpose(matrix) printm('Its conjugate transpose:', ct) print('Hermitian? %s.' % ishermitian(matrix, ct)) print('Normal? %s.' % isnormal(matrix, ct)) print('Unitary? %s.' % isunitary(matrix, ct))
Produce a functionally identical Python code for the snippet given in C.
#include <stdio.h> #include <gmp.h> void jacobsthal(mpz_t r, unsigned long n) { mpz_t s; mpz_init(s); mpz_set_ui(r, 1); mpz_mul_2exp(r, r, n); mpz_set_ui(s, 1); if (n % 2) mpz_neg(s, s); mpz_sub(r, r, s); mpz_div_ui(r, r, 3); } void jacobsthal_lucas(mpz_t r, unsigned long n) { mpz_t a; mpz_init(a); mpz_set_ui(r, 1); mpz_mul_2exp(r, r, n); mpz_set_ui(a, 1); if (n % 2) mpz_neg(a, a); mpz_add(r, r, a); } int main() { int i, count; mpz_t jac[30], j; printf("First 30 Jacobsthal numbers:\n"); for (i = 0; i < 30; ++i) { mpz_init(jac[i]); jacobsthal(jac[i], i); gmp_printf("%9Zd ", jac[i]); if (!((i+1)%5)) printf("\n"); } printf("\nFirst 30 Jacobsthal-Lucas numbers:\n"); mpz_init(j); for (i = 0; i < 30; ++i) { jacobsthal_lucas(j, i); gmp_printf("%9Zd ", j); if (!((i+1)%5)) printf("\n"); } printf("\nFirst 20 Jacobsthal oblong numbers:\n"); for (i = 0; i < 20; ++i) { mpz_mul(j, jac[i], jac[i+1]); gmp_printf("%11Zd ", j); if (!((i+1)%5)) printf("\n"); } printf("\nFirst 20 Jacobsthal primes:\n"); for (i = 0, count = 0; count < 20; ++i) { jacobsthal(j, i); if (mpz_probab_prime_p(j, 15) > 0) { gmp_printf("%Zd\n", j); ++count; } } return 0; }
from math import floor, pow def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True def odd(n): return n and 1 != 0 def jacobsthal(n): return floor((pow(2,n)+odd(n))/3) def jacobsthal_lucas(n): return int(pow(2,n)+pow(-1,n)) def jacobsthal_oblong(n): return jacobsthal(n)*jacobsthal(n+1) if __name__ == '__main__': print("First 30 Jacobsthal numbers:") for j in range(0, 30): print(jacobsthal(j), end=" ") print("\n\nFirst 30 Jacobsthal-Lucas numbers: ") for j in range(0, 30): print(jacobsthal_lucas(j), end = '\t') print("\n\nFirst 20 Jacobsthal oblong numbers: ") for j in range(0, 20): print(jacobsthal_oblong(j), end=" ") print("\n\nFirst 10 Jacobsthal primes: ") for j in range(3, 33): if isPrime(jacobsthal(j)): print(jacobsthal(j))
Can you help me rewrite this code in Python instead of C, keeping it the same logically?
#include <stdio.h> #include <gmp.h> void jacobsthal(mpz_t r, unsigned long n) { mpz_t s; mpz_init(s); mpz_set_ui(r, 1); mpz_mul_2exp(r, r, n); mpz_set_ui(s, 1); if (n % 2) mpz_neg(s, s); mpz_sub(r, r, s); mpz_div_ui(r, r, 3); } void jacobsthal_lucas(mpz_t r, unsigned long n) { mpz_t a; mpz_init(a); mpz_set_ui(r, 1); mpz_mul_2exp(r, r, n); mpz_set_ui(a, 1); if (n % 2) mpz_neg(a, a); mpz_add(r, r, a); } int main() { int i, count; mpz_t jac[30], j; printf("First 30 Jacobsthal numbers:\n"); for (i = 0; i < 30; ++i) { mpz_init(jac[i]); jacobsthal(jac[i], i); gmp_printf("%9Zd ", jac[i]); if (!((i+1)%5)) printf("\n"); } printf("\nFirst 30 Jacobsthal-Lucas numbers:\n"); mpz_init(j); for (i = 0; i < 30; ++i) { jacobsthal_lucas(j, i); gmp_printf("%9Zd ", j); if (!((i+1)%5)) printf("\n"); } printf("\nFirst 20 Jacobsthal oblong numbers:\n"); for (i = 0; i < 20; ++i) { mpz_mul(j, jac[i], jac[i+1]); gmp_printf("%11Zd ", j); if (!((i+1)%5)) printf("\n"); } printf("\nFirst 20 Jacobsthal primes:\n"); for (i = 0, count = 0; count < 20; ++i) { jacobsthal(j, i); if (mpz_probab_prime_p(j, 15) > 0) { gmp_printf("%Zd\n", j); ++count; } } return 0; }
from math import floor, pow def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True def odd(n): return n and 1 != 0 def jacobsthal(n): return floor((pow(2,n)+odd(n))/3) def jacobsthal_lucas(n): return int(pow(2,n)+pow(-1,n)) def jacobsthal_oblong(n): return jacobsthal(n)*jacobsthal(n+1) if __name__ == '__main__': print("First 30 Jacobsthal numbers:") for j in range(0, 30): print(jacobsthal(j), end=" ") print("\n\nFirst 30 Jacobsthal-Lucas numbers: ") for j in range(0, 30): print(jacobsthal_lucas(j), end = '\t') print("\n\nFirst 20 Jacobsthal oblong numbers: ") for j in range(0, 20): print(jacobsthal_oblong(j), end=" ") print("\n\nFirst 10 Jacobsthal primes: ") for j in range(3, 33): if isPrime(jacobsthal(j)): print(jacobsthal(j))
Write the same algorithm in Python as shown in this C implementation.
#include <stdio.h> #include <stdlib.h> void bead_sort(int *a, int len) { int i, j, max, sum; unsigned char *beads; # define BEAD(i, j) beads[i * max + j] for (i = 1, max = a[0]; i < len; i++) if (a[i] > max) max = a[i]; beads = calloc(1, max * len); for (i = 0; i < len; i++) for (j = 0; j < a[i]; j++) BEAD(i, j) = 1; for (j = 0; j < max; j++) { for (sum = i = 0; i < len; i++) { sum += BEAD(i, j); BEAD(i, j) = 0; } for (i = len - sum; i < len; i++) BEAD(i, j) = 1; } for (i = 0; i < len; i++) { for (j = 0; j < max && BEAD(i, j); j++); a[i] = j; } free(beads); } int main() { int i, x[] = {5, 3, 1, 7, 4, 1, 1, 20}; int len = sizeof(x)/sizeof(x[0]); bead_sort(x, len); for (i = 0; i < len; i++) printf("%d\n", x[i]); return 0; }
from itertools import zip_longest def beadsort(l): return list(map(sum, zip_longest(*[[1] * e for e in l], fillvalue=0))) print(beadsort([5,3,1,7,4,1,1]))
Translate the given C code snippet into Python without altering its behavior.
#include <stdio.h> #define GRID_SIZE 15 char canvas[GRID_SIZE][GRID_SIZE]; void initN() { int i, j; for (i = 0; i < GRID_SIZE; i++) { for (j = 0; j < GRID_SIZE; j++) { canvas[i][j] = ' '; } canvas[i][5] = 'x'; } } void horizontal(size_t c1, size_t c2, size_t r) { size_t c; for (c = c1; c <= c2; c++) { canvas[r][c] = 'x'; } } void vertical(size_t r1, size_t r2, size_t c) { size_t r; for (r = r1; r <= r2; r++) { canvas[r][c] = 'x'; } } void diagd(size_t c1, size_t c2, size_t r) { size_t c; for (c = c1; c <= c2; c++) { canvas[r + c - c1][c] = 'x'; } } void diagu(size_t c1, size_t c2, size_t r) { size_t c; for (c = c1; c <= c2; c++) { canvas[r - c + c1][c] = 'x'; } } void drawOnes(int v) { switch (v) { case 1: horizontal(6, 10, 0); break; case 2: horizontal(6, 10, 4); break; case 3: diagd(6, 10, 0); break; case 4: diagu(6, 10, 4); break; case 5: drawOnes(1); drawOnes(4); break; case 6: vertical(0, 4, 10); break; case 7: drawOnes(1); drawOnes(6); break; case 8: drawOnes(2); drawOnes(6); break; case 9: drawOnes(1); drawOnes(8); break; default: break; } } void drawTens(int v) { switch (v) { case 1: horizontal(0, 4, 0); break; case 2: horizontal(0, 4, 4); break; case 3: diagu(0, 4, 4); break; case 4: diagd(0, 4, 0); break; case 5: drawTens(1); drawTens(4); break; case 6: vertical(0, 4, 0); break; case 7: drawTens(1); drawTens(6); break; case 8: drawTens(2); drawTens(6); break; case 9: drawTens(1); drawTens(8); break; default: break; } } void drawHundreds(int hundreds) { switch (hundreds) { case 1: horizontal(6, 10, 14); break; case 2: horizontal(6, 10, 10); break; case 3: diagu(6, 10, 14); break; case 4: diagd(6, 10, 10); break; case 5: drawHundreds(1); drawHundreds(4); break; case 6: vertical(10, 14, 10); break; case 7: drawHundreds(1); drawHundreds(6); break; case 8: drawHundreds(2); drawHundreds(6); break; case 9: drawHundreds(1); drawHundreds(8); break; default: break; } } void drawThousands(int thousands) { switch (thousands) { case 1: horizontal(0, 4, 14); break; case 2: horizontal(0, 4, 10); break; case 3: diagd(0, 4, 10); break; case 4: diagu(0, 4, 14); break; case 5: drawThousands(1); drawThousands(4); break; case 6: vertical(10, 14, 0); break; case 7: drawThousands(1); drawThousands(6); break; case 8: drawThousands(2); drawThousands(6); break; case 9: drawThousands(1); drawThousands(8); break; default: break; } } void draw(int v) { int thousands = v / 1000; v %= 1000; int hundreds = v / 100; v %= 100; int tens = v / 10; int ones = v % 10; if (thousands > 0) { drawThousands(thousands); } if (hundreds > 0) { drawHundreds(hundreds); } if (tens > 0) { drawTens(tens); } if (ones > 0) { drawOnes(ones); } } void write(FILE *out) { int i; for (i = 0; i < GRID_SIZE; i++) { fprintf(out, "%-.*s", GRID_SIZE, canvas[i]); putc('\n', out); } } void test(int n) { printf("%d:\n", n); initN(); draw(n); write(stdout); printf("\n\n"); } int main() { test(0); test(1); test(20); test(300); test(4000); test(5555); test(6789); test(9999); return 0; }
def _init(): "digit sections for forming numbers" digi_bits = .strip() lines = [[d.replace('.', ' ') for d in ln.strip().split()] for ln in digi_bits.strip().split('\n') if ' formats = '<2 >2 <2 >2'.split() digits = [[f"{dig:{f}}" for dig in line] for f, line in zip(formats, lines)] return digits _digits = _init() def _to_digits(n): assert 0 <= n < 10_000 and int(n) == n return [int(digit) for digit in f"{int(n):04}"][::-1] def num_to_lines(n): global _digits d = _to_digits(n) lines = [ ''.join((_digits[1][d[1]], '┃', _digits[0][d[0]])), ''.join((_digits[0][ 0], '┃', _digits[0][ 0])), ''.join((_digits[3][d[3]], '┃', _digits[2][d[2]])), ] return lines def cjoin(c1, c2, spaces=' '): return [spaces.join(by_row) for by_row in zip(c1, c2)] if __name__ == '__main__': for pow10 in range(4): step = 10 ** pow10 print(f'\nArabic {step}-to-{9*step} by {step} in Cistercian:\n') lines = num_to_lines(step) for n in range(step*2, step*10, step): lines = cjoin(lines, num_to_lines(n)) print('\n'.join(lines)) numbers = [0, 5555, 6789, 6666] print(f'\nArabic {str(numbers)[1:-1]} in Cistercian:\n') lines = num_to_lines(numbers[0]) for n in numbers[1:]: lines = cjoin(lines, num_to_lines(n)) print('\n'.join(lines))
Preserve the algorithm and functionality while converting the code from C to Python.
#include <stdio.h> #define GRID_SIZE 15 char canvas[GRID_SIZE][GRID_SIZE]; void initN() { int i, j; for (i = 0; i < GRID_SIZE; i++) { for (j = 0; j < GRID_SIZE; j++) { canvas[i][j] = ' '; } canvas[i][5] = 'x'; } } void horizontal(size_t c1, size_t c2, size_t r) { size_t c; for (c = c1; c <= c2; c++) { canvas[r][c] = 'x'; } } void vertical(size_t r1, size_t r2, size_t c) { size_t r; for (r = r1; r <= r2; r++) { canvas[r][c] = 'x'; } } void diagd(size_t c1, size_t c2, size_t r) { size_t c; for (c = c1; c <= c2; c++) { canvas[r + c - c1][c] = 'x'; } } void diagu(size_t c1, size_t c2, size_t r) { size_t c; for (c = c1; c <= c2; c++) { canvas[r - c + c1][c] = 'x'; } } void drawOnes(int v) { switch (v) { case 1: horizontal(6, 10, 0); break; case 2: horizontal(6, 10, 4); break; case 3: diagd(6, 10, 0); break; case 4: diagu(6, 10, 4); break; case 5: drawOnes(1); drawOnes(4); break; case 6: vertical(0, 4, 10); break; case 7: drawOnes(1); drawOnes(6); break; case 8: drawOnes(2); drawOnes(6); break; case 9: drawOnes(1); drawOnes(8); break; default: break; } } void drawTens(int v) { switch (v) { case 1: horizontal(0, 4, 0); break; case 2: horizontal(0, 4, 4); break; case 3: diagu(0, 4, 4); break; case 4: diagd(0, 4, 0); break; case 5: drawTens(1); drawTens(4); break; case 6: vertical(0, 4, 0); break; case 7: drawTens(1); drawTens(6); break; case 8: drawTens(2); drawTens(6); break; case 9: drawTens(1); drawTens(8); break; default: break; } } void drawHundreds(int hundreds) { switch (hundreds) { case 1: horizontal(6, 10, 14); break; case 2: horizontal(6, 10, 10); break; case 3: diagu(6, 10, 14); break; case 4: diagd(6, 10, 10); break; case 5: drawHundreds(1); drawHundreds(4); break; case 6: vertical(10, 14, 10); break; case 7: drawHundreds(1); drawHundreds(6); break; case 8: drawHundreds(2); drawHundreds(6); break; case 9: drawHundreds(1); drawHundreds(8); break; default: break; } } void drawThousands(int thousands) { switch (thousands) { case 1: horizontal(0, 4, 14); break; case 2: horizontal(0, 4, 10); break; case 3: diagd(0, 4, 10); break; case 4: diagu(0, 4, 14); break; case 5: drawThousands(1); drawThousands(4); break; case 6: vertical(10, 14, 0); break; case 7: drawThousands(1); drawThousands(6); break; case 8: drawThousands(2); drawThousands(6); break; case 9: drawThousands(1); drawThousands(8); break; default: break; } } void draw(int v) { int thousands = v / 1000; v %= 1000; int hundreds = v / 100; v %= 100; int tens = v / 10; int ones = v % 10; if (thousands > 0) { drawThousands(thousands); } if (hundreds > 0) { drawHundreds(hundreds); } if (tens > 0) { drawTens(tens); } if (ones > 0) { drawOnes(ones); } } void write(FILE *out) { int i; for (i = 0; i < GRID_SIZE; i++) { fprintf(out, "%-.*s", GRID_SIZE, canvas[i]); putc('\n', out); } } void test(int n) { printf("%d:\n", n); initN(); draw(n); write(stdout); printf("\n\n"); } int main() { test(0); test(1); test(20); test(300); test(4000); test(5555); test(6789); test(9999); return 0; }
def _init(): "digit sections for forming numbers" digi_bits = .strip() lines = [[d.replace('.', ' ') for d in ln.strip().split()] for ln in digi_bits.strip().split('\n') if ' formats = '<2 >2 <2 >2'.split() digits = [[f"{dig:{f}}" for dig in line] for f, line in zip(formats, lines)] return digits _digits = _init() def _to_digits(n): assert 0 <= n < 10_000 and int(n) == n return [int(digit) for digit in f"{int(n):04}"][::-1] def num_to_lines(n): global _digits d = _to_digits(n) lines = [ ''.join((_digits[1][d[1]], '┃', _digits[0][d[0]])), ''.join((_digits[0][ 0], '┃', _digits[0][ 0])), ''.join((_digits[3][d[3]], '┃', _digits[2][d[2]])), ] return lines def cjoin(c1, c2, spaces=' '): return [spaces.join(by_row) for by_row in zip(c1, c2)] if __name__ == '__main__': for pow10 in range(4): step = 10 ** pow10 print(f'\nArabic {step}-to-{9*step} by {step} in Cistercian:\n') lines = num_to_lines(step) for n in range(step*2, step*10, step): lines = cjoin(lines, num_to_lines(n)) print('\n'.join(lines)) numbers = [0, 5555, 6789, 6666] print(f'\nArabic {str(numbers)[1:-1]} in Cistercian:\n') lines = num_to_lines(numbers[0]) for n in numbers[1:]: lines = cjoin(lines, num_to_lines(n)) print('\n'.join(lines))
Maintain the same structure and functionality when rewriting this code in Python.
#include <gmp.h> #include <stdio.h> #include <string.h> int main() { mpz_t a; mpz_init_set_ui(a, 5); mpz_pow_ui(a, a, 1 << 18); int len = mpz_sizeinbase(a, 10); printf("GMP says size is: %d\n", len); char *s = mpz_get_str(0, 10, a); printf("size really is %d\n", len = strlen(s)); printf("Digits: %.20s...%s\n", s, s + len - 20); return 0; }
>>> y = str( 5**4**3**2 ) >>> print ("5**4**3**2 = %s...%s and has %i digits" % (y[:20], y[-20:], len(y))) 5**4**3**2 = 62060698786608744707...92256259918212890625 and has 183231 digits
Produce a functionally identical Python code for the snippet given in C.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <math.h> const char *shades = ".:!*oe&#%@"; double light[3] = { 30, 30, -50 }; void normalize(double * v) { double len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]); v[0] /= len; v[1] /= len; v[2] /= len; } double dot(double *x, double *y) { double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]; return d < 0 ? -d : 0; } void draw_sphere(double R, double k, double ambient) { int i, j, intensity; double b; double vec[3], x, y; for (i = floor(-R); i <= ceil(R); i++) { x = i + .5; for (j = floor(-2 * R); j <= ceil(2 * R); j++) { y = j / 2. + .5; if (x * x + y * y <= R * R) { vec[0] = x; vec[1] = y; vec[2] = sqrt(R * R - x * x - y * y); normalize(vec); b = pow(dot(light, vec), k) + ambient; intensity = (1 - b) * (sizeof(shades) - 1); if (intensity < 0) intensity = 0; if (intensity >= sizeof(shades) - 1) intensity = sizeof(shades) - 2; putchar(shades[intensity]); } else putchar(' '); } putchar('\n'); } } int main() { normalize(light); draw_sphere(20, 4, .1); draw_sphere(10, 2, .4); return 0; }
import math shades = ('.',':','!','*','o','e','&',' def normalize(v): len = math.sqrt(v[0]**2 + v[1]**2 + v[2]**2) return (v[0]/len, v[1]/len, v[2]/len) def dot(x,y): d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2] return -d if d < 0 else 0 def draw_sphere(r, k, ambient, light): for i in range(int(math.floor(-r)),int(math.ceil(r)+1)): x = i + 0.5 line = '' for j in range(int(math.floor(-2*r)),int(math.ceil(2*r)+1)): y = j/2 + 0.5 if x*x + y*y <= r*r: vec = normalize((x,y,math.sqrt(r*r - x*x - y*y))) b = dot(light,vec)**k + ambient intensity = int((1-b)*(len(shades)-1)) line += shades[intensity] if 0 <= intensity < len(shades) else shades[0] else: line += ' ' print(line) light = normalize((30,30,-50)) draw_sphere(20,4,0.1, light) draw_sphere(10,2,0.4, light)
Change the following C code into Python without altering its purpose.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <math.h> const char *shades = ".:!*oe&#%@"; double light[3] = { 30, 30, -50 }; void normalize(double * v) { double len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]); v[0] /= len; v[1] /= len; v[2] /= len; } double dot(double *x, double *y) { double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]; return d < 0 ? -d : 0; } void draw_sphere(double R, double k, double ambient) { int i, j, intensity; double b; double vec[3], x, y; for (i = floor(-R); i <= ceil(R); i++) { x = i + .5; for (j = floor(-2 * R); j <= ceil(2 * R); j++) { y = j / 2. + .5; if (x * x + y * y <= R * R) { vec[0] = x; vec[1] = y; vec[2] = sqrt(R * R - x * x - y * y); normalize(vec); b = pow(dot(light, vec), k) + ambient; intensity = (1 - b) * (sizeof(shades) - 1); if (intensity < 0) intensity = 0; if (intensity >= sizeof(shades) - 1) intensity = sizeof(shades) - 2; putchar(shades[intensity]); } else putchar(' '); } putchar('\n'); } } int main() { normalize(light); draw_sphere(20, 4, .1); draw_sphere(10, 2, .4); return 0; }
import math shades = ('.',':','!','*','o','e','&',' def normalize(v): len = math.sqrt(v[0]**2 + v[1]**2 + v[2]**2) return (v[0]/len, v[1]/len, v[2]/len) def dot(x,y): d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2] return -d if d < 0 else 0 def draw_sphere(r, k, ambient, light): for i in range(int(math.floor(-r)),int(math.ceil(r)+1)): x = i + 0.5 line = '' for j in range(int(math.floor(-2*r)),int(math.ceil(2*r)+1)): y = j/2 + 0.5 if x*x + y*y <= r*r: vec = normalize((x,y,math.sqrt(r*r - x*x - y*y))) b = dot(light,vec)**k + ambient intensity = int((1-b)*(len(shades)-1)) line += shades[intensity] if 0 <= intensity < len(shades) else shades[0] else: line += ' ' print(line) light = normalize((30,30,-50)) draw_sphere(20,4,0.1, light) draw_sphere(10,2,0.4, light)
Convert this C block to Python, preserving its control flow and logic.
#include <stdio.h> #include <stdlib.h> char chr_legal[] = "abcdefghijklmnopqrstuvwxyz0123456789_-./"; int chr_idx[256] = {0}; char idx_chr[256] = {0}; #define FNAME 0 typedef struct trie_t *trie, trie_t; struct trie_t { trie next[sizeof(chr_legal)]; int eow; }; trie trie_new() { return calloc(sizeof(trie_t), 1); } #define find_word(r, w) trie_trav(r, w, 1) trie trie_trav(trie root, const char * str, int no_create) { int c; while (root) { if ((c = str[0]) == '\0') { if (!root->eow && no_create) return 0; break; } if (! (c = chr_idx[c]) ) { str++; continue; } if (!root->next[c]) { if (no_create) return 0; root->next[c] = trie_new(); } root = root->next[c]; str++; } return root; } int trie_all(trie root, char path[], int depth, int (*callback)(char *)) { int i; if (root->eow && !callback(path)) return 0; for (i = 1; i < sizeof(chr_legal); i++) { if (!root->next[i]) continue; path[depth] = idx_chr[i]; path[depth + 1] = '\0'; if (!trie_all(root->next[i], path, depth + 1, callback)) return 0; } return 1; } void add_index(trie root, const char *word, const char *fname) { trie x = trie_trav(root, word, 0); x->eow = 1; if (!x->next[FNAME]) x->next[FNAME] = trie_new(); x = trie_trav(x->next[FNAME], fname, 0); x->eow = 1; } int print_path(char *path) { printf(" %s", path); return 1; } const char *files[] = { "f1.txt", "source/f2.txt", "other_file" }; const char *text[][5] ={{ "it", "is", "what", "it", "is" }, { "what", "is", "it", 0 }, { "it", "is", "a", "banana", 0 }}; trie init_tables() { int i, j; trie root = trie_new(); for (i = 0; i < sizeof(chr_legal); i++) { chr_idx[(int)chr_legal[i]] = i + 1; idx_chr[i + 1] = chr_legal[i]; } #define USE_ADVANCED_FILE_HANDLING 0 #if USE_ADVANCED_FILE_HANDLING void read_file(const char * fname) { char cmd[1024]; char word[1024]; sprintf(cmd, "perl -p -e 'while(/(\\w+)/g) {print lc($1),\"\\n\"}' %s", fname); FILE *in = popen(cmd, "r"); while (!feof(in)) { fscanf(in, "%1000s", word); add_index(root, word, fname); } pclose(in); }; read_file("f1.txt"); read_file("source/f2.txt"); read_file("other_file"); #else for (i = 0; i < 3; i++) { for (j = 0; j < 5; j++) { if (!text[i][j]) break; add_index(root, text[i][j], files[i]); } } #endif return root; } void search_index(trie root, const char *word) { char path[1024]; printf("Search for \"%s\": ", word); trie found = find_word(root, word); if (!found) printf("not found\n"); else { trie_all(found->next[FNAME], path, 0, print_path); printf("\n"); } } int main() { trie root = init_tables(); search_index(root, "what"); search_index(root, "is"); search_index(root, "banana"); search_index(root, "boo"); return 0; }
from pprint import pprint as pp from glob import glob try: reduce except: from functools import reduce try: raw_input except: raw_input = input def parsetexts(fileglob='InvertedIndex/T*.txt'): texts, words = {}, set() for txtfile in glob(fileglob): with open(txtfile, 'r') as f: txt = f.read().split() words |= set(txt) texts[txtfile.split('\\')[-1]] = txt return texts, words def termsearch(terms): return reduce(set.intersection, (invindex[term] for term in terms), set(texts.keys())) texts, words = parsetexts() print('\nTexts') pp(texts) print('\nWords') pp(sorted(words)) invindex = {word:set(txt for txt, wrds in texts.items() if word in wrds) for word in words} print('\nInverted Index') pp({k:sorted(v) for k,v in invindex.items()}) terms = ["what", "is", "it"] print('\nTerm Search for: ' + repr(terms)) pp(sorted(termsearch(terms)))
Transform the following C implementation into Python, maintaining the same output and logic.
#include <stdio.h> int gcd(int m, int n) { int tmp; while(m) { tmp = m; m = n % m; n = tmp; } return n; } int lcm(int m, int n) { return m / gcd(m, n) * n; } int main() { printf("lcm(35, 21) = %d\n", lcm(21,35)); return 0; }
>>> import fractions >>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0 >>> lcm(12, 18) 36 >>> lcm(-6, 14) 42 >>> assert lcm(0, 2) == lcm(2, 0) == 0 >>>
Convert this C block to Python, preserving its control flow and logic.
#include <stdio.h> int gcd(int m, int n) { int tmp; while(m) { tmp = m; m = n % m; n = tmp; } return n; } int lcm(int m, int n) { return m / gcd(m, n) * n; } int main() { printf("lcm(35, 21) = %d\n", lcm(21,35)); return 0; }
>>> import fractions >>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0 >>> lcm(12, 18) 36 >>> lcm(-6, 14) 42 >>> assert lcm(0, 2) == lcm(2, 0) == 0 >>>
Change the programming language of this snippet from C to Python without modifying what it does.
#include <stdio.h> int gcd(int m, int n) { int tmp; while(m) { tmp = m; m = n % m; n = tmp; } return n; } int lcm(int m, int n) { return m / gcd(m, n) * n; } int main() { printf("lcm(35, 21) = %d\n", lcm(21,35)); return 0; }
>>> import fractions >>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0 >>> lcm(12, 18) 36 >>> lcm(-6, 14) 42 >>> assert lcm(0, 2) == lcm(2, 0) == 0 >>>
Transform the following C implementation into Python, maintaining the same output and logic.
#include <stdlib.h> #include <stdio.h> #include <gmp.h> void mpz_factors(mpz_t n) { int factors = 0; mpz_t s, m, p; mpz_init(s), mpz_init(m), mpz_init(p); mpz_set_ui(m, 3); mpz_set(p, n); mpz_sqrt(s, p); while (mpz_cmp(m, s) < 0) { if (mpz_divisible_p(p, m)) { gmp_printf("%Zd ", m); mpz_fdiv_q(p, p, m); mpz_sqrt(s, p); factors ++; } mpz_add_ui(m, m, 2); } if (factors == 0) printf("PRIME\n"); else gmp_printf("%Zd\n", p); } int main(int argc, char const *argv[]) { mpz_t fermat; mpz_init_set_ui(fermat, 3); printf("F(0) = 3 -> PRIME\n"); for (unsigned i = 1; i < 10; i ++) { mpz_sub_ui(fermat, fermat, 1); mpz_mul(fermat, fermat, fermat); mpz_add_ui(fermat, fermat, 1); gmp_printf("F(%d) = %Zd -> ", i, fermat); mpz_factors(fermat); } return 0; }
def factors(x): factors = [] i = 2 s = int(x ** 0.5) while i < s: if x % i == 0: factors.append(i) x = int(x / i) s = int(x ** 0.5) i += 1 factors.append(x) return factors print("First 10 Fermat numbers:") for i in range(10): fermat = 2 ** 2 ** i + 1 print("F{} = {}".format(chr(i + 0x2080) , fermat)) print("\nFactors of first few Fermat numbers:") for i in range(10): fermat = 2 ** 2 ** i + 1 fac = factors(fermat) if len(fac) == 1: print("F{} -> IS PRIME".format(chr(i + 0x2080))) else: print("F{} -> FACTORS: {}".format(chr(i + 0x2080), fac))
Rewrite the snippet below in Python so it works the same as the original C code.
int main(){ time_t t; int a, b; srand((unsigned)time(&t)); for(;;){ a = rand() % 20; printf("%d\n", a); if(a == 10) break; b = rand() % 20; printf("%d\n", b); } return 0; }
from random import randrange while True: a = randrange(20) print(a) if a == 10: break b = randrange(20) print(b)
Generate an equivalent Python version of this C code.
#include <stdio.h> int main() { FILE *lp; lp = fopen("/dev/lp0","w"); fprintf(lp,"Hello world!\n"); fclose(lp); return 0; }
lp = open("/dev/lp0") lp.write("Hello World!\n") lp.close()
Translate the given C code snippet into Python without altering its behavior.
#include <stdio.h> int main() { FILE *lp; lp = fopen("/dev/lp0","w"); fprintf(lp,"Hello world!\n"); fclose(lp); return 0; }
lp = open("/dev/lp0") lp.write("Hello World!\n") lp.close()
Translate this program into Python but keep the logic exactly as in C.
#include<stdlib.h> #include<stdio.h> int getWater(int* arr,int start,int end,int cutoff){ int i, sum = 0; for(i=start;i<=end;i++) sum += ((arr[cutoff] > arr[i])?(arr[cutoff] - arr[i]):0); return sum; } int netWater(int* arr,int size){ int i, j, ref1, ref2, marker, markerSet = 0,sum = 0; if(size<3) return 0; for(i=0;i<size-1;i++){ start:if(i!=size-2 && arr[i]>arr[i+1]){ ref1 = i; for(j=ref1+1;j<size;j++){ if(arr[j]>=arr[ref1]){ ref2 = j; sum += getWater(arr,ref1+1,ref2-1,ref1); i = ref2; goto start; } else if(j!=size-1 && arr[j] < arr[j+1] && (markerSet==0||(arr[j+1]>=arr[marker]))){ marker = j+1; markerSet = 1; } } if(markerSet==1){ sum += getWater(arr,ref1+1,marker-1,marker); i = marker; markerSet = 0; goto start; } } } return sum; } int main(int argC,char* argV[]) { int *arr,i; if(argC==1) printf("Usage : %s <followed by space separated series of integers>"); else{ arr = (int*)malloc((argC-1)*sizeof(int)); for(i=1;i<argC;i++) arr[i-1] = atoi(argV[i]); printf("Water collected : %d",netWater(arr,argC-1)); } return 0; }
def water_collected(tower): N = len(tower) highest_left = [0] + [max(tower[:n]) for n in range(1,N)] highest_right = [max(tower[n:N]) for n in range(1,N)] + [0] water_level = [max(min(highest_left[n], highest_right[n]) - tower[n], 0) for n in range(N)] print("highest_left: ", highest_left) print("highest_right: ", highest_right) print("water_level: ", water_level) print("tower_level: ", tower) print("total_water: ", sum(water_level)) print("") return sum(water_level) towers = [[1, 5, 3, 7, 2], [5, 3, 7, 2, 6, 4, 5, 9, 1, 2], [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1], [5, 5, 5, 5], [5, 6, 7, 8], [8, 7, 7, 6], [6, 7, 10, 7, 6]] [water_collected(tower) for tower in towers]
Convert this C block to Python, preserving its control flow and logic.
#include <stdio.h> int ispr(unsigned int n) { if ((n & 1) == 0 || n < 2) return n == 2; for (unsigned int j = 3; j * j <= n; j += 2) if (n % j == 0) return 0; return 1; } int main() { unsigned int c = 0, nc, pc = 9, i, a, b, l, ps[128], nxt[128]; for (a = 0, b = 1; a < pc; a = b++) ps[a] = b; while (1) { nc = 0; for (i = 0; i < pc; i++) { if (ispr(a = ps[i])) printf("%8d%s", a, ++c % 5 == 0 ? "\n" : " "); for (b = a * 10, l = a % 10 + b++; b < l; b++) nxt[nc++] = b; } if (nc > 1) for(i = 0, pc = nc; i < pc; i++) ps[i] = nxt[i]; else break; } printf("\n%d descending primes found", c); }
from sympy import isprime def descending(xs=range(10)): for x in xs: yield x yield from descending(x*10 + d for d in range(x%10)) for i, p in enumerate(sorted(filter(isprime, descending()))): print(f'{p:9d}', end=' ' if (1 + i)%8 else '\n') print()
Change the following C code into Python without altering its purpose.
#include <stdio.h> #include <stdlib.h> #include <math.h> #define TRUE 1 #define FALSE 0 #define TRILLION 1000000000000 typedef unsigned char bool; typedef unsigned long long uint64; void sieve(uint64 limit, uint64 *primes, uint64 *length) { uint64 i, count, p, p2; bool *c = calloc(limit + 1, sizeof(bool)); primes[0] = 2; count = 1; p = 3; for (;;) { p2 = p * p; if (p2 > limit) break; for (i = p2; i <= limit; i += 2 * p) c[i] = TRUE; for (;;) { p += 2; if (!c[p]) break; } } for (i = 3; i <= limit; i += 2) { if (!c[i]) primes[count++] = i; } *length = count; free(c); } void squareFree(uint64 from, uint64 to, uint64 *results, uint64 *len) { uint64 i, j, p, p2, np, count = 0, limit = (uint64)sqrt((double)to); uint64 *primes = malloc((limit + 1) * sizeof(uint64)); bool add; sieve(limit, primes, &np); for (i = from; i <= to; ++i) { add = TRUE; for (j = 0; j < np; ++j) { p = primes[j]; p2 = p * p; if (p2 > i) break; if (i % p2 == 0) { add = FALSE; break; } } if (add) results[count++] = i; } *len = count; free(primes); } int main() { uint64 i, *sf, len; sf = malloc(1000000 * sizeof(uint64)); printf("Square-free integers from 1 to 145:\n"); squareFree(1, 145, sf, &len); for (i = 0; i < len; ++i) { if (i > 0 && i % 20 == 0) { printf("\n"); } printf("%4lld", sf[i]); } printf("\n\nSquare-free integers from %ld to %ld:\n", TRILLION, TRILLION + 145); squareFree(TRILLION, TRILLION + 145, sf, &len); for (i = 0; i < len; ++i) { if (i > 0 && i % 5 == 0) { printf("\n"); } printf("%14lld", sf[i]); } printf("\n\nNumber of square-free integers:\n"); int a[5] = {100, 1000, 10000, 100000, 1000000}; for (i = 0; i < 5; ++i) { squareFree(1, a[i], sf, &len); printf(" from %d to %d = %lld\n", 1, a[i], len); } free(sf); return 0; }
import math def SquareFree ( _number ) : max = (int) (math.sqrt ( _number )) for root in range ( 2, max+1 ): if 0 == _number % ( root * root ): return False return True def ListSquareFrees( _start, _end ): count = 0 for i in range ( _start, _end+1 ): if True == SquareFree( i ): print ( "{}\t".format(i), end="" ) count += 1 print ( "\n\nTotal count of square-free numbers between {} and {}: {}".format(_start, _end, count)) ListSquareFrees( 1, 100 ) ListSquareFrees( 1000000000000, 1000000000145 )
Can you help me rewrite this code in Python instead of C, keeping it the same logically?
#include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdio.h> #define TRUE 1 #define FALSE 0 #define max(a, b) ((a) > (b) ? (a) : (b)) #define min(a, b) ((a) < (b) ? (a) : (b)) double jaro(const char *str1, const char *str2) { int str1_len = strlen(str1); int str2_len = strlen(str2); if (str1_len == 0) return str2_len == 0 ? 1.0 : 0.0; int match_distance = (int) max(str1_len, str2_len)/2 - 1; int *str1_matches = calloc(str1_len, sizeof(int)); int *str2_matches = calloc(str2_len, sizeof(int)); double matches = 0.0; double transpositions = 0.0; for (int i = 0; i < str1_len; i++) { int start = max(0, i - match_distance); int end = min(i + match_distance + 1, str2_len); for (int k = start; k < end; k++) { if (str2_matches[k]) continue; if (str1[i] != str2[k]) continue; str1_matches[i] = TRUE; str2_matches[k] = TRUE; matches++; break; } } if (matches == 0) { free(str1_matches); free(str2_matches); return 0.0; } int k = 0; for (int i = 0; i < str1_len; i++) { if (!str1_matches[i]) continue; while (!str2_matches[k]) k++; if (str1[i] != str2[k]) transpositions++; k++; } transpositions /= 2.0; free(str1_matches); free(str2_matches); return ((matches / str1_len) + (matches / str2_len) + ((matches - transpositions) / matches)) / 3.0; } int main() { printf("%f\n", jaro("MARTHA", "MARHTA")); printf("%f\n", jaro("DIXON", "DICKSONX")); printf("%f\n", jaro("JELLYFISH", "SMELLYFISH")); }
from __future__ import division def jaro(s, t): s_len = len(s) t_len = len(t) if s_len == 0 and t_len == 0: return 1 match_distance = (max(s_len, t_len) // 2) - 1 s_matches = [False] * s_len t_matches = [False] * t_len matches = 0 transpositions = 0 for i in range(s_len): start = max(0, i - match_distance) end = min(i + match_distance + 1, t_len) for j in range(start, end): if t_matches[j]: continue if s[i] != t[j]: continue s_matches[i] = True t_matches[j] = True matches += 1 break if matches == 0: return 0 k = 0 for i in range(s_len): if not s_matches[i]: continue while not t_matches[k]: k += 1 if s[i] != t[k]: transpositions += 1 k += 1 return ((matches / s_len) + (matches / t_len) + ((matches - transpositions / 2) / matches)) / 3 def main(): for s, t in [('MARTHA', 'MARHTA'), ('DIXON', 'DICKSONX'), ('JELLYFISH', 'SMELLYFISH')]: print("jaro(%r, %r) = %.10f" % (s, t, jaro(s, t))) if __name__ == '__main__': main()
Preserve the algorithm and functionality while converting the code from C to Python.
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> typedef struct node_t { int x, y; struct node_t *prev, *next; } node; node *new_node(int x, int y) { node *n = malloc(sizeof(node)); n->x = x; n->y = y; n->next = NULL; n->prev = NULL; return n; } void free_node(node **n) { if (n == NULL) { return; } (*n)->prev = NULL; (*n)->next = NULL; free(*n); *n = NULL; } typedef struct list_t { node *head; node *tail; } list; list make_list() { list lst = { NULL, NULL }; return lst; } void append_node(list *const lst, int x, int y) { if (lst == NULL) { return; } node *n = new_node(x, y); if (lst->head == NULL) { lst->head = n; lst->tail = n; } else { n->prev = lst->tail; lst->tail->next = n; lst->tail = n; } } void remove_node(list *const lst, const node *const n) { if (lst == NULL || n == NULL) { return; } if (n->prev != NULL) { n->prev->next = n->next; if (n->next != NULL) { n->next->prev = n->prev; } else { lst->tail = n->prev; } } else { if (n->next != NULL) { n->next->prev = NULL; lst->head = n->next; } } free_node(&n); } void free_list(list *const lst) { node *ptr; if (lst == NULL) { return; } ptr = lst->head; while (ptr != NULL) { node *nxt = ptr->next; free_node(&ptr); ptr = nxt; } lst->head = NULL; lst->tail = NULL; } void print_list(const list *lst) { node *it; if (lst == NULL) { return; } for (it = lst->head; it != NULL; it = it->next) { int sum = it->x + it->y; int prod = it->x * it->y; printf("[%d, %d] S=%d P=%d\n", it->x, it->y, sum, prod); } } void print_count(const list *const lst) { node *it; int c = 0; if (lst == NULL) { return; } for (it = lst->head; it != NULL; it = it->next) { c++; } if (c == 0) { printf("no candidates\n"); } else if (c == 1) { printf("one candidate\n"); } else { printf("%d candidates\n", c); } } void setup(list *const lst) { int x, y; if (lst == NULL) { return; } for (x = 2; x <= 98; x++) { for (y = x + 1; y <= 98; y++) { if (x + y <= 100) { append_node(lst, x, y); } } } } void remove_by_sum(list *const lst, const int sum) { node *it; if (lst == NULL) { return; } it = lst->head; while (it != NULL) { int s = it->x + it->y; if (s == sum) { remove_node(lst, it); it = lst->head; } else { it = it->next; } } } void remove_by_prod(list *const lst, const int prod) { node *it; if (lst == NULL) { return; } it = lst->head; while (it != NULL) { int p = it->x * it->y; if (p == prod) { remove_node(lst, it); it = lst->head; } else { it = it->next; } } } void statement1(list *const lst) { short *unique = calloc(100000, sizeof(short)); node *it, *nxt; for (it = lst->head; it != NULL; it = it->next) { int prod = it->x * it->y; unique[prod]++; } it = lst->head; while (it != NULL) { int prod = it->x * it->y; nxt = it->next; if (unique[prod] == 1) { remove_by_sum(lst, it->x + it->y); it = lst->head; } else { it = nxt; } } free(unique); } void statement2(list *const candidates) { short *unique = calloc(100000, sizeof(short)); node *it, *nxt; for (it = candidates->head; it != NULL; it = it->next) { int prod = it->x * it->y; unique[prod]++; } it = candidates->head; while (it != NULL) { int prod = it->x * it->y; nxt = it->next; if (unique[prod] > 1) { remove_by_prod(candidates, prod); it = candidates->head; } else { it = nxt; } } free(unique); } void statement3(list *const candidates) { short *unique = calloc(100, sizeof(short)); node *it, *nxt; for (it = candidates->head; it != NULL; it = it->next) { int sum = it->x + it->y; unique[sum]++; } it = candidates->head; while (it != NULL) { int sum = it->x + it->y; nxt = it->next; if (unique[sum] > 1) { remove_by_sum(candidates, sum); it = candidates->head; } else { it = nxt; } } free(unique); } int main() { list candidates = make_list(); setup(&candidates); print_count(&candidates); statement1(&candidates); print_count(&candidates); statement2(&candidates); print_count(&candidates); statement3(&candidates); print_count(&candidates); print_list(&candidates); free_list(&candidates); return 0; }
from collections import Counter def decompose_sum(s): return [(a,s-a) for a in range(2,int(s/2+1))] all_pairs = set((a,b) for a in range(2,100) for b in range(a+1,100) if a+b<100) product_counts = Counter(c*d for c,d in all_pairs) unique_products = set((a,b) for a,b in all_pairs if product_counts[a*b]==1) s_pairs = [(a,b) for a,b in all_pairs if all((x,y) not in unique_products for (x,y) in decompose_sum(a+b))] product_counts = Counter(c*d for c,d in s_pairs) p_pairs = [(a,b) for a,b in s_pairs if product_counts[a*b]==1] sum_counts = Counter(c+d for c,d in p_pairs) final_pairs = [(a,b) for a,b in p_pairs if sum_counts[a+b]==1] print(final_pairs)
Port the following code from C to Python with equivalent syntax and logic.
#include <stdio.h> #include <stdlib.h> int turn(int base, int n) { int sum = 0; while (n != 0) { int rem = n % base; n = n / base; sum += rem; } return sum % base; } void fairshare(int base, int count) { int i; printf("Base %2d:", base); for (i = 0; i < count; i++) { int t = turn(base, i); printf(" %2d", t); } printf("\n"); } void turnCount(int base, int count) { int *cnt = calloc(base, sizeof(int)); int i, minTurn, maxTurn, portion; if (NULL == cnt) { printf("Failed to allocate space to determine the spread of turns.\n"); return; } for (i = 0; i < count; i++) { int t = turn(base, i); cnt[t]++; } minTurn = INT_MAX; maxTurn = INT_MIN; portion = 0; for (i = 0; i < base; i++) { if (cnt[i] > 0) { portion++; } if (cnt[i] < minTurn) { minTurn = cnt[i]; } if (cnt[i] > maxTurn) { maxTurn = cnt[i]; } } printf(" With %d people: ", base); if (0 == minTurn) { printf("Only %d have a turn\n", portion); } else if (minTurn == maxTurn) { printf("%d\n", minTurn); } else { printf("%d or %d\n", minTurn, maxTurn); } free(cnt); } int main() { fairshare(2, 25); fairshare(3, 25); fairshare(5, 25); fairshare(11, 25); printf("How many times does each get a turn in 50000 iterations?\n"); turnCount(191, 50000); turnCount(1377, 50000); turnCount(49999, 50000); turnCount(50000, 50000); turnCount(50001, 50000); return 0; }
from itertools import count, islice def _basechange_int(num, b): if num == 0: return [0] result = [] while num != 0: num, d = divmod(num, b) result.append(d) return result[::-1] def fairshare(b=2): for i in count(): yield sum(_basechange_int(i, b)) % b if __name__ == '__main__': for b in (2, 3, 5, 11): print(f"{b:>2}: {str(list(islice(fairshare(b), 25)))[1:-1]}")
Can you help me rewrite this code in Python instead of C, keeping it the same logically?
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> static int nextInt(int size) { return rand() % size; } static bool cylinder[6]; static void rshift() { bool t = cylinder[5]; int i; for (i = 4; i >= 0; i--) { cylinder[i + 1] = cylinder[i]; } cylinder[0] = t; } static void unload() { int i; for (i = 0; i < 6; i++) { cylinder[i] = false; } } static void load() { while (cylinder[0]) { rshift(); } cylinder[0] = true; rshift(); } static void spin() { int lim = nextInt(6) + 1; int i; for (i = 1; i < lim; i++) { rshift(); } } static bool fire() { bool shot = cylinder[0]; rshift(); return shot; } static int method(const char *s) { unload(); for (; *s != '\0'; s++) { switch (*s) { case 'L': load(); break; case 'S': spin(); break; case 'F': if (fire()) { return 1; } break; } } return 0; } static void append(char *out, const char *txt) { if (*out != '\0') { strcat(out, ", "); } strcat(out, txt); } static void mstring(const char *s, char *out) { for (; *s != '\0'; s++) { switch (*s) { case 'L': append(out, "load"); break; case 'S': append(out, "spin"); break; case 'F': append(out, "fire"); break; } } } static void test(char *src) { char buffer[41] = ""; const int tests = 100000; int sum = 0; int t; double pc; for (t = 0; t < tests; t++) { sum += method(src); } mstring(src, buffer); pc = 100.0 * sum / tests; printf("%-40s produces %6.3f%% deaths.\n", buffer, pc); } int main() { srand(time(0)); test("LSLSFSF"); test("LSLSFF"); test("LLSFSF"); test("LLSFF"); return 0; }
import numpy as np class Revolver: def __init__(self): self.cylinder = np.array([False] * 6) def unload(self): self.cylinder[:] = False def load(self): while self.cylinder[1]: self.cylinder[:] = np.roll(self.cylinder, 1) self.cylinder[1] = True def spin(self): self.cylinder[:] = np.roll(self.cylinder, np.random.randint(1, high=7)) def fire(self): shot = self.cylinder[0] self.cylinder[:] = np.roll(self.cylinder, 1) return shot def LSLSFSF(self): self.unload() self.load() self.spin() self.load() self.spin() if self.fire(): return True self.spin() if self.fire(): return True return False def LSLSFF(self): self.unload() self.load() self.spin() self.load() self.spin() if self.fire(): return True if self.fire(): return True return False def LLSFSF(self): self.unload() self.load() self.load() self.spin() if self.fire(): return True self.spin() if self.fire(): return True return False def LLSFF(self): self.unload() self.load() self.load() self.spin() if self.fire(): return True if self.fire(): return True return False if __name__ == '__main__': REV = Revolver() TESTCOUNT = 100000 for (name, method) in [['load, spin, load, spin, fire, spin, fire', REV.LSLSFSF], ['load, spin, load, spin, fire, fire', REV.LSLSFF], ['load, load, spin, fire, spin, fire', REV.LLSFSF], ['load, load, spin, fire, fire', REV.LLSFF]]: percentage = 100 * sum([method() for _ in range(TESTCOUNT)]) / TESTCOUNT print("Method", name, "produces", percentage, "per cent deaths.")
Rewrite this program in Python while keeping its functionality equivalent to the C version.
#include <sys/types.h> #include <regex.h> #include <stdio.h> typedef struct { const char *s; int len, prec, assoc; } str_tok_t; typedef struct { const char * str; int assoc, prec; regex_t re; } pat_t; enum assoc { A_NONE, A_L, A_R }; pat_t pat_eos = {"", A_NONE, 0}; pat_t pat_ops[] = { {"^\\)", A_NONE, -1}, {"^\\*\\*", A_R, 3}, {"^\\^", A_R, 3}, {"^\\*", A_L, 2}, {"^/", A_L, 2}, {"^\\+", A_L, 1}, {"^-", A_L, 1}, {0} }; pat_t pat_arg[] = { {"^[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?"}, {"^[a-zA-Z_][a-zA-Z_0-9]*"}, {"^\\(", A_L, -1}, {0} }; str_tok_t stack[256]; str_tok_t queue[256]; int l_queue, l_stack; #define qpush(x) queue[l_queue++] = x #define spush(x) stack[l_stack++] = x #define spop() stack[--l_stack] void display(const char *s) { int i; printf("\033[1;1H\033[JText | %s", s); printf("\nStack| "); for (i = 0; i < l_stack; i++) printf("%.*s ", stack[i].len, stack[i].s); printf("\nQueue| "); for (i = 0; i < l_queue; i++) printf("%.*s ", queue[i].len, queue[i].s); puts("\n\n<press enter>"); getchar(); } int prec_booster; #define fail(s1, s2) {fprintf(stderr, "[Error %s] %s\n", s1, s2); return 0;} int init(void) { int i; pat_t *p; for (i = 0, p = pat_ops; p[i].str; i++) if (regcomp(&(p[i].re), p[i].str, REG_NEWLINE|REG_EXTENDED)) fail("comp", p[i].str); for (i = 0, p = pat_arg; p[i].str; i++) if (regcomp(&(p[i].re), p[i].str, REG_NEWLINE|REG_EXTENDED)) fail("comp", p[i].str); return 1; } pat_t* match(const char *s, pat_t *p, str_tok_t * t, const char **e) { int i; regmatch_t m; while (*s == ' ') s++; *e = s; if (!*s) return &pat_eos; for (i = 0; p[i].str; i++) { if (regexec(&(p[i].re), s, 1, &m, REG_NOTEOL)) continue; t->s = s; *e = s + (t->len = m.rm_eo - m.rm_so); return p + i; } return 0; } int parse(const char *s) { pat_t *p; str_tok_t *t, tok; prec_booster = l_queue = l_stack = 0; display(s); while (*s) { p = match(s, pat_arg, &tok, &s); if (!p || p == &pat_eos) fail("parse arg", s); if (p->prec == -1) { prec_booster += 100; continue; } qpush(tok); display(s); re_op: p = match(s, pat_ops, &tok, &s); if (!p) fail("parse op", s); tok.assoc = p->assoc; tok.prec = p->prec; if (p->prec > 0) tok.prec = p->prec + prec_booster; else if (p->prec == -1) { if (prec_booster < 100) fail("unmatched )", s); tok.prec = prec_booster; } while (l_stack) { t = stack + l_stack - 1; if (!(t->prec == tok.prec && t->assoc == A_L) && t->prec <= tok.prec) break; qpush(spop()); display(s); } if (p->prec == -1) { prec_booster -= 100; goto re_op; } if (!p->prec) { display(s); if (prec_booster) fail("unmatched (", s); return 1; } spush(tok); display(s); } if (p->prec > 0) fail("unexpected eol", s); return 1; } int main() { int i; const char *tests[] = { "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3", "123", "3+4 * 2 / ( 1 - 5 ) ^ 2 ^ 3.14", "(((((((1+2+3**(4 + 5))))))", "a^(b + c/d * .1e5)!", "(1**2)**3", "2 + 2 *", 0 }; if (!init()) return 1; for (i = 0; tests[i]; i++) { printf("Testing string `%s' <enter>\n", tests[i]); getchar(); printf("string `%s': %s\n\n", tests[i], parse(tests[i]) ? "Ok" : "Error"); } return 0; }
from collections import namedtuple from pprint import pprint as pp OpInfo = namedtuple('OpInfo', 'prec assoc') L, R = 'Left Right'.split() ops = { '^': OpInfo(prec=4, assoc=R), '*': OpInfo(prec=3, assoc=L), '/': OpInfo(prec=3, assoc=L), '+': OpInfo(prec=2, assoc=L), '-': OpInfo(prec=2, assoc=L), '(': OpInfo(prec=9, assoc=L), ')': OpInfo(prec=0, assoc=L), } NUM, LPAREN, RPAREN = 'NUMBER ( )'.split() def get_input(inp = None): 'Inputs an expression and returns list of (TOKENTYPE, tokenvalue)' if inp is None: inp = input('expression: ') tokens = inp.strip().split() tokenvals = [] for token in tokens: if token in ops: tokenvals.append((token, ops[token])) else: tokenvals.append((NUM, token)) return tokenvals def shunting(tokenvals): outq, stack = [], [] table = ['TOKEN,ACTION,RPN OUTPUT,OP STACK,NOTES'.split(',')] for token, val in tokenvals: note = action = '' if token is NUM: action = 'Add number to output' outq.append(val) table.append( (val, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) ) elif token in ops: t1, (p1, a1) = token, val v = t1 note = 'Pop ops from stack to output' while stack: t2, (p2, a2) = stack[-1] if (a1 == L and p1 <= p2) or (a1 == R and p1 < p2): if t1 != RPAREN: if t2 != LPAREN: stack.pop() action = '(Pop op)' outq.append(t2) else: break else: if t2 != LPAREN: stack.pop() action = '(Pop op)' outq.append(t2) else: stack.pop() action = '(Pop & discard "(")' table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) ) break table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) ) v = note = '' else: note = '' break note = '' note = '' if t1 != RPAREN: stack.append((token, val)) action = 'Push op token to stack' else: action = 'Discard ")"' table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) ) note = 'Drain stack to output' while stack: v = '' t2, (p2, a2) = stack[-1] action = '(Pop op)' stack.pop() outq.append(t2) table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) ) v = note = '' return table if __name__ == '__main__': infix = '3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3' print( 'For infix expression: %r\n' % infix ) rp = shunting(get_input(infix)) maxcolwidths = [len(max(x, key=len)) for x in zip(*rp)] row = rp[0] print( ' '.join('{cell:^{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row))) for row in rp[1:]: print( ' '.join('{cell:<{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row))) print('\n The final output RPN is: %r' % rp[-1][2])
Generate a Python translation of this C snippet without changing its computational steps.
#include<math.h> #include<stdio.h> int main () { double inputs[11], check = 400, result; int i; printf ("\nPlease enter 11 numbers :"); for (i = 0; i < 11; i++) { scanf ("%lf", &inputs[i]); } printf ("\n\n\nEvaluating f(x) = |x|^0.5 + 5x^3 for the given inputs :"); for (i = 10; i >= 0; i--) { result = sqrt (fabs (inputs[i])) + 5 * pow (inputs[i], 3); printf ("\nf(%lf) = "); if (result > check) { printf ("Overflow!"); } else { printf ("%lf", result); } } return 0; }
Python 3.2.2 (default, Sep 4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> def f(x): return abs(x) ** 0.5 + 5 * x**3 >>> print(', '.join('%s:%s' % (x, v if v<=400 else "TOO LARGE!") for x,v in ((y, f(float(y))) for y in input('\nnumbers: ').strip().split()[:11][::-1]))) 11 numbers: 1 2 3 4 5 6 7 8 9 10 11 11:TOO LARGE!, 10:TOO LARGE!, 9:TOO LARGE!, 8:TOO LARGE!, 7:TOO LARGE!, 6:TOO LARGE!, 5:TOO LARGE!, 4:322.0, 3:136.73205080756887, 2:41.41421356237309, 1:6.0 >>>
Rewrite this program in Python while keeping its functionality equivalent to the C version.
#include <stdio.h> #include <stdlib.h> #include <string.h> char * mid3(int n) { static char buf[32]; int l; sprintf(buf, "%d", n > 0 ? n : -n); l = strlen(buf); if (l < 3 || !(l & 1)) return 0; l = l / 2 - 1; buf[l + 3] = 0; return buf + l; } int main(void) { int x[] = {123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0, 1234567890}; int i; char *m; for (i = 0; i < sizeof(x)/sizeof(x[0]); i++) { if (!(m = mid3(x[i]))) m = "error"; printf("%d: %s\n", x[i], m); } return 0; }
>>> def middle_three_digits(i): s = str(abs(i)) length = len(s) assert length >= 3 and length % 2 == 1, "Need odd and >= 3 digits" mid = length // 2 return s[mid-1:mid+2] >>> passing = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345] >>> failing = [1, 2, -1, -10, 2002, -2002, 0] >>> for x in passing + failing: try: answer = middle_three_digits(x) except AssertionError as error: answer = error print("middle_three_digits(%s) returned: %r" % (x, answer)) middle_three_digits(123) returned: '123' middle_three_digits(12345) returned: '234' middle_three_digits(1234567) returned: '345' middle_three_digits(987654321) returned: '654' middle_three_digits(10001) returned: '000' middle_three_digits(-10001) returned: '000' middle_three_digits(-123) returned: '123' middle_three_digits(-100) returned: '100' middle_three_digits(100) returned: '100' middle_three_digits(-12345) returned: '234' middle_three_digits(1) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(2) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(-1) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(-10) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(2002) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(-2002) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(0) returned: AssertionError('Need odd and >= 3 digits',) >>>
Ensure the translated Python code behaves exactly like the original C snippet.
#include <math.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> #define LIMIT 15 int smallPrimes[LIMIT]; static void sieve() { int i = 2, j; int p = 5; smallPrimes[0] = 2; smallPrimes[1] = 3; while (i < LIMIT) { for (j = 0; j < i; j++) { if (smallPrimes[j] * smallPrimes[j] <= p) { if (p % smallPrimes[j] == 0) { p += 2; break; } } else { smallPrimes[i++] = p; p += 2; break; } } } } static bool is_prime(uint64_t n) { uint64_t i; for (i = 0; i < LIMIT; i++) { if (n % smallPrimes[i] == 0) { return n == smallPrimes[i]; } } i = smallPrimes[LIMIT - 1] + 2; for (; i * i <= n; i += 2) { if (n % i == 0) { return false; } } return true; } static uint64_t divisor_count(uint64_t n) { uint64_t count = 1; uint64_t d; while (n % 2 == 0) { n /= 2; count++; } for (d = 3; d * d <= n; d += 2) { uint64_t q = n / d; uint64_t r = n % d; uint64_t dc = 0; while (r == 0) { dc += count; n = q; q = n / d; r = n % d; } count += dc; } if (n != 1) { return count *= 2; } return count; } static uint64_t OEISA073916(size_t n) { uint64_t count = 0; uint64_t result = 0; size_t i; if (is_prime(n)) { return (uint64_t)pow(smallPrimes[n - 1], n - 1); } for (i = 1; count < n; i++) { if (n % 2 == 1) { uint64_t root = (uint64_t)sqrt(i); if (root * root != i) { continue; } } if (divisor_count(i) == n) { count++; result = i; } } return result; } int main() { size_t n; sieve(); for (n = 1; n <= LIMIT; n++) { if (n == 13) { printf("A073916(%lu) = One more bit needed to represent result.\n", n); } else { printf("A073916(%lu) = %llu\n", n, OEISA073916(n)); } } return 0; }
def divisors(n): divs = [1] for ii in range(2, int(n ** 0.5) + 3): if n % ii == 0: divs.append(ii) divs.append(int(n / ii)) divs.append(n) return list(set(divs)) def is_prime(n): return len(divisors(n)) == 2 def primes(): ii = 1 while True: ii += 1 if is_prime(ii): yield ii def prime(n): generator = primes() for ii in range(n - 1): generator.__next__() return generator.__next__() def n_divisors(n): ii = 0 while True: ii += 1 if len(divisors(ii)) == n: yield ii def sequence(max_n=None): if max_n is not None: for ii in range(1, max_n + 1): if is_prime(ii): yield prime(ii) ** (ii - 1) else: generator = n_divisors(ii) for jj, out in zip(range(ii - 1), generator): pass yield generator.__next__() else: ii = 1 while True: ii += 1 if is_prime(ii): yield prime(ii) ** (ii - 1) else: generator = n_divisors(ii) for jj, out in zip(range(ii - 1), generator): pass yield generator.__next__() if __name__ == '__main__': for item in sequence(15): print(item)
Write the same algorithm in Python as shown in this C implementation.
#include <stdio.h> #define MAX 15 int count_divisors(int n) { int i, count = 0; for (i = 1; i * i <= n; ++i) { if (!(n % i)) { if (i == n / i) count++; else count += 2; } } return count; } int main() { int i, k, n, seq[MAX]; for (i = 0; i < MAX; ++i) seq[i] = 0; printf("The first %d terms of the sequence are:\n", MAX); for (i = 1, n = 0; n < MAX; ++i) { k = count_divisors(i); if (k <= MAX && seq[k - 1] == 0) { seq[k - 1] = i; ++n; } } for (i = 0; i < MAX; ++i) printf("%d ", seq[i]); printf("\n"); return 0; }
def divisors(n): divs = [1] for ii in range(2, int(n ** 0.5) + 3): if n % ii == 0: divs.append(ii) divs.append(int(n / ii)) divs.append(n) return list(set(divs)) def sequence(max_n=None): n = 0 while True: n += 1 ii = 0 if max_n is not None: if n > max_n: break while True: ii += 1 if len(divisors(ii)) == n: yield ii break if __name__ == '__main__': for item in sequence(15): print(item)
Port the provided C code into Python while preserving the original functionality.
#include <stdio.h> #define MAX 15 int count_divisors(int n) { int i, count = 0; for (i = 1; i * i <= n; ++i) { if (!(n % i)) { if (i == n / i) count++; else count += 2; } } return count; } int main() { int i, k, n, seq[MAX]; for (i = 0; i < MAX; ++i) seq[i] = 0; printf("The first %d terms of the sequence are:\n", MAX); for (i = 1, n = 0; n < MAX; ++i) { k = count_divisors(i); if (k <= MAX && seq[k - 1] == 0) { seq[k - 1] = i; ++n; } } for (i = 0; i < MAX; ++i) printf("%d ", seq[i]); printf("\n"); return 0; }
def divisors(n): divs = [1] for ii in range(2, int(n ** 0.5) + 3): if n % ii == 0: divs.append(ii) divs.append(int(n / ii)) divs.append(n) return list(set(divs)) def sequence(max_n=None): n = 0 while True: n += 1 ii = 0 if max_n is not None: if n > max_n: break while True: ii += 1 if len(divisors(ii)) == n: yield ii break if __name__ == '__main__': for item in sequence(15): print(item)
Convert this C block to Python, preserving its control flow and logic.
#include <stdio.h> int pancake(int n) { int gap = 2, sum = 2, adj = -1; while (sum < n) { adj++; gap = gap * 2 - 1; sum += gap; } return n + adj; } int main() { int i, j; for (i = 0; i < 4; i++) { for (j = 1; j < 6; j++) { int n = i * 5 + j; printf("p(%2d) = %2d ", n, pancake(n)); } printf("\n"); } return 0; }
import time from collections import deque from operator import itemgetter from typing import Tuple Pancakes = Tuple[int, ...] def flip(pancakes: Pancakes, position: int) -> Pancakes: return tuple([*reversed(pancakes[:position]), *pancakes[position:]]) def pancake(n: int) -> Tuple[Pancakes, int]: init_stack = tuple(range(1, n + 1)) stack_flips = {init_stack: 0} queue = deque([init_stack]) while queue: stack = queue.popleft() flips = stack_flips[stack] + 1 for i in range(2, n + 1): flipped = flip(stack, i) if flipped not in stack_flips: stack_flips[flipped] = flips queue.append(flipped) return max(stack_flips.items(), key=itemgetter(1)) if __name__ == "__main__": start = time.time() for n in range(1, 10): pancakes, p = pancake(n) print(f"pancake({n}) = {p:>2}. Example: {list(pancakes)}") print(f"\nTook {time.time() - start:.3} seconds.")
Port the provided C code into Python while preserving the original functionality.
#include <stdio.h> #include <math.h> #include <string.h> #include <stdlib.h> #include <time.h> #define TRUE 1 #define FALSE 0 typedef int bool; char grid[8][8]; void placeKings() { int r1, r2, c1, c2; for (;;) { r1 = rand() % 8; c1 = rand() % 8; r2 = rand() % 8; c2 = rand() % 8; if (r1 != r2 && abs(r1 - r2) > 1 && abs(c1 - c2) > 1) { grid[r1][c1] = 'K'; grid[r2][c2] = 'k'; return; } } } void placePieces(const char *pieces, bool isPawn) { int n, r, c; int numToPlace = rand() % strlen(pieces); for (n = 0; n < numToPlace; ++n) { do { r = rand() % 8; c = rand() % 8; } while (grid[r][c] != 0 || (isPawn && (r == 7 || r == 0))); grid[r][c] = pieces[n]; } } void toFen() { char fen[80], ch; int r, c, countEmpty = 0, index = 0; for (r = 0; r < 8; ++r) { for (c = 0; c < 8; ++c) { ch = grid[r][c]; printf("%2c ", ch == 0 ? '.' : ch); if (ch == 0) { countEmpty++; } else { if (countEmpty > 0) { fen[index++] = countEmpty + 48; countEmpty = 0; } fen[index++] = ch; } } if (countEmpty > 0) { fen[index++] = countEmpty + 48; countEmpty = 0; } fen[index++]= '/'; printf("\n"); } strcpy(fen + index, " w - - 0 1"); printf("%s\n", fen); } char *createFen() { placeKings(); placePieces("PPPPPPPP", TRUE); placePieces("pppppppp", TRUE); placePieces("RNBQBNR", FALSE); placePieces("rnbqbnr", FALSE); toFen(); } int main() { srand(time(NULL)); createFen(); return 0; }
import random board = [[" " for x in range(8)] for y in range(8)] piece_list = ["R", "N", "B", "Q", "P"] def place_kings(brd): while True: rank_white, file_white, rank_black, file_black = random.randint(0,7), random.randint(0,7), random.randint(0,7), random.randint(0,7) diff_list = [abs(rank_white - rank_black), abs(file_white - file_black)] if sum(diff_list) > 2 or set(diff_list) == set([0, 2]): brd[rank_white][file_white], brd[rank_black][file_black] = "K", "k" break def populate_board(brd, wp, bp): for x in range(2): if x == 0: piece_amount = wp pieces = piece_list else: piece_amount = bp pieces = [s.lower() for s in piece_list] while piece_amount != 0: piece_rank, piece_file = random.randint(0, 7), random.randint(0, 7) piece = random.choice(pieces) if brd[piece_rank][piece_file] == " " and pawn_on_promotion_square(piece, piece_rank) == False: brd[piece_rank][piece_file] = piece piece_amount -= 1 def fen_from_board(brd): fen = "" for x in brd: n = 0 for y in x: if y == " ": n += 1 else: if n != 0: fen += str(n) fen += y n = 0 if n != 0: fen += str(n) fen += "/" if fen.count("/") < 7 else "" fen += " w - - 0 1\n" return fen def pawn_on_promotion_square(pc, pr): if pc == "P" and pr == 0: return True elif pc == "p" and pr == 7: return True return False def start(): piece_amount_white, piece_amount_black = random.randint(0, 15), random.randint(0, 15) place_kings(board) populate_board(board, piece_amount_white, piece_amount_black) print(fen_from_board(board)) for x in board: print(x) start()
Generate an equivalent Python version of this C code.
#include <stdio.h> #include <string.h> #include <locale.h> typedef int bool; typedef unsigned long long ull; #define TRUE 1 #define FALSE 0 char as_digit(int d) { return (d >= 0 && d <= 9) ? d + '0' : d - 10 + 'a'; } void revstr(char *str) { int i, len = strlen(str); char t; for (i = 0; i < len/2; ++i) { t = str[i]; str[i] = str[len - i - 1]; str[len - i - 1] = t; } } char* to_base(char s[], ull n, int b) { int i = 0; while (n) { s[i++] = as_digit(n % b); n /= b; } s[i] = '\0'; revstr(s); return s; } ull uabs(ull a, ull b) { return a > b ? a - b : b - a; } bool is_esthetic(ull n, int b) { int i, j; if (!n) return FALSE; i = n % b; n /= b; while (n) { j = n % b; if (uabs(i, j) != 1) return FALSE; n /= b; i = j; } return TRUE; } ull esths[45000]; int le = 0; void dfs(ull n, ull m, ull i) { ull d, i1, i2; if (i >= n && i <= m) esths[le++] = i; if (i == 0 || i > m) return; d = i % 10; i1 = i * 10 + d - 1; i2 = i1 + 2; if (d == 0) { dfs(n, m, i2); } else if (d == 9) { dfs(n, m, i1); } else { dfs(n, m, i1); dfs(n, m, i2); } } void list_esths(ull n, ull n2, ull m, ull m2, int per_line, bool all) { int i; le = 0; for (i = 0; i < 10; ++i) { dfs(n2, m2, i); } printf("Base 10: %'d esthetic numbers between %'llu and %'llu:\n", le, n, m); if (all) { for (i = 0; i < le; ++i) { printf("%llu ", esths[i]); if (!(i+1)%per_line) printf("\n"); } } else { for (i = 0; i < per_line; ++i) printf("%llu ", esths[i]); printf("\n............\n"); for (i = le - per_line; i < le; ++i) printf("%llu ", esths[i]); } printf("\n\n"); } int main() { ull n; int b, c; char ch[15] = {0}; for (b = 2; b <= 16; ++b) { printf("Base %d: %dth to %dth esthetic numbers:\n", b, 4*b, 6*b); for (n = 1, c = 0; c < 6 * b; ++n) { if (is_esthetic(n, b)) { if (++c >= 4 * b) printf("%s ", to_base(ch, n, b)); } } printf("\n\n"); } char *oldLocale = setlocale(LC_NUMERIC, NULL); setlocale(LC_NUMERIC, ""); list_esths(1000, 1010, 9999, 9898, 16, TRUE); list_esths(1e8, 101010101, 13*1e7, 123456789, 9, TRUE); list_esths(1e11, 101010101010, 13*1e10, 123456789898, 7, FALSE); list_esths(1e14, 101010101010101, 13*1e13, 123456789898989, 5, FALSE); list_esths(1e17, 101010101010101010, 13*1e16, 123456789898989898, 4, FALSE); setlocale(LC_NUMERIC, oldLocale); return 0; }
from collections import deque from itertools import dropwhile, islice, takewhile from textwrap import wrap from typing import Iterable, Iterator Digits = str def esthetic_nums(base: int) -> Iterator[int]: queue: deque[tuple[int, int]] = deque() queue.extendleft((d, d) for d in range(1, base)) while True: num, lsd = queue.pop() yield num new_lsds = (d for d in (lsd - 1, lsd + 1) if 0 <= d < base) num *= base queue.extendleft((num + d, d) for d in new_lsds) def to_digits(num: int, base: int) -> Digits: digits: list[str] = [] while num: num, d = divmod(num, base) digits.append("0123456789abcdef"[d]) return "".join(reversed(digits)) if digits else "0" def pprint_it(it: Iterable[str], indent: int = 4, width: int = 80) -> None: joined = ", ".join(it) lines = wrap(joined, width=width - indent) for line in lines: print(f"{indent*' '}{line}") print() def task_2() -> None: nums: Iterator[int] for base in range(2, 16 + 1): start, stop = 4 * base, 6 * base nums = esthetic_nums(base) nums = islice(nums, start - 1, stop) print( f"Base-{base} esthetic numbers from " f"index {start} through index {stop} inclusive:\n" ) pprint_it(to_digits(num, base) for num in nums) def task_3(lower: int, upper: int, base: int = 10) -> None: nums: Iterator[int] = esthetic_nums(base) nums = dropwhile(lambda num: num < lower, nums) nums = takewhile(lambda num: num <= upper, nums) print( f"Base-{base} esthetic numbers with " f"magnitude between {lower:,} and {upper:,}:\n" ) pprint_it(to_digits(num, base) for num in nums) if __name__ == "__main__": print("======\nTask 2\n======\n") task_2() print("======\nTask 3\n======\n") task_3(1_000, 9_999) print("======\nTask 4\n======\n") task_3(100_000_000, 130_000_000)
Change the programming language of this snippet from C to Python without modifying what it does.
#include <stdio.h> #include <string.h> typedef struct { char v[16]; } deck; typedef unsigned int uint; uint n, d, best[16]; void tryswaps(deck *a, uint f, uint s) { # define A a->v # define B b.v if (d > best[n]) best[n] = d; while (1) { if ((A[s] == s || (A[s] == -1 && !(f & 1U << s))) && (d + best[s] >= best[n] || A[s] == -1)) break; if (d + best[s] <= best[n]) return; if (!--s) return; } d++; deck b = *a; for (uint i = 1, k = 2; i <= s; k <<= 1, i++) { if (A[i] != i && (A[i] != -1 || (f & k))) continue; for (uint j = B[0] = i; j--;) B[i - j] = A[j]; tryswaps(&b, f | k, s); } d--; } int main(void) { deck x; memset(&x, -1, sizeof(x)); x.v[0] = 0; for (n = 1; n < 13; n++) { tryswaps(&x, 1, n - 1); printf("%2d: %d\n", n, best[n]); } return 0; }
>>> from itertools import permutations >>> def f1(p): i = 0 while True: p0 = p[0] if p0 == 1: break p[:p0] = p[:p0][::-1] i += 1 return i >>> def fannkuch(n): return max(f1(list(p)) for p in permutations(range(1, n+1))) >>> for n in range(1, 11): print(n,fannkuch(n)) 1 0 2 1 3 2 4 4 5 7 6 10 7 16 8 22 9 30 10 38 >>>
Convert this C snippet to Python and keep its semantics consistent.
#include<string.h> #include<stdlib.h> #include<ctype.h> #include<stdio.h> #define UNITS_LENGTH 13 int main(int argC,char* argV[]) { int i,reference; char *units[UNITS_LENGTH] = {"kilometer","meter","centimeter","tochka","liniya","diuym","vershok","piad","fut","arshin","sazhen","versta","milia"}; double factor, values[UNITS_LENGTH] = {1000.0,1.0,0.01,0.000254,0.00254,0.0254,0.04445,0.1778,0.3048,0.7112,2.1336,1066.8,7467.6}; if(argC!=3) printf("Usage : %s followed by length as <value> <unit>"); else{ for(i=0;argV[2][i]!=00;i++) argV[2][i] = tolower(argV[2][i]); for(i=0;i<UNITS_LENGTH;i++){ if(strstr(argV[2],units[i])!=NULL){ reference = i; factor = atof(argV[1])*values[i]; break; } } printf("%s %s is equal in length to : \n",argV[1],argV[2]); for(i=0;i<UNITS_LENGTH;i++){ if(i!=reference) printf("\n%lf %s",factor/values[i],units[i]); } } return 0; }
from sys import argv unit2mult = {"arshin": 0.7112, "centimeter": 0.01, "diuym": 0.0254, "fut": 0.3048, "kilometer": 1000.0, "liniya": 0.00254, "meter": 1.0, "milia": 7467.6, "piad": 0.1778, "sazhen": 2.1336, "tochka": 0.000254, "vershok": 0.04445, "versta": 1066.8} if __name__ == '__main__': assert len(argv) == 3, 'ERROR. Need two arguments - number then units' try: value = float(argv[1]) except: print('ERROR. First argument must be a (float) number') raise unit = argv[2] assert unit in unit2mult, ( 'ERROR. Only know the following units: ' + ' '.join(unit2mult.keys()) ) print("%g %s to:" % (value, unit)) for unt, mlt in sorted(unit2mult.items()): print(' %10s: %g' % (unt, value * unit2mult[unit] / mlt))
Port the following code from C to Python with equivalent syntax and logic.
#include <stdio.h> #include <time.h> struct rate_state_s { time_t lastFlush; time_t period; size_t tickCount; }; void tic_rate(struct rate_state_s* pRate) { pRate->tickCount += 1; time_t now = time(NULL); if((now - pRate->lastFlush) >= pRate->period) { size_t tps = 0.0; if(pRate->tickCount > 0) tps = pRate->tickCount / (now - pRate->lastFlush); printf("%u tics per second.\n", tps); pRate->tickCount = 0; pRate->lastFlush = now; } } void something_we_do() { volatile size_t anchor = 0; size_t x = 0; for(x = 0; x < 0xffff; ++x) { anchor = x; } } int main() { time_t start = time(NULL); struct rate_state_s rateWatch; rateWatch.lastFlush = start; rateWatch.tickCount = 0; rateWatch.period = 5; time_t latest = start; for(latest = start; (latest - start) < 20; latest = time(NULL)) { something_we_do(); tic_rate(&rateWatch); } return 0; }
import subprocess import time class Tlogger(object): def __init__(self): self.counts = 0 self.tottime = 0.0 self.laststart = 0.0 self.lastreport = time.time() def logstart(self): self.laststart = time.time() def logend(self): self.counts +=1 self.tottime += (time.time()-self.laststart) if (time.time()-self.lastreport)>5.0: self.report() def report(self): if ( self.counts > 4*self.tottime): print "Subtask execution rate: %f times/second"% (self.counts/self.tottime); else: print "Average execution time: %f seconds"%(self.tottime/self.counts); self.lastreport = time.time() def taskTimer( n, subproc_args ): logger = Tlogger() for x in range(n): logger.logstart() p = subprocess.Popen(subproc_args) p.wait() logger.logend() logger.report() import timeit import sys def main( ): s = timer = timeit.Timer(s) rzlts = timer.repeat(5, 5000) for t in rzlts: print "Time for 5000 executions of statement = ",t print " print "Command:",sys.argv[2:] print "" for k in range(3): taskTimer( int(sys.argv[1]), sys.argv[2:]) main()
Convert the following code from C to Python, ensuring the logic remains intact.
#include <stdio.h> #define MAX 15 int count_divisors(int n) { int i, count = 0; for (i = 1; i * i <= n; ++i) { if (!(n % i)) { if (i == n / i) count++; else count += 2; } } return count; } int main() { int i, next = 1; printf("The first %d terms of the sequence are:\n", MAX); for (i = 1; next <= MAX; ++i) { if (next == count_divisors(i)) { printf("%d ", i); next++; } } printf("\n"); return 0; }
def divisors(n): divs = [1] for ii in range(2, int(n ** 0.5) + 3): if n % ii == 0: divs.append(ii) divs.append(int(n / ii)) divs.append(n) return list(set(divs)) def sequence(max_n=None): previous = 0 n = 0 while True: n += 1 ii = previous if max_n is not None: if n > max_n: break while True: ii += 1 if len(divisors(ii)) == n: yield ii previous = ii break if __name__ == '__main__': for item in sequence(15): print(item)
Convert the following code from C to Python, ensuring the logic remains intact.
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> int pRec(int n) { static int *memo = NULL; static size_t curSize = 0; if (curSize <= (size_t) n) { size_t lastSize = curSize; while (curSize <= (size_t) n) curSize += 1024 * sizeof(int); memo = realloc(memo, curSize * sizeof(int)); memset(memo + lastSize, 0, (curSize - lastSize) * sizeof(int)); } if (memo[n] == 0) { if (n<=2) memo[n] = 1; else memo[n] = pRec(n-2) + pRec(n-3); } return memo[n]; } int pFloor(int n) { long double p = 1.324717957244746025960908854; long double s = 1.0453567932525329623; return powl(p, n-1)/s + 0.5; } void nextLSystem(const char *prev, char *buf) { while (*prev) { switch (*prev++) { case 'A': *buf++ = 'B'; break; case 'B': *buf++ = 'C'; break; case 'C': *buf++ = 'A'; *buf++ = 'B'; break; } } *buf = '\0'; } int main() { #define BUFSZ 8192 char buf1[BUFSZ], buf2[BUFSZ]; int i; printf("P_0 .. P_19: "); for (i=0; i<20; i++) printf("%d ", pRec(i)); printf("\n"); printf("The floor- and recurrence-based functions "); for (i=0; i<64; i++) { if (pRec(i) != pFloor(i)) { printf("do not match at %d: %d != %d.\n", i, pRec(i), pFloor(i)); break; } } if (i == 64) { printf("match from P_0 to P_63.\n"); } printf("\nThe first 10 L-system strings are:\n"); for (strcpy(buf1, "A"), i=0; i<10; i++) { printf("%s\n", buf1); strcpy(buf2, buf1); nextLSystem(buf2, buf1); } printf("\nThe floor- and L-system-based functions "); for (strcpy(buf1, "A"), i=0; i<32; i++) { if ((int)strlen(buf1) != pFloor(i)) { printf("do not match at %d: %d != %d\n", i, (int)strlen(buf1), pFloor(i)); break; } strcpy(buf2, buf1); nextLSystem(buf2, buf1); } if (i == 32) { printf("match from P_0 to P_31.\n"); } return 0; }
from math import floor from collections import deque from typing import Dict, Generator def padovan_r() -> Generator[int, None, None]: last = deque([1, 1, 1], 4) while True: last.append(last[-2] + last[-3]) yield last.popleft() _p, _s = 1.324717957244746025960908854, 1.0453567932525329623 def padovan_f(n: int) -> int: return floor(_p**(n-1) / _s + .5) def padovan_l(start: str='A', rules: Dict[str, str]=dict(A='B', B='C', C='AB') ) -> Generator[str, None, None]: axiom = start while True: yield axiom axiom = ''.join(rules[ch] for ch in axiom) if __name__ == "__main__": from itertools import islice print("The first twenty terms of the sequence.") print(str([padovan_f(n) for n in range(20)])[1:-1]) r_generator = padovan_r() if all(next(r_generator) == padovan_f(n) for n in range(64)): print("\nThe recurrence and floor based algorithms match to n=63 .") else: print("\nThe recurrence and floor based algorithms DIFFER!") print("\nThe first 10 L-system string-lengths and strings") l_generator = padovan_l(start='A', rules=dict(A='B', B='C', C='AB')) print('\n'.join(f" {len(string):3} {repr(string)}" for string in islice(l_generator, 10))) r_generator = padovan_r() l_generator = padovan_l(start='A', rules=dict(A='B', B='C', C='AB')) if all(len(next(l_generator)) == padovan_f(n) == next(r_generator) for n in range(32)): print("\nThe L-system, recurrence and floor based algorithms match to n=31 .") else: print("\nThe L-system, recurrence and floor based algorithms DIFFER!")
Produce a language-to-language conversion: from C to Python, same semantics.
#include<graphics.h> #include<stdlib.h> #include<stdio.h> #include<time.h> typedef struct{ double x,y; }point; void pythagorasTree(point a,point b,int times){ point c,d,e; c.x = b.x - (a.y - b.y); c.y = b.y - (b.x - a.x); d.x = a.x - (a.y - b.y); d.y = a.y - (b.x - a.x); e.x = d.x + ( b.x - a.x - (a.y - b.y) ) / 2; e.y = d.y - ( b.x - a.x + a.y - b.y ) / 2; if(times>0){ setcolor(rand()%15 + 1); line(a.x,a.y,b.x,b.y); line(c.x,c.y,b.x,b.y); line(c.x,c.y,d.x,d.y); line(a.x,a.y,d.x,d.y); pythagorasTree(d,e,times-1); pythagorasTree(e,c,times-1); } } int main(){ point a,b; double side; int iter; time_t t; printf("Enter initial side length : "); scanf("%lf",&side); printf("Enter number of iterations : "); scanf("%d",&iter); a.x = 6*side/2 - side/2; a.y = 4*side; b.x = 6*side/2 + side/2; b.y = 4*side; initwindow(6*side,4*side,"Pythagoras Tree ?"); srand((unsigned)time(&t)); pythagorasTree(a,b,iter); getch(); closegraph(); return 0; }
def setup(): size(800, 400) background(255) stroke(0, 255, 0) tree(width / 2.3, height, width / 1.8, height, 10) def tree(x1, y1, x2, y2, depth): if depth <= 0: return dx = (x2 - x1) dy = (y1 - y2) x3 = (x2 - dy) y3 = (y2 - dx) x4 = (x1 - dy) y4 = (y1 - dx) x5 = (x4 + 0.5 * (dx - dy)) y5 = (y4 - 0.5 * (dx + dy)) beginShape() fill(0.0, 255.0 / depth, 0.0) vertex(x1, y1) vertex(x2, y2) vertex(x3, y3) vertex(x4, y4) vertex(x1, y1) endShape() beginShape() fill(0.0, 255.0 / depth, 0.0) vertex(x3, y3) vertex(x4, y4) vertex(x5, y5) vertex(x3, y3) endShape() tree(x4, y4, x5, y5, depth - 1) tree(x5, y5, x3, y3, depth - 1)
Ensure the translated Python code behaves exactly like the original C snippet.
#include <stdio.h> #include <ctype.h> static int owp(int odd) { int ch, ret; ch = getc(stdin); if (!odd) { putc(ch, stdout); if (ch == EOF || ch == '.') return EOF; if (ispunct(ch)) return 0; owp(odd); return 0; } else { if (ispunct(ch)) return ch; ret = owp(odd); putc(ch, stdout); return ret; } } int main(int argc, char **argv) { int ch = 1; while ((ch = owp(!ch)) != EOF) { if (ch) putc(ch, stdout); if (ch == '.') break; } return 0; }
from sys import stdin, stdout def char_in(): return stdin.read(1) def char_out(c): stdout.write(c) def odd(prev = lambda: None): a = char_in() if not a.isalpha(): prev() char_out(a) return a != '.' def clos(): char_out(a) prev() return odd(clos) def even(): while True: c = char_in() char_out(c) if not c.isalpha(): return c != '.' e = False while odd() if e else even(): e = not e
Please provide an equivalent version of this C code in Python.
#include <math.h> #include <stdio.h> #include <stdint.h> int64_t mod(int64_t x, int64_t y) { int64_t m = x % y; if (m < 0) { if (y < 0) { return m - y; } else { return m + y; } } return m; } const static int64_t a1[3] = { 0, 1403580, -810728 }; const static int64_t m1 = (1LL << 32) - 209; const static int64_t a2[3] = { 527612, 0, -1370589 }; const static int64_t m2 = (1LL << 32) - 22853; const static int64_t d = (1LL << 32) - 209 + 1; static int64_t x1[3]; static int64_t x2[3]; void seed(int64_t seed_state) { x1[0] = seed_state; x1[1] = 0; x1[2] = 0; x2[0] = seed_state; x2[1] = 0; x2[2] = 0; } int64_t next_int() { int64_t x1i = mod((a1[0] * x1[0] + a1[1] * x1[1] + a1[2] * x1[2]), m1); int64_t x2i = mod((a2[0] * x2[0] + a2[1] * x2[1] + a2[2] * x2[2]), m2); int64_t z = mod(x1i - x2i, m1); x1[2] = x1[1]; x1[1] = x1[0]; x1[0] = x1i; x2[2] = x2[1]; x2[1] = x2[0]; x2[0] = x2i; return z + 1; } double next_float() { return (double)next_int() / d; } int main() { int counts[5] = { 0, 0, 0, 0, 0 }; int i; seed(1234567); printf("%lld\n", next_int()); printf("%lld\n", next_int()); printf("%lld\n", next_int()); printf("%lld\n", next_int()); printf("%lld\n", next_int()); printf("\n"); seed(987654321); for (i = 0; i < 100000; i++) { int64_t value = floor(next_float() * 5); counts[value]++; } for (i = 0; i < 5; i++) { printf("%d: %d\n", i, counts[i]); } return 0; }
a1 = [0, 1403580, -810728] m1 = 2**32 - 209 a2 = [527612, 0, -1370589] m2 = 2**32 - 22853 d = m1 + 1 class MRG32k3a(): def __init__(self, seed_state=123): self.seed(seed_state) def seed(self, seed_state): assert 0 <seed_state < d, f"Out of Range 0 x < {d}" self.x1 = [seed_state, 0, 0] self.x2 = [seed_state, 0, 0] def next_int(self): "return random int in range 0..d" x1i = sum(aa * xx for aa, xx in zip(a1, self.x1)) % m1 x2i = sum(aa * xx for aa, xx in zip(a2, self.x2)) % m2 self.x1 = [x1i] + self.x1[:2] self.x2 = [x2i] + self.x2[:2] z = (x1i - x2i) % m1 answer = (z + 1) return answer def next_float(self): "return random float between 0 and 1" return self.next_int() / d if __name__ == '__main__': random_gen = MRG32k3a() random_gen.seed(1234567) for i in range(5): print(random_gen.next_int()) random_gen.seed(987654321) hist = {i:0 for i in range(5)} for i in range(100_000): hist[int(random_gen.next_float() *5)] += 1 print(hist)
Keep all operations the same but rewrite the snippet in Python.
#include <locale.h> #include <stdbool.h> #include <stdio.h> #include <time.h> bool colorful(int n) { if (n < 0 || n > 98765432) return false; int digit_count[10] = {}; int digits[8] = {}; int num_digits = 0; for (int m = n; m > 0; m /= 10) { int d = m % 10; if (n > 9 && (d == 0 || d == 1)) return false; if (++digit_count[d] > 1) return false; digits[num_digits++] = d; } int products[36] = {}; for (int i = 0, product_count = 0; i < num_digits; ++i) { for (int j = i, p = 1; j < num_digits; ++j) { p *= digits[j]; for (int k = 0; k < product_count; ++k) { if (products[k] == p) return false; } products[product_count++] = p; } } return true; } static int count[8]; static bool used[10]; static int largest = 0; void count_colorful(int taken, int n, int digits) { if (taken == 0) { for (int d = 0; d < 10; ++d) { used[d] = true; count_colorful(d < 2 ? 9 : 1, d, 1); used[d] = false; } } else { if (colorful(n)) { ++count[digits - 1]; if (n > largest) largest = n; } if (taken < 9) { for (int d = 2; d < 10; ++d) { if (!used[d]) { used[d] = true; count_colorful(taken + 1, n * 10 + d, digits + 1); used[d] = false; } } } } } int main() { setlocale(LC_ALL, ""); clock_t start = clock(); printf("Colorful numbers less than 100:\n"); for (int n = 0, count = 0; n < 100; ++n) { if (colorful(n)) printf("%2d%c", n, ++count % 10 == 0 ? '\n' : ' '); } count_colorful(0, 0, 0); printf("\n\nLargest colorful number: %'d\n", largest); printf("\nCount of colorful numbers by number of digits:\n"); int total = 0; for (int d = 0; d < 8; ++d) { printf("%d  %'d\n", d + 1, count[d]); total += count[d]; } printf("\nTotal: %'d\n", total); clock_t end = clock(); printf("\nElapsed time: %f seconds\n", (end - start + 0.0) / CLOCKS_PER_SEC); return 0; }
from math import prod largest = [0] def iscolorful(n): if 0 <= n < 10: return True dig = [int(c) for c in str(n)] if 1 in dig or 0 in dig or len(dig) > len(set(dig)): return False products = list(set(dig)) for i in range(len(dig)): for j in range(i+2, len(dig)+1): p = prod(dig[i:j]) if p in products: return False products.append(p) largest[0] = max(n, largest[0]) return True print('Colorful numbers for 1:25, 26:50, 51:75, and 76:100:') for i in range(1, 101, 25): for j in range(25): if iscolorful(i + j): print(f'{i + j: 5,}', end='') print() csum = 0 for i in range(8): j = 0 if i == 0 else 10**i k = 10**(i+1) - 1 n = sum(iscolorful(x) for x in range(j, k+1)) csum += n print(f'The count of colorful numbers between {j} and {k} is {n}.') print(f'The largest possible colorful number is {largest[0]}.') print(f'The total number of colorful numbers is {csum}.')
Maintain the same structure and functionality when rewriting this code in Python.
#include <locale.h> #include <stdbool.h> #include <stdio.h> #include <time.h> bool colorful(int n) { if (n < 0 || n > 98765432) return false; int digit_count[10] = {}; int digits[8] = {}; int num_digits = 0; for (int m = n; m > 0; m /= 10) { int d = m % 10; if (n > 9 && (d == 0 || d == 1)) return false; if (++digit_count[d] > 1) return false; digits[num_digits++] = d; } int products[36] = {}; for (int i = 0, product_count = 0; i < num_digits; ++i) { for (int j = i, p = 1; j < num_digits; ++j) { p *= digits[j]; for (int k = 0; k < product_count; ++k) { if (products[k] == p) return false; } products[product_count++] = p; } } return true; } static int count[8]; static bool used[10]; static int largest = 0; void count_colorful(int taken, int n, int digits) { if (taken == 0) { for (int d = 0; d < 10; ++d) { used[d] = true; count_colorful(d < 2 ? 9 : 1, d, 1); used[d] = false; } } else { if (colorful(n)) { ++count[digits - 1]; if (n > largest) largest = n; } if (taken < 9) { for (int d = 2; d < 10; ++d) { if (!used[d]) { used[d] = true; count_colorful(taken + 1, n * 10 + d, digits + 1); used[d] = false; } } } } } int main() { setlocale(LC_ALL, ""); clock_t start = clock(); printf("Colorful numbers less than 100:\n"); for (int n = 0, count = 0; n < 100; ++n) { if (colorful(n)) printf("%2d%c", n, ++count % 10 == 0 ? '\n' : ' '); } count_colorful(0, 0, 0); printf("\n\nLargest colorful number: %'d\n", largest); printf("\nCount of colorful numbers by number of digits:\n"); int total = 0; for (int d = 0; d < 8; ++d) { printf("%d  %'d\n", d + 1, count[d]); total += count[d]; } printf("\nTotal: %'d\n", total); clock_t end = clock(); printf("\nElapsed time: %f seconds\n", (end - start + 0.0) / CLOCKS_PER_SEC); return 0; }
from math import prod largest = [0] def iscolorful(n): if 0 <= n < 10: return True dig = [int(c) for c in str(n)] if 1 in dig or 0 in dig or len(dig) > len(set(dig)): return False products = list(set(dig)) for i in range(len(dig)): for j in range(i+2, len(dig)+1): p = prod(dig[i:j]) if p in products: return False products.append(p) largest[0] = max(n, largest[0]) return True print('Colorful numbers for 1:25, 26:50, 51:75, and 76:100:') for i in range(1, 101, 25): for j in range(25): if iscolorful(i + j): print(f'{i + j: 5,}', end='') print() csum = 0 for i in range(8): j = 0 if i == 0 else 10**i k = 10**(i+1) - 1 n = sum(iscolorful(x) for x in range(j, k+1)) csum += n print(f'The count of colorful numbers between {j} and {k} is {n}.') print(f'The largest possible colorful number is {largest[0]}.') print(f'The total number of colorful numbers is {csum}.')
Change the programming language of this snippet from C to Python without modifying what it does.
#include <stdio.h> #include <stdlib.h> #include <math.h> int day(int y, int m, int d) { return 367 * y - 7 * (y + (m + 9) / 12) / 4 + 275 * m / 9 + d - 730530; } void cycle(int diff, int l, char *t) { int p = round(100 * sin(2 * M_PI * diff / l)); printf("%12s cycle: %3i%%", t, p); if (abs(p) < 15) printf(" (critical day)"); printf("\n"); } int main(int argc, char *argv[]) { int diff; if (argc < 7) { printf("Usage:\n"); printf("cbio y1 m1 d1 y2 m2 d2\n"); exit(1); } diff = abs(day(atoi(argv[1]), atoi(argv[2]), atoi(argv[3])) - day(atoi(argv[4]), atoi(argv[5]), atoi(argv[6]))); printf("Age: %u days\n", diff); cycle(diff, 23, "Physical"); cycle(diff, 28, "Emotional"); cycle(diff, 33, "Intellectual"); }
from datetime import date, timedelta from math import floor, sin, pi def biorhythms(birthdate,targetdate): print("Born: "+birthdate+" Target: "+targetdate) birthdate = date.fromisoformat(birthdate) targetdate = date.fromisoformat(targetdate) days = (targetdate - birthdate).days print("Day: "+str(days)) cycle_labels = ["Physical", "Emotional", "Mental"] cycle_lengths = [23, 28, 33] quadrants = [("up and rising", "peak"), ("up but falling", "transition"), ("down and falling", "valley"), ("down but rising", "transition")] for i in range(3): label = cycle_labels[i] length = cycle_lengths[i] position = days % length quadrant = int(floor((4 * position) / length)) percentage = int(round(100 * sin(2 * pi * position / length),0)) transition_date = targetdate + timedelta(days=floor((quadrant + 1)/4 * length) - position) trend, next = quadrants[quadrant] if percentage > 95: description = "peak" elif percentage < -95: description = "valley" elif abs(percentage) < 5: description = "critical transition" else: description = str(percentage)+"% ("+trend+", next "+next+" "+str(transition_date)+")" print(label+" day "+str(position)+": "+description) biorhythms("1943-03-09","1972-07-11")
Change the programming language of this snippet from C to Python without modifying what it does.
#include <stdio.h> #include <stdlib.h> #include <math.h> int day(int y, int m, int d) { return 367 * y - 7 * (y + (m + 9) / 12) / 4 + 275 * m / 9 + d - 730530; } void cycle(int diff, int l, char *t) { int p = round(100 * sin(2 * M_PI * diff / l)); printf("%12s cycle: %3i%%", t, p); if (abs(p) < 15) printf(" (critical day)"); printf("\n"); } int main(int argc, char *argv[]) { int diff; if (argc < 7) { printf("Usage:\n"); printf("cbio y1 m1 d1 y2 m2 d2\n"); exit(1); } diff = abs(day(atoi(argv[1]), atoi(argv[2]), atoi(argv[3])) - day(atoi(argv[4]), atoi(argv[5]), atoi(argv[6]))); printf("Age: %u days\n", diff); cycle(diff, 23, "Physical"); cycle(diff, 28, "Emotional"); cycle(diff, 33, "Intellectual"); }
from datetime import date, timedelta from math import floor, sin, pi def biorhythms(birthdate,targetdate): print("Born: "+birthdate+" Target: "+targetdate) birthdate = date.fromisoformat(birthdate) targetdate = date.fromisoformat(targetdate) days = (targetdate - birthdate).days print("Day: "+str(days)) cycle_labels = ["Physical", "Emotional", "Mental"] cycle_lengths = [23, 28, 33] quadrants = [("up and rising", "peak"), ("up but falling", "transition"), ("down and falling", "valley"), ("down but rising", "transition")] for i in range(3): label = cycle_labels[i] length = cycle_lengths[i] position = days % length quadrant = int(floor((4 * position) / length)) percentage = int(round(100 * sin(2 * pi * position / length),0)) transition_date = targetdate + timedelta(days=floor((quadrant + 1)/4 * length) - position) trend, next = quadrants[quadrant] if percentage > 95: description = "peak" elif percentage < -95: description = "valley" elif abs(percentage) < 5: description = "critical transition" else: description = str(percentage)+"% ("+trend+", next "+next+" "+str(transition_date)+")" print(label+" day "+str(position)+": "+description) biorhythms("1943-03-09","1972-07-11")
Maintain the same structure and functionality when rewriting this code in Python.
#include <stdio.h> #include <stdlib.h> #include <sqlite3.h> const char *code = "CREATE TABLE address (\n" " addrID INTEGER PRIMARY KEY AUTOINCREMENT,\n" " addrStreet TEXT NOT NULL,\n" " addrCity TEXT NOT NULL,\n" " addrState TEXT NOT NULL,\n" " addrZIP TEXT NOT NULL)\n" ; int main() { sqlite3 *db = NULL; char *errmsg; if ( sqlite3_open("address.db", &db) == SQLITE_OK ) { if ( sqlite3_exec(db, code, NULL, NULL, &errmsg) != SQLITE_OK ) { fprintf(stderr, errmsg); sqlite3_free(errmsg); sqlite3_close(db); exit(EXIT_FAILURE); } sqlite3_close(db); } else { fprintf(stderr, "cannot open db...\n"); sqlite3_close(db); exit(EXIT_FAILURE); } return EXIT_SUCCESS; }
>>> import sqlite3 >>> conn = sqlite3.connect(':memory:') >>> conn.execute() <sqlite3.Cursor object at 0x013265C0> >>>
Rewrite the snippet below in Python so it works the same as the original C code.
#include <stdio.h> #include <math.h> #include <stdlib.h> int header[] = {46, 115, 110, 100, 0, 0, 0, 24, 255, 255, 255, 255, 0, 0, 0, 3, 0, 0, 172, 68, 0, 0, 0, 1}; int main(int argc, char *argv[]){ float freq, dur; long i, v; if (argc < 3) { printf("Usage:\n"); printf(" csine <frequency> <duration>\n"); exit(1); } freq = atof(argv[1]); dur = atof(argv[2]); for (i = 0; i < 24; i++) putchar(header[i]); for (i = 0; i < dur * 44100; i++) { v = (long) round(32000. * sin(2. * M_PI * freq * i / 44100.)); v = v % 65536; putchar(v >> 8); putchar(v % 256); } }
import os from math import pi, sin au_header = bytearray( [46, 115, 110, 100, 0, 0, 0, 24, 255, 255, 255, 255, 0, 0, 0, 3, 0, 0, 172, 68, 0, 0, 0, 1]) def f(x, freq): "Compute sine wave as 16-bit integer" return round(32000 * sin(2 * pi * freq * x / 44100)) % 65536 def play_sine(freq=440, duration=5, oname="pysine.au"): "Play a sine wave for `duration` seconds" out = open(oname, 'wb') out.write(au_header) v = [f(x, freq) for x in range(duration * 44100 + 1)] s = [] for i in v: s.append(i >> 8) s.append(i % 256) out.write(bytearray(s)) out.close() os.system("vlc " + oname) play_sine()
Write the same code in Python as shown below in C.
count = 1; while (count < 10) { print("count is: ", count, "\n"); count = count + 1; }
def load_ast() line = readline() line_list = tokenize the line, respecting double quotes text = line_list[0] if text == ";" return None node_type = text if len(line_list) > 1 return make_leaf(node_type, line_list[1]) left = load_ast() right = load_ast() return make_node(node_type, left, right)
Generate an equivalent Python version of this C code.
count = 1; while (count < 10) { print("count is: ", count, "\n"); count = count + 1; }
def load_ast() line = readline() line_list = tokenize the line, respecting double quotes text = line_list[0] if text == ";" return None node_type = text if len(line_list) > 1 return make_leaf(node_type, line_list[1]) left = load_ast() right = load_ast() return make_node(node_type, left, right)
Generate an equivalent Python version of this C code.
count = 1; while (count < 10) { print("count is: ", count, "\n"); count = count + 1; }
def load_ast() line = readline() line_list = tokenize the line, respecting double quotes text = line_list[0] if text == ";" return None node_type = text if len(line_list) > 1 return make_leaf(node_type, line_list[1]) left = load_ast() right = load_ast() return make_node(node_type, left, right)
Ensure the translated Python code behaves exactly like the original C snippet.
k=2; i=1; j=2; while(k<nn); k++; sb[k]=sb[k-i]+sb[k-j]; k++; sb[k]=sb[k-j]; i++; j++; }
def stern_brocot(predicate=lambda series: len(series) < 20): sb, i = [1, 1], 0 while predicate(sb): sb += [sum(sb[i:i + 2]), sb[i + 1]] i += 1 return sb if __name__ == '__main__': from fractions import gcd n_first = 15 print('The first %i values:\n ' % n_first, stern_brocot(lambda series: len(series) < n_first)[:n_first]) print() n_max = 10 for n_occur in list(range(1, n_max + 1)) + [100]: print('1-based index of the first occurrence of %3i in the series:' % n_occur, stern_brocot(lambda series: n_occur not in series).index(n_occur) + 1) print() n_gcd = 1000 s = stern_brocot(lambda series: len(series) < n_gcd)[:n_gcd] assert all(gcd(prev, this) == 1 for prev, this in zip(s, s[1:])), 'A fraction from adjacent terms is reducible'
Port the provided C code into Python while preserving the original functionality.
#include <stdlib.h> #include <string.h> #include <stdio.h> #include <math.h> typedef struct{ double value; double delta; }imprecise; #define SQR(x) ((x) * (x)) imprecise imprecise_add(imprecise a, imprecise b) { imprecise ret; ret.value = a.value + b.value; ret.delta = sqrt(SQR(a.delta) + SQR(b.delta)); return ret; } imprecise imprecise_mul(imprecise a, imprecise b) { imprecise ret; ret.value = a.value * b.value; ret.delta = sqrt(SQR(a.value * b.delta) + SQR(b.value * a.delta)); return ret; } imprecise imprecise_div(imprecise a, imprecise b) { imprecise ret; ret.value = a.value / b.value; ret.delta = sqrt(SQR(a.value * b.delta) + SQR(b.value * a.delta)) / SQR(b.value); return ret; } imprecise imprecise_pow(imprecise a, double c) { imprecise ret; ret.value = pow(a.value, c); ret.delta = fabs(ret.value * c * a.delta / a.value); return ret; } char* printImprecise(imprecise val) { char principal[30],error[30],*string,sign[2]; sign[0] = 241; sign[1] = 00; sprintf(principal,"%f",val.value); sprintf(error,"%f",val.delta); string = (char*)malloc((strlen(principal)+1+strlen(error)+1)*sizeof(char)); strcpy(string,principal); strcat(string,sign); strcat(string,error); return string; } int main(void) { imprecise x1 = {100, 1.1}; imprecise y1 = {50, 1.2}; imprecise x2 = {-200, 2.2}; imprecise y2 = {-100, 2.3}; imprecise d; d = imprecise_pow(imprecise_add(imprecise_pow(imprecise_add(x1, x2), 2),imprecise_pow(imprecise_add(y1, y2), 2)), 0.5); printf("Distance, d, between the following points :"); printf("\n( x1, y1) = ( %s, %s)",printImprecise(x1),printImprecise(y1)); printf("\n( x2, y2) = ( %s, %s)",printImprecise(x2),printImprecise(y2)); printf("\nis d = %s", printImprecise(d)); return 0; }
from collections import namedtuple import math class I(namedtuple('Imprecise', 'value, delta')): 'Imprecise type: I(value=0.0, delta=0.0)' __slots__ = () def __new__(_cls, value=0.0, delta=0.0): 'Defaults to 0.0 ± delta' return super().__new__(_cls, float(value), abs(float(delta))) def reciprocal(self): return I(1. / self.value, self.delta / (self.value**2)) def __str__(self): 'Shorter form of Imprecise as string' return 'I(%g, %g)' % self def __neg__(self): return I(-self.value, self.delta) def __add__(self, other): if type(other) == I: return I( self.value + other.value, (self.delta**2 + other.delta**2)**0.5 ) try: c = float(other) except: return NotImplemented return I(self.value + c, self.delta) def __sub__(self, other): return self + (-other) def __radd__(self, other): return I.__add__(self, other) def __mul__(self, other): if type(other) == I: a1,b1 = self a2,b2 = other f = a1 * a2 return I( f, f * ( (b1 / a1)**2 + (b2 / a2)**2 )**0.5 ) try: c = float(other) except: return NotImplemented return I(self.value * c, self.delta * c) def __pow__(self, other): if type(other) == I: return NotImplemented try: c = float(other) except: return NotImplemented f = self.value ** c return I(f, f * c * (self.delta / self.value)) def __rmul__(self, other): return I.__mul__(self, other) def __truediv__(self, other): if type(other) == I: return self.__mul__(other.reciprocal()) try: c = float(other) except: return NotImplemented return I(self.value / c, self.delta / c) def __rtruediv__(self, other): return other * self.reciprocal() __div__, __rdiv__ = __truediv__, __rtruediv__ Imprecise = I def distance(p1, p2): x1, y1 = p1 x2, y2 = p2 return ((x1 - x2)**2 + (y1 - y2)**2)**0.5 x1 = I(100, 1.1) x2 = I(200, 2.2) y1 = I( 50, 1.2) y2 = I(100, 2.3) p1, p2 = (x1, y1), (x2, y2) print("Distance between points\n p1: %s\n and p2: %s\n = %r" % ( p1, p2, distance(p1, p2)))
Port the following code from C to Python with equivalent syntax and logic.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> static char code[128] = { 0 }; void add_code(const char *s, int c) { while (*s) { code[(int)*s] = code[0x20 ^ (int)*s] = c; s++; } } void init() { static const char *cls[] = { "AEIOU", "", "BFPV", "CGJKQSXZ", "DT", "L", "MN", "R", 0}; int i; for (i = 0; cls[i]; i++) add_code(cls[i], i - 1); } const char* soundex(const char *s) { static char out[5]; int c, prev, i; out[0] = out[4] = 0; if (!s || !*s) return out; out[0] = *s++; prev = code[(int)out[0]]; for (i = 1; *s && i < 4; s++) { if ((c = code[(int)*s]) == prev) continue; if (c == -1) prev = 0; else if (c > 0) { out[i++] = c + '0'; prev = c; } } while (i < 4) out[i++] = '0'; return out; } int main() { int i; const char *sdx, *names[][2] = { {"Soundex", "S532"}, {"Example", "E251"}, {"Sownteks", "S532"}, {"Ekzampul", "E251"}, {"Euler", "E460"}, {"Gauss", "G200"}, {"Hilbert", "H416"}, {"Knuth", "K530"}, {"Lloyd", "L300"}, {"Lukasiewicz", "L222"}, {"Ellery", "E460"}, {"Ghosh", "G200"}, {"Heilbronn", "H416"}, {"Kant", "K530"}, {"Ladd", "L300"}, {"Lissajous", "L222"}, {"Wheaton", "W350"}, {"Burroughs", "B620"}, {"Burrows", "B620"}, {"O'Hara", "O600"}, {"Washington", "W252"}, {"Lee", "L000"}, {"Gutierrez", "G362"}, {"Pfister", "P236"}, {"Jackson", "J250"}, {"Tymczak", "T522"}, {"VanDeusen", "V532"}, {"Ashcraft", "A261"}, {0, 0} }; init(); puts(" Test name Code Got\n----------------------"); for (i = 0; names[i][0]; i++) { sdx = soundex(names[i][0]); printf("%11s %s %s ", names[i][0], names[i][1], sdx); printf("%s\n", strcmp(sdx, names[i][1]) ? "not ok" : "ok"); } return 0; }
from itertools import groupby def soundex(word): codes = ("bfpv","cgjkqsxz", "dt", "l", "mn", "r") soundDict = dict((ch, str(ix+1)) for ix,cod in enumerate(codes) for ch in cod) cmap2 = lambda kar: soundDict.get(kar, '9') sdx = ''.join(cmap2(kar) for kar in word.lower()) sdx2 = word[0].upper() + ''.join(k for k,g in list(groupby(sdx))[1:] if k!='9') sdx3 = sdx2[0:4].ljust(4,'0') return sdx3
Convert this C snippet to Python and keep its semantics consistent.
#include <stdio.h> #include <stdlib.h> typedef unsigned int uint; typedef unsigned long long tree; #define B(x) (1ULL<<(x)) tree *list = 0; uint cap = 0, len = 0; uint offset[32] = {0, 1, 0}; void append(tree t) { if (len == cap) { cap = cap ? cap*2 : 2; list = realloc(list, cap*sizeof(tree)); } list[len++] = 1 | t<<1; } void show(tree t, uint len) { for (; len--; t >>= 1) putchar(t&1 ? '(' : ')'); } void listtrees(uint n) { uint i; for (i = offset[n]; i < offset[n+1]; i++) { show(list[i], n*2); putchar('\n'); } } void assemble(uint n, tree t, uint sl, uint pos, uint rem) { if (!rem) { append(t); return; } if (sl > rem) pos = offset[sl = rem]; else if (pos >= offset[sl + 1]) { if (!--sl) return; pos = offset[sl]; } assemble(n, t<<(2*sl) | list[pos], sl, pos, rem - sl); assemble(n, t, sl, pos + 1, rem); } void mktrees(uint n) { if (offset[n + 1]) return; if (n) mktrees(n - 1); assemble(n, 0, n-1, offset[n-1], n-1); offset[n+1] = len; } int main(int c, char**v) { int n; if (c < 2 || (n = atoi(v[1])) <= 0 || n > 25) n = 5; append(0); mktrees((uint)n); fprintf(stderr, "Number of %d-trees: %u\n", n, offset[n+1] - offset[n]); listtrees((uint)n); return 0; }
def bags(n,cache={}): if not n: return [(0, "")] upto = sum([bags(x) for x in range(n-1, 0, -1)], []) return [(c+1, '('+s+')') for c,s in bagchain((0, ""), n-1, upto)] def bagchain(x, n, bb, start=0): if not n: return [x] out = [] for i in range(start, len(bb)): c,s = bb[i] if c <= n: out += bagchain((x[0] + c, x[1] + s), n-c, bb, i) return out def replace_brackets(s): depth,out = 0,[] for c in s: if c == '(': out.append("([{"[depth%3]) depth += 1 else: depth -= 1 out.append(")]}"[depth%3]) return "".join(out) for x in bags(5): print(replace_brackets(x[1]))
Translate this program into Python but keep the logic exactly as in C.
int add(int a, int b) { return a + b; }
class Doc(object): def method(self, num): pass
Change the following C code into Python without altering its purpose.
#include <sqlite3.h> #include <stdlib.h> #include <stdio.h> int main() { sqlite3 *db = NULL; char *errmsg; const char *code = "CREATE TABLE employee (\n" " empID INTEGER PRIMARY KEY AUTOINCREMENT,\n" " firstName TEXT NOT NULL,\n" " lastName TEXT NOT NULL,\n" " AGE INTEGER NOT NULL,\n" " DOB DATE NOT NULL)\n" ; if ( sqlite3_open("employee.db", &db) == SQLITE_OK ) { sqlite3_exec(db, code, NULL, NULL, &errmsg); sqlite3_close(db); } else { fprintf(stderr, "cannot open db...\n"); sqlite3_close(db); exit(EXIT_FAILURE); } return 0; }
>>> import sqlite3 >>> conn = sqlite3.connect(':memory:') >>> c = conn.cursor() >>> c.execute() <sqlite3.Cursor object at 0x013263B0> >>> c.execute() <sqlite3.Cursor object at 0x013263B0> >>> for t in [('2006-03-28', 'BUY', 'IBM', 1000, 45.00), ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00), ('2006-04-06', 'SELL', 'IBM', 500, 53.00), ]: c.execute('insert into stocks values (?,?,?,?,?)', t) <sqlite3.Cursor object at 0x013263B0> <sqlite3.Cursor object at 0x013263B0> <sqlite3.Cursor object at 0x013263B0> >>> >>> c = conn.cursor() >>> c.execute('select * from stocks order by price') <sqlite3.Cursor object at 0x01326530> >>> for row in c: print row (u'2006-01-05', u'BUY', u'RHAT', 100.0, 35.140000000000001) (u'2006-03-28', u'BUY', u'IBM', 1000.0, 45.0) (u'2006-04-06', u'SELL', u'IBM', 500.0, 53.0) (u'2006-04-05', u'BUY', u'MSOFT', 1000.0, 72.0) >>>
Port the following code from C to Python with equivalent syntax and logic.
#include <sqlite3.h> #include <stdlib.h> #include <stdio.h> int main() { sqlite3 *db = NULL; char *errmsg; const char *code = "CREATE TABLE employee (\n" " empID INTEGER PRIMARY KEY AUTOINCREMENT,\n" " firstName TEXT NOT NULL,\n" " lastName TEXT NOT NULL,\n" " AGE INTEGER NOT NULL,\n" " DOB DATE NOT NULL)\n" ; if ( sqlite3_open("employee.db", &db) == SQLITE_OK ) { sqlite3_exec(db, code, NULL, NULL, &errmsg); sqlite3_close(db); } else { fprintf(stderr, "cannot open db...\n"); sqlite3_close(db); exit(EXIT_FAILURE); } return 0; }
>>> import sqlite3 >>> conn = sqlite3.connect(':memory:') >>> c = conn.cursor() >>> c.execute() <sqlite3.Cursor object at 0x013263B0> >>> c.execute() <sqlite3.Cursor object at 0x013263B0> >>> for t in [('2006-03-28', 'BUY', 'IBM', 1000, 45.00), ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00), ('2006-04-06', 'SELL', 'IBM', 500, 53.00), ]: c.execute('insert into stocks values (?,?,?,?,?)', t) <sqlite3.Cursor object at 0x013263B0> <sqlite3.Cursor object at 0x013263B0> <sqlite3.Cursor object at 0x013263B0> >>> >>> c = conn.cursor() >>> c.execute('select * from stocks order by price') <sqlite3.Cursor object at 0x01326530> >>> for row in c: print row (u'2006-01-05', u'BUY', u'RHAT', 100.0, 35.140000000000001) (u'2006-03-28', u'BUY', u'IBM', 1000.0, 45.0) (u'2006-04-06', u'SELL', u'IBM', 500.0, 53.0) (u'2006-04-05', u'BUY', u'MSOFT', 1000.0, 72.0) >>>
Convert the following code from C to Python, ensuring the logic remains intact.
#include <stdio.h> #include <tgmath.h> #define VERBOSE 0 #define for3 for(int i = 0; i < 3; i++) typedef complex double vec; typedef struct { vec c; double r; } circ; #define re(x) creal(x) #define im(x) cimag(x) #define cp(x) re(x), im(x) #define CPLX "(%6.3f,%6.3f)" #define CPLX3 CPLX" "CPLX" "CPLX double cross(vec a, vec b) { return re(a) * im(b) - im(a) * re(b); } double abs2(vec a) { return a * conj(a); } int apollonius_in(circ aa[], int ss[], int flip, int divert) { vec n[3], x[3], t[3], a, b, center; int s[3], iter = 0, res = 0; double diff = 1, diff_old = -1, axb, d, r; for3 { s[i] = ss[i] ? 1 : -1; x[i] = aa[i].c; } while (diff > 1e-20) { a = x[0] - x[2], b = x[1] - x[2]; diff = 0; axb = -cross(a, b); d = sqrt(abs2(a) * abs2(b) * abs2(a - b)); if (VERBOSE) { const char *z = 1 + "-0+"; printf("%c%c%c|%c%c|", z[s[0]], z[s[1]], z[s[2]], z[flip], z[divert]); printf(CPLX3, cp(x[0]), cp(x[1]), cp(x[2])); } r = fabs(d / (2 * axb)); center = (abs2(a)*b - abs2(b)*a) / (2 * axb) * I + x[2]; if (!axb && flip != -1 && !divert) { if (!d) { printf("Given conditions confused me.\n"); return 0; } if (VERBOSE) puts("\n[divert]"); divert = 1; res = apollonius_in(aa, ss, -1, 1); } for3 n[i] = axb ? aa[i].c - center : a * I * flip; for3 t[i] = aa[i].c + n[i] / cabs(n[i]) * aa[i].r * s[i]; for3 diff += abs2(t[i] - x[i]), x[i] = t[i]; if (VERBOSE) printf(" %g\n", diff); if (diff >= diff_old && diff_old >= 0) if (iter++ > 20) return res; diff_old = diff; } printf("found: "); if (axb) printf("circle "CPLX", r = %f\n", cp(center), r); else printf("line "CPLX3"\n", cp(x[0]), cp(x[1]), cp(x[2])); return res + 1; } int apollonius(circ aa[]) { int s[3], i, sum = 0; for (i = 0; i < 8; i++) { s[0] = i & 1, s[1] = i & 2, s[2] = i & 4; if (s[0] && !aa[0].r) continue; if (s[1] && !aa[1].r) continue; if (s[2] && !aa[2].r) continue; sum += apollonius_in(aa, s, 1, 0); } return sum; } int main() { circ a[3] = {{0, 1}, {4, 1}, {2 + 4 * I, 1}}; circ b[3] = {{-3, 2}, {0, 1}, {3, 2}}; circ c[3] = {{-2, 1}, {0, 1}, {2 * I, 1}}; puts("set 1"); apollonius(a); puts("set 2"); apollonius(b); puts("set 3"); apollonius(c); }
from collections import namedtuple import math Circle = namedtuple('Circle', 'x, y, r') def solveApollonius(c1, c2, c3, s1, s2, s3): x1, y1, r1 = c1 x2, y2, r2 = c2 x3, y3, r3 = c3 v11 = 2*x2 - 2*x1 v12 = 2*y2 - 2*y1 v13 = x1*x1 - x2*x2 + y1*y1 - y2*y2 - r1*r1 + r2*r2 v14 = 2*s2*r2 - 2*s1*r1 v21 = 2*x3 - 2*x2 v22 = 2*y3 - 2*y2 v23 = x2*x2 - x3*x3 + y2*y2 - y3*y3 - r2*r2 + r3*r3 v24 = 2*s3*r3 - 2*s2*r2 w12 = v12/v11 w13 = v13/v11 w14 = v14/v11 w22 = v22/v21-w12 w23 = v23/v21-w13 w24 = v24/v21-w14 P = -w23/w22 Q = w24/w22 M = -w12*P-w13 N = w14 - w12*Q a = N*N + Q*Q - 1 b = 2*M*N - 2*N*x1 + 2*P*Q - 2*Q*y1 + 2*s1*r1 c = x1*x1 + M*M - 2*M*x1 + P*P + y1*y1 - 2*P*y1 - r1*r1 D = b*b-4*a*c rs = (-b-math.sqrt(D))/(2*a) xs = M+N*rs ys = P+Q*rs return Circle(xs, ys, rs) if __name__ == '__main__': c1, c2, c3 = Circle(0, 0, 1), Circle(4, 0, 1), Circle(2, 4, 2) print(solveApollonius(c1, c2, c3, 1, 1, 1)) print(solveApollonius(c1, c2, c3, -1, -1, -1))
Keep all operations the same but rewrite the snippet in Python.
#include<stdio.h> #include<stdlib.h> int main(void) { int list[3][9], i; for(i=0;i<27;i++) list[i/9][i%9]=1+i; for(i=0;i<9;i++) printf( "%d%d%d ", list[0][i], list[1][i], list[2][i] ); return 0; }
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9] list2 = [10, 11, 12, 13, 14, 15, 16, 17, 18] list3 = [19, 20, 21, 22, 23, 24, 25, 26, 27] print([ ''.join(str(n) for n in z) for z in zip(list1, list2, list3) ])
Keep all operations the same but rewrite the snippet in Python.
#include<stdio.h> #include<stdlib.h> int main(void) { int list[3][9], i; for(i=0;i<27;i++) list[i/9][i%9]=1+i; for(i=0;i<9;i++) printf( "%d%d%d ", list[0][i], list[1][i], list[2][i] ); return 0; }
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9] list2 = [10, 11, 12, 13, 14, 15, 16, 17, 18] list3 = [19, 20, 21, 22, 23, 24, 25, 26, 27] print([ ''.join(str(n) for n in z) for z in zip(list1, list2, list3) ])
Translate the given C code snippet into Python without altering its behavior.
#include<stdio.h> #include<stdlib.h> int main(void) { int list[3][9], i; for(i=0;i<27;i++) list[i/9][i%9]=1+i; for(i=0;i<9;i++) printf( "%d%d%d ", list[0][i], list[1][i], list[2][i] ); return 0; }
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9] list2 = [10, 11, 12, 13, 14, 15, 16, 17, 18] list3 = [19, 20, 21, 22, 23, 24, 25, 26, 27] print([ ''.join(str(n) for n in z) for z in zip(list1, list2, list3) ])
Write a version of this C function in Python with identical behavior.
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct node_t { char *elem; int length; struct node_t *next; } node; node *make_node(char *s) { node *t = malloc(sizeof(node)); t->elem = s; t->length = strlen(s); t->next = NULL; return t; } void append_node(node *head, node *elem) { while (head->next != NULL) { head = head->next; } head->next = elem; } void print_node(node *n) { putc('[', stdout); while (n != NULL) { printf("`%s` ", n->elem); n = n->next; } putc(']', stdout); } char *lcs(node *list) { int minLen = INT_MAX; int i; char *res; node *ptr; if (list == NULL) { return ""; } if (list->next == NULL) { return list->elem; } for (ptr = list; ptr != NULL; ptr = ptr->next) { minLen = min(minLen, ptr->length); } if (minLen == 0) { return ""; } res = ""; for (i = 1; i < minLen; i++) { char *suffix = &list->elem[list->length - i]; for (ptr = list->next; ptr != NULL; ptr = ptr->next) { char *e = &ptr->elem[ptr->length - i]; if (strcmp(suffix, e) != 0) { return res; } } res = suffix; } return res; } void test(node *n) { print_node(n); printf(" -> `%s`\n", lcs(n)); } void case1() { node *n = make_node("baabababc"); append_node(n, make_node("baabc")); append_node(n, make_node("bbbabc")); test(n); } void case2() { node *n = make_node("baabababc"); append_node(n, make_node("baabc")); append_node(n, make_node("bbbazc")); test(n); } void case3() { node *n = make_node("Sunday"); append_node(n, make_node("Monday")); append_node(n, make_node("Tuesday")); append_node(n, make_node("Wednesday")); append_node(n, make_node("Thursday")); append_node(n, make_node("Friday")); append_node(n, make_node("Saturday")); test(n); } void case4() { node *n = make_node("longest"); append_node(n, make_node("common")); append_node(n, make_node("suffix")); test(n); } void case5() { node *n = make_node("suffix"); test(n); } void case6() { node *n = make_node(""); test(n); } int main() { case1(); case2(); case3(); case4(); case5(); case6(); return 0; }
from itertools import takewhile from functools import reduce def longestCommonSuffix(xs): def allSame(cs): h = cs[0] return all(h == c for c in cs[1:]) def firstCharPrepended(s, cs): return cs[0] + s return reduce( firstCharPrepended, takewhile( allSame, zip(*(reversed(x) for x in xs)) ), '' ) def main(): samples = [ [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ], [ "Sondag", "Maandag", "Dinsdag", "Woensdag", "Donderdag", "Vrydag", "Saterdag" ] ] for xs in samples: print( longestCommonSuffix(xs) ) if __name__ == '__main__': main()
Can you help me rewrite this code in Python instead of C, keeping it the same logically?
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct node_t { char *elem; int length; struct node_t *next; } node; node *make_node(char *s) { node *t = malloc(sizeof(node)); t->elem = s; t->length = strlen(s); t->next = NULL; return t; } void append_node(node *head, node *elem) { while (head->next != NULL) { head = head->next; } head->next = elem; } void print_node(node *n) { putc('[', stdout); while (n != NULL) { printf("`%s` ", n->elem); n = n->next; } putc(']', stdout); } char *lcs(node *list) { int minLen = INT_MAX; int i; char *res; node *ptr; if (list == NULL) { return ""; } if (list->next == NULL) { return list->elem; } for (ptr = list; ptr != NULL; ptr = ptr->next) { minLen = min(minLen, ptr->length); } if (minLen == 0) { return ""; } res = ""; for (i = 1; i < minLen; i++) { char *suffix = &list->elem[list->length - i]; for (ptr = list->next; ptr != NULL; ptr = ptr->next) { char *e = &ptr->elem[ptr->length - i]; if (strcmp(suffix, e) != 0) { return res; } } res = suffix; } return res; } void test(node *n) { print_node(n); printf(" -> `%s`\n", lcs(n)); } void case1() { node *n = make_node("baabababc"); append_node(n, make_node("baabc")); append_node(n, make_node("bbbabc")); test(n); } void case2() { node *n = make_node("baabababc"); append_node(n, make_node("baabc")); append_node(n, make_node("bbbazc")); test(n); } void case3() { node *n = make_node("Sunday"); append_node(n, make_node("Monday")); append_node(n, make_node("Tuesday")); append_node(n, make_node("Wednesday")); append_node(n, make_node("Thursday")); append_node(n, make_node("Friday")); append_node(n, make_node("Saturday")); test(n); } void case4() { node *n = make_node("longest"); append_node(n, make_node("common")); append_node(n, make_node("suffix")); test(n); } void case5() { node *n = make_node("suffix"); test(n); } void case6() { node *n = make_node(""); test(n); } int main() { case1(); case2(); case3(); case4(); case5(); case6(); return 0; }
from itertools import takewhile from functools import reduce def longestCommonSuffix(xs): def allSame(cs): h = cs[0] return all(h == c for c in cs[1:]) def firstCharPrepended(s, cs): return cs[0] + s return reduce( firstCharPrepended, takewhile( allSame, zip(*(reversed(x) for x in xs)) ), '' ) def main(): samples = [ [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ], [ "Sondag", "Maandag", "Dinsdag", "Woensdag", "Donderdag", "Vrydag", "Saterdag" ] ] for xs in samples: print( longestCommonSuffix(xs) ) if __name__ == '__main__': main()
Please provide an equivalent version of this C code in Python.
#include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <sys/select.h> #include <netinet/in.h> #include <netinet/ip.h> int tsocket; struct sockaddr_in tsockinfo; fd_set status, current; void ClientText(int handle, char *buf, int buf_len); struct client { char buffer[4096]; int pos; char name[32]; } *connections[FD_SETSIZE]; void AddConnection(int handle) { connections[handle] = malloc(sizeof(struct client)); connections[handle]->buffer[0] = '\0'; connections[handle]->pos = 0; connections[handle]->name[0] = '\0'; } void CloseConnection(int handle) { char buf[512]; int j; FD_CLR(handle, &status); if (connections[handle]->name[0]) { sprintf(buf, "* Disconnected: %s\r\n", connections[handle]->name); for (j = 0; j < FD_SETSIZE; j++) { if (handle != j && j != tsocket && FD_ISSET(j, &status)) { if (write(j, buf, strlen(buf)) < 0) { CloseConnection(j); } } } } else { printf ("-- Connection %d disconnected\n", handle); } if (connections[handle]) { free(connections[handle]); } close(handle); } void strip(char *buf) { char *x; x = strchr(buf, '\n'); if (x) { *x='\0'; } x = strchr(buf, '\r'); if (x) { *x='\0'; } } int RelayText(int handle) { char *begin, *end; int ret = 0; begin = connections[handle]->buffer; if (connections[handle]->pos == 4000) { if (begin[3999] != '\n') begin[4000] = '\0'; else { begin[4000] = '\n'; begin[4001] = '\0'; } } else { begin[connections[handle]->pos] = '\0'; } end = strchr(begin, '\n'); while (end != NULL) { char output[8000]; output[0] = '\0'; if (!connections[handle]->name[0]) { strncpy(connections[handle]->name, begin, 31); connections[handle]->name[31] = '\0'; strip(connections[handle]->name); sprintf(output, "* Connected: %s\r\n", connections[handle]->name); ret = 1; } else { sprintf(output, "%s: %.*s\r\n", connections[handle]->name, end-begin, begin); ret = 1; } if (output[0]) { int j; for (j = 0; j < FD_SETSIZE; j++) { if (handle != j && j != tsocket && FD_ISSET(j, &status)) { if (write(j, output, strlen(output)) < 0) { CloseConnection(j); } } } } begin = end+1; end = strchr(begin, '\n'); } strcpy(connections[handle]->buffer, begin); connections[handle]->pos -= begin - connections[handle]->buffer; return ret; } void ClientText(int handle, char *buf, int buf_len) { int i, j; if (!connections[handle]) return; j = connections[handle]->pos; for (i = 0; i < buf_len; ++i, ++j) { connections[handle]->buffer[j] = buf[i]; if (j == 4000) { while (RelayText(handle)); j = connections[handle]->pos; } } connections[handle]->pos = j; while (RelayText(handle)); } int ChatLoop() { int i, j; FD_ZERO(&status); FD_SET(tsocket, &status); FD_SET(0, &status); while(1) { current = status; if (select(FD_SETSIZE, &current, NULL, NULL, NULL)==-1) { perror("Select"); return 0; } for (i = 0; i < FD_SETSIZE; ++i) { if (FD_ISSET(i, &current)) { if (i == tsocket) { struct sockaddr_in cliinfo; socklen_t addrlen = sizeof(cliinfo); int handle; handle = accept(tsocket, &cliinfo, &addrlen); if (handle == -1) { perror ("Couldn't accept connection"); } else if (handle > FD_SETSIZE) { printf ("Unable to accept new connection.\n"); close(handle); } else { if (write(handle, "Enter name: ", 12) >= 0) { printf("-- New connection %d from %s:%hu\n", handle, inet_ntoa (cliinfo.sin_addr), ntohs(cliinfo.sin_port)); FD_SET(handle, &status); AddConnection(handle); } } } else { char buf[512]; int b; b = read(i, buf, 500); if (b <= 0) { CloseConnection(i); } else { ClientText(i, buf, b); } } } } } } int main (int argc, char*argv[]) { tsocket = socket(PF_INET, SOCK_STREAM, 0); tsockinfo.sin_family = AF_INET; tsockinfo.sin_port = htons(7070); if (argc > 1) { tsockinfo.sin_port = htons(atoi(argv[1])); } tsockinfo.sin_addr.s_addr = htonl(INADDR_ANY); printf ("Socket %d on port %hu\n", tsocket, ntohs(tsockinfo.sin_port)); if (bind(tsocket, &tsockinfo, sizeof(tsockinfo)) == -1) { perror("Couldn't bind socket"); return -1; } if (listen(tsocket, 10) == -1) { perror("Couldn't listen to port"); } ChatLoop(); return 0; }
import socket import thread import time HOST = "" PORT = 4004 def accept(conn): def threaded(): while True: conn.send("Please enter your name: ") try: name = conn.recv(1024).strip() except socket.error: continue if name in users: conn.send("Name entered is already in use.\n") elif name: conn.setblocking(False) users[name] = conn broadcast(name, "+++ %s arrived +++" % name) break thread.start_new_thread(threaded, ()) def broadcast(name, message): print message for to_name, conn in users.items(): if to_name != name: try: conn.send(message + "\n") except socket.error: pass server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server.setblocking(False) server.bind((HOST, PORT)) server.listen(1) print "Listening on %s" % ("%s:%s" % server.getsockname()) users = {} while True: try: while True: try: conn, addr = server.accept() except socket.error: break accept(conn) for name, conn in users.items(): try: message = conn.recv(1024) except socket.error: continue if not message: del users[name] broadcast(name, "--- %s leaves ---" % name) else: broadcast(name, "%s> %s" % (name, message.strip())) time.sleep(.1) except (SystemExit, KeyboardInterrupt): break
Generate a Python translation of this C snippet without changing its computational steps.
#include <stdio.h> int main(int argc, char const *argv[]) { for (char c = 0x41; c < 0x5b; c ++) putchar(c); putchar('\n'); for (char c = 0x61; c < 0x7b; c ++) putchar(c); putchar('\n'); return 0; }
classes = (str.isupper, str.islower, str.isalnum, str.isalpha, str.isdecimal, str.isdigit, str.isidentifier, str.isnumeric, str.isprintable, str.isspace, str.istitle) for stringclass in classes: chars = ''.join(chr(i) for i in range(0x10FFFF+1) if stringclass(chr(i))) print('\nString class %s has %i characters the first of which are:\n %r' % (stringclass.__name__, len(chars), chars[:100]))
Convert the following code from C to Python, ensuring the logic remains intact.
#include<stdlib.h> #include<stdio.h> typedef struct{ int rows,cols; int** dataSet; }matrix; matrix readMatrix(char* dataFile){ FILE* fp = fopen(dataFile,"r"); matrix rosetta; int i,j; fscanf(fp,"%d%d",&rosetta.rows,&rosetta.cols); rosetta.dataSet = (int**)malloc(rosetta.rows*sizeof(int*)); for(i=0;i<rosetta.rows;i++){ rosetta.dataSet[i] = (int*)malloc(rosetta.cols*sizeof(int)); for(j=0;j<rosetta.cols;j++) fscanf(fp,"%d",&rosetta.dataSet[i][j]); } fclose(fp); return rosetta; } void printMatrix(matrix rosetta){ int i,j; for(i=0;i<rosetta.rows;i++){ printf("\n"); for(j=0;j<rosetta.cols;j++) printf("%3d",rosetta.dataSet[i][j]); } } int findSum(matrix rosetta){ int i,j,sum = 0; for(i=1;i<rosetta.rows;i++){ for(j=0;j<i;j++){ sum += rosetta.dataSet[i][j]; } } return sum; } int main(int argC,char* argV[]) { if(argC!=2) return printf("Usage : %s <filename>",argV[0]); matrix data = readMatrix(argV[1]); printf("\n\nMatrix is : \n\n"); printMatrix(data); printf("\n\nSum below main diagonal : %d",findSum(data)); return 0; }
from numpy import array, tril, sum A = [[1,3,7,8,10], [2,4,16,14,4], [3,1,9,18,11], [12,14,17,18,20], [7,1,3,9,5]] print(sum(tril(A, -1)))
Generate a Python translation of this C snippet without changing its computational steps.
#include<curl/curl.h> #include<string.h> #include<stdio.h> #define MAX_LEN 1000 void searchChatLogs(char* searchString){ char* baseURL = "http: time_t t; struct tm* currentDate; char dateString[30],dateStringFile[30],lineData[MAX_LEN],targetURL[100]; int i,flag; FILE *fp; CURL *curl; CURLcode res; time(&t); currentDate = localtime(&t); strftime(dateString, 30, "%Y-%m-%d", currentDate); printf("Today is : %s",dateString); if((curl = curl_easy_init())!=NULL){ for(i=0;i<=10;i++){ flag = 0; sprintf(targetURL,"%s%s.tcl",baseURL,dateString); strcpy(dateStringFile,dateString); printf("\nRetrieving chat logs from %s\n",targetURL); if((fp = fopen("nul","w"))==0){ printf("Cant's read from %s",targetURL); } else{ curl_easy_setopt(curl, CURLOPT_URL, targetURL); curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp); res = curl_easy_perform(curl); if(res == CURLE_OK){ while(fgets(lineData,MAX_LEN,fp)!=NULL){ if(strstr(lineData,searchString)!=NULL){ flag = 1; fputs(lineData,stdout); } } if(flag==0) printf("\nNo matching lines found."); } fflush(fp); fclose(fp); } currentDate->tm_mday--; mktime(currentDate); strftime(dateString, 30, "%Y-%m-%d", currentDate); } curl_easy_cleanup(curl); } } int main(int argC,char* argV[]) { if(argC!=2) printf("Usage : %s <followed by search string, enclosed by \" if it contains spaces>",argV[0]); else searchChatLogs(argV[1]); return 0; }
import datetime import re import urllib.request import sys def get(url): with urllib.request.urlopen(url) as response: html = response.read().decode('utf-8') if re.match(r'<!Doctype HTML[\s\S]*<Title>URL Not Found</Title>', html): return None return html def main(): template = 'http://tclers.tk/conferences/tcl/%Y-%m-%d.tcl' today = datetime.datetime.utcnow() back = 10 needle = sys.argv[1] for i in range(-back, 2): day = today + datetime.timedelta(days=i) url = day.strftime(template) haystack = get(url) if haystack: mentions = [x for x in haystack.split('\n') if needle in x] if mentions: print('{}\n------\n{}\n------\n' .format(url, '\n'.join(mentions))) main()
Write a version of this C function in Python with identical behavior.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <curl/curl.h> #include "wren.h" struct MemoryStruct { char *memory; size_t size; }; static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) { size_t realsize = size * nmemb; struct MemoryStruct *mem = (struct MemoryStruct *)userp; char *ptr = realloc(mem->memory, mem->size + realsize + 1); if(!ptr) { printf("not enough memory (realloc returned NULL)\n"); return 0; } mem->memory = ptr; memcpy(&(mem->memory[mem->size]), contents, realsize); mem->size += realsize; mem->memory[mem->size] = 0; return realsize; } void C_bufferAllocate(WrenVM* vm) { struct MemoryStruct *ms = (struct MemoryStruct *)wrenSetSlotNewForeign(vm, 0, 0, sizeof(struct MemoryStruct)); ms->memory = malloc(1); ms->size = 0; } void C_bufferFinalize(void* data) { struct MemoryStruct *ms = (struct MemoryStruct *)data; free(ms->memory); } void C_curlAllocate(WrenVM* vm) { CURL** pcurl = (CURL**)wrenSetSlotNewForeign(vm, 0, 0, sizeof(CURL*)); *pcurl = curl_easy_init(); } void C_value(WrenVM* vm) { struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 0); wrenSetSlotString(vm, 0, ms->memory); } void C_easyPerform(WrenVM* vm) { CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0); curl_easy_perform(curl); } void C_easyCleanup(WrenVM* vm) { CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0); curl_easy_cleanup(curl); } void C_easySetOpt(WrenVM* vm) { CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0); CURLoption opt = (CURLoption)wrenGetSlotDouble(vm, 1); if (opt < 10000) { long lparam = (long)wrenGetSlotDouble(vm, 2); curl_easy_setopt(curl, opt, lparam); } else if (opt < 20000) { if (opt == CURLOPT_WRITEDATA) { struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 2); curl_easy_setopt(curl, opt, (void *)ms); } else if (opt == CURLOPT_URL) { const char *url = wrenGetSlotString(vm, 2); curl_easy_setopt(curl, opt, url); } } else if (opt < 30000) { if (opt == CURLOPT_WRITEFUNCTION) { curl_easy_setopt(curl, opt, &WriteMemoryCallback); } } } WrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) { WrenForeignClassMethods methods; methods.allocate = NULL; methods.finalize = NULL; if (strcmp(module, "main") == 0) { if (strcmp(className, "Buffer") == 0) { methods.allocate = C_bufferAllocate; methods.finalize = C_bufferFinalize; } else if (strcmp(className, "Curl") == 0) { methods.allocate = C_curlAllocate; } } return methods; } WrenForeignMethodFn bindForeignMethod( WrenVM* vm, const char* module, const char* className, bool isStatic, const char* signature) { if (strcmp(module, "main") == 0) { if (strcmp(className, "Buffer") == 0) { if (!isStatic && strcmp(signature, "value") == 0) return C_value; } else if (strcmp(className, "Curl") == 0) { if (!isStatic && strcmp(signature, "easySetOpt(_,_)") == 0) return C_easySetOpt; if (!isStatic && strcmp(signature, "easyPerform()") == 0) return C_easyPerform; if (!isStatic && strcmp(signature, "easyCleanup()") == 0) return C_easyCleanup; } } return NULL; } static void writeFn(WrenVM* vm, const char* text) { printf("%s", text); } void errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) { switch (errorType) { case WREN_ERROR_COMPILE: printf("[%s line %d] [Error] %s\n", module, line, msg); break; case WREN_ERROR_STACK_TRACE: printf("[%s line %d] in %s\n", module, line, msg); break; case WREN_ERROR_RUNTIME: printf("[Runtime Error] %s\n", msg); break; } } char *readFile(const char *fileName) { FILE *f = fopen(fileName, "r"); fseek(f, 0, SEEK_END); long fsize = ftell(f); rewind(f); char *script = malloc(fsize + 1); fread(script, 1, fsize, f); fclose(f); script[fsize] = 0; return script; } static void loadModuleComplete(WrenVM* vm, const char* module, WrenLoadModuleResult result) { if( result.source) free((void*)result.source); } WrenLoadModuleResult loadModule(WrenVM* vm, const char* name) { WrenLoadModuleResult result = {0}; if (strcmp(name, "random") != 0 && strcmp(name, "meta") != 0) { result.onComplete = loadModuleComplete; char fullName[strlen(name) + 6]; strcpy(fullName, name); strcat(fullName, ".wren"); result.source = readFile(fullName); } return result; } int main(int argc, char **argv) { WrenConfiguration config; wrenInitConfiguration(&config); config.writeFn = &writeFn; config.errorFn = &errorFn; config.bindForeignClassFn = &bindForeignClass; config.bindForeignMethodFn = &bindForeignMethod; config.loadModuleFn = &loadModule; WrenVM* vm = wrenNewVM(&config); const char* module = "main"; const char* fileName = "rc_rank_languages_by_number_of_users.wren"; char *script = readFile(fileName); WrenInterpretResult result = wrenInterpret(vm, module, script); switch (result) { case WREN_RESULT_COMPILE_ERROR: printf("Compile Error!\n"); break; case WREN_RESULT_RUNTIME_ERROR: printf("Runtime Error!\n"); break; case WREN_RESULT_SUCCESS: break; } wrenFreeVM(vm); free(script); return 0; }
import requests URL = "http://rosettacode.org/mw/api.php" PARAMS = { "action": "query", "format": "json", "formatversion": 2, "generator": "categorymembers", "gcmtitle": "Category:Language users", "gcmlimit": 500, "prop": "categoryinfo", } def fetch_data(): counts = {} continue_ = {"continue": ""} while continue_: resp = requests.get(URL, params={**PARAMS, **continue_}) resp.raise_for_status() data = resp.json() counts.update( { p["title"]: p.get("categoryinfo", {}).get("size", 0) for p in data["query"]["pages"] } ) continue_ = data.get("continue", {}) return counts if __name__ == "__main__": counts = fetch_data() at_least_100 = [(lang, count) for lang, count in counts.items() if count >= 100] top_languages = sorted(at_least_100, key=lambda x: x[1], reverse=True) for i, lang in enumerate(top_languages): print(f"{i+1:<5}{lang[0][9:][:-5]:<20}{lang[1]}")
Port the following code from C to Python with equivalent syntax and logic.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <curl/curl.h> #include "wren.h" struct MemoryStruct { char *memory; size_t size; }; static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) { size_t realsize = size * nmemb; struct MemoryStruct *mem = (struct MemoryStruct *)userp; char *ptr = realloc(mem->memory, mem->size + realsize + 1); if(!ptr) { printf("not enough memory (realloc returned NULL)\n"); return 0; } mem->memory = ptr; memcpy(&(mem->memory[mem->size]), contents, realsize); mem->size += realsize; mem->memory[mem->size] = 0; return realsize; } void C_bufferAllocate(WrenVM* vm) { struct MemoryStruct *ms = (struct MemoryStruct *)wrenSetSlotNewForeign(vm, 0, 0, sizeof(struct MemoryStruct)); ms->memory = malloc(1); ms->size = 0; } void C_bufferFinalize(void* data) { struct MemoryStruct *ms = (struct MemoryStruct *)data; free(ms->memory); } void C_curlAllocate(WrenVM* vm) { CURL** pcurl = (CURL**)wrenSetSlotNewForeign(vm, 0, 0, sizeof(CURL*)); *pcurl = curl_easy_init(); } void C_value(WrenVM* vm) { struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 0); wrenSetSlotString(vm, 0, ms->memory); } void C_easyPerform(WrenVM* vm) { CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0); curl_easy_perform(curl); } void C_easyCleanup(WrenVM* vm) { CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0); curl_easy_cleanup(curl); } void C_easySetOpt(WrenVM* vm) { CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0); CURLoption opt = (CURLoption)wrenGetSlotDouble(vm, 1); if (opt < 10000) { long lparam = (long)wrenGetSlotDouble(vm, 2); curl_easy_setopt(curl, opt, lparam); } else if (opt < 20000) { if (opt == CURLOPT_WRITEDATA) { struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 2); curl_easy_setopt(curl, opt, (void *)ms); } else if (opt == CURLOPT_URL) { const char *url = wrenGetSlotString(vm, 2); curl_easy_setopt(curl, opt, url); } } else if (opt < 30000) { if (opt == CURLOPT_WRITEFUNCTION) { curl_easy_setopt(curl, opt, &WriteMemoryCallback); } } } WrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) { WrenForeignClassMethods methods; methods.allocate = NULL; methods.finalize = NULL; if (strcmp(module, "main") == 0) { if (strcmp(className, "Buffer") == 0) { methods.allocate = C_bufferAllocate; methods.finalize = C_bufferFinalize; } else if (strcmp(className, "Curl") == 0) { methods.allocate = C_curlAllocate; } } return methods; } WrenForeignMethodFn bindForeignMethod( WrenVM* vm, const char* module, const char* className, bool isStatic, const char* signature) { if (strcmp(module, "main") == 0) { if (strcmp(className, "Buffer") == 0) { if (!isStatic && strcmp(signature, "value") == 0) return C_value; } else if (strcmp(className, "Curl") == 0) { if (!isStatic && strcmp(signature, "easySetOpt(_,_)") == 0) return C_easySetOpt; if (!isStatic && strcmp(signature, "easyPerform()") == 0) return C_easyPerform; if (!isStatic && strcmp(signature, "easyCleanup()") == 0) return C_easyCleanup; } } return NULL; } static void writeFn(WrenVM* vm, const char* text) { printf("%s", text); } void errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) { switch (errorType) { case WREN_ERROR_COMPILE: printf("[%s line %d] [Error] %s\n", module, line, msg); break; case WREN_ERROR_STACK_TRACE: printf("[%s line %d] in %s\n", module, line, msg); break; case WREN_ERROR_RUNTIME: printf("[Runtime Error] %s\n", msg); break; } } char *readFile(const char *fileName) { FILE *f = fopen(fileName, "r"); fseek(f, 0, SEEK_END); long fsize = ftell(f); rewind(f); char *script = malloc(fsize + 1); fread(script, 1, fsize, f); fclose(f); script[fsize] = 0; return script; } static void loadModuleComplete(WrenVM* vm, const char* module, WrenLoadModuleResult result) { if( result.source) free((void*)result.source); } WrenLoadModuleResult loadModule(WrenVM* vm, const char* name) { WrenLoadModuleResult result = {0}; if (strcmp(name, "random") != 0 && strcmp(name, "meta") != 0) { result.onComplete = loadModuleComplete; char fullName[strlen(name) + 6]; strcpy(fullName, name); strcat(fullName, ".wren"); result.source = readFile(fullName); } return result; } int main(int argc, char **argv) { WrenConfiguration config; wrenInitConfiguration(&config); config.writeFn = &writeFn; config.errorFn = &errorFn; config.bindForeignClassFn = &bindForeignClass; config.bindForeignMethodFn = &bindForeignMethod; config.loadModuleFn = &loadModule; WrenVM* vm = wrenNewVM(&config); const char* module = "main"; const char* fileName = "rc_rank_languages_by_number_of_users.wren"; char *script = readFile(fileName); WrenInterpretResult result = wrenInterpret(vm, module, script); switch (result) { case WREN_RESULT_COMPILE_ERROR: printf("Compile Error!\n"); break; case WREN_RESULT_RUNTIME_ERROR: printf("Runtime Error!\n"); break; case WREN_RESULT_SUCCESS: break; } wrenFreeVM(vm); free(script); return 0; }
import requests URL = "http://rosettacode.org/mw/api.php" PARAMS = { "action": "query", "format": "json", "formatversion": 2, "generator": "categorymembers", "gcmtitle": "Category:Language users", "gcmlimit": 500, "prop": "categoryinfo", } def fetch_data(): counts = {} continue_ = {"continue": ""} while continue_: resp = requests.get(URL, params={**PARAMS, **continue_}) resp.raise_for_status() data = resp.json() counts.update( { p["title"]: p.get("categoryinfo", {}).get("size", 0) for p in data["query"]["pages"] } ) continue_ = data.get("continue", {}) return counts if __name__ == "__main__": counts = fetch_data() at_least_100 = [(lang, count) for lang, count in counts.items() if count >= 100] top_languages = sorted(at_least_100, key=lambda x: x[1], reverse=True) for i, lang in enumerate(top_languages): print(f"{i+1:<5}{lang[0][9:][:-5]:<20}{lang[1]}")
Maintain the same structure and functionality when rewriting this code in Python.
#include <stdio.h> #include "achain.c" typedef struct {double u, v;} cplx; inline cplx c_mul(cplx a, cplx b) { cplx c; c.u = a.u * b.u - a.v * b.v; c.v = a.u * b.v + a.v * b.u; return c; } cplx chain_expo(cplx x, int n) { int i, j, k, l, e[32]; cplx v[32]; l = seq(n, 0, e); puts("Exponents:"); for (i = 0; i <= l; i++) printf("%d%c", e[i], i == l ? '\n' : ' '); v[0] = x; v[1] = c_mul(x, x); for (i = 2; i <= l; i++) { for (j = i - 1; j; j--) { for (k = j; k >= 0; k--) { if (e[k] + e[j] < e[i]) break; if (e[k] + e[j] > e[i]) continue; v[i] = c_mul(v[j], v[k]); j = 1; break; } } } printf("(%f + i%f)^%d = %f + i%f\n", x.u, x.v, n, v[l].u, v[l].v); return x; } int bin_len(int n) { int r, o; for (r = o = -1; n; n >>= 1, r++) if (n & 1) o++; return r + o; } int main() { cplx r1 = {1.0000254989, 0.0000577896}, r2 = {1.0000220632, 0.0000500026}; int n1 = 27182, n2 = 31415, i; init(); puts("Precompute chain lengths"); seq_len(n2); chain_expo(r1, n1); chain_expo(r2, n2); puts("\nchain lengths: shortest binary"); printf("%14d %7d %7d\n", n1, seq_len(n1), bin_len(n1)); printf("%14d %7d %7d\n", n2, seq_len(n2), bin_len(n2)); for (i = 1; i < 100; i++) printf("%14d %7d %7d\n", i, seq_len(i), bin_len(i)); return 0; }
from math import sqrt from numpy import array from mpmath import mpf class AdditionChains: def __init__(self): self.chains, self.idx, self.pos = [[1]], 0, 0 self.pat, self.lvl = {1: 0}, [[1]] def add_chain(self): newchain = self.chains[self.idx].copy() newchain.append(self.chains[self.idx][-1] + self.chains[self.idx][self.pos]) self.chains.append(newchain) if self.pos == len(self.chains[self.idx])-1: self.idx += 1 self.pos = 0 else: self.pos += 1 return newchain def find_chain(self, nexp): assert nexp > 0 if nexp == 1: return [1] chn = next((a for a in self.chains if a[-1] == nexp), None) if chn is None: while True: chn = self.add_chain() if chn[-1] == nexp: break return chn def knuth_path(self, ngoal): if ngoal < 1: return [] while not ngoal in self.pat: new_lvl = [] for i in self.lvl[0]: for j in self.knuth_path(i): if not i + j in self.pat: self.pat[i + j] = i new_lvl.append(i + j) self.lvl[0] = new_lvl returnpath = self.knuth_path(self.pat[ngoal]) returnpath.append(ngoal) return returnpath def cpow(xbase, chain): pows, products = 0, {0: 1, 1: xbase} for i in chain: products[i] = products[pows] * products[i - pows] pows = i return products[chain[-1]] if __name__ == '__main__': acs = AdditionChains() print('First one hundred addition chain lengths:') for k in range(1, 101): print(f'{len(acs.find_chain(k))-1:3}', end='\n'if k % 10 == 0 else '') print('\nKnuth chains for addition chains of 31415 and 27182:') chns = {m: acs.knuth_path(m) for m in [31415, 27182]} for (num, cha) in chns.items(): print(f'Exponent: {num:10}\n Addition Chain: {cha[:-1]}') print('\n1.00002206445416^31415 =', cpow(1.00002206445416, chns[31415])) print('1.00002550055251^27182 =', cpow(1.00002550055251, chns[27182])) print('1.000025 + 0.000058i)^27182 =', cpow(complex(1.000025, 0.000058), chns[27182])) print('1.000022 + 0.000050i)^31415 =', cpow(complex(1.000022, 0.000050), chns[31415])) sq05 = mpf(sqrt(0.5)) mat = array([[sq05, 0, sq05, 0, 0, 0], [0, sq05, 0, sq05, 0, 0], [0, sq05, 0, -sq05, 0, 0], [-sq05, 0, sq05, 0, 0, 0], [0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 1, 0]]) print('matrix A ^ 27182 =') print(cpow(mat, chns[27182])) print('matrix A ^ 31415 =') print(cpow(mat, chns[31415])) print('(matrix A ** 27182) ** 31415 =') print(cpow(cpow(mat, chns[27182]), chns[31415]))
Convert this C snippet to Python and keep its semantics consistent.
#include <stdio.h> #include "achain.c" typedef struct {double u, v;} cplx; inline cplx c_mul(cplx a, cplx b) { cplx c; c.u = a.u * b.u - a.v * b.v; c.v = a.u * b.v + a.v * b.u; return c; } cplx chain_expo(cplx x, int n) { int i, j, k, l, e[32]; cplx v[32]; l = seq(n, 0, e); puts("Exponents:"); for (i = 0; i <= l; i++) printf("%d%c", e[i], i == l ? '\n' : ' '); v[0] = x; v[1] = c_mul(x, x); for (i = 2; i <= l; i++) { for (j = i - 1; j; j--) { for (k = j; k >= 0; k--) { if (e[k] + e[j] < e[i]) break; if (e[k] + e[j] > e[i]) continue; v[i] = c_mul(v[j], v[k]); j = 1; break; } } } printf("(%f + i%f)^%d = %f + i%f\n", x.u, x.v, n, v[l].u, v[l].v); return x; } int bin_len(int n) { int r, o; for (r = o = -1; n; n >>= 1, r++) if (n & 1) o++; return r + o; } int main() { cplx r1 = {1.0000254989, 0.0000577896}, r2 = {1.0000220632, 0.0000500026}; int n1 = 27182, n2 = 31415, i; init(); puts("Precompute chain lengths"); seq_len(n2); chain_expo(r1, n1); chain_expo(r2, n2); puts("\nchain lengths: shortest binary"); printf("%14d %7d %7d\n", n1, seq_len(n1), bin_len(n1)); printf("%14d %7d %7d\n", n2, seq_len(n2), bin_len(n2)); for (i = 1; i < 100; i++) printf("%14d %7d %7d\n", i, seq_len(i), bin_len(i)); return 0; }
from math import sqrt from numpy import array from mpmath import mpf class AdditionChains: def __init__(self): self.chains, self.idx, self.pos = [[1]], 0, 0 self.pat, self.lvl = {1: 0}, [[1]] def add_chain(self): newchain = self.chains[self.idx].copy() newchain.append(self.chains[self.idx][-1] + self.chains[self.idx][self.pos]) self.chains.append(newchain) if self.pos == len(self.chains[self.idx])-1: self.idx += 1 self.pos = 0 else: self.pos += 1 return newchain def find_chain(self, nexp): assert nexp > 0 if nexp == 1: return [1] chn = next((a for a in self.chains if a[-1] == nexp), None) if chn is None: while True: chn = self.add_chain() if chn[-1] == nexp: break return chn def knuth_path(self, ngoal): if ngoal < 1: return [] while not ngoal in self.pat: new_lvl = [] for i in self.lvl[0]: for j in self.knuth_path(i): if not i + j in self.pat: self.pat[i + j] = i new_lvl.append(i + j) self.lvl[0] = new_lvl returnpath = self.knuth_path(self.pat[ngoal]) returnpath.append(ngoal) return returnpath def cpow(xbase, chain): pows, products = 0, {0: 1, 1: xbase} for i in chain: products[i] = products[pows] * products[i - pows] pows = i return products[chain[-1]] if __name__ == '__main__': acs = AdditionChains() print('First one hundred addition chain lengths:') for k in range(1, 101): print(f'{len(acs.find_chain(k))-1:3}', end='\n'if k % 10 == 0 else '') print('\nKnuth chains for addition chains of 31415 and 27182:') chns = {m: acs.knuth_path(m) for m in [31415, 27182]} for (num, cha) in chns.items(): print(f'Exponent: {num:10}\n Addition Chain: {cha[:-1]}') print('\n1.00002206445416^31415 =', cpow(1.00002206445416, chns[31415])) print('1.00002550055251^27182 =', cpow(1.00002550055251, chns[27182])) print('1.000025 + 0.000058i)^27182 =', cpow(complex(1.000025, 0.000058), chns[27182])) print('1.000022 + 0.000050i)^31415 =', cpow(complex(1.000022, 0.000050), chns[31415])) sq05 = mpf(sqrt(0.5)) mat = array([[sq05, 0, sq05, 0, 0, 0], [0, sq05, 0, sq05, 0, 0], [0, sq05, 0, -sq05, 0, 0], [-sq05, 0, sq05, 0, 0, 0], [0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 1, 0]]) print('matrix A ^ 27182 =') print(cpow(mat, chns[27182])) print('matrix A ^ 31415 =') print(cpow(mat, chns[31415])) print('(matrix A ** 27182) ** 31415 =') print(cpow(cpow(mat, chns[27182]), chns[31415]))
Produce a language-to-language conversion: from C to Python, same semantics.
#include<stdlib.h> #include<stdio.h> int main () { int i; char *str = getenv ("LANG"); for (i = 0; str[i + 2] != 00; i++) { if ((str[i] == 'u' && str[i + 1] == 't' && str[i + 2] == 'f') || (str[i] == 'U' && str[i + 1] == 'T' && str[i + 2] == 'F')) { printf ("Unicode is supported on this terminal and U+25B3 is : \u25b3"); i = -1; break; } } if (i != -1) printf ("Unicode is not supported on this terminal."); return 0; }
import sys if "UTF-8" in sys.stdout.encoding: print("△") else: raise Exception("Terminal can't handle UTF-8")
Write a version of this C function in Python with identical behavior.
#include<stdlib.h> #include<stdio.h> int main () { int i; char *str = getenv ("LANG"); for (i = 0; str[i + 2] != 00; i++) { if ((str[i] == 'u' && str[i + 1] == 't' && str[i + 2] == 'f') || (str[i] == 'U' && str[i + 1] == 'T' && str[i + 2] == 'F')) { printf ("Unicode is supported on this terminal and U+25B3 is : \u25b3"); i = -1; break; } } if (i != -1) printf ("Unicode is not supported on this terminal."); return 0; }
import sys if "UTF-8" in sys.stdout.encoding: print("△") else: raise Exception("Terminal can't handle UTF-8")
Translate this program into Python but keep the logic exactly as in C.
#include<stdio.h> #include<stdlib.h> int isprime( int p ) { int i; if(p==2) return 1; if(!(p%2)) return 0; for(i=3; i*i<=p; i+=2) { if(!(p%i)) return 0; } return 1; } int nextprime( int p ) { int i=0; if(p==0) return 2; if(p<3) return p+1; while(!isprime(++i + p)); return i+p; } int issquare( int p ) { int i; for(i=0;i*i<p;i++); return i*i==p; } int main(void) { int i=3, j=2; for(i=3;j<=1000000;i=j) { j=nextprime(i); if(j-i>36&&issquare(j-i)) printf( "%d %d %d\n", i, j, j-i ); } return 0; }
import math print("working...") limit = 1000000 Primes = [] oldPrime = 0 newPrime = 0 x = 0 def isPrime(n): for i in range(2,int(n**0.5)+1): if n%i==0: return False return True def issquare(x): for n in range(x): if (x == n*n): return 1 return 0 for n in range(limit): if isPrime(n): Primes.append(n) for n in range(2,len(Primes)): pr1 = Primes[n] pr2 = Primes[n-1] diff = pr1 - pr2 flag = issquare(diff) if (flag == 1 and diff > 36): print(str(pr1) + " " + str(pr2) + " diff = " + str(diff)) print("done...")
Transform the following C implementation into Python, maintaining the same output and logic.
#include<stdio.h> #include<stdlib.h> int isprime( int p ) { int i; if(p==2) return 1; if(!(p%2)) return 0; for(i=3; i*i<=p; i+=2) { if(!(p%i)) return 0; } return 1; } int nextprime( int p ) { int i=0; if(p==0) return 2; if(p<3) return p+1; while(!isprime(++i + p)); return i+p; } int issquare( int p ) { int i; for(i=0;i*i<p;i++); return i*i==p; } int main(void) { int i=3, j=2; for(i=3;j<=1000000;i=j) { j=nextprime(i); if(j-i>36&&issquare(j-i)) printf( "%d %d %d\n", i, j, j-i ); } return 0; }
import math print("working...") limit = 1000000 Primes = [] oldPrime = 0 newPrime = 0 x = 0 def isPrime(n): for i in range(2,int(n**0.5)+1): if n%i==0: return False return True def issquare(x): for n in range(x): if (x == n*n): return 1 return 0 for n in range(limit): if isPrime(n): Primes.append(n) for n in range(2,len(Primes)): pr1 = Primes[n] pr2 = Primes[n-1] diff = pr1 - pr2 flag = issquare(diff) if (flag == 1 and diff > 36): print(str(pr1) + " " + str(pr2) + " diff = " + str(diff)) print("done...")
Can you help me rewrite this code in Python instead of C, keeping it the same logically?
#include <windows.h> #include <stdio.h> #include <wchar.h> void oops(const wchar_t *message) { wchar_t *buf; DWORD error; buf = NULL; error = GetLastError(); FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, error, 0, (wchar_t *)&buf, 0, NULL); if (buf) { fwprintf(stderr, L"%ls: %ls", message, buf); LocalFree(buf); } else { fwprintf(stderr, L"%ls: unknown error 0x%x\n", message, error); } } int dotruncate(wchar_t *fn, LARGE_INTEGER fp) { HANDLE fh; fh = CreateFileW(fn, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); if (fh == INVALID_HANDLE_VALUE) { oops(fn); return 1; } if (SetFilePointerEx(fh, fp, NULL, FILE_BEGIN) == 0 || SetEndOfFile(fh) == 0) { oops(fn); CloseHandle(fh); return 1; } CloseHandle(fh); return 0; } int main() { LARGE_INTEGER fp; int argc; wchar_t **argv, *fn, junk[2]; argv = CommandLineToArgvW(GetCommandLineW(), &argc); if (argv == NULL) { oops(L"CommandLineToArgvW"); return 1; } if (argc != 3) { fwprintf(stderr, L"usage: %ls filename length\n", argv[0]); return 1; } fn = argv[1]; if (swscanf(argv[2], L"%lld%1ls", &fp.QuadPart, &junk) != 1) { fwprintf(stderr, L"%ls: not a number\n", argv[2]); return 1; } return dotruncate(fn, fp); }
def truncate_file(name, length): if not os.path.isfile(name): return False if length >= os.path.getsize(name): return False with open(name, 'ab') as f: f.truncate(length) return True
Produce a language-to-language conversion: from C to Python, same semantics.
#include <windows.h> #include <stdio.h> #include <wchar.h> void oops(const wchar_t *message) { wchar_t *buf; DWORD error; buf = NULL; error = GetLastError(); FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, error, 0, (wchar_t *)&buf, 0, NULL); if (buf) { fwprintf(stderr, L"%ls: %ls", message, buf); LocalFree(buf); } else { fwprintf(stderr, L"%ls: unknown error 0x%x\n", message, error); } } int dotruncate(wchar_t *fn, LARGE_INTEGER fp) { HANDLE fh; fh = CreateFileW(fn, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); if (fh == INVALID_HANDLE_VALUE) { oops(fn); return 1; } if (SetFilePointerEx(fh, fp, NULL, FILE_BEGIN) == 0 || SetEndOfFile(fh) == 0) { oops(fn); CloseHandle(fh); return 1; } CloseHandle(fh); return 0; } int main() { LARGE_INTEGER fp; int argc; wchar_t **argv, *fn, junk[2]; argv = CommandLineToArgvW(GetCommandLineW(), &argc); if (argv == NULL) { oops(L"CommandLineToArgvW"); return 1; } if (argc != 3) { fwprintf(stderr, L"usage: %ls filename length\n", argv[0]); return 1; } fn = argv[1]; if (swscanf(argv[2], L"%lld%1ls", &fp.QuadPart, &junk) != 1) { fwprintf(stderr, L"%ls: not a number\n", argv[2]); return 1; } return dotruncate(fn, fp); }
def truncate_file(name, length): if not os.path.isfile(name): return False if length >= os.path.getsize(name): return False with open(name, 'ab') as f: f.truncate(length) return True
Port the following code from C to Python with equivalent syntax and logic.
#include <windows.h> #include <stdio.h> #include <wchar.h> void oops(const wchar_t *message) { wchar_t *buf; DWORD error; buf = NULL; error = GetLastError(); FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, error, 0, (wchar_t *)&buf, 0, NULL); if (buf) { fwprintf(stderr, L"%ls: %ls", message, buf); LocalFree(buf); } else { fwprintf(stderr, L"%ls: unknown error 0x%x\n", message, error); } } int dotruncate(wchar_t *fn, LARGE_INTEGER fp) { HANDLE fh; fh = CreateFileW(fn, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); if (fh == INVALID_HANDLE_VALUE) { oops(fn); return 1; } if (SetFilePointerEx(fh, fp, NULL, FILE_BEGIN) == 0 || SetEndOfFile(fh) == 0) { oops(fn); CloseHandle(fh); return 1; } CloseHandle(fh); return 0; } int main() { LARGE_INTEGER fp; int argc; wchar_t **argv, *fn, junk[2]; argv = CommandLineToArgvW(GetCommandLineW(), &argc); if (argv == NULL) { oops(L"CommandLineToArgvW"); return 1; } if (argc != 3) { fwprintf(stderr, L"usage: %ls filename length\n", argv[0]); return 1; } fn = argv[1]; if (swscanf(argv[2], L"%lld%1ls", &fp.QuadPart, &junk) != 1) { fwprintf(stderr, L"%ls: not a number\n", argv[2]); return 1; } return dotruncate(fn, fp); }
def truncate_file(name, length): if not os.path.isfile(name): return False if length >= os.path.getsize(name): return False with open(name, 'ab') as f: f.truncate(length) return True
Can you help me rewrite this code in Python instead of C, keeping it the same logically?
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include "wren.h" void C_xrandr(WrenVM* vm) { const char *arg = wrenGetSlotString(vm, 1); char command[strlen(arg) + 8]; strcpy(command, "xrandr "); strcat(command, arg); system(command); } void C_usleep(WrenVM* vm) { useconds_t usec = (useconds_t)wrenGetSlotDouble(vm, 1); usleep(usec); } WrenForeignMethodFn bindForeignMethod( WrenVM* vm, const char* module, const char* className, bool isStatic, const char* signature) { if (strcmp(module, "main") == 0) { if (strcmp(className, "C") == 0) { if (isStatic && strcmp(signature, "xrandr(_)") == 0) return C_xrandr; if (isStatic && strcmp(signature, "usleep(_)") == 0) return C_usleep; } } return NULL; } static void writeFn(WrenVM* vm, const char* text) { printf("%s", text); } char *readFile(const char *fileName) { FILE *f = fopen(fileName, "r"); fseek(f, 0, SEEK_END); long fsize = ftell(f); rewind(f); char *script = malloc(fsize + 1); fread(script, 1, fsize, f); fclose(f); script[fsize] = 0; return script; } int main(int argc, char **argv) { WrenConfiguration config; wrenInitConfiguration(&config); config.writeFn = &writeFn; config.bindForeignMethodFn = &bindForeignMethod; WrenVM* vm = wrenNewVM(&config); const char* module = "main"; const char* fileName = "video_display_modes.wren"; char *script = readFile(fileName); wrenInterpret(vm, module, script); wrenFreeVM(vm); free(script); return 0; }
import win32api import win32con import pywintypes devmode=pywintypes.DEVMODEType() devmode.PelsWidth=640 devmode.PelsHeight=480 devmode.Fields=win32con.DM_PELSWIDTH | win32con.DM_PELSHEIGHT win32api.ChangeDisplaySettings(devmode,0)
Generate a Python translation of this C snippet without changing its computational steps.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include "wren.h" void C_xrandr(WrenVM* vm) { const char *arg = wrenGetSlotString(vm, 1); char command[strlen(arg) + 8]; strcpy(command, "xrandr "); strcat(command, arg); system(command); } void C_usleep(WrenVM* vm) { useconds_t usec = (useconds_t)wrenGetSlotDouble(vm, 1); usleep(usec); } WrenForeignMethodFn bindForeignMethod( WrenVM* vm, const char* module, const char* className, bool isStatic, const char* signature) { if (strcmp(module, "main") == 0) { if (strcmp(className, "C") == 0) { if (isStatic && strcmp(signature, "xrandr(_)") == 0) return C_xrandr; if (isStatic && strcmp(signature, "usleep(_)") == 0) return C_usleep; } } return NULL; } static void writeFn(WrenVM* vm, const char* text) { printf("%s", text); } char *readFile(const char *fileName) { FILE *f = fopen(fileName, "r"); fseek(f, 0, SEEK_END); long fsize = ftell(f); rewind(f); char *script = malloc(fsize + 1); fread(script, 1, fsize, f); fclose(f); script[fsize] = 0; return script; } int main(int argc, char **argv) { WrenConfiguration config; wrenInitConfiguration(&config); config.writeFn = &writeFn; config.bindForeignMethodFn = &bindForeignMethod; WrenVM* vm = wrenNewVM(&config); const char* module = "main"; const char* fileName = "video_display_modes.wren"; char *script = readFile(fileName); wrenInterpret(vm, module, script); wrenFreeVM(vm); free(script); return 0; }
import win32api import win32con import pywintypes devmode=pywintypes.DEVMODEType() devmode.PelsWidth=640 devmode.PelsHeight=480 devmode.Fields=win32con.DM_PELSWIDTH | win32con.DM_PELSHEIGHT win32api.ChangeDisplaySettings(devmode,0)
Convert the following code from C to Python, ensuring the logic remains intact.
#include <stdio.h> #include <stdlib.h> int main(int argc, char* argv[]) { char text[256]; getchar(); fseek(stdin, 0, SEEK_END); fgets(text, sizeof(text), stdin); puts(text); return EXIT_SUCCESS; }
def flush_input(): try: import msvcrt while msvcrt.kbhit(): msvcrt.getch() except ImportError: import sys, termios termios.tcflush(sys.stdin, termios.TCIOFLUSH)
Keep all operations the same but rewrite the snippet in Python.
#include <stdio.h> #include <math.h> typedef struct { double m; double fm; double simp; } triple; triple _quad_simpsons_mem(double (*f)(double), double a, double fa, double b, double fb) { double m = (a + b) / 2; double fm = f(m); double simp = fabs(b - a) / 6 * (fa + 4*fm + fb); triple t = {m, fm, simp}; return t; } double _quad_asr(double (*f)(double), double a, double fa, double b, double fb, double eps, double whole, double m, double fm) { triple lt = _quad_simpsons_mem(f, a, fa, m, fm); triple rt = _quad_simpsons_mem(f, m, fm, b, fb); double delta = lt.simp + rt.simp - whole; if (fabs(delta) <= eps * 15) return lt.simp + rt.simp + delta/15; return _quad_asr(f, a, fa, m, fm, eps/2, lt.simp, lt.m, lt.fm) + _quad_asr(f, m, fm, b, fb, eps/2, rt.simp, rt.m, rt.fm); } double quad_asr(double (*f)(double), double a, double b, double eps) { double fa = f(a); double fb = f(b); triple t = _quad_simpsons_mem(f, a, fa, b, fb); return _quad_asr(f, a, fa, b, fb, eps, t.simp, t.m, t.fm); } int main(){ double a = 0.0, b = 1.0; double sinx = quad_asr(sin, a, b, 1e-09); printf("Simpson's integration of sine from %g to %g = %f\n", a, b, sinx); return 0; }
import math import collections triple = collections.namedtuple('triple', 'm fm simp') def _quad_simpsons_mem(f: callable, a: float , fa: float, b: float, fb: float)->tuple: m = a + (b - a) / 2 fm = f(m) simp = abs(b - a) / 6 * (fa + 4*fm + fb) return triple(m, fm, simp,) def _quad_asr(f: callable, a: float, fa: float, b: float, fb: float, eps: float, whole: float, m: float, fm: float)->float: lt = _quad_simpsons_mem(f, a, fa, m, fm) rt = _quad_simpsons_mem(f, m, fm, b, fb) delta = lt.simp + rt.simp - whole return (lt.simp + rt.simp + delta/15 if (abs(delta) <= eps * 15) else _quad_asr(f, a, fa, m, fm, eps/2, lt.simp, lt.m, lt.fm) + _quad_asr(f, m, fm, b, fb, eps/2, rt.simp, rt.m, rt.fm) ) def quad_asr(f: callable, a: float, b: float, eps: float)->float: fa = f(a) fb = f(b) t = _quad_simpsons_mem(f, a, fa, b, fb) return _quad_asr(f, a, fa, b, fb, eps, t.simp, t.m, t.fm) def main(): (a, b,) = (0.0, 1.0,) sinx = quad_asr(math.sin, a, b, 1e-09); print("Simpson's integration of sine from {} to {} = {}\n".format(a, b, sinx)) main()
Write the same algorithm in Python as shown in this C implementation.
#include <stdio.h> #include <math.h> typedef struct { double m; double fm; double simp; } triple; triple _quad_simpsons_mem(double (*f)(double), double a, double fa, double b, double fb) { double m = (a + b) / 2; double fm = f(m); double simp = fabs(b - a) / 6 * (fa + 4*fm + fb); triple t = {m, fm, simp}; return t; } double _quad_asr(double (*f)(double), double a, double fa, double b, double fb, double eps, double whole, double m, double fm) { triple lt = _quad_simpsons_mem(f, a, fa, m, fm); triple rt = _quad_simpsons_mem(f, m, fm, b, fb); double delta = lt.simp + rt.simp - whole; if (fabs(delta) <= eps * 15) return lt.simp + rt.simp + delta/15; return _quad_asr(f, a, fa, m, fm, eps/2, lt.simp, lt.m, lt.fm) + _quad_asr(f, m, fm, b, fb, eps/2, rt.simp, rt.m, rt.fm); } double quad_asr(double (*f)(double), double a, double b, double eps) { double fa = f(a); double fb = f(b); triple t = _quad_simpsons_mem(f, a, fa, b, fb); return _quad_asr(f, a, fa, b, fb, eps, t.simp, t.m, t.fm); } int main(){ double a = 0.0, b = 1.0; double sinx = quad_asr(sin, a, b, 1e-09); printf("Simpson's integration of sine from %g to %g = %f\n", a, b, sinx); return 0; }
import math import collections triple = collections.namedtuple('triple', 'm fm simp') def _quad_simpsons_mem(f: callable, a: float , fa: float, b: float, fb: float)->tuple: m = a + (b - a) / 2 fm = f(m) simp = abs(b - a) / 6 * (fa + 4*fm + fb) return triple(m, fm, simp,) def _quad_asr(f: callable, a: float, fa: float, b: float, fb: float, eps: float, whole: float, m: float, fm: float)->float: lt = _quad_simpsons_mem(f, a, fa, m, fm) rt = _quad_simpsons_mem(f, m, fm, b, fb) delta = lt.simp + rt.simp - whole return (lt.simp + rt.simp + delta/15 if (abs(delta) <= eps * 15) else _quad_asr(f, a, fa, m, fm, eps/2, lt.simp, lt.m, lt.fm) + _quad_asr(f, m, fm, b, fb, eps/2, rt.simp, rt.m, rt.fm) ) def quad_asr(f: callable, a: float, b: float, eps: float)->float: fa = f(a) fb = f(b) t = _quad_simpsons_mem(f, a, fa, b, fb) return _quad_asr(f, a, fa, b, fb, eps, t.simp, t.m, t.fm) def main(): (a, b,) = (0.0, 1.0,) sinx = quad_asr(math.sin, a, b, 1e-09); print("Simpson's integration of sine from {} to {} = {}\n".format(a, b, sinx)) main()
Ensure the translated Python code behaves exactly like the original C snippet.
#include <stdio.h> #include <stdlib.h> #include <string.h> void main() { FILE * fp; char * line = NULL; size_t len = 0; ssize_t read; fp = fopen("fasta.txt", "r"); if (fp == NULL) exit(EXIT_FAILURE); int state = 0; while ((read = getline(&line, &len, fp)) != -1) { if (line[read - 1] == '\n') line[read - 1] = 0; if (line[0] == '>') { if (state == 1) printf("\n"); printf("%s: ", line+1); state = 1; } else { printf("%s", line); } } printf("\n"); fclose(fp); if (line) free(line); exit(EXIT_SUCCESS); }
import io FASTA= infile = io.StringIO(FASTA) def fasta_parse(infile): key = '' for line in infile: if line.startswith('>'): if key: yield key, val key, val = line[1:].rstrip().split()[0], '' elif key: val += line.rstrip() if key: yield key, val print('\n'.join('%s: %s' % keyval for keyval in fasta_parse(infile)))
Produce a language-to-language conversion: from C to Python, same semantics.
#include <stdio.h> #include <string.h> #define LIMIT 1000 void sieve(int max, char *s) { int p, k; memset(s, 0, max); for (p=2; p*p<=max; p++) if (!s[p]) for (k=p*p; k<=max; k+=p) s[k]=1; } int main(void) { char primes[LIMIT+1]; int p, count=0; sieve(LIMIT, primes); for (p=2; p<=LIMIT; p++) { if (!primes[p] && !primes[p+4]) { count++; printf("%4d: %4d\n", p, p+4); } } printf("There are %d cousin prime pairs below %d.\n", count, LIMIT); return 0; }
from itertools import chain, takewhile def cousinPrimes(): def go(x): n = 4 + x return [(x, n)] if isPrime(n) else [] return chain.from_iterable( map(go, primes()) ) def main(): pairs = list( takewhile( lambda ab: 1000 > ab[1], cousinPrimes() ) ) print(f'{len(pairs)} cousin pairs below 1000:\n') print( spacedTable(list( chunksOf(4)([ repr(x) for x in pairs ]) )) ) def chunksOf(n): def go(xs): return ( xs[i:n + i] for i in range(0, len(xs), n) ) if 0 < n else None return go def isPrime(n): if n in (2, 3): return True if 2 > n or 0 == n % 2: return False if 9 > n: return True if 0 == n % 3: return False def p(x): return 0 == n % x or 0 == n % (2 + x) return not any(map(p, range(5, 1 + int(n ** 0.5), 6))) def primes(): n = 2 dct = {} while True: if n in dct: for p in dct[n]: dct.setdefault(n + p, []).append(p) del dct[n] else: yield n dct[n * n] = [n] n = 1 + n def listTranspose(xss): def go(xss): if xss: h, *t = xss return ( [[h[0]] + [xs[0] for xs in t if xs]] + ( go([h[1:]] + [xs[1:] for xs in t]) ) ) if h and isinstance(h, list) else go(t) else: return [] return go(xss) def spacedTable(rows): columnWidths = [ len(str(row[-1])) for row in listTranspose(rows) ] return '\n'.join([ ' '.join( map( lambda w, s: s.rjust(w, ' '), columnWidths, row ) ) for row in rows ]) if __name__ == '__main__': main()
Convert this C block to Python, preserving its control flow and logic.
#include <stdio.h> #include <string.h> #define LIMIT 1000 void sieve(int max, char *s) { int p, k; memset(s, 0, max); for (p=2; p*p<=max; p++) if (!s[p]) for (k=p*p; k<=max; k+=p) s[k]=1; } int main(void) { char primes[LIMIT+1]; int p, count=0; sieve(LIMIT, primes); for (p=2; p<=LIMIT; p++) { if (!primes[p] && !primes[p+4]) { count++; printf("%4d: %4d\n", p, p+4); } } printf("There are %d cousin prime pairs below %d.\n", count, LIMIT); return 0; }
from itertools import chain, takewhile def cousinPrimes(): def go(x): n = 4 + x return [(x, n)] if isPrime(n) else [] return chain.from_iterable( map(go, primes()) ) def main(): pairs = list( takewhile( lambda ab: 1000 > ab[1], cousinPrimes() ) ) print(f'{len(pairs)} cousin pairs below 1000:\n') print( spacedTable(list( chunksOf(4)([ repr(x) for x in pairs ]) )) ) def chunksOf(n): def go(xs): return ( xs[i:n + i] for i in range(0, len(xs), n) ) if 0 < n else None return go def isPrime(n): if n in (2, 3): return True if 2 > n or 0 == n % 2: return False if 9 > n: return True if 0 == n % 3: return False def p(x): return 0 == n % x or 0 == n % (2 + x) return not any(map(p, range(5, 1 + int(n ** 0.5), 6))) def primes(): n = 2 dct = {} while True: if n in dct: for p in dct[n]: dct.setdefault(n + p, []).append(p) del dct[n] else: yield n dct[n * n] = [n] n = 1 + n def listTranspose(xss): def go(xss): if xss: h, *t = xss return ( [[h[0]] + [xs[0] for xs in t if xs]] + ( go([h[1:]] + [xs[1:] for xs in t]) ) ) if h and isinstance(h, list) else go(t) else: return [] return go(xss) def spacedTable(rows): columnWidths = [ len(str(row[-1])) for row in listTranspose(rows) ] return '\n'.join([ ' '.join( map( lambda w, s: s.rjust(w, ' '), columnWidths, row ) ) for row in rows ]) if __name__ == '__main__': main()
Generate a Python translation of this C snippet without changing its computational steps.
#include <stdio.h> typedef unsigned long long xint; int is_palin2(xint n) { xint x = 0; if (!(n&1)) return !n; while (x < n) x = x<<1 | (n&1), n >>= 1; return n == x || n == x>>1; } xint reverse3(xint n) { xint x = 0; while (n) x = x*3 + (n%3), n /= 3; return x; } void print(xint n, xint base) { putchar(' '); do { putchar('0' + (n%base)), n /= base; } while(n); printf("(%lld)", base); } void show(xint n) { printf("%llu", n); print(n, 2); print(n, 3); putchar('\n'); } xint min(xint a, xint b) { return a < b ? a : b; } xint max(xint a, xint b) { return a > b ? a : b; } int main(void) { xint lo, hi, lo2, hi2, lo3, hi3, pow2, pow3, i, n; int cnt; show(0); cnt = 1; lo = 0; hi = pow2 = pow3 = 1; while (1) { for (i = lo; i < hi; i++) { n = (i * 3 + 1) * pow3 + reverse3(i); if (!is_palin2(n)) continue; show(n); if (++cnt >= 7) return 0; } if (i == pow3) pow3 *= 3; else pow2 *= 4; while (1) { while (pow2 <= pow3) pow2 *= 4; lo2 = (pow2 / pow3 - 1) / 3; hi2 = (pow2 * 2 / pow3 - 1) / 3 + 1; lo3 = pow3 / 3; hi3 = pow3; if (lo2 >= hi3) pow3 *= 3; else if (lo3 >= hi2) pow2 *= 4; else { lo = max(lo2, lo3); hi = min(hi2, hi3); break; } } } return 0; }
from itertools import islice digits = "0123456789abcdefghijklmnopqrstuvwxyz" def baseN(num,b): if num == 0: return "0" result = "" while num != 0: num, d = divmod(num, b) result += digits[d] return result[::-1] def pal2(num): if num == 0 or num == 1: return True based = bin(num)[2:] return based == based[::-1] def pal_23(): yield 0 yield 1 n = 1 while True: n += 1 b = baseN(n, 3) revb = b[::-1] for trial in ('{0}{1}'.format(b, revb), '{0}0{1}'.format(b, revb), '{0}1{1}'.format(b, revb), '{0}2{1}'.format(b, revb)): t = int(trial, 3) if pal2(t): yield t for pal23 in islice(pal_23(), 6): print(pal23, baseN(pal23, 3), baseN(pal23, 2))
Produce a functionally identical Python code for the snippet given in C.
#include <stdio.h> typedef unsigned long long xint; int is_palin2(xint n) { xint x = 0; if (!(n&1)) return !n; while (x < n) x = x<<1 | (n&1), n >>= 1; return n == x || n == x>>1; } xint reverse3(xint n) { xint x = 0; while (n) x = x*3 + (n%3), n /= 3; return x; } void print(xint n, xint base) { putchar(' '); do { putchar('0' + (n%base)), n /= base; } while(n); printf("(%lld)", base); } void show(xint n) { printf("%llu", n); print(n, 2); print(n, 3); putchar('\n'); } xint min(xint a, xint b) { return a < b ? a : b; } xint max(xint a, xint b) { return a > b ? a : b; } int main(void) { xint lo, hi, lo2, hi2, lo3, hi3, pow2, pow3, i, n; int cnt; show(0); cnt = 1; lo = 0; hi = pow2 = pow3 = 1; while (1) { for (i = lo; i < hi; i++) { n = (i * 3 + 1) * pow3 + reverse3(i); if (!is_palin2(n)) continue; show(n); if (++cnt >= 7) return 0; } if (i == pow3) pow3 *= 3; else pow2 *= 4; while (1) { while (pow2 <= pow3) pow2 *= 4; lo2 = (pow2 / pow3 - 1) / 3; hi2 = (pow2 * 2 / pow3 - 1) / 3 + 1; lo3 = pow3 / 3; hi3 = pow3; if (lo2 >= hi3) pow3 *= 3; else if (lo3 >= hi2) pow2 *= 4; else { lo = max(lo2, lo3); hi = min(hi2, hi3); break; } } } return 0; }
from itertools import islice digits = "0123456789abcdefghijklmnopqrstuvwxyz" def baseN(num,b): if num == 0: return "0" result = "" while num != 0: num, d = divmod(num, b) result += digits[d] return result[::-1] def pal2(num): if num == 0 or num == 1: return True based = bin(num)[2:] return based == based[::-1] def pal_23(): yield 0 yield 1 n = 1 while True: n += 1 b = baseN(n, 3) revb = b[::-1] for trial in ('{0}{1}'.format(b, revb), '{0}0{1}'.format(b, revb), '{0}1{1}'.format(b, revb), '{0}2{1}'.format(b, revb)): t = int(trial, 3) if pal2(t): yield t for pal23 in islice(pal_23(), 6): print(pal23, baseN(pal23, 3), baseN(pal23, 2))
Can you help me rewrite this code in Python instead of C, keeping it the same logically?
#include <unistd.h> #include <stdio.h> int main(void) { puts(isatty(fileno(stdin)) ? "stdin is tty" : "stdin is not tty"); return 0; }
from sys import stdin if stdin.isatty(): print("Input comes from tty.") else: print("Input doesn't come from tty.")
Transform the following C implementation into Python, maintaining the same output and logic.
#include <unistd.h> #include <stdio.h> int main(void) { puts(isatty(fileno(stdin)) ? "stdin is tty" : "stdin is not tty"); return 0; }
from sys import stdin if stdin.isatty(): print("Input comes from tty.") else: print("Input doesn't come from tty.")
Ensure the translated Python code behaves exactly like the original C snippet.
'--- added a flush to exit cleanly PRAGMA LDFLAGS `pkg-config --cflags --libs x11` PRAGMA INCLUDE <X11/Xlib.h> PRAGMA INCLUDE <X11/Xutil.h> OPTION PARSE FALSE '---XLIB is so ugly ALIAS XNextEvent TO EVENT ALIAS XOpenDisplay TO DISPLAY ALIAS DefaultScreen TO SCREEN ALIAS XCreateSimpleWindow TO CREATE ALIAS XCloseDisplay TO CLOSE_DISPLAY ALIAS XSelectInput TO EVENT_TYPE ALIAS XMapWindow TO MAP_EVENT ALIAS XFillRectangle TO FILL_RECTANGLE ALIAS XDrawString TO DRAW_STRING ALIAS XFlush TO FLUSH '---pointer to X Display structure DECLARE d TYPE Display* '---pointer to the newly created window 'DECLARE w TYPE WINDOW '---pointer to the XEvent DECLARE e TYPE XEvent DECLARE msg TYPE char* '--- number of screen to place the window on DECLARE s TYPE int msg = "Hello, World!" d = DISPLAY(NULL) IF d == NULL THEN EPRINT "Cannot open display" FORMAT "%s%s\n" END END IF s = SCREEN(d) w = CREATE(d, RootWindow(d, s), 10, 10, 100, 100, 1,BlackPixel(d, s), WhitePixel(d, s)) EVENT_TYPE(d, w, ExposureMask | KeyPressMask) MAP_EVENT(d, w) WHILE (1) EVENT(d, &e) IF e.type == Expose THEN FILL_RECTANGLE(d, w, DefaultGC(d, s), 20, 20, 10, 10) DRAW_STRING(d, w, DefaultGC(d, s), 10, 50, msg, strlen(msg)) END IF IF e.type == KeyPress THEN BREAK END IF WEND FLUSH(d) CLOSE_DISPLAY(d)
from Xlib import X, display class Window: def __init__(self, display, msg): self.display = display self.msg = msg self.screen = self.display.screen() self.window = self.screen.root.create_window( 10, 10, 100, 100, 1, self.screen.root_depth, background_pixel=self.screen.white_pixel, event_mask=X.ExposureMask | X.KeyPressMask, ) self.gc = self.window.create_gc( foreground = self.screen.black_pixel, background = self.screen.white_pixel, ) self.window.map() def loop(self): while True: e = self.display.next_event() if e.type == X.Expose: self.window.fill_rectangle(self.gc, 20, 20, 10, 10) self.window.draw_text(self.gc, 10, 50, self.msg) elif e.type == X.KeyPress: raise SystemExit if __name__ == "__main__": Window(display.Display(), "Hello, World!").loop()