Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Ensure the translated Python code behaves exactly like the original C snippet. | #include <stdio.h>
#include <limits.h>
typedef unsigned long long ull;
#define N (sizeof(ull) * CHAR_BIT)
#define B(x) (1ULL << (x))
void evolve(ull state, int rule)
{
int i, p, q, b;
for (p = 0; p < 10; p++) {
for (b = 0, q = 8; q--; ) {
ull st = state;
b |= (st&1) << q;
for (state = i = 0; i < N; i++)
if (rule & B(7 & (st>>(i-1) | st<<(N+1-i))))
state |= B(i);
}
printf(" %d", b);
}
putchar('\n');
return;
}
int main(void)
{
evolve(1, 30);
return 0;
}
| from elementary_cellular_automaton import eca, eca_wrap
def rule30bytes(lencells=100):
cells = '1' + '0' * (lencells - 1)
gen = eca(cells, 30)
while True:
yield int(''.join(next(gen)[0] for i in range(8)), 2)
if __name__ == '__main__':
print([b for i,b in zip(range(10), rule30bytes())])
|
Please provide an equivalent version of this C code in Python. | #include <sys/ioctl.h>
#include <err.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
int
main()
{
struct winsize ws;
int fd;
fd = open("/dev/tty", O_RDWR);
if (fd < 0)
err(1, "/dev/tty");
if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
err(1, "/dev/tty");
printf("%d rows by %d columns\n", ws.ws_row, ws.ws_col);
printf("(%d by %d pixels)\n", ws.ws_xpixel, ws.ws_ypixel);
close(fd);
return 0;
}
| import os
def get_windows_terminal():
from ctypes import windll, create_string_buffer
h = windll.kernel32.GetStdHandle(-12)
csbi = create_string_buffer(22)
res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)
if not res: return 80, 25
import struct
(bufx, bufy, curx, cury, wattr, left, top, right, bottom, maxx, maxy)\
= struct.unpack("hhhhHhhhhhh", csbi.raw)
width = right - left + 1
height = bottom - top + 1
return width, height
def get_linux_terminal():
width = os.popen('tput cols', 'r').readline()
height = os.popen('tput lines', 'r').readline()
return int(width), int(height)
print get_linux_terminal() if os.name == 'posix' else get_windows_terminal()
|
Convert this C snippet to Python and keep its semantics consistent. | #include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
typedef enum State { READY, WAITING, REFUND, DISPENSE, COLLECT, QUIT } State;
typedef struct statechange {
const int in;
const State out;
} statechange;
#define MAXINPUTS 3
typedef struct FSM {
const State state;
void (*Action)(void);
const statechange table[MAXINPUTS];
} FSM;
char str[10];
void Ready(void) { fprintf(stderr, "\nMachine is READY. (D)eposit or (Q)uit :"); scanf("%s", str); }
void Waiting(void) { fprintf(stderr, "(S)elect product or choose to (R)efund :"); scanf("%s", str); }
void Refund(void) { fprintf(stderr, "Please collect refund.\n"); }
void Dispense(void) { fprintf(stderr, "Dispensing product...\n"); }
void Collect(void) { fprintf(stderr, "Please (C)ollect product. :"); scanf("%s", str); }
void Quit(void) { fprintf(stderr, "Thank you, shutting down now.\n"); exit(0); }
const FSM fsm[] = {
{ READY, &Ready, {{'D', WAITING}, {'Q', QUIT }, {-1, READY} }},
{ WAITING, &Waiting, {{'S', DISPENSE}, {'R', REFUND}, {-1, WAITING} }},
{ REFUND, &Refund, {{ -1, READY} }},
{ DISPENSE, &Dispense, {{ -1, COLLECT} }},
{ COLLECT, &Collect, {{'C', READY}, { -1, COLLECT } }},
{ QUIT, &Quit, {{ -1, QUIT} }},
};
int each;
State state = READY;
for (;;) {
fsm[state].Action();
each = 0;
while (!( ((fsm[state].table[each].in == -1)
|| (isalpha(str[0]) && fsm[state].table[each].in == toupper(str[0]) )))) each++;
state = fsm[state].table[each].out;
}
return 0;
}
|
states = { 'ready':{
'prompt' : 'Machine ready: (d)eposit, or (q)uit?',
'responses' : ['d','q']},
'waiting':{
'prompt' : 'Machine waiting: (s)elect, or (r)efund?',
'responses' : ['s','r']},
'dispense' : {
'prompt' : 'Machine dispensing: please (r)emove product',
'responses' : ['r']},
'refunding' : {
'prompt' : 'Refunding money',
'responses' : []},
'exit' :{}
}
transitions = { 'ready': {
'd': 'waiting',
'q': 'exit'},
'waiting' : {
's' : 'dispense',
'r' : 'refunding'},
'dispense' : {
'r' : 'ready'},
'refunding' : {
'' : 'ready'}}
def Acceptor(prompt, valids):
if not valids:
print(prompt)
return ''
else:
while True:
resp = input(prompt)[0].lower()
if resp in valids:
return resp
def finite_state_machine(initial_state, exit_state):
response = True
next_state = initial_state
current_state = states[next_state]
while response != exit_state:
response = Acceptor(current_state['prompt'], current_state['responses'])
next_state = transitions[next_state][response]
current_state = states[next_state]
if __name__ == "__main__":
finite_state_machine('ready','q')
|
Generate an equivalent Python version of this C code. |
#include<graphics.h>
void vibratingRectangles(int winWidth,int winHeight,int leastLength,int leastWidth,int num, int msec)
{
int color = 1,i,x = winWidth/2, y = winHeight/2;
while(!kbhit()){
setcolor(color++);
for(i=num;i>0;i--){
rectangle(x - i*leastLength,y - i*leastWidth,x + i*leastLength,y + i*leastWidth);
delay(msec);
}
if(color>MAXCOLORS){
color = 1;
}
}
}
int main()
{
initwindow(1000,1000,"Vibrating Rectangles...");
vibratingRectangles(1000,1000,30,15,20,500);
closegraph();
return 0;
}
| import turtle
from itertools import cycle
from time import sleep
def rect(t, x, y):
x2, y2 = x/2, y/2
t.setpos(-x2, -y2)
t.pendown()
for pos in [(-x2, y2), (x2, y2), (x2, -y2), (-x2, -y2)]:
t.goto(pos)
t.penup()
def rects(t, colour, wait_between_rect=0.1):
for x in range(550, 0, -25):
t.color(colour)
rect(t, x, x*.75)
sleep(wait_between_rect)
tl=turtle.Turtle()
screen=turtle.Screen()
screen.setup(620,620)
screen.bgcolor('black')
screen.title('Rosetta Code Vibrating Rectangles')
tl.pensize(3)
tl.speed(0)
tl.penup()
tl.ht()
colours = 'red green blue orange white yellow'.split()
for colour in cycle(colours):
rects(tl, colour)
sleep(0.5)
|
Transform the following C implementation into Python, maintaining the same output and logic. | #include <stdio.h>
#include <stdlib.h>
int compare(const void *a, const void *b) {
int aa = *(const int *)a;
int bb = *(const int *)b;
if (aa < bb) return -1;
if (aa > bb) return 1;
return 0;
}
int main() {
int a[] = {6, 81, 243, 14, 25, 49, 123, 69, 11};
int isize = sizeof(int);
int asize = sizeof(a) / isize;
int i, sum;
while (asize > 1) {
qsort(a, asize, isize, compare);
printf("Sorted list: ");
for (i = 0; i < asize; ++i) printf("%d ", a[i]);
printf("\n");
sum = a[0] + a[1];
printf("Two smallest: %d + %d = %d\n", a[0], a[1], sum);
for (i = 2; i < asize; ++i) a[i-2] = a[i];
a[asize - 2] = sum;
asize--;
}
printf("Last item is %d.\n", a[0]);
return 0;
}
|
def add_least_reduce(lis):
while len(lis) > 1:
lis.append(lis.pop(lis.index(min(lis))) + lis.pop(lis.index(min(lis))))
print('Interim list:', lis)
return lis
LIST = [6, 81, 243, 14, 25, 49, 123, 69, 11]
print(LIST, ' ==> ', add_least_reduce(LIST.copy()))
|
Change the following C code into Python without altering its purpose. | #include <stdio.h>
int min(int a, int b) {
if (a < b) return a;
return b;
}
int main() {
int n;
int numbers1[5] = {5, 45, 23, 21, 67};
int numbers2[5] = {43, 22, 78, 46, 38};
int numbers3[5] = {9, 98, 12, 98, 53};
int numbers[5] = {};
for (n = 0; n < 5; ++n) {
numbers[n] = min(min(numbers1[n], numbers2[n]), numbers3[n]);
printf("%d ", numbers[n]);
}
printf("\n");
return 0;
}
| numbers1 = [5,45,23,21,67]
numbers2 = [43,22,78,46,38]
numbers3 = [9,98,12,98,53]
numbers = [min(numbers1[i],numbers2[i],numbers3[i]) for i in range(0,len(numbers1))]
print(numbers)
|
Rewrite the snippet below in Python so it works the same as the original C code. | #include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
struct fp2 {
int64_t x, y;
};
uint64_t randULong(uint64_t min, uint64_t max) {
uint64_t t = (uint64_t)rand();
return min + t % (max - min);
}
uint64_t mul_mod(uint64_t a, uint64_t b, uint64_t modulus) {
uint64_t x = 0, y = a % modulus;
while (b > 0) {
if ((b & 1) == 1) {
x = (x + y) % modulus;
}
y = (y << 1) % modulus;
b = b >> 1;
}
return x;
}
uint64_t pow_mod(uint64_t b, uint64_t power, uint64_t modulus) {
uint64_t x = 1;
while (power > 0) {
if ((power & 1) == 1) {
x = mul_mod(x, b, modulus);
}
b = mul_mod(b, b, modulus);
power = power >> 1;
}
return x;
}
bool isPrime(uint64_t n, int64_t k) {
uint64_t a, x, n_one = n - 1, d = n_one;
uint32_t s = 0;
uint32_t r;
if (n < 2) {
return false;
}
if (n > 9223372036854775808ull) {
printf("The number is too big, program will end.\n");
exit(1);
}
if ((n % 2) == 0) {
return n == 2;
}
while ((d & 1) == 0) {
d = d >> 1;
s = s + 1;
}
while (k > 0) {
k = k - 1;
a = randULong(2, n);
x = pow_mod(a, d, n);
if (x == 1 || x == n_one) {
continue;
}
for (r = 1; r < s; r++) {
x = pow_mod(x, 2, n);
if (x == 1) return false;
if (x == n_one) goto continue_while;
}
if (x != n_one) {
return false;
}
continue_while: {}
}
return true;
}
int64_t legendre_symbol(int64_t a, int64_t p) {
int64_t x = pow_mod(a, (p - 1) / 2, p);
if ((p - 1) == x) {
return x - p;
} else {
return x;
}
}
struct fp2 fp2mul(struct fp2 a, struct fp2 b, int64_t p, int64_t w2) {
struct fp2 answer;
uint64_t tmp1, tmp2;
tmp1 = mul_mod(a.x, b.x, p);
tmp2 = mul_mod(a.y, b.y, p);
tmp2 = mul_mod(tmp2, w2, p);
answer.x = (tmp1 + tmp2) % p;
tmp1 = mul_mod(a.x, b.y, p);
tmp2 = mul_mod(a.y, b.x, p);
answer.y = (tmp1 + tmp2) % p;
return answer;
}
struct fp2 fp2square(struct fp2 a, int64_t p, int64_t w2) {
return fp2mul(a, a, p, w2);
}
struct fp2 fp2pow(struct fp2 a, int64_t n, int64_t p, int64_t w2) {
struct fp2 ret;
if (n == 0) {
ret.x = 1;
ret.y = 0;
return ret;
}
if (n == 1) {
return a;
}
if ((n & 1) == 0) {
return fp2square(fp2pow(a, n / 2, p, w2), p, w2);
} else {
return fp2mul(a, fp2pow(a, n - 1, p, w2), p, w2);
}
}
void test(int64_t n, int64_t p) {
int64_t a, w2;
int64_t x1, x2;
struct fp2 answer;
printf("Find solution for n = %lld and p = %lld\n", n, p);
if (p == 2 || !isPrime(p, 15)) {
printf("No solution, p is not an odd prime.\n\n");
return;
}
if (legendre_symbol(n, p) != 1) {
printf(" %lld is not a square in F%lld\n\n", n, p);
return;
}
while (true) {
do {
a = randULong(2, p);
w2 = a * a - n;
} while (legendre_symbol(w2, p) != -1);
answer.x = a;
answer.y = 1;
answer = fp2pow(answer, (p + 1) / 2, p, w2);
if (answer.y != 0) {
continue;
}
x1 = answer.x;
x2 = p - x1;
if (mul_mod(x1, x1, p) == n && mul_mod(x2, x2, p) == n) {
printf("Solution found: x1 = %lld, x2 = %lld\n\n", x1, x2);
return;
}
}
}
int main() {
srand((size_t)time(0));
test(10, 13);
test(56, 101);
test(8218, 10007);
test(8219, 10007);
test(331575, 1000003);
test(665165880, 1000000007);
return 0;
}
|
def convertToBase(n, b):
if(n < 2):
return [n];
temp = n;
ans = [];
while(temp != 0):
ans = [temp % b]+ ans;
temp /= b;
return ans;
def cipolla(n,p):
n %= p
if(n == 0 or n == 1):
return (n,-n%p)
phi = p - 1
if(pow(n, phi/2, p) != 1):
return ()
if(p%4 == 3):
ans = pow(n,(p+1)/4,p)
return (ans,-ans%p)
aa = 0
for i in xrange(1,p):
temp = pow((i*i-n)%p,phi/2,p)
if(temp == phi):
aa = i
break;
exponent = convertToBase((p+1)/2,2)
def cipollaMult((a,b),(c,d),w,p):
return ((a*c+b*d*w)%p,(a*d+b*c)%p)
x1 = (aa,1)
x2 = cipollaMult(x1,x1,aa*aa-n,p)
for i in xrange(1,len(exponent)):
if(exponent[i] == 0):
x2 = cipollaMult(x2,x1,aa*aa-n,p)
x1 = cipollaMult(x1,x1,aa*aa-n,p)
else:
x1 = cipollaMult(x1,x2,aa*aa-n,p)
x2 = cipollaMult(x2,x2,aa*aa-n,p)
return (x1[0],-x1[0]%p)
print "Roots of 2 mod 7: " +str(cipolla(2,7))
print "Roots of 8218 mod 10007: " +str(cipolla(8218,10007))
print "Roots of 56 mod 101: " +str(cipolla(56,101))
print "Roots of 1 mod 11: " +str(cipolla(1,11))
print "Roots of 8219 mod 10007: " +str(cipolla(8219,10007))
|
Translate the given C code snippet into Python without altering its behavior. | #include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
struct fp2 {
int64_t x, y;
};
uint64_t randULong(uint64_t min, uint64_t max) {
uint64_t t = (uint64_t)rand();
return min + t % (max - min);
}
uint64_t mul_mod(uint64_t a, uint64_t b, uint64_t modulus) {
uint64_t x = 0, y = a % modulus;
while (b > 0) {
if ((b & 1) == 1) {
x = (x + y) % modulus;
}
y = (y << 1) % modulus;
b = b >> 1;
}
return x;
}
uint64_t pow_mod(uint64_t b, uint64_t power, uint64_t modulus) {
uint64_t x = 1;
while (power > 0) {
if ((power & 1) == 1) {
x = mul_mod(x, b, modulus);
}
b = mul_mod(b, b, modulus);
power = power >> 1;
}
return x;
}
bool isPrime(uint64_t n, int64_t k) {
uint64_t a, x, n_one = n - 1, d = n_one;
uint32_t s = 0;
uint32_t r;
if (n < 2) {
return false;
}
if (n > 9223372036854775808ull) {
printf("The number is too big, program will end.\n");
exit(1);
}
if ((n % 2) == 0) {
return n == 2;
}
while ((d & 1) == 0) {
d = d >> 1;
s = s + 1;
}
while (k > 0) {
k = k - 1;
a = randULong(2, n);
x = pow_mod(a, d, n);
if (x == 1 || x == n_one) {
continue;
}
for (r = 1; r < s; r++) {
x = pow_mod(x, 2, n);
if (x == 1) return false;
if (x == n_one) goto continue_while;
}
if (x != n_one) {
return false;
}
continue_while: {}
}
return true;
}
int64_t legendre_symbol(int64_t a, int64_t p) {
int64_t x = pow_mod(a, (p - 1) / 2, p);
if ((p - 1) == x) {
return x - p;
} else {
return x;
}
}
struct fp2 fp2mul(struct fp2 a, struct fp2 b, int64_t p, int64_t w2) {
struct fp2 answer;
uint64_t tmp1, tmp2;
tmp1 = mul_mod(a.x, b.x, p);
tmp2 = mul_mod(a.y, b.y, p);
tmp2 = mul_mod(tmp2, w2, p);
answer.x = (tmp1 + tmp2) % p;
tmp1 = mul_mod(a.x, b.y, p);
tmp2 = mul_mod(a.y, b.x, p);
answer.y = (tmp1 + tmp2) % p;
return answer;
}
struct fp2 fp2square(struct fp2 a, int64_t p, int64_t w2) {
return fp2mul(a, a, p, w2);
}
struct fp2 fp2pow(struct fp2 a, int64_t n, int64_t p, int64_t w2) {
struct fp2 ret;
if (n == 0) {
ret.x = 1;
ret.y = 0;
return ret;
}
if (n == 1) {
return a;
}
if ((n & 1) == 0) {
return fp2square(fp2pow(a, n / 2, p, w2), p, w2);
} else {
return fp2mul(a, fp2pow(a, n - 1, p, w2), p, w2);
}
}
void test(int64_t n, int64_t p) {
int64_t a, w2;
int64_t x1, x2;
struct fp2 answer;
printf("Find solution for n = %lld and p = %lld\n", n, p);
if (p == 2 || !isPrime(p, 15)) {
printf("No solution, p is not an odd prime.\n\n");
return;
}
if (legendre_symbol(n, p) != 1) {
printf(" %lld is not a square in F%lld\n\n", n, p);
return;
}
while (true) {
do {
a = randULong(2, p);
w2 = a * a - n;
} while (legendre_symbol(w2, p) != -1);
answer.x = a;
answer.y = 1;
answer = fp2pow(answer, (p + 1) / 2, p, w2);
if (answer.y != 0) {
continue;
}
x1 = answer.x;
x2 = p - x1;
if (mul_mod(x1, x1, p) == n && mul_mod(x2, x2, p) == n) {
printf("Solution found: x1 = %lld, x2 = %lld\n\n", x1, x2);
return;
}
}
}
int main() {
srand((size_t)time(0));
test(10, 13);
test(56, 101);
test(8218, 10007);
test(8219, 10007);
test(331575, 1000003);
test(665165880, 1000000007);
return 0;
}
|
def convertToBase(n, b):
if(n < 2):
return [n];
temp = n;
ans = [];
while(temp != 0):
ans = [temp % b]+ ans;
temp /= b;
return ans;
def cipolla(n,p):
n %= p
if(n == 0 or n == 1):
return (n,-n%p)
phi = p - 1
if(pow(n, phi/2, p) != 1):
return ()
if(p%4 == 3):
ans = pow(n,(p+1)/4,p)
return (ans,-ans%p)
aa = 0
for i in xrange(1,p):
temp = pow((i*i-n)%p,phi/2,p)
if(temp == phi):
aa = i
break;
exponent = convertToBase((p+1)/2,2)
def cipollaMult((a,b),(c,d),w,p):
return ((a*c+b*d*w)%p,(a*d+b*c)%p)
x1 = (aa,1)
x2 = cipollaMult(x1,x1,aa*aa-n,p)
for i in xrange(1,len(exponent)):
if(exponent[i] == 0):
x2 = cipollaMult(x2,x1,aa*aa-n,p)
x1 = cipollaMult(x1,x1,aa*aa-n,p)
else:
x1 = cipollaMult(x1,x2,aa*aa-n,p)
x2 = cipollaMult(x2,x2,aa*aa-n,p)
return (x1[0],-x1[0]%p)
print "Roots of 2 mod 7: " +str(cipolla(2,7))
print "Roots of 8218 mod 10007: " +str(cipolla(8218,10007))
print "Roots of 56 mod 101: " +str(cipolla(56,101))
print "Roots of 1 mod 11: " +str(cipolla(1,11))
print "Roots of 8219 mod 10007: " +str(cipolla(8219,10007))
|
Rewrite this program in Python while keeping its functionality equivalent to the C version. | #include <math.h>
#include <stdint.h>
#include <stdio.h>
const uint64_t N = 6364136223846793005;
static uint64_t state = 0x853c49e6748fea9b;
static uint64_t inc = 0xda3e39cb94b95bdb;
uint32_t pcg32_int() {
uint64_t old = state;
state = old * N + inc;
uint32_t shifted = (uint32_t)(((old >> 18) ^ old) >> 27);
uint32_t rot = old >> 59;
return (shifted >> rot) | (shifted << ((~rot + 1) & 31));
}
double pcg32_float() {
return ((double)pcg32_int()) / (1LL << 32);
}
void pcg32_seed(uint64_t seed_state, uint64_t seed_sequence) {
state = 0;
inc = (seed_sequence << 1) | 1;
pcg32_int();
state = state + seed_state;
pcg32_int();
}
int main() {
int counts[5] = { 0, 0, 0, 0, 0 };
int i;
pcg32_seed(42, 54);
printf("%u\n", pcg32_int());
printf("%u\n", pcg32_int());
printf("%u\n", pcg32_int());
printf("%u\n", pcg32_int());
printf("%u\n", pcg32_int());
printf("\n");
pcg32_seed(987654321, 1);
for (i = 0; i < 100000; i++) {
int j = (int)floor(pcg32_float() * 5.0);
counts[j]++;
}
printf("The counts for 100,000 repetitions are:\n");
for (i = 0; i < 5; i++) {
printf(" %d : %d\n", i, counts[i]);
}
return 0;
}
| mask64 = (1 << 64) - 1
mask32 = (1 << 32) - 1
CONST = 6364136223846793005
class PCG32():
def __init__(self, seed_state=None, seed_sequence=None):
if all(type(x) == int for x in (seed_state, seed_sequence)):
self.seed(seed_state, seed_sequence)
else:
self.state = self.inc = 0
def seed(self, seed_state, seed_sequence):
self.state = 0
self.inc = ((seed_sequence << 1) | 1) & mask64
self.next_int()
self.state = (self.state + seed_state)
self.next_int()
def next_int(self):
"return random 32 bit unsigned int"
old = self.state
self.state = ((old * CONST) + self.inc) & mask64
xorshifted = (((old >> 18) ^ old) >> 27) & mask32
rot = (old >> 59) & mask32
answer = (xorshifted >> rot) | (xorshifted << ((-rot) & 31))
answer = answer &mask32
return answer
def next_float(self):
"return random float between 0 and 1"
return self.next_int() / (1 << 32)
if __name__ == '__main__':
random_gen = PCG32()
random_gen.seed(42, 54)
for i in range(5):
print(random_gen.next_int())
random_gen.seed(987654321, 1)
hist = {i:0 for i in range(5)}
for i in range(100_000):
hist[int(random_gen.next_float() *5)] += 1
print(hist)
|
Please provide an equivalent version of this C code in Python. | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <complex.h>
double PI;
typedef double complex cplx;
void _fft(cplx buf[], cplx out[], int n, int step)
{
if (step < n) {
_fft(out, buf, n, step * 2);
_fft(out + step, buf + step, n, step * 2);
for (int i = 0; i < n; i += 2 * step) {
cplx t = cexp(-I * PI * i / n) * out[i + step];
buf[i / 2] = out[i] + t;
buf[(i + n)/2] = out[i] - t;
}
}
}
void fft(cplx buf[], int n)
{
cplx out[n];
for (int i = 0; i < n; i++) out[i] = buf[i];
_fft(buf, out, n, 1);
}
cplx *pad_two(double g[], int len, int *ns)
{
int n = 1;
if (*ns) n = *ns;
else while (n < len) n *= 2;
cplx *buf = calloc(sizeof(cplx), n);
for (int i = 0; i < len; i++) buf[i] = g[i];
*ns = n;
return buf;
}
void deconv(double g[], int lg, double f[], int lf, double out[]) {
int ns = 0;
cplx *g2 = pad_two(g, lg, &ns);
cplx *f2 = pad_two(f, lf, &ns);
fft(g2, ns);
fft(f2, ns);
cplx h[ns];
for (int i = 0; i < ns; i++) h[i] = g2[i] / f2[i];
fft(h, ns);
for (int i = 0; i >= lf - lg; i--)
out[-i] = h[(i + ns) % ns]/32;
free(g2);
free(f2);
}
int main()
{
PI = atan2(1,1) * 4;
double g[] = {24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7};
double f[] = { -3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1 };
double h[] = { -8,-9,-3,-1,-6,7 };
int lg = sizeof(g)/sizeof(double);
int lf = sizeof(f)/sizeof(double);
int lh = sizeof(h)/sizeof(double);
double h2[lh];
double f2[lf];
printf("f[] data is : ");
for (int i = 0; i < lf; i++) printf(" %g", f[i]);
printf("\n");
printf("deconv(g, h): ");
deconv(g, lg, h, lh, f2);
for (int i = 0; i < lf; i++) printf(" %g", f2[i]);
printf("\n");
printf("h[] data is : ");
for (int i = 0; i < lh; i++) printf(" %g", h[i]);
printf("\n");
printf("deconv(g, f): ");
deconv(g, lg, f, lf, h2);
for (int i = 0; i < lh; i++) printf(" %g", h2[i]);
printf("\n");
}
| def ToReducedRowEchelonForm( M ):
if not M: return
lead = 0
rowCount = len(M)
columnCount = len(M[0])
for r in range(rowCount):
if lead >= columnCount:
return
i = r
while M[i][lead] == 0:
i += 1
if i == rowCount:
i = r
lead += 1
if columnCount == lead:
return
M[i],M[r] = M[r],M[i]
lv = M[r][lead]
M[r] = [ mrx / lv for mrx in M[r]]
for i in range(rowCount):
if i != r:
lv = M[i][lead]
M[i] = [ iv - lv*rv for rv,iv in zip(M[r],M[i])]
lead += 1
return M
def pmtx(mtx):
print ('\n'.join(''.join(' %4s' % col for col in row) for row in mtx))
def convolve(f, h):
g = [0] * (len(f) + len(h) - 1)
for hindex, hval in enumerate(h):
for findex, fval in enumerate(f):
g[hindex + findex] += fval * hval
return g
def deconvolve(g, f):
lenh = len(g) - len(f) + 1
mtx = [[0 for x in range(lenh+1)] for y in g]
for hindex in range(lenh):
for findex, fval in enumerate(f):
gindex = hindex + findex
mtx[gindex][hindex] = fval
for gindex, gval in enumerate(g):
mtx[gindex][lenh] = gval
ToReducedRowEchelonForm( mtx )
return [mtx[i][lenh] for i in range(lenh)]
if __name__ == '__main__':
h = [-8,-9,-3,-1,-6,7]
f = [-3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1]
g = [24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7]
assert convolve(f,h) == g
assert deconvolve(g, f) == h
|
Write a version of this C function in Python with identical behavior. |
void print_jpg(image img, int qual);
|
from PIL import Image
im = Image.open("boxes_1.ppm")
im.save("boxes_1.jpg")
|
Convert this C snippet to Python and keep its semantics consistent. | #include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <openssl/sha.h>
#include <openssl/ripemd.h>
#define COIN_VER 0
const char *coin_err;
typedef unsigned char byte;
int is_hex(const char *s) {
int i;
for (i = 0; i < 64; i++)
if (!isxdigit(s[i])) return 0;
return 1;
}
void str_to_byte(const char *src, byte *dst, int n) {
while (n--) sscanf(src + n * 2, "%2hhx", dst + n);
}
char* base58(byte *s, char *out) {
static const char *tmpl = "123456789"
"ABCDEFGHJKLMNPQRSTUVWXYZ"
"abcdefghijkmnopqrstuvwxyz";
static char buf[40];
int c, i, n;
if (!out) out = buf;
out[n = 34] = 0;
while (n--) {
for (c = i = 0; i < 25; i++) {
c = c * 256 + s[i];
s[i] = c / 58;
c %= 58;
}
out[n] = tmpl[c];
}
for (n = 0; out[n] == '1'; n++);
memmove(out, out + n, 34 - n);
return out;
}
char *coin_encode(const char *x, const char *y, char *out) {
byte s[65];
byte rmd[5 + RIPEMD160_DIGEST_LENGTH];
if (!is_hex(x) || !(is_hex(y))) {
coin_err = "bad public point string";
return 0;
}
s[0] = 4;
str_to_byte(x, s + 1, 32);
str_to_byte(y, s + 33, 32);
rmd[0] = COIN_VER;
RIPEMD160(SHA256(s, 65, 0), SHA256_DIGEST_LENGTH, rmd + 1);
memcpy(rmd + 21, SHA256(SHA256(rmd, 21, 0), SHA256_DIGEST_LENGTH, 0), 4);
return base58(rmd, out);
}
int main(void) {
puts(coin_encode(
"50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352",
"2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6",
0));
return 0;
}
|
import binascii
import functools
import hashlib
digits58 = b'123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
def b58(n):
return b58(n//58) + digits58[n%58:n%58+1] if n else b''
def public_point_to_address(x, y):
c = b'\x04' + binascii.unhexlify(x) + binascii.unhexlify(y)
r = hashlib.new('ripemd160')
r.update(hashlib.sha256(c).digest())
c = b'\x00' + r.digest()
d = hashlib.sha256(hashlib.sha256(c).digest()).digest()
return b58(functools.reduce(lambda n, b: n<<8|b, c + d[:4]))
if __name__ == '__main__':
print(public_point_to_address(
b'50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352',
b'2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6'))
|
Write the same algorithm in Python as shown in this C implementation. | #include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <openssl/sha.h>
#include <openssl/ripemd.h>
#define COIN_VER 0
const char *coin_err;
typedef unsigned char byte;
int is_hex(const char *s) {
int i;
for (i = 0; i < 64; i++)
if (!isxdigit(s[i])) return 0;
return 1;
}
void str_to_byte(const char *src, byte *dst, int n) {
while (n--) sscanf(src + n * 2, "%2hhx", dst + n);
}
char* base58(byte *s, char *out) {
static const char *tmpl = "123456789"
"ABCDEFGHJKLMNPQRSTUVWXYZ"
"abcdefghijkmnopqrstuvwxyz";
static char buf[40];
int c, i, n;
if (!out) out = buf;
out[n = 34] = 0;
while (n--) {
for (c = i = 0; i < 25; i++) {
c = c * 256 + s[i];
s[i] = c / 58;
c %= 58;
}
out[n] = tmpl[c];
}
for (n = 0; out[n] == '1'; n++);
memmove(out, out + n, 34 - n);
return out;
}
char *coin_encode(const char *x, const char *y, char *out) {
byte s[65];
byte rmd[5 + RIPEMD160_DIGEST_LENGTH];
if (!is_hex(x) || !(is_hex(y))) {
coin_err = "bad public point string";
return 0;
}
s[0] = 4;
str_to_byte(x, s + 1, 32);
str_to_byte(y, s + 33, 32);
rmd[0] = COIN_VER;
RIPEMD160(SHA256(s, 65, 0), SHA256_DIGEST_LENGTH, rmd + 1);
memcpy(rmd + 21, SHA256(SHA256(rmd, 21, 0), SHA256_DIGEST_LENGTH, 0), 4);
return base58(rmd, out);
}
int main(void) {
puts(coin_encode(
"50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352",
"2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6",
0));
return 0;
}
|
import binascii
import functools
import hashlib
digits58 = b'123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
def b58(n):
return b58(n//58) + digits58[n%58:n%58+1] if n else b''
def public_point_to_address(x, y):
c = b'\x04' + binascii.unhexlify(x) + binascii.unhexlify(y)
r = hashlib.new('ripemd160')
r.update(hashlib.sha256(c).digest())
c = b'\x00' + r.digest()
d = hashlib.sha256(hashlib.sha256(c).digest()).digest()
return b58(functools.reduce(lambda n, b: n<<8|b, c + d[:4]))
if __name__ == '__main__':
print(public_point_to_address(
b'50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352',
b'2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6'))
|
Generate a Python translation of this C snippet without changing its computational steps. | #include <iostream>
#include <iomanip>
#include <string>
std::string NYSIIS( std::string const& str )
{
std::string s, out;
s.reserve( str.length() );
for( auto const c : str )
{
if( c >= 'a' && c <= 'z' )
s += c - ('a' - 'A');
else if( c >= 'A' && c <= 'Z' )
s += c;
}
auto replace = []( char const * const from, char const* to, char* const dst ) -> bool
{
auto const n = strlen( from );
if( strncmp( from, dst, n ) == 0 )
{
strncpy( dst, to, n );
return true;
}
return false;
};
auto multiReplace = []( char const* const* from, char const* to, char* const dst ) -> bool
{
auto const n = strlen( *from );
for( ; *from; ++from )
if( strncmp( *from, dst, n ) == 0 )
{
memcpy( dst, to, n );
return true;
}
return false;
};
auto isVowel = []( char const c ) -> bool
{
return c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U';
};
size_t n = s.length();
replace( "MAC", "MCC", &s[0] );
replace( "KN", "NN", &s[0] );
replace( "K", "C", &s[0] );
char const* const prefix[] = { "PH", "PF", 0 };
multiReplace( prefix, "FF", &s[0] );
replace( "SCH", "SSS", &s[0] );
char const* const suffix1[] = { "EE", "IE", 0 };
char const* const suffix2[] = { "DT", "RT", "RD", "NT", "ND", 0 };
if( multiReplace( suffix1, "Y", &s[n - 2] ) || multiReplace( suffix2, "D", &s[n - 2] ))
{
s.pop_back();
--n;
}
out += s[0];
char* vowels[] = { "A", "E", "I", "O", "U", 0 };
for( unsigned i = 1; i < n; ++i )
{
char* const c = &s[i];
if( !replace( "EV", "AV", c ) )
multiReplace( vowels, "A", c );
replace( "Q", "G", c );
replace( "Z", "S", c );
replace( "M", "N", c );
if( !replace( "KN", "NN", c ))
replace( "K", "C", c );
replace( "SCH", "SSS", c );
replace( "PH", "FF", c );
if( *c == 'H' && (!isVowel( s[i - 1] ) || i + 1 >= n || !isVowel( s[i + 1] )))
*c = s[i - 1];
if( *c == 'W' && isVowel( s[i - 1] ))
*c = 'A';
if( out.back() != *c )
out += *c;
}
if( out.back() == 'S' || out.back() == 'A' )
out.pop_back();
n = out.length() - 2;
if( out[n] == 'A' && out[n + 1] == 'Y' )
out = out.substr( 0, n ) + "Y";
return out;
}
int main()
{
static char const * const names[][2] = {
{ "Bishop", "BASAP" },
{ "Carlson", "CARLSAN" },
{ "Carr", "CAR" },
{ "Chapman", "CAPNAN" },
{ "Franklin", "FRANCLAN" },
{ "Greene", "GRAN" },
{ "Harper", "HARPAR" },
{ "Jacobs", "JACAB" },
{ "Larson", "LARSAN" },
{ "Lawrence", "LARANC" },
{ "Lawson", "LASAN" },
{ "Louis, XVI", "LASXV" },
{ "Lynch", "LYNC" },
{ "Mackenzie", "MCANSY" },
{ "Matthews", "MATA" },
{ "McCormack", "MCARNAC" },
{ "McDaniel", "MCDANAL" },
{ "McDonald", "MCDANALD" },
{ "Mclaughlin", "MCLAGLAN" },
{ "Morrison", "MARASAN" },
{ "O'Banion", "OBANAN" },
{ "O'Brien", "OBRAN" },
{ "Richards", "RACARD" },
{ "Silva", "SALV" },
{ "Watkins", "WATCAN" },
{ "Wheeler", "WALAR" },
{ "Willis", "WALA" },
{ "brown, sr", "BRANSR" },
{ "browne, III", "BRAN" },
{ "browne, IV", "BRANAV" },
{ "knight", "NAGT" },
{ "mitchell", "MATCAL" },
{ "o'daniel", "ODANAL" } };
for( auto const& name : names )
{
auto const code = NYSIIS( name[0] );
std::cout << std::left << std::setw( 16 ) << name[0] << std::setw( 8 ) << code;
if( code == std::string( name[1] ))
std::cout << " ok";
else
std::cout << " ERROR: " << name[1] << " expected";
std::cout << std::endl;
}
return 0;
}
| import re
_vowels = 'AEIOU'
def replace_at(text, position, fromlist, tolist):
for f, t in zip(fromlist, tolist):
if text[position:].startswith(f):
return ''.join([text[:position],
t,
text[position+len(f):]])
return text
def replace_end(text, fromlist, tolist):
for f, t in zip(fromlist, tolist):
if text.endswith(f):
return text[:-len(f)] + t
return text
def nysiis(name):
name = re.sub(r'\W', '', name).upper()
name = replace_at(name, 0, ['MAC', 'KN', 'K', 'PH', 'PF', 'SCH'],
['MCC', 'N', 'C', 'FF', 'FF', 'SSS'])
name = replace_end(name, ['EE', 'IE', 'DT', 'RT', 'RD', 'NT', 'ND'],
['Y', 'Y', 'D', 'D', 'D', 'D', 'D'])
key, key1 = name[0], ''
i = 1
while i < len(name):
n_1, n = name[i-1], name[i]
n1_ = name[i+1] if i+1 < len(name) else ''
name = replace_at(name, i, ['EV'] + list(_vowels), ['AF'] + ['A']*5)
name = replace_at(name, i, 'QZM', 'GSN')
name = replace_at(name, i, ['KN', 'K'], ['N', 'C'])
name = replace_at(name, i, ['SCH', 'PH'], ['SSS', 'FF'])
if n == 'H' and (n_1 not in _vowels or n1_ not in _vowels):
name = ''.join([name[:i], n_1, name[i+1:]])
if n == 'W' and n_1 in _vowels:
name = ''.join([name[:i], 'A', name[i+1:]])
if key and key[-1] != name[i]:
key += name[i]
i += 1
key = replace_end(key, ['S', 'AY', 'A'], ['', 'Y', ''])
return key1 + key
if __name__ == '__main__':
names = ['Bishop', 'Carlson', 'Carr', 'Chapman', 'Franklin',
'Greene', 'Harper', 'Jacobs', 'Larson', 'Lawrence',
'Lawson', 'Louis, XVI', 'Lynch', 'Mackenzie', 'Matthews',
'McCormack', 'McDaniel', 'McDonald', 'Mclaughlin', 'Morrison',
"O'Banion", "O'Brien", 'Richards', 'Silva', 'Watkins',
'Wheeler', 'Willis', 'brown, sr', 'browne, III', 'browne, IV',
'knight', 'mitchell', "o'daniel"]
for name in names:
print('%15s: %s' % (name, nysiis(name)))
|
Convert this C snippet to Python and keep its semantics consistent. | #include <iostream>
#include <iomanip>
#include <string>
std::string NYSIIS( std::string const& str )
{
std::string s, out;
s.reserve( str.length() );
for( auto const c : str )
{
if( c >= 'a' && c <= 'z' )
s += c - ('a' - 'A');
else if( c >= 'A' && c <= 'Z' )
s += c;
}
auto replace = []( char const * const from, char const* to, char* const dst ) -> bool
{
auto const n = strlen( from );
if( strncmp( from, dst, n ) == 0 )
{
strncpy( dst, to, n );
return true;
}
return false;
};
auto multiReplace = []( char const* const* from, char const* to, char* const dst ) -> bool
{
auto const n = strlen( *from );
for( ; *from; ++from )
if( strncmp( *from, dst, n ) == 0 )
{
memcpy( dst, to, n );
return true;
}
return false;
};
auto isVowel = []( char const c ) -> bool
{
return c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U';
};
size_t n = s.length();
replace( "MAC", "MCC", &s[0] );
replace( "KN", "NN", &s[0] );
replace( "K", "C", &s[0] );
char const* const prefix[] = { "PH", "PF", 0 };
multiReplace( prefix, "FF", &s[0] );
replace( "SCH", "SSS", &s[0] );
char const* const suffix1[] = { "EE", "IE", 0 };
char const* const suffix2[] = { "DT", "RT", "RD", "NT", "ND", 0 };
if( multiReplace( suffix1, "Y", &s[n - 2] ) || multiReplace( suffix2, "D", &s[n - 2] ))
{
s.pop_back();
--n;
}
out += s[0];
char* vowels[] = { "A", "E", "I", "O", "U", 0 };
for( unsigned i = 1; i < n; ++i )
{
char* const c = &s[i];
if( !replace( "EV", "AV", c ) )
multiReplace( vowels, "A", c );
replace( "Q", "G", c );
replace( "Z", "S", c );
replace( "M", "N", c );
if( !replace( "KN", "NN", c ))
replace( "K", "C", c );
replace( "SCH", "SSS", c );
replace( "PH", "FF", c );
if( *c == 'H' && (!isVowel( s[i - 1] ) || i + 1 >= n || !isVowel( s[i + 1] )))
*c = s[i - 1];
if( *c == 'W' && isVowel( s[i - 1] ))
*c = 'A';
if( out.back() != *c )
out += *c;
}
if( out.back() == 'S' || out.back() == 'A' )
out.pop_back();
n = out.length() - 2;
if( out[n] == 'A' && out[n + 1] == 'Y' )
out = out.substr( 0, n ) + "Y";
return out;
}
int main()
{
static char const * const names[][2] = {
{ "Bishop", "BASAP" },
{ "Carlson", "CARLSAN" },
{ "Carr", "CAR" },
{ "Chapman", "CAPNAN" },
{ "Franklin", "FRANCLAN" },
{ "Greene", "GRAN" },
{ "Harper", "HARPAR" },
{ "Jacobs", "JACAB" },
{ "Larson", "LARSAN" },
{ "Lawrence", "LARANC" },
{ "Lawson", "LASAN" },
{ "Louis, XVI", "LASXV" },
{ "Lynch", "LYNC" },
{ "Mackenzie", "MCANSY" },
{ "Matthews", "MATA" },
{ "McCormack", "MCARNAC" },
{ "McDaniel", "MCDANAL" },
{ "McDonald", "MCDANALD" },
{ "Mclaughlin", "MCLAGLAN" },
{ "Morrison", "MARASAN" },
{ "O'Banion", "OBANAN" },
{ "O'Brien", "OBRAN" },
{ "Richards", "RACARD" },
{ "Silva", "SALV" },
{ "Watkins", "WATCAN" },
{ "Wheeler", "WALAR" },
{ "Willis", "WALA" },
{ "brown, sr", "BRANSR" },
{ "browne, III", "BRAN" },
{ "browne, IV", "BRANAV" },
{ "knight", "NAGT" },
{ "mitchell", "MATCAL" },
{ "o'daniel", "ODANAL" } };
for( auto const& name : names )
{
auto const code = NYSIIS( name[0] );
std::cout << std::left << std::setw( 16 ) << name[0] << std::setw( 8 ) << code;
if( code == std::string( name[1] ))
std::cout << " ok";
else
std::cout << " ERROR: " << name[1] << " expected";
std::cout << std::endl;
}
return 0;
}
| import re
_vowels = 'AEIOU'
def replace_at(text, position, fromlist, tolist):
for f, t in zip(fromlist, tolist):
if text[position:].startswith(f):
return ''.join([text[:position],
t,
text[position+len(f):]])
return text
def replace_end(text, fromlist, tolist):
for f, t in zip(fromlist, tolist):
if text.endswith(f):
return text[:-len(f)] + t
return text
def nysiis(name):
name = re.sub(r'\W', '', name).upper()
name = replace_at(name, 0, ['MAC', 'KN', 'K', 'PH', 'PF', 'SCH'],
['MCC', 'N', 'C', 'FF', 'FF', 'SSS'])
name = replace_end(name, ['EE', 'IE', 'DT', 'RT', 'RD', 'NT', 'ND'],
['Y', 'Y', 'D', 'D', 'D', 'D', 'D'])
key, key1 = name[0], ''
i = 1
while i < len(name):
n_1, n = name[i-1], name[i]
n1_ = name[i+1] if i+1 < len(name) else ''
name = replace_at(name, i, ['EV'] + list(_vowels), ['AF'] + ['A']*5)
name = replace_at(name, i, 'QZM', 'GSN')
name = replace_at(name, i, ['KN', 'K'], ['N', 'C'])
name = replace_at(name, i, ['SCH', 'PH'], ['SSS', 'FF'])
if n == 'H' and (n_1 not in _vowels or n1_ not in _vowels):
name = ''.join([name[:i], n_1, name[i+1:]])
if n == 'W' and n_1 in _vowels:
name = ''.join([name[:i], 'A', name[i+1:]])
if key and key[-1] != name[i]:
key += name[i]
i += 1
key = replace_end(key, ['S', 'AY', 'A'], ['', 'Y', ''])
return key1 + key
if __name__ == '__main__':
names = ['Bishop', 'Carlson', 'Carr', 'Chapman', 'Franklin',
'Greene', 'Harper', 'Jacobs', 'Larson', 'Lawrence',
'Lawson', 'Louis, XVI', 'Lynch', 'Mackenzie', 'Matthews',
'McCormack', 'McDaniel', 'McDonald', 'Mclaughlin', 'Morrison',
"O'Banion", "O'Brien", 'Richards', 'Silva', 'Watkins',
'Wheeler', 'Willis', 'brown, sr', 'browne, III', 'browne, IV',
'knight', 'mitchell', "o'daniel"]
for name in names:
print('%15s: %s' % (name, nysiis(name)))
|
Produce a functionally identical Python code for the snippet given in C. | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
int power (int base, int exponent) {
int result = 1;
for (int i = 1; i <= exponent; i++) {
result *= base;
}
return result;
}
int is_disarium (int num) {
int n = num;
int sum = 0;
int len = n <= 9 ? 1 : floor(log10(n)) + 1;
while (n > 0) {
sum += power(n % 10, len);
n /= 10;
len--;
}
return num == sum;
}
int main() {
int count = 0;
int i = 0;
while (count < 19) {
if (is_disarium(i)) {
printf("%d ", i);
count++;
}
i++;
}
printf("%s\n", "\n");
}
|
def isDisarium(n):
digitos = len(str(n))
suma = 0
x = n
while x != 0:
suma += (x % 10) ** digitos
digitos -= 1
x //= 10
if suma == n:
return True
else:
return False
if __name__ == '__main__':
limite = 19
cont = 0
n = 0
print("The first",limite,"Disarium numbers are:")
while cont < limite:
if isDisarium(n):
print(n, end = " ")
cont += 1
n += 1
|
Generate a Python translation of this C snippet without changing its computational steps. | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
int power (int base, int exponent) {
int result = 1;
for (int i = 1; i <= exponent; i++) {
result *= base;
}
return result;
}
int is_disarium (int num) {
int n = num;
int sum = 0;
int len = n <= 9 ? 1 : floor(log10(n)) + 1;
while (n > 0) {
sum += power(n % 10, len);
n /= 10;
len--;
}
return num == sum;
}
int main() {
int count = 0;
int i = 0;
while (count < 19) {
if (is_disarium(i)) {
printf("%d ", i);
count++;
}
i++;
}
printf("%s\n", "\n");
}
|
def isDisarium(n):
digitos = len(str(n))
suma = 0
x = n
while x != 0:
suma += (x % 10) ** digitos
digitos -= 1
x //= 10
if suma == n:
return True
else:
return False
if __name__ == '__main__':
limite = 19
cont = 0
n = 0
print("The first",limite,"Disarium numbers are:")
while cont < limite:
if isDisarium(n):
print(n, end = " ")
cont += 1
n += 1
|
Translate the given C code snippet into Python without altering its behavior. | #include<graphics.h>
#include<stdlib.h>
#include<stdio.h>
#include<math.h>
#include<time.h>
#define pi M_PI
int main(){
time_t t;
double side, **vertices,seedX,seedY,windowSide = 500,sumX=0,sumY=0;
int i,iter,choice,numSides;
printf("Enter number of sides : ");
scanf("%d",&numSides);
printf("Enter polygon side length : ");
scanf("%lf",&side);
printf("Enter number of iterations : ");
scanf("%d",&iter);
initwindow(windowSide,windowSide,"Polygon Chaos");
vertices = (double**)malloc(numSides*sizeof(double*));
for(i=0;i<numSides;i++){
vertices[i] = (double*)malloc(2 * sizeof(double));
vertices[i][0] = windowSide/2 + side*cos(i*2*pi/numSides);
vertices[i][1] = windowSide/2 + side*sin(i*2*pi/numSides);
sumX+= vertices[i][0];
sumY+= vertices[i][1];
putpixel(vertices[i][0],vertices[i][1],15);
}
srand((unsigned)time(&t));
seedX = sumX/numSides;
seedY = sumY/numSides;
putpixel(seedX,seedY,15);
for(i=0;i<iter;i++){
choice = rand()%numSides;
seedX = (seedX + (numSides-2)*vertices[choice][0])/(numSides-1);
seedY = (seedY + (numSides-2)*vertices[choice][1])/(numSides-1);
putpixel(seedX,seedY,15);
}
free(vertices);
getch();
closegraph();
return 0;
}
| from turtle import *
import math
speed(0)
hideturtle()
part_ratio = 2 * math.cos(math.radians(72))
side_ratio = 1 / (part_ratio + 2)
hide_turtles = True
path_color = "black"
fill_color = "black"
def pentagon(t, s):
t.color(path_color, fill_color)
t.pendown()
t.right(36)
t.begin_fill()
for i in range(5):
t.forward(s)
t.right(72)
t.end_fill()
def sierpinski(i, t, s):
t.setheading(0)
new_size = s * side_ratio
if i > 1:
i -= 1
for j in range(4):
t.right(36)
short = s * side_ratio / part_ratio
dist = [short, s, s, short][j]
spawn = Turtle()
if hide_turtles:spawn.hideturtle()
spawn.penup()
spawn.setposition(t.position())
spawn.setheading(t.heading())
spawn.forward(dist)
sierpinski(i, spawn, new_size)
sierpinski(i, t, new_size)
else:
pentagon(t, s)
del t
def main():
t = Turtle()
t.hideturtle()
t.penup()
screen = t.getscreen()
y = screen.window_height()
t.goto(0, y/2-20)
i = 5
size = 300
size *= part_ratio
sierpinski(i, t, size)
main()
|
Port the following code from C to Python with equivalent syntax and logic. | typedef unsigned int histogram_t;
typedef histogram_t *histogram;
#define GET_LUM(IMG, X, Y) ( (IMG)->buf[ (Y) * (IMG)->width + (X)][0] )
histogram get_histogram(grayimage im);
luminance histogram_median(histogram h);
| from PIL import Image
image = Image.open("lena.jpg")
width, height = image.size
amount = width * height
total = 0
bw_image = Image.new('L', (width, height), 0)
bm_image = Image.new('1', (width, height), 0)
for h in range(0, height):
for w in range(0, width):
r, g, b = image.getpixel((w, h))
greyscale = int((r + g + b) / 3)
total += greyscale
bw_image.putpixel((w, h), gray_scale)
avg = total / amount
black = 0
white = 1
for h in range(0, height):
for w in range(0, width):
v = bw_image.getpixel((w, h))
if v >= avg:
bm_image.putpixel((w, h), white)
else:
bm_image.putpixel((w, h), black)
bw_image.show()
bm_image.show()
|
Generate an equivalent Python version of this C code. | #include <stdio.h>
void padovanN(int n, size_t t, int *p) {
int i, j;
if (n < 2 || t < 3) {
for (i = 0; i < t; ++i) p[i] = 1;
return;
}
padovanN(n-1, t, p);
for (i = n + 1; i < t; ++i) {
p[i] = 0;
for (j = i - 2; j >= i - n - 1; --j) p[i] += p[j];
}
}
int main() {
int n, i;
const size_t t = 15;
int p[t];
printf("First %ld terms of the Padovan n-step number sequences:\n", t);
for (n = 2; n <= 8; ++n) {
for (i = 0; i < t; ++i) p[i] = 0;
padovanN(n, t, p);
printf("%d: ", n);
for (i = 0; i < t; ++i) printf("%3d ", p[i]);
printf("\n");
}
return 0;
}
| def pad_like(max_n=8, t=15):
start = [[], [1, 1, 1]]
for n in range(2, max_n+1):
this = start[n-1][:n+1]
while len(this) < t:
this.append(sum(this[i] for i in range(-2, -n - 2, -1)))
start.append(this)
return start[2:]
def pr(p):
print(.strip())
for n, seq in enumerate(p, 2):
print(f"| {n:2} || {str(seq)[1:-1].replace(' ', '')+', ...'}\n|-")
print('|}')
if __name__ == '__main__':
p = pad_like()
pr(p)
|
Port the following code from C to Python with equivalent syntax and logic. | HANDLE hMutex = CreateMutex(NULL, FALSE, NULL);
| import threading
from time import sleep
res = 2
sema = threading.Semaphore(res)
class res_thread(threading.Thread):
def run(self):
global res
n = self.getName()
for i in range(1, 4):
sema.acquire()
res = res - 1
print n, "+ res count", res
sleep(2)
res = res + 1
print n, "- res count", res
sema.release()
for i in range(1, 5):
t = res_thread()
t.start()
|
Transform the following C implementation into Python, maintaining the same output and logic. | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdint.h>
#include <signal.h>
#include <time.h>
#include <sys/time.h>
struct timeval start, last;
inline int64_t tv_to_u(struct timeval s)
{
return s.tv_sec * 1000000 + s.tv_usec;
}
inline struct timeval u_to_tv(int64_t x)
{
struct timeval s;
s.tv_sec = x / 1000000;
s.tv_usec = x % 1000000;
return s;
}
void draw(int dir, int64_t period, int64_t cur, int64_t next)
{
int len = 40 * (next - cur) / period;
int s, i;
if (len > 20) len = 40 - len;
s = 20 + (dir ? len : -len);
printf("\033[H");
for (i = 0; i <= 40; i++) putchar(i == 20 ? '|': i == s ? '#' : '-');
}
void beat(int delay)
{
struct timeval tv = start;
int dir = 0;
int64_t d = 0, corr = 0, slp, cur, next = tv_to_u(start) + delay;
int64_t draw_interval = 20000;
printf("\033[H\033[J");
while (1) {
gettimeofday(&tv, 0);
slp = next - tv_to_u(tv) - corr;
usleep(slp);
gettimeofday(&tv, 0);
putchar(7);
fflush(stdout);
printf("\033[5;1Hdrift: %d compensate: %d (usec) ",
(int)d, (int)corr);
dir = !dir;
cur = tv_to_u(tv);
d = cur - next;
corr = (corr + d) / 2;
next += delay;
while (cur + d + draw_interval < next) {
usleep(draw_interval);
gettimeofday(&tv, 0);
cur = tv_to_u(tv);
draw(dir, delay, cur, next);
fflush(stdout);
}
}
}
int main(int c, char**v)
{
int bpm;
if (c < 2 || (bpm = atoi(v[1])) <= 0) bpm = 60;
if (bpm > 600) {
fprintf(stderr, "frequency %d too high\n", bpm);
exit(1);
}
gettimeofday(&start, 0);
last = start;
beat(60 * 1000000 / bpm);
return 0;
}
|
import time
def main(bpm = 72, bpb = 4):
sleep = 60.0 / bpm
counter = 0
while True:
counter += 1
if counter % bpb:
print 'tick'
else:
print 'TICK'
time.sleep(sleep)
main()
|
Rewrite this program in Python while keeping its functionality equivalent to the C version. | #!/usr/local/bin/script_gcc.sh
#include <errno.h>
#include <libgen.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
typedef char *STRING;
typedef enum{FALSE=0, TRUE=1} BOOL;
const STRING ENDCAT = NULL;
#define DIALECT "c"
const STRING
CC="gcc",
COPTS="-lm -x "DIALECT,
IEXT="."DIALECT,
OEXT=".out";
const BOOL OPT_CACHE = TRUE;
char strcat_out[BUFSIZ];
STRING STRCAT(STRING argv, ... ){
va_list ap;
va_start(ap, argv);
STRING arg;
strcat_out[0]='\0';
for(arg=argv; arg != ENDCAT; arg=va_arg(ap, STRING)){
strncat(strcat_out, arg, sizeof strcat_out);
}
va_end(ap);
return strndup(strcat_out, sizeof strcat_out);
}
char itoa_out[BUFSIZ];
STRING itoa_(int i){
sprintf(itoa_out, "%d", i);
return itoa_out;
}
time_t modtime(STRING filename){
struct stat buf;
if(stat(filename, &buf) != EXIT_SUCCESS)perror(filename);
return buf.st_mtime;
}
BOOL compile(STRING srcpath, STRING binpath){
int out;
STRING compiler_command=STRCAT(CC, " ", COPTS, " -o ", binpath, " -", ENDCAT);
FILE *src=fopen(srcpath, "r"),
*compiler=popen(compiler_command, "w");
char buf[BUFSIZ];
BOOL shebang;
for(shebang=TRUE; fgets(buf, sizeof buf, src); shebang=FALSE)
if(!shebang)fwrite(buf, strlen(buf), 1, compiler);
out=pclose(compiler);
return out;
}
void main(int argc, STRING *argv, STRING *envp){
STRING binpath,
srcpath=argv[1],
argv0_basename=STRCAT(basename((char*)srcpath ), ENDCAT),
*dirnamew, *dirnamex;
argv++;
STRING paths[] = {
dirname(strdup(srcpath)),
STRCAT(getenv("HOME"), "/bin", ENDCAT),
"/usr/local/bin",
".",
STRCAT(getenv("HOME"), "/tmp", ENDCAT),
getenv("HOME"),
STRCAT(getenv("HOME"), "/Desktop", ENDCAT),
ENDCAT
};
for(dirnamew = paths; *dirnamew; dirnamew++){
if(access(*dirnamew, W_OK) == EXIT_SUCCESS) break;
}
if(OPT_CACHE == FALSE){
binpath=STRCAT(*dirnamew, "/", argv0_basename, itoa_(getpid()), OEXT, ENDCAT);
if(compile(srcpath, binpath) == EXIT_SUCCESS){
if(fork()){
sleep(0.1); unlink(binpath);
} else {
execvp(binpath, argv);
}
}
} else {
time_t modtime_srcpath = modtime(srcpath);
for(dirnamex = paths; *dirnamex; dirnamex++){
binpath=STRCAT(*dirnamex, "/", argv0_basename, OEXT, ENDCAT);
if((access(binpath, X_OK) == EXIT_SUCCESS) && (modtime(binpath) >= modtime_srcpath))
execvp(binpath, argv);
}
}
binpath=STRCAT(*dirnamew, "/", argv0_basename, OEXT, ENDCAT);
if(compile(srcpath, binpath) == EXIT_SUCCESS)
execvp(binpath, argv);
perror(STRCAT(binpath, ": executable not available", ENDCAT));
exit(errno);
}
|
import sys
print " ".join(sys.argv[1:])
|
Generate an equivalent Python version of this C code. | #!/usr/local/bin/script_gcc.sh
#include <errno.h>
#include <libgen.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
typedef char *STRING;
typedef enum{FALSE=0, TRUE=1} BOOL;
const STRING ENDCAT = NULL;
#define DIALECT "c"
const STRING
CC="gcc",
COPTS="-lm -x "DIALECT,
IEXT="."DIALECT,
OEXT=".out";
const BOOL OPT_CACHE = TRUE;
char strcat_out[BUFSIZ];
STRING STRCAT(STRING argv, ... ){
va_list ap;
va_start(ap, argv);
STRING arg;
strcat_out[0]='\0';
for(arg=argv; arg != ENDCAT; arg=va_arg(ap, STRING)){
strncat(strcat_out, arg, sizeof strcat_out);
}
va_end(ap);
return strndup(strcat_out, sizeof strcat_out);
}
char itoa_out[BUFSIZ];
STRING itoa_(int i){
sprintf(itoa_out, "%d", i);
return itoa_out;
}
time_t modtime(STRING filename){
struct stat buf;
if(stat(filename, &buf) != EXIT_SUCCESS)perror(filename);
return buf.st_mtime;
}
BOOL compile(STRING srcpath, STRING binpath){
int out;
STRING compiler_command=STRCAT(CC, " ", COPTS, " -o ", binpath, " -", ENDCAT);
FILE *src=fopen(srcpath, "r"),
*compiler=popen(compiler_command, "w");
char buf[BUFSIZ];
BOOL shebang;
for(shebang=TRUE; fgets(buf, sizeof buf, src); shebang=FALSE)
if(!shebang)fwrite(buf, strlen(buf), 1, compiler);
out=pclose(compiler);
return out;
}
void main(int argc, STRING *argv, STRING *envp){
STRING binpath,
srcpath=argv[1],
argv0_basename=STRCAT(basename((char*)srcpath ), ENDCAT),
*dirnamew, *dirnamex;
argv++;
STRING paths[] = {
dirname(strdup(srcpath)),
STRCAT(getenv("HOME"), "/bin", ENDCAT),
"/usr/local/bin",
".",
STRCAT(getenv("HOME"), "/tmp", ENDCAT),
getenv("HOME"),
STRCAT(getenv("HOME"), "/Desktop", ENDCAT),
ENDCAT
};
for(dirnamew = paths; *dirnamew; dirnamew++){
if(access(*dirnamew, W_OK) == EXIT_SUCCESS) break;
}
if(OPT_CACHE == FALSE){
binpath=STRCAT(*dirnamew, "/", argv0_basename, itoa_(getpid()), OEXT, ENDCAT);
if(compile(srcpath, binpath) == EXIT_SUCCESS){
if(fork()){
sleep(0.1); unlink(binpath);
} else {
execvp(binpath, argv);
}
}
} else {
time_t modtime_srcpath = modtime(srcpath);
for(dirnamex = paths; *dirnamex; dirnamex++){
binpath=STRCAT(*dirnamex, "/", argv0_basename, OEXT, ENDCAT);
if((access(binpath, X_OK) == EXIT_SUCCESS) && (modtime(binpath) >= modtime_srcpath))
execvp(binpath, argv);
}
}
binpath=STRCAT(*dirnamew, "/", argv0_basename, OEXT, ENDCAT);
if(compile(srcpath, binpath) == EXIT_SUCCESS)
execvp(binpath, argv);
perror(STRCAT(binpath, ": executable not available", ENDCAT));
exit(errno);
}
|
import sys
print " ".join(sys.argv[1:])
|
Rewrite this program in Python while keeping its functionality equivalent to the C version. | #include <stdio.h>
#include <stdlib.h>
#define TRUE 1
#define FALSE 0
#define LIMIT 100
typedef int bool;
int compareInts(const void *a, const void *b) {
int aa = *(int *)a;
int bb = *(int *)b;
return aa - bb;
}
bool contains(int a[], int b, size_t len) {
int i;
for (i = 0; i < len; ++i) {
if (a[i] == b) return TRUE;
}
return FALSE;
}
int gcd(int a, int b) {
while (a != b) {
if (a > b)
a -= b;
else
b -= a;
}
return a;
}
bool areSame(int s[], int t[], size_t len) {
int i;
qsort(s, len, sizeof(int), compareInts);
qsort(t, len, sizeof(int), compareInts);
for (i = 0; i < len; ++i) {
if (s[i] != t[i]) return FALSE;
}
return TRUE;
}
int main() {
int s, n, i;
int starts[5] = {2, 5, 7, 9, 10};
int ekg[5][LIMIT];
for (s = 0; s < 5; ++s) {
ekg[s][0] = 1;
ekg[s][1] = starts[s];
for (n = 2; n < LIMIT; ++n) {
for (i = 2; ; ++i) {
if (!contains(ekg[s], i, n) && gcd(ekg[s][n - 1], i) > 1) {
ekg[s][n] = i;
break;
}
}
}
printf("EKG(%2d): [", starts[s]);
for (i = 0; i < 30; ++i) printf("%d ", ekg[s][i]);
printf("\b]\n");
}
for (i = 2; i < LIMIT; ++i) {
if (ekg[1][i] == ekg[2][i] && areSame(ekg[1], ekg[2], i)) {
printf("\nEKG(5) and EKG(7) converge at term %d\n", i + 1);
return 0;
}
}
printf("\nEKG5(5) and EKG(7) do not converge within %d terms\n", LIMIT);
return 0;
}
| from itertools import count, islice, takewhile
from math import gcd
def EKG_gen(start=2):
c = count(start + 1)
last, so_far = start, list(range(2, start))
yield 1, []
yield last, []
while True:
for index, sf in enumerate(so_far):
if gcd(last, sf) > 1:
last = so_far.pop(index)
yield last, so_far[::]
break
else:
so_far.append(next(c))
def find_convergence(ekgs=(5,7)):
"Returns the convergence point or zero if not found within the limit"
ekg = [EKG_gen(n) for n in ekgs]
for e in ekg:
next(e)
return 2 + len(list(takewhile(lambda state: not all(state[0] == s for s in state[1:]),
zip(*ekg))))
if __name__ == '__main__':
for start in 2, 5, 7, 9, 10:
print(f"EKG({start}):", str([n[0] for n in islice(EKG_gen(start), 10)])[1: -1])
print(f"\nEKG(5) and EKG(7) converge at term {find_convergence(ekgs=(5,7))}!")
|
Convert this C snippet to Python and keep its semantics consistent. | #include <stdio.h>
#include <string.h>
int repstr(char *str)
{
if (!str) return 0;
size_t sl = strlen(str) / 2;
while (sl > 0) {
if (strstr(str, str + sl) == str)
return sl;
--sl;
}
return 0;
}
int main(void)
{
char *strs[] = { "1001110011", "1110111011", "0010010010", "1111111111",
"0100101101", "0100100", "101", "11", "00", "1" };
size_t strslen = sizeof(strs) / sizeof(strs[0]);
size_t i;
for (i = 0; i < strslen; ++i) {
int n = repstr(strs[i]);
if (n)
printf("\"%s\" = rep-string \"%.*s\"\n", strs[i], n, strs[i]);
else
printf("\"%s\" = not a rep-string\n", strs[i]);
}
return 0;
}
| def is_repeated(text):
'check if the first part of the string is repeated throughout the string'
for x in range(len(text)//2, 0, -1):
if text.startswith(text[x:]): return x
return 0
matchstr =
for line in matchstr.split():
ln = is_repeated(line)
print('%r has a repetition length of %i i.e. %s'
% (line, ln, repr(line[:ln]) if ln else '*not* a rep-string'))
|
Convert this C snippet to Python and keep its semantics consistent. | #include <stdio.h>
#include <unistd.h>
int main()
{
int i;
printf("\033[?1049h\033[H");
printf("Alternate screen buffer\n");
for (i = 5; i; i--) {
printf("\rgoing back in %d...", i);
fflush(stdout);
sleep(1);
}
printf("\033[?1049l");
return 0;
}
|
import time
print "\033[?1049h\033[H"
print "Alternate buffer!"
for i in xrange(5, 0, -1):
print "Going back in:", i
time.sleep(1)
print "\033[?1049l"
|
Generate a Python translation of this C snippet without changing its computational steps. | char ch = 'z';
| 'c' == "c"
'text' == "text"
' " '
" ' "
'\x20' == ' '
u'unicode string'
u'\u05d0'
|
Rewrite the snippet below in Python so it works the same as the original C code. | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_WORD_SIZE 32
typedef struct string_tag {
size_t length;
char str[MAX_WORD_SIZE];
} string_t;
void fatal(const char* message) {
fprintf(stderr, "%s\n", message);
exit(1);
}
void* xmalloc(size_t n) {
void* ptr = malloc(n);
if (ptr == NULL)
fatal("Out of memory");
return ptr;
}
void* xrealloc(void* p, size_t n) {
void* ptr = realloc(p, n);
if (ptr == NULL)
fatal("Out of memory");
return ptr;
}
int hamming_distance(const string_t* str1, const string_t* str2) {
size_t len1 = str1->length;
size_t len2 = str2->length;
if (len1 != len2)
return 0;
int count = 0;
const char* s1 = str1->str;
const char* s2 = str2->str;
for (size_t i = 0; i < len1; ++i) {
if (s1[i] != s2[i])
++count;
if (count == 2)
break;
}
return count;
}
int main(int argc, char** argv) {
const char* filename = argc < 2 ? "unixdict.txt" : argv[1];
FILE* in = fopen(filename, "r");
if (!in) {
perror(filename);
return EXIT_FAILURE;
}
char line[MAX_WORD_SIZE];
size_t size = 0, capacity = 1024;
string_t* dictionary = xmalloc(sizeof(string_t) * capacity);
while (fgets(line, sizeof(line), in)) {
if (size == capacity) {
capacity *= 2;
dictionary = xrealloc(dictionary, sizeof(string_t) * capacity);
}
size_t len = strlen(line) - 1;
if (len > 11) {
string_t* str = &dictionary[size];
str->length = len;
memcpy(str->str, line, len);
str->str[len] = '\0';
++size;
}
}
fclose(in);
printf("Changeable words in %s:\n", filename);
int n = 1;
for (size_t i = 0; i < size; ++i) {
const string_t* str1 = &dictionary[i];
for (size_t j = 0; j < size; ++j) {
const string_t* str2 = &dictionary[j];
if (i != j && hamming_distance(str1, str2) == 1)
printf("%2d: %-14s -> %s\n", n++, str1->str, str2->str);
}
}
free(dictionary);
return EXIT_SUCCESS;
}
| from collections import defaultdict, Counter
def getwords(minlength=11, fname='unixdict.txt'):
"Return set of lowercased words of > given number of characters"
with open(fname) as f:
words = f.read().strip().lower().split()
return {w for w in words if len(w) > minlength}
words11 = getwords()
word_minus_1 = defaultdict(list)
minus_1_to_word = defaultdict(list)
for w in words11:
for i in range(len(w)):
minus_1 = w[:i] + w[i+1:]
word_minus_1[minus_1].append((w, i))
if minus_1 in words11:
minus_1_to_word[minus_1].append(w)
cwords = set()
for _, v in word_minus_1.items():
if len(v) >1:
change_indices = Counter(i for wrd, i in v)
change_words = set(wrd for wrd, i in v)
words_changed = None
if len(change_words) > 1 and change_indices.most_common(1)[0][1] > 1:
words_changed = [wrd for wrd, i in v
if change_indices[i] > 1]
if words_changed:
cwords.add(tuple(sorted(words_changed)))
print(f"{len(minus_1_to_word)} words that are from deleting a char from other words:")
for k, v in sorted(minus_1_to_word.items()):
print(f" {k:12} From {', '.join(v)}")
print(f"\n{len(cwords)} words that are from changing a char from other words:")
for v in sorted(cwords):
print(f" {v[0]:12} From {', '.join(v[1:])}")
|
Convert this C block to Python, preserving its control flow and logic. | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_WORD_SIZE 32
typedef struct string_tag {
size_t length;
char str[MAX_WORD_SIZE];
} string_t;
void fatal(const char* message) {
fprintf(stderr, "%s\n", message);
exit(1);
}
void* xmalloc(size_t n) {
void* ptr = malloc(n);
if (ptr == NULL)
fatal("Out of memory");
return ptr;
}
void* xrealloc(void* p, size_t n) {
void* ptr = realloc(p, n);
if (ptr == NULL)
fatal("Out of memory");
return ptr;
}
int hamming_distance(const string_t* str1, const string_t* str2) {
size_t len1 = str1->length;
size_t len2 = str2->length;
if (len1 != len2)
return 0;
int count = 0;
const char* s1 = str1->str;
const char* s2 = str2->str;
for (size_t i = 0; i < len1; ++i) {
if (s1[i] != s2[i])
++count;
if (count == 2)
break;
}
return count;
}
int main(int argc, char** argv) {
const char* filename = argc < 2 ? "unixdict.txt" : argv[1];
FILE* in = fopen(filename, "r");
if (!in) {
perror(filename);
return EXIT_FAILURE;
}
char line[MAX_WORD_SIZE];
size_t size = 0, capacity = 1024;
string_t* dictionary = xmalloc(sizeof(string_t) * capacity);
while (fgets(line, sizeof(line), in)) {
if (size == capacity) {
capacity *= 2;
dictionary = xrealloc(dictionary, sizeof(string_t) * capacity);
}
size_t len = strlen(line) - 1;
if (len > 11) {
string_t* str = &dictionary[size];
str->length = len;
memcpy(str->str, line, len);
str->str[len] = '\0';
++size;
}
}
fclose(in);
printf("Changeable words in %s:\n", filename);
int n = 1;
for (size_t i = 0; i < size; ++i) {
const string_t* str1 = &dictionary[i];
for (size_t j = 0; j < size; ++j) {
const string_t* str2 = &dictionary[j];
if (i != j && hamming_distance(str1, str2) == 1)
printf("%2d: %-14s -> %s\n", n++, str1->str, str2->str);
}
}
free(dictionary);
return EXIT_SUCCESS;
}
| from collections import defaultdict, Counter
def getwords(minlength=11, fname='unixdict.txt'):
"Return set of lowercased words of > given number of characters"
with open(fname) as f:
words = f.read().strip().lower().split()
return {w for w in words if len(w) > minlength}
words11 = getwords()
word_minus_1 = defaultdict(list)
minus_1_to_word = defaultdict(list)
for w in words11:
for i in range(len(w)):
minus_1 = w[:i] + w[i+1:]
word_minus_1[minus_1].append((w, i))
if minus_1 in words11:
minus_1_to_word[minus_1].append(w)
cwords = set()
for _, v in word_minus_1.items():
if len(v) >1:
change_indices = Counter(i for wrd, i in v)
change_words = set(wrd for wrd, i in v)
words_changed = None
if len(change_words) > 1 and change_indices.most_common(1)[0][1] > 1:
words_changed = [wrd for wrd, i in v
if change_indices[i] > 1]
if words_changed:
cwords.add(tuple(sorted(words_changed)))
print(f"{len(minus_1_to_word)} words that are from deleting a char from other words:")
for k, v in sorted(minus_1_to_word.items()):
print(f" {k:12} From {', '.join(v)}")
print(f"\n{len(cwords)} words that are from changing a char from other words:")
for v in sorted(cwords):
print(f" {v[0]:12} From {', '.join(v[1:])}")
|
Please provide an equivalent version of this C code in Python. | #include<windows.h>
#include<unistd.h>
#include<stdio.h>
const char g_szClassName[] = "weirdWindow";
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch(msg)
{
case WM_CLOSE:
DestroyWindow(hwnd);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hwnd, msg, wParam, lParam);
}
return 0;
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpCmdLine, int nCmdShow)
{
WNDCLASSEX wc;
HWND hwnd[3];
MSG Msg;
int i,x=0,y=0;
char str[3][100];
int maxX = GetSystemMetrics(SM_CXSCREEN), maxY = GetSystemMetrics(SM_CYSCREEN);
char messages[15][180] = {"Welcome to the Rosettacode Window C implementation.",
"If you can see two blank windows just behind this message box, you are in luck.",
"Let's get started....",
"Yes, you will be seeing a lot of me :)",
"Now to get started with the tasks, the windows here are stored in an array of type HWND, the array is called hwnd (yes, I know it's very innovative.)",
"Let's compare the windows for equality.",
"Now let's hide Window 1.",
"Now let's see Window 1 again.",
"Let's close Window 2, bye, bye, Number 2 !",
"Let's minimize Window 1.",
"Now let's maximize Window 1.",
"And finally we come to the fun part, watch Window 1 move !",
"Let's double Window 1 in size for all the good work.",
"That's all folks ! (You still have to close that window, that was not part of the contract, sue me :D )"};
wc.cbSize = sizeof(WNDCLASSEX);
wc.style = 0;
wc.lpfnWndProc = WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wc.lpszMenuName = NULL;
wc.lpszClassName = g_szClassName;
wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
if(!RegisterClassEx(&wc))
{
MessageBox(NULL, "Window Registration Failed!", "Error!",MB_ICONEXCLAMATION | MB_OK);
return 0;
}
for(i=0;i<2;i++){
sprintf(str[i],"Window Number %d",i+1);
hwnd[i] = CreateWindow(g_szClassName,str[i],WS_OVERLAPPEDWINDOW,i*maxX/2 , 0, maxX/2-10, maxY/2-10,NULL, NULL, hInstance, NULL);
if(hwnd[i] == NULL)
{
MessageBox(NULL, "Window Creation Failed!", "Error!",MB_ICONEXCLAMATION | MB_OK);
return 0;
}
ShowWindow(hwnd[i], nCmdShow);
UpdateWindow(hwnd[i]);
}
for(i=0;i<6;i++){
MessageBox(NULL, messages[i], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);
}
if(hwnd[0]==hwnd[1])
MessageBox(NULL, "Window 1 and 2 are equal.", "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);
else
MessageBox(NULL, "Nope, they are not.", "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);
MessageBox(NULL, messages[6], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);
ShowWindow(hwnd[0], SW_HIDE);
MessageBox(NULL, messages[7], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);
ShowWindow(hwnd[0], SW_SHOW);
MessageBox(NULL, messages[8], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);
ShowWindow(hwnd[1], SW_HIDE);
MessageBox(NULL, messages[9], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);
ShowWindow(hwnd[0], SW_MINIMIZE);
MessageBox(NULL, messages[10], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);
ShowWindow(hwnd[0], SW_MAXIMIZE);
MessageBox(NULL, messages[11], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);
ShowWindow(hwnd[0], SW_RESTORE);
while(x!=maxX/2||y!=maxY/2){
if(x<maxX/2)
x++;
if(y<maxY/2)
y++;
MoveWindow(hwnd[0],x,y,maxX/2-10, maxY/2-10,0);
sleep(10);
}
MessageBox(NULL, messages[12], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);
MoveWindow(hwnd[0],0,0,maxX, maxY,0);
MessageBox(NULL, messages[13], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);
while(GetMessage(&Msg, NULL, 0, 0) > 0)
{
TranslateMessage(&Msg);
DispatchMessage(&Msg);
}
return Msg.wParam;
}
| from tkinter import *
import tkinter.messagebox
def maximise():
root.geometry("{}x{}+{}+{}".format(root.winfo_screenwidth(), root.winfo_screenheight(), 0, 0))
def minimise():
root.iconify()
def delete():
if tkinter.messagebox.askokcancel("OK/Cancel","Are you sure?"):
root.quit()
root = Tk()
mx=Button(root,text="maximise",command=maximise)
mx.grid()
mx.bind(maximise)
mn=Button(root,text="minimise",command=minimise)
mn.grid()
mn.bind(minimise)
root.protocol("WM_DELETE_WINDOW",delete)
mainloop()
|
Rewrite the snippet below in Python so it works the same as the original C code. | #include <stdio.h>
#include <stdlib.h>
#define MONAD void*
#define INTBIND(f, g, x) (f((int*)g(x)))
#define RETURN(type,x) &((type)*)(x)
MONAD boundInt(int *x) {
return (MONAD)(x);
}
MONAD boundInt2str(int *x) {
char buf[100];
char*str= malloc(1+sprintf(buf, "%d", *x));
sprintf(str, "%d", *x);
return (MONAD)(str);
}
void task(int y) {
char *z= INTBIND(boundInt2str, boundInt, &y);
printf("%s\n", z);
free(z);
}
int main() {
task(13);
}
|
from __future__ import annotations
from itertools import chain
from typing import Any
from typing import Callable
from typing import Iterable
from typing import List
from typing import TypeVar
T = TypeVar("T")
class MList(List[T]):
@classmethod
def unit(cls, value: Iterable[T]) -> MList[T]:
return cls(value)
def bind(self, func: Callable[[T], MList[Any]]) -> MList[Any]:
return MList(chain.from_iterable(map(func, self)))
def __rshift__(self, func: Callable[[T], MList[Any]]) -> MList[Any]:
return self.bind(func)
if __name__ == "__main__":
print(
MList([1, 99, 4])
.bind(lambda val: MList([val + 1]))
.bind(lambda val: MList([f"${val}.00"]))
)
print(
MList([1, 99, 4])
>> (lambda val: MList([val + 1]))
>> (lambda val: MList([f"${val}.00"]))
)
print(
MList(range(1, 6)).bind(
lambda x: MList(range(6, 11)).bind(lambda y: MList([(x, y)]))
)
)
print(
MList(range(1, 26)).bind(
lambda x: MList(range(x + 1, 26)).bind(
lambda y: MList(range(y + 1, 26)).bind(
lambda z: MList([(x, y, z)])
if x * x + y * y == z * z
else MList([])
)
)
)
)
|
Keep all operations the same but rewrite the snippet in Python. | #include <stdio.h>
#include <stdbool.h>
#include <math.h>
#define MAX 1000
void sieve(int n, bool *prime) {
prime[0] = prime[1] = false;
for (int i=2; i<=n; i++) prime[i] = true;
for (int p=2; p*p<=n; p++)
if (prime[p])
for (int c=p*p; c<=n; c+=p) prime[c] = false;
}
bool square(int n) {
int sq = sqrt(n);
return (sq * sq == n);
}
int main() {
bool prime[MAX + 1];
sieve(MAX, prime);
for (int i=2; i<=MAX; i++) if (prime[i]) {
int sq = i-1;
if (square(sq)) printf("%d ", sq);
}
printf("\n");
return 0;
}
| limit = 1000
print("working...")
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(1,x+1):
if (x == n*n):
return 1
return 0
for n in range(limit-1):
if issquare(n) and isprime(n+1):
print(n,end=" ")
print()
print("done...")
|
Translate this program into Python but keep the logic exactly as in C. | #include <stdio.h>
#include <stdbool.h>
#include <math.h>
#define MAX 1000
void sieve(int n, bool *prime) {
prime[0] = prime[1] = false;
for (int i=2; i<=n; i++) prime[i] = true;
for (int p=2; p*p<=n; p++)
if (prime[p])
for (int c=p*p; c<=n; c+=p) prime[c] = false;
}
bool square(int n) {
int sq = sqrt(n);
return (sq * sq == n);
}
int main() {
bool prime[MAX + 1];
sieve(MAX, prime);
for (int i=2; i<=MAX; i++) if (prime[i]) {
int sq = i-1;
if (square(sq)) printf("%d ", sq);
}
printf("\n");
return 0;
}
| limit = 1000
print("working...")
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(1,x+1):
if (x == n*n):
return 1
return 0
for n in range(limit-1):
if issquare(n) and isprime(n+1):
print(n,end=" ")
print()
print("done...")
|
Generate an equivalent Python version of this C code. | #include <stdio.h>
#include <stdbool.h>
#include <math.h>
#define MAX 1000
void sieve(int n, bool *prime) {
prime[0] = prime[1] = false;
for (int i=2; i<=n; i++) prime[i] = true;
for (int p=2; p*p<=n; p++)
if (prime[p])
for (int c=p*p; c<=n; c+=p) prime[c] = false;
}
bool square(int n) {
int sq = sqrt(n);
return (sq * sq == n);
}
int main() {
bool prime[MAX + 1];
sieve(MAX, prime);
for (int i=2; i<=MAX; i++) if (prime[i]) {
int sq = i-1;
if (square(sq)) printf("%d ", sq);
}
printf("\n");
return 0;
}
| limit = 1000
print("working...")
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(1,x+1):
if (x == n*n):
return 1
return 0
for n in range(limit-1):
if issquare(n) and isprime(n+1):
print(n,end=" ")
print()
print("done...")
|
Keep all operations the same but rewrite the snippet in Python. | #include <stdio.h>
#include <stdbool.h>
bool isPrime(int n) {
int d;
if (n < 2) return false;
if (!(n%2)) return n == 2;
if (!(n%3)) return n == 3;
d = 5;
while (d*d <= n) {
if (!(n%d)) return false;
d += 2;
if (!(n%d)) return false;
d += 4;
}
return true;
}
int main() {
int i, lastSpecial = 3, lastGap = 1;
printf("Special primes under 1,050:\n");
printf("Prime1 Prime2 Gap\n");
printf("%6d %6d %3d\n", 2, 3, lastGap);
for (i = 5; i < 1050; i += 2) {
if (isPrime(i) && (i-lastSpecial) > lastGap) {
lastGap = i - lastSpecial;
printf("%6d %6d %3d\n", lastSpecial, i, lastGap);
lastSpecial = i;
}
}
}
|
def isPrime(n):
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
if __name__ == '__main__':
p = 3
i = 2
print("2 3", end = " ");
while True:
if isPrime(p + i) == 1:
p += i
print(p, end = " ");
i += 2
if p + i >= 1050:
break
|
Generate an equivalent Python version of this C code. | #include <stdio.h>
#include <stdbool.h>
bool isPrime(int n) {
int d;
if (n < 2) return false;
if (!(n%2)) return n == 2;
if (!(n%3)) return n == 3;
d = 5;
while (d*d <= n) {
if (!(n%d)) return false;
d += 2;
if (!(n%d)) return false;
d += 4;
}
return true;
}
int main() {
int i, lastSpecial = 3, lastGap = 1;
printf("Special primes under 1,050:\n");
printf("Prime1 Prime2 Gap\n");
printf("%6d %6d %3d\n", 2, 3, lastGap);
for (i = 5; i < 1050; i += 2) {
if (isPrime(i) && (i-lastSpecial) > lastGap) {
lastGap = i - lastSpecial;
printf("%6d %6d %3d\n", lastSpecial, i, lastGap);
lastSpecial = i;
}
}
}
|
def isPrime(n):
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
if __name__ == '__main__':
p = 3
i = 2
print("2 3", end = " ");
while True:
if isPrime(p + i) == 1:
p += i
print(p, end = " ");
i += 2
if p + i >= 1050:
break
|
Keep all operations the same but rewrite the snippet in Python. | #include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <stdlib.h>
#define MAX(x,y) ((x) > (y) ? (x) : (y))
#define MIN(x,y) ((x) < (y) ? (x) : (y))
size_t base20(unsigned int n, uint8_t *out) {
uint8_t *start = out;
do {*out++ = n % 20;} while (n /= 20);
size_t length = out - start;
while (out > start) {
uint8_t x = *--out;
*out = *start;
*start++ = x;
}
return length;
}
void make_digit(int n, char *place, size_t line_length) {
static const char *parts[] = {" "," . "," .. ","... ","....","----"};
int i;
for (i=4; i>0; i--, n -= 5)
memcpy(place + i*line_length, parts[MAX(0, MIN(5, n))], 4);
if (n == -20) place[4 * line_length + 1] = '@';
}
char *mayan(unsigned int n) {
if (n == 0) return NULL;
uint8_t digits[15];
size_t n_digits = base20(n, digits);
size_t line_length = n_digits*5 + 2;
char *str = malloc(line_length * 6 + 1);
if (str == NULL) return NULL;
str[line_length * 6] = 0;
char *ptr;
unsigned int i;
for (ptr=str, i=0; i<line_length; i+=5, ptr+=5)
memcpy(ptr, "+----", 5);
memcpy(ptr-5, "+\n", 2);
memcpy(str+5*line_length, str, line_length);
for (ptr=str+line_length, i=0; i<line_length; i+=5, ptr+=5)
memcpy(ptr, "| ", 5);
memcpy(ptr-5, "|\n", 2);
memcpy(str+2*line_length, str+line_length, line_length);
memcpy(str+3*line_length, str+line_length, 2*line_length);
for (i=0; i<n_digits; i++)
make_digit(digits[i], str+1+5*i, line_length);
return str;
}
int main(int argc, char **argv) {
if (argc != 2) {
fprintf(stderr, "usage: mayan <number>\n");
return 1;
}
int i = atoi(argv[1]);
if (i <= 0) {
fprintf(stderr, "number must be positive\n");
return 1;
}
char *m = mayan(i);
printf("%s",m);
free(m);
return 0;
}
|
from functools import (reduce)
def mayanNumerals(n):
return showIntAtBase(20)(
mayanDigit
)(n)([])
def mayanDigit(n):
if 0 < n:
r = n % 5
return [
(['●' * r] if 0 < r else []) +
(['━━'] * (n // 5))
]
else:
return ['Θ']
def mayanFramed(n):
return 'Mayan ' + str(n) + ':\n\n' + (
wikiTable({
'class': 'wikitable',
'style': cssFromDict({
'text-align': 'center',
'background-color': '
'color': '
'border': '2px solid silver'
}),
'colwidth': '3em',
'cell': 'vertical-align: bottom;'
})([[
'<br>'.join(col) for col in mayanNumerals(n)
]])
)
def main():
print(
main.__doc__ + ':\n\n' +
'\n'.join(mayanFramed(n) for n in [
4005, 8017, 326205, 886205, 1081439556,
1000000, 1000000000
])
)
def wikiTable(opts):
def colWidth():
return 'width:' + opts['colwidth'] + '; ' if (
'colwidth' in opts
) else ''
def cellStyle():
return opts['cell'] if 'cell' in opts else ''
return lambda rows: '{| ' + reduce(
lambda a, k: (
a + k + '="' + opts[k] + '" ' if (
k in opts
) else a
),
['class', 'style'],
''
) + '\n' + '\n|-\n'.join(
'\n'.join(
('|' if (
0 != i and ('cell' not in opts)
) else (
'|style="' + colWidth() + cellStyle() + '"|'
)) + (
str(x) or ' '
) for x in row
) for i, row in enumerate(rows)
) + '\n|}\n\n'
def cssFromDict(dct):
return reduce(
lambda a, k: a + k + ':' + dct[k] + '; ',
dct.keys(),
''
)
def showIntAtBase(base):
def wrap(toChr, n, rs):
def go(nd, r):
n, d = nd
r_ = toChr(d) + r
return go(divmod(n, base), r_) if 0 != n else r_
return 'unsupported base' if 1 >= base else (
'negative number' if 0 > n else (
go(divmod(n, base), rs))
)
return lambda toChr: lambda n: lambda rs: (
wrap(toChr, n, rs)
)
if __name__ == '__main__':
main()
|
Change the following C code into Python without altering its purpose. | #include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <stdlib.h>
#define MAX(x,y) ((x) > (y) ? (x) : (y))
#define MIN(x,y) ((x) < (y) ? (x) : (y))
size_t base20(unsigned int n, uint8_t *out) {
uint8_t *start = out;
do {*out++ = n % 20;} while (n /= 20);
size_t length = out - start;
while (out > start) {
uint8_t x = *--out;
*out = *start;
*start++ = x;
}
return length;
}
void make_digit(int n, char *place, size_t line_length) {
static const char *parts[] = {" "," . "," .. ","... ","....","----"};
int i;
for (i=4; i>0; i--, n -= 5)
memcpy(place + i*line_length, parts[MAX(0, MIN(5, n))], 4);
if (n == -20) place[4 * line_length + 1] = '@';
}
char *mayan(unsigned int n) {
if (n == 0) return NULL;
uint8_t digits[15];
size_t n_digits = base20(n, digits);
size_t line_length = n_digits*5 + 2;
char *str = malloc(line_length * 6 + 1);
if (str == NULL) return NULL;
str[line_length * 6] = 0;
char *ptr;
unsigned int i;
for (ptr=str, i=0; i<line_length; i+=5, ptr+=5)
memcpy(ptr, "+----", 5);
memcpy(ptr-5, "+\n", 2);
memcpy(str+5*line_length, str, line_length);
for (ptr=str+line_length, i=0; i<line_length; i+=5, ptr+=5)
memcpy(ptr, "| ", 5);
memcpy(ptr-5, "|\n", 2);
memcpy(str+2*line_length, str+line_length, line_length);
memcpy(str+3*line_length, str+line_length, 2*line_length);
for (i=0; i<n_digits; i++)
make_digit(digits[i], str+1+5*i, line_length);
return str;
}
int main(int argc, char **argv) {
if (argc != 2) {
fprintf(stderr, "usage: mayan <number>\n");
return 1;
}
int i = atoi(argv[1]);
if (i <= 0) {
fprintf(stderr, "number must be positive\n");
return 1;
}
char *m = mayan(i);
printf("%s",m);
free(m);
return 0;
}
|
from functools import (reduce)
def mayanNumerals(n):
return showIntAtBase(20)(
mayanDigit
)(n)([])
def mayanDigit(n):
if 0 < n:
r = n % 5
return [
(['●' * r] if 0 < r else []) +
(['━━'] * (n // 5))
]
else:
return ['Θ']
def mayanFramed(n):
return 'Mayan ' + str(n) + ':\n\n' + (
wikiTable({
'class': 'wikitable',
'style': cssFromDict({
'text-align': 'center',
'background-color': '
'color': '
'border': '2px solid silver'
}),
'colwidth': '3em',
'cell': 'vertical-align: bottom;'
})([[
'<br>'.join(col) for col in mayanNumerals(n)
]])
)
def main():
print(
main.__doc__ + ':\n\n' +
'\n'.join(mayanFramed(n) for n in [
4005, 8017, 326205, 886205, 1081439556,
1000000, 1000000000
])
)
def wikiTable(opts):
def colWidth():
return 'width:' + opts['colwidth'] + '; ' if (
'colwidth' in opts
) else ''
def cellStyle():
return opts['cell'] if 'cell' in opts else ''
return lambda rows: '{| ' + reduce(
lambda a, k: (
a + k + '="' + opts[k] + '" ' if (
k in opts
) else a
),
['class', 'style'],
''
) + '\n' + '\n|-\n'.join(
'\n'.join(
('|' if (
0 != i and ('cell' not in opts)
) else (
'|style="' + colWidth() + cellStyle() + '"|'
)) + (
str(x) or ' '
) for x in row
) for i, row in enumerate(rows)
) + '\n|}\n\n'
def cssFromDict(dct):
return reduce(
lambda a, k: a + k + ':' + dct[k] + '; ',
dct.keys(),
''
)
def showIntAtBase(base):
def wrap(toChr, n, rs):
def go(nd, r):
n, d = nd
r_ = toChr(d) + r
return go(divmod(n, base), r_) if 0 != n else r_
return 'unsupported base' if 1 >= base else (
'negative number' if 0 > n else (
go(divmod(n, base), rs))
)
return lambda toChr: lambda n: lambda rs: (
wrap(toChr, n, rs)
)
if __name__ == '__main__':
main()
|
Maintain the same structure and functionality when rewriting this code in Python. | #include <math.h>
#include <stdint.h>
#include <stdio.h>
uint64_t factorial(int n) {
uint64_t result = 1;
int i;
for (i = 1; i <= n; i++) {
result *= i;
}
return result;
}
int inverse_factorial(uint64_t f) {
int p = 1;
int i = 1;
if (f == 1) {
return 0;
}
while (p < f) {
p *= i;
i++;
}
if (p == f) {
return i - 1;
}
return -1;
}
uint64_t super_factorial(int n) {
uint64_t result = 1;
int i;
for (i = 1; i <= n; i++) {
result *= factorial(i);
}
return result;
}
uint64_t hyper_factorial(int n) {
uint64_t result = 1;
int i;
for (i = 1; i <= n; i++) {
result *= (uint64_t)powl(i, i);
}
return result;
}
uint64_t alternating_factorial(int n) {
uint64_t result = 0;
int i;
for (i = 1; i <= n; i++) {
if ((n - i) % 2 == 0) {
result += factorial(i);
} else {
result -= factorial(i);
}
}
return result;
}
uint64_t exponential_factorial(int n) {
uint64_t result = 0;
int i;
for (i = 1; i <= n; i++) {
result = (uint64_t)powl(i, (long double)result);
}
return result;
}
void test_factorial(int count, uint64_t(*func)(int), char *name) {
int i;
printf("First %d %s:\n", count, name);
for (i = 0; i < count ; i++) {
printf("%llu ", func(i));
}
printf("\n");
}
void test_inverse(uint64_t f) {
int n = inverse_factorial(f);
if (n < 0) {
printf("rf(%llu) = No Solution\n", f);
} else {
printf("rf(%llu) = %d\n", f, n);
}
}
int main() {
int i;
test_factorial(9, super_factorial, "super factorials");
printf("\n");
test_factorial(8, super_factorial, "hyper factorials");
printf("\n");
test_factorial(10, alternating_factorial, "alternating factorials");
printf("\n");
test_factorial(5, exponential_factorial, "exponential factorials");
printf("\n");
test_inverse(1);
test_inverse(2);
test_inverse(6);
test_inverse(24);
test_inverse(120);
test_inverse(720);
test_inverse(5040);
test_inverse(40320);
test_inverse(362880);
test_inverse(3628800);
test_inverse(119);
return 0;
}
|
from math import prod
def superFactorial(n):
return prod([prod(range(1,i+1)) for i in range(1,n+1)])
def hyperFactorial(n):
return prod([i**i for i in range(1,n+1)])
def alternatingFactorial(n):
return sum([(-1)**(n-i)*prod(range(1,i+1)) for i in range(1,n+1)])
def exponentialFactorial(n):
if n in [0,1]:
return 1
else:
return n**exponentialFactorial(n-1)
def inverseFactorial(n):
i = 1
while True:
if n == prod(range(1,i)):
return i-1
elif n < prod(range(1,i)):
return "undefined"
i+=1
print("Superfactorials for [0,9] :")
print({"sf(" + str(i) + ") " : superFactorial(i) for i in range(0,10)})
print("\nHyperfactorials for [0,9] :")
print({"H(" + str(i) + ") " : hyperFactorial(i) for i in range(0,10)})
print("\nAlternating factorials for [0,9] :")
print({"af(" + str(i) + ") " : alternatingFactorial(i) for i in range(0,10)})
print("\nExponential factorials for [0,4] :")
print({str(i) + "$ " : exponentialFactorial(i) for i in range(0,5)})
print("\nDigits in 5$ : " , len(str(exponentialFactorial(5))))
factorialSet = [1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800]
print("\nInverse factorials for " , factorialSet)
print({"rf(" + str(i) + ") ":inverseFactorial(i) for i in factorialSet})
print("\nrf(119) : " + inverseFactorial(119))
|
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 main(void) {
int p1, p2;
for(p1=3;p1<=99;p1+=2) {
p2=nextprime(p1);
if(p2<100&&isprime(p1)&&isprime(p2+p1-1)) {
printf( "%d + %d - 1 = %d\n", p1, p2, p1+p2-1 );
}
}
return 0;
}
|
def isPrime(n):
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def nextPrime(n):
if n == 0:
return 2
if n < 3:
return n + 1
q = n + 2
while not isPrime(q):
q += 2
return q
if __name__ == "__main__":
for p1 in range(3,100,2):
p2 = nextPrime(p1)
if isPrime(p1) and p2 < 100 and isPrime(p1 + p2 - 1):
print(p1,'\t', p2,'\t', p1 + p2 - 1)
|
Change the programming language of this snippet from C to Python without modifying what it does. | #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 main(void) {
int p1, p2;
for(p1=3;p1<=99;p1+=2) {
p2=nextprime(p1);
if(p2<100&&isprime(p1)&&isprime(p2+p1-1)) {
printf( "%d + %d - 1 = %d\n", p1, p2, p1+p2-1 );
}
}
return 0;
}
|
def isPrime(n):
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def nextPrime(n):
if n == 0:
return 2
if n < 3:
return n + 1
q = n + 2
while not isPrime(q):
q += 2
return q
if __name__ == "__main__":
for p1 in range(3,100,2):
p2 = nextPrime(p1)
if isPrime(p1) and p2 < 100 and isPrime(p1 + p2 - 1):
print(p1,'\t', p2,'\t', p1 + p2 - 1)
|
Port the provided C code into Python while preserving the original functionality. | #include <stdio.h>
int a[17][17], idx[4];
int find_group(int type, int min_n, int max_n, int depth)
{
int i, n;
if (depth == 4) {
printf("totally %sconnected group:", type ? "" : "un");
for (i = 0; i < 4; i++) printf(" %d", idx[i]);
putchar('\n');
return 1;
}
for (i = min_n; i < max_n; i++) {
for (n = 0; n < depth; n++)
if (a[idx[n]][i] != type) break;
if (n == depth) {
idx[n] = i;
if (find_group(type, 1, max_n, depth + 1))
return 1;
}
}
return 0;
}
int main()
{
int i, j, k;
const char *mark = "01-";
for (i = 0; i < 17; i++)
a[i][i] = 2;
for (k = 1; k <= 8; k <<= 1) {
for (i = 0; i < 17; i++) {
j = (i + k) % 17;
a[i][j] = a[j][i] = 1;
}
}
for (i = 0; i < 17; i++) {
for (j = 0; j < 17; j++)
printf("%c ", mark[a[i][j]]);
putchar('\n');
}
for (i = 0; i < 17; i++) {
idx[0] = i;
if (find_group(1, i+1, 17, 1) || find_group(0, i+1, 17, 1)) {
puts("no good");
return 0;
}
}
puts("all good");
return 0;
}
| range17 = range(17)
a = [['0'] * 17 for i in range17]
idx = [0] * 4
def find_group(mark, min_n, max_n, depth=1):
if (depth == 4):
prefix = "" if (mark == '1') else "un"
print("Fail, found totally {}connected group:".format(prefix))
for i in range(4):
print(idx[i])
return True
for i in range(min_n, max_n):
n = 0
while (n < depth):
if (a[idx[n]][i] != mark):
break
n += 1
if (n == depth):
idx[n] = i
if (find_group(mark, 1, max_n, depth + 1)):
return True
return False
if __name__ == '__main__':
for i in range17:
a[i][i] = '-'
for k in range(4):
for i in range17:
j = (i + pow(2, k)) % 17
a[i][j] = a[j][i] = '1'
for row in a:
print(' '.join(row))
for i in range17:
idx[0] = i
if (find_group('1', i + 1, 17) or find_group('0', i + 1, 17)):
print("no good")
exit()
print("all good")
|
Change the programming language of this snippet from C to Python without modifying what it does. | #include<windows.h>
#include<stdio.h>
int main()
{
printf("Dimensions of the screen are (w x h) : %d x %d pixels",GetSystemMetrics(SM_CXSCREEN),GetSystemMetrics(SM_CYSCREEN));
return 0;
}
|
import tkinter as tk
root = tk.Tk()
root.state('zoomed')
root.update_idletasks()
tk.Label(root, text=(str(root.winfo_width())+ " x " +str(root.winfo_height())),
font=("Helvetica", 25)).pack()
root.mainloop()
|
Write the same algorithm in Python as shown in this C implementation. | #include <stdio.h>
int main()
{
printf("\033[7mReversed\033[m Normal\n");
return 0;
}
|
print "\033[7mReversed\033[m Normal"
|
Please provide an equivalent version of this C code in Python. | #include <stdint.h>
#include <stdio.h>
#include <glib.h>
typedef struct named_number_tag {
const char* name;
uint64_t number;
} named_number;
const named_number named_numbers[] = {
{ "hundred", 100 },
{ "thousand", 1000 },
{ "million", 1000000 },
{ "billion", 1000000000 },
{ "trillion", 1000000000000 },
{ "quadrillion", 1000000000000000ULL },
{ "quintillion", 1000000000000000000ULL }
};
const named_number* get_named_number(uint64_t n) {
const size_t names_len = sizeof(named_numbers)/sizeof(named_number);
for (size_t i = 0; i + 1 < names_len; ++i) {
if (n < named_numbers[i + 1].number)
return &named_numbers[i];
}
return &named_numbers[names_len - 1];
}
size_t append_number_name(GString* str, uint64_t n) {
static const char* small[] = {
"zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
"nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
"sixteen", "seventeen", "eighteen", "nineteen"
};
static const char* tens[] = {
"twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"
};
size_t len = str->len;
if (n < 20) {
g_string_append(str, small[n]);
}
else if (n < 100) {
g_string_append(str, tens[n/10 - 2]);
if (n % 10 != 0) {
g_string_append_c(str, '-');
g_string_append(str, small[n % 10]);
}
} else {
const named_number* num = get_named_number(n);
uint64_t p = num->number;
append_number_name(str, n/p);
g_string_append_c(str, ' ');
g_string_append(str, num->name);
if (n % p != 0) {
g_string_append_c(str, ' ');
append_number_name(str, n % p);
}
}
return str->len - len;
}
GString* magic(uint64_t n) {
GString* str = g_string_new(NULL);
for (unsigned int i = 0; ; ++i) {
size_t count = append_number_name(str, n);
if (i == 0)
str->str[0] = g_ascii_toupper(str->str[0]);
if (n == 4) {
g_string_append(str, " is magic.");
break;
}
g_string_append(str, " is ");
append_number_name(str, count);
g_string_append(str, ", ");
n = count;
}
return str;
}
void test_magic(uint64_t n) {
GString* str = magic(n);
printf("%s\n", str->str);
g_string_free(str, TRUE);
}
int main() {
test_magic(5);
test_magic(13);
test_magic(78);
test_magic(797);
test_magic(2739);
test_magic(4000);
test_magic(7893);
test_magic(93497412);
test_magic(2673497412U);
test_magic(10344658531277200972ULL);
return 0;
}
| import random
from collections import OrderedDict
numbers = {
1: 'one',
2: 'two',
3: 'three',
4: 'four',
5: 'five',
6: 'six',
7: 'seven',
8: 'eight',
9: 'nine',
10: 'ten',
11: 'eleven',
12: 'twelve',
13: 'thirteen',
14: 'fourteen',
15: 'fifteen',
16: 'sixteen',
17: 'seventeen',
18: 'eighteen',
19: 'nineteen',
20: 'twenty',
30: 'thirty',
40: 'forty',
50: 'fifty',
60: 'sixty',
70: 'seventy',
80: 'eighty',
90: 'ninety',
100: 'hundred',
1000: 'thousand',
10 ** 6: 'million',
10 ** 9: 'billion',
10 ** 12: 'trillion',
10 ** 15: 'quadrillion',
10 ** 18: 'quintillion',
10 ** 21: 'sextillion',
10 ** 24: 'septillion',
10 ** 27: 'octillion',
10 ** 30: 'nonillion',
10 ** 33: 'decillion',
10 ** 36: 'undecillion',
10 ** 39: 'duodecillion',
10 ** 42: 'tredecillion',
10 ** 45: 'quattuordecillion',
10 ** 48: 'quinquadecillion',
10 ** 51: 'sedecillion',
10 ** 54: 'septendecillion',
10 ** 57: 'octodecillion',
10 ** 60: 'novendecillion',
10 ** 63: 'vigintillion',
10 ** 66: 'unvigintillion',
10 ** 69: 'duovigintillion',
10 ** 72: 'tresvigintillion',
10 ** 75: 'quattuorvigintillion',
10 ** 78: 'quinquavigintillion',
10 ** 81: 'sesvigintillion',
10 ** 84: 'septemvigintillion',
10 ** 87: 'octovigintillion',
10 ** 90: 'novemvigintillion',
10 ** 93: 'trigintillion',
10 ** 96: 'untrigintillion',
10 ** 99: 'duotrigintillion',
10 ** 102: 'trestrigintillion',
10 ** 105: 'quattuortrigintillion',
10 ** 108: 'quinquatrigintillion',
10 ** 111: 'sestrigintillion',
10 ** 114: 'septentrigintillion',
10 ** 117: 'octotrigintillion',
10 ** 120: 'noventrigintillion',
10 ** 123: 'quadragintillion',
10 ** 153: 'quinquagintillion',
10 ** 183: 'sexagintillion',
10 ** 213: 'septuagintillion',
10 ** 243: 'octogintillion',
10 ** 273: 'nonagintillion',
10 ** 303: 'centillion',
10 ** 306: 'uncentillion',
10 ** 309: 'duocentillion',
10 ** 312: 'trescentillion',
10 ** 333: 'decicentillion',
10 ** 336: 'undecicentillion',
10 ** 363: 'viginticentillion',
10 ** 366: 'unviginticentillion',
10 ** 393: 'trigintacentillion',
10 ** 423: 'quadragintacentillion',
10 ** 453: 'quinquagintacentillion',
10 ** 483: 'sexagintacentillion',
10 ** 513: 'septuagintacentillion',
10 ** 543: 'octogintacentillion',
10 ** 573: 'nonagintacentillion',
10 ** 603: 'ducentillion',
10 ** 903: 'trecentillion',
10 ** 1203: 'quadringentillion',
10 ** 1503: 'quingentillion',
10 ** 1803: 'sescentillion',
10 ** 2103: 'septingentillion',
10 ** 2403: 'octingentillion',
10 ** 2703: 'nongentillion',
10 ** 3003: 'millinillion'
}
numbers = OrderedDict(sorted(numbers.items(), key=lambda t: t[0], reverse=True))
def string_representation(i: int) -> str:
if i == 0:
return 'zero'
words = ['negative'] if i < 0 else []
working_copy = abs(i)
for key, value in numbers.items():
if key <= working_copy:
times = int(working_copy / key)
if key >= 100:
words.append(string_representation(times))
words.append(value)
working_copy -= times * key
if working_copy == 0:
break
return ' '.join(words)
def next_phrase(i: int):
while not i == 4:
str_i = string_representation(i)
len_i = len(str_i)
yield str_i, 'is', string_representation(len_i)
i = len_i
yield string_representation(i), 'is', 'magic'
def magic(i: int) -> str:
phrases = []
for phrase in next_phrase(i):
phrases.append(' '.join(phrase))
return f'{", ".join(phrases)}.'.capitalize()
if __name__ == '__main__':
for j in (random.randint(0, 10 ** 3) for i in range(5)):
print(j, ':\n', magic(j), '\n')
for j in (random.randint(-10 ** 24, 10 ** 24) for i in range(2)):
print(j, ':\n', magic(j), '\n')
|
Rewrite the snippet below in Python so it works the same as the original C code. | #include <stdio.h>
int findNumOfDec(double x) {
char buffer[128];
int pos, num;
sprintf(buffer, "%.14f", x);
pos = 0;
num = 0;
while (buffer[pos] != 0 && buffer[pos] != '.') {
pos++;
}
if (buffer[pos] != 0) {
pos++;
while (buffer[pos] != 0) {
pos++;
}
pos--;
while (buffer[pos] == '0') {
pos--;
}
while (buffer[pos] != '.') {
num++;
pos--;
}
}
return num;
}
void test(double x) {
int num = findNumOfDec(x);
printf("%f has %d decimals\n", x, num);
}
int main() {
test(12.0);
test(12.345);
test(12.345555555555);
test(12.3450);
test(12.34555555555555555555);
test(1.2345e+54);
return 0;
}
| In [6]: def dec(n):
...: return len(n.rsplit('.')[-1]) if '.' in n else 0
In [7]: dec('12.345')
Out[7]: 3
In [8]: dec('12.3450')
Out[8]: 4
In [9]:
|
Rewrite the snippet below in Python so it works the same as the original C code. | enum fruits { apple, banana, cherry };
enum fruits { apple = 0, banana = 1, cherry = 2 };
| >>> from enum import Enum
>>> Contact = Enum('Contact', 'FIRST_NAME, LAST_NAME, PHONE')
>>> Contact.__members__
mappingproxy(OrderedDict([('FIRST_NAME', <Contact.FIRST_NAME: 1>), ('LAST_NAME', <Contact.LAST_NAME: 2>), ('PHONE', <Contact.PHONE: 3>)]))
>>>
>>>
>>> class Contact2(Enum):
FIRST_NAME = 1
LAST_NAME = 2
PHONE = 3
>>> Contact2.__members__
mappingproxy(OrderedDict([('FIRST_NAME', <Contact2.FIRST_NAME: 1>), ('LAST_NAME', <Contact2.LAST_NAME: 2>), ('PHONE', <Contact2.PHONE: 3>)]))
>>>
|
Preserve the algorithm and functionality while converting the code from C to Python. | #include <stdio.h>
#define MAX_N 33
#define BRANCH 4
typedef unsigned long long xint;
#define FMT "llu"
xint rooted[MAX_N] = {1, 1, 0};
xint unrooted[MAX_N] = {1, 1, 0};
xint choose(xint m, xint k)
{
xint i, r;
if (k == 1) return m;
for (r = m, i = 1; i < k; i++)
r = r * (m + i) / (i + 1);
return r;
}
void tree(xint br, xint n, xint cnt, xint sum, xint l)
{
xint b, c, m, s;
for (b = br + 1; b <= BRANCH; b++) {
s = sum + (b - br) * n;
if (s >= MAX_N) return;
c = choose(rooted[n], b - br) * cnt;
if (l * 2 < s) unrooted[s] += c;
if (b == BRANCH) return;
rooted[s] += c;
for (m = n; --m; ) tree(b, m, c, s, l);
}
}
void bicenter(int s)
{
if (s & 1) return;
unrooted[s] += rooted[s/2] * (rooted[s/2] + 1) / 2;
}
int main()
{
xint n;
for (n = 1; n < MAX_N; n++) {
tree(0, n, 1, 1, n);
bicenter(n);
printf("%"FMT": %"FMT"\n", n, unrooted[n]);
}
return 0;
}
| try:
import psyco
psyco.full()
except ImportError:
pass
MAX_N = 300
BRANCH = 4
ra = [0] * MAX_N
unrooted = [0] * MAX_N
def tree(br, n, l, sum = 1, cnt = 1):
global ra, unrooted, MAX_N, BRANCH
for b in xrange(br + 1, BRANCH + 1):
sum += n
if sum >= MAX_N:
return
if l * 2 >= sum and b >= BRANCH:
return
if b == br + 1:
c = ra[n] * cnt
else:
c = c * (ra[n] + (b - br - 1)) / (b - br)
if l * 2 < sum:
unrooted[sum] += c
if b < BRANCH:
ra[sum] += c;
for m in range(1, n):
tree(b, m, l, sum, c)
def bicenter(s):
global ra, unrooted
if not (s & 1):
aux = ra[s / 2]
unrooted[s] += aux * (aux + 1) / 2
def main():
global ra, unrooted, MAX_N
ra[0] = ra[1] = unrooted[0] = unrooted[1] = 1
for n in xrange(1, MAX_N):
tree(0, n, n)
bicenter(n)
print "%d: %d" % (n, unrooted[n])
main()
|
Translate this program into Python but keep the logic exactly as in C. | #include <stdio.h>
#define MAX_N 33
#define BRANCH 4
typedef unsigned long long xint;
#define FMT "llu"
xint rooted[MAX_N] = {1, 1, 0};
xint unrooted[MAX_N] = {1, 1, 0};
xint choose(xint m, xint k)
{
xint i, r;
if (k == 1) return m;
for (r = m, i = 1; i < k; i++)
r = r * (m + i) / (i + 1);
return r;
}
void tree(xint br, xint n, xint cnt, xint sum, xint l)
{
xint b, c, m, s;
for (b = br + 1; b <= BRANCH; b++) {
s = sum + (b - br) * n;
if (s >= MAX_N) return;
c = choose(rooted[n], b - br) * cnt;
if (l * 2 < s) unrooted[s] += c;
if (b == BRANCH) return;
rooted[s] += c;
for (m = n; --m; ) tree(b, m, c, s, l);
}
}
void bicenter(int s)
{
if (s & 1) return;
unrooted[s] += rooted[s/2] * (rooted[s/2] + 1) / 2;
}
int main()
{
xint n;
for (n = 1; n < MAX_N; n++) {
tree(0, n, 1, 1, n);
bicenter(n);
printf("%"FMT": %"FMT"\n", n, unrooted[n]);
}
return 0;
}
| try:
import psyco
psyco.full()
except ImportError:
pass
MAX_N = 300
BRANCH = 4
ra = [0] * MAX_N
unrooted = [0] * MAX_N
def tree(br, n, l, sum = 1, cnt = 1):
global ra, unrooted, MAX_N, BRANCH
for b in xrange(br + 1, BRANCH + 1):
sum += n
if sum >= MAX_N:
return
if l * 2 >= sum and b >= BRANCH:
return
if b == br + 1:
c = ra[n] * cnt
else:
c = c * (ra[n] + (b - br - 1)) / (b - br)
if l * 2 < sum:
unrooted[sum] += c
if b < BRANCH:
ra[sum] += c;
for m in range(1, n):
tree(b, m, l, sum, c)
def bicenter(s):
global ra, unrooted
if not (s & 1):
aux = ra[s / 2]
unrooted[s] += aux * (aux + 1) / 2
def main():
global ra, unrooted, MAX_N
ra[0] = ra[1] = unrooted[0] = unrooted[1] = 1
for n in xrange(1, MAX_N):
tree(0, n, n)
bicenter(n)
print "%d: %d" % (n, unrooted[n])
main()
|
Write the same code in Python as shown below in C. | #include<stdio.h>
#include<stdlib.h>
#define min(a, b) (a<=b?a:b)
void minab( unsigned int n ) {
int i, j;
for(i=0;i<n;i++) {
for(j=0;j<n;j++) {
printf( "%2d ", min( min(i, n-1-i), min(j, n-1-j) ));
}
printf( "\n" );
}
return;
}
int main(void) {
minab(10);
return 0;
}
| def min_cells_matrix(siz):
return [[min(row, col, siz - row - 1, siz - col - 1) for col in range(siz)] for row in range(siz)]
def display_matrix(mat):
siz = len(mat)
spaces = 2 if siz < 20 else 3 if siz < 200 else 4
print(f"\nMinimum number of cells after, before, above and below {siz} x {siz} square:")
for row in range(siz):
print("".join([f"{n:{spaces}}" for n in mat[row]]))
def test_min_mat():
for siz in [23, 10, 9, 2, 1]:
display_matrix(min_cells_matrix(siz))
if __name__ == "__main__":
test_min_mat()
|
Write a version of this C function in Python with identical behavior. | #include<graphics.h>
#include<stdio.h>
#include<math.h>
#define pi M_PI
int main(){
char colourNames[][14] = { "BLACK", "BLUE", "GREEN", "CYAN", "RED", "MAGENTA", "BROWN", "LIGHTGRAY", "DARKGRAY",
"LIGHTBLUE", "LIGHTGREEN", "LIGHTCYAN", "LIGHTRED", "LIGHTMAGENTA", "YELLOW", "WHITE" };
int stroke=0,fill=0,back=0,i;
double centerX = 300,centerY = 300,coreSide,armLength,pentaLength;
printf("Enter core pentagon side length : ");
scanf("%lf",&coreSide);
printf("Enter pentagram arm length : ");
scanf("%lf",&armLength);
printf("Available colours are :\n");
for(i=0;i<16;i++){
printf("%d. %s\t",i+1,colourNames[i]);
if((i+1) % 3 == 0){
printf("\n");
}
}
while(stroke==fill && fill==back){
printf("\nEnter three diffrenet options for stroke, fill and background : ");
scanf("%d%d%d",&stroke,&fill,&back);
}
pentaLength = coreSide/(2 * tan(pi/5)) + sqrt(armLength*armLength - coreSide*coreSide/4);
initwindow(2*centerX,2*centerY,"Pentagram");
setcolor(stroke-1);
setfillstyle(SOLID_FILL,back-1);
bar(0,0,2*centerX,2*centerY);
floodfill(centerX,centerY,back-1);
setfillstyle(SOLID_FILL,fill-1);
for(i=0;i<5;i++){
line(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)));
line(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5));
line(centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5));
floodfill(centerX + coreSide*cos(i*2*pi/5 + pi/10)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5 + pi/10)/(2*sin(pi/5)),stroke-1);
}
floodfill(centerX,centerY,stroke-1);
getch();
closegraph();
}
| import turtle
turtle.bgcolor("green")
t = turtle.Turtle()
t.color("red", "blue")
t.begin_fill()
for i in range(0, 5):
t.forward(200)
t.right(144)
t.end_fill()
|
Ensure the translated Python code behaves exactly like the original C snippet. | #include<graphics.h>
#include<stdio.h>
#include<math.h>
#define pi M_PI
int main(){
char colourNames[][14] = { "BLACK", "BLUE", "GREEN", "CYAN", "RED", "MAGENTA", "BROWN", "LIGHTGRAY", "DARKGRAY",
"LIGHTBLUE", "LIGHTGREEN", "LIGHTCYAN", "LIGHTRED", "LIGHTMAGENTA", "YELLOW", "WHITE" };
int stroke=0,fill=0,back=0,i;
double centerX = 300,centerY = 300,coreSide,armLength,pentaLength;
printf("Enter core pentagon side length : ");
scanf("%lf",&coreSide);
printf("Enter pentagram arm length : ");
scanf("%lf",&armLength);
printf("Available colours are :\n");
for(i=0;i<16;i++){
printf("%d. %s\t",i+1,colourNames[i]);
if((i+1) % 3 == 0){
printf("\n");
}
}
while(stroke==fill && fill==back){
printf("\nEnter three diffrenet options for stroke, fill and background : ");
scanf("%d%d%d",&stroke,&fill,&back);
}
pentaLength = coreSide/(2 * tan(pi/5)) + sqrt(armLength*armLength - coreSide*coreSide/4);
initwindow(2*centerX,2*centerY,"Pentagram");
setcolor(stroke-1);
setfillstyle(SOLID_FILL,back-1);
bar(0,0,2*centerX,2*centerY);
floodfill(centerX,centerY,back-1);
setfillstyle(SOLID_FILL,fill-1);
for(i=0;i<5;i++){
line(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)));
line(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5));
line(centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5));
floodfill(centerX + coreSide*cos(i*2*pi/5 + pi/10)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5 + pi/10)/(2*sin(pi/5)),stroke-1);
}
floodfill(centerX,centerY,stroke-1);
getch();
closegraph();
}
| import turtle
turtle.bgcolor("green")
t = turtle.Turtle()
t.color("red", "blue")
t.begin_fill()
for i in range(0, 5):
t.forward(200)
t.right(144)
t.end_fill()
|
Convert the following code from C to Python, ensuring the logic remains intact. | #include <string.h>
#include <memory.h>
static unsigned int _parseDecimal ( const char** pchCursor )
{
unsigned int nVal = 0;
char chNow;
while ( chNow = **pchCursor, chNow >= '0' && chNow <= '9' )
{
nVal *= 10;
nVal += chNow - '0';
++*pchCursor;
}
return nVal;
}
static unsigned int _parseHex ( const char** pchCursor )
{
unsigned int nVal = 0;
char chNow;
while ( chNow = **pchCursor & 0x5f,
(chNow >= ('0'&0x5f) && chNow <= ('9'&0x5f)) ||
(chNow >= 'A' && chNow <= 'F')
)
{
unsigned char nybbleValue;
chNow -= 0x10;
nybbleValue = ( chNow > 9 ? chNow - (0x31-0x0a) : chNow );
nVal <<= 4;
nVal += nybbleValue;
++*pchCursor;
}
return nVal;
}
int ParseIPv4OrIPv6 ( const char** ppszText,
unsigned char* abyAddr, int* pnPort, int* pbIsIPv6 )
{
unsigned char* abyAddrLocal;
unsigned char abyDummyAddr[16];
const char* pchColon = strchr ( *ppszText, ':' );
const char* pchDot = strchr ( *ppszText, '.' );
const char* pchOpenBracket = strchr ( *ppszText, '[' );
const char* pchCloseBracket = NULL;
int bIsIPv6local = NULL != pchOpenBracket || NULL == pchDot ||
( NULL != pchColon && ( NULL == pchDot || pchColon < pchDot ) );
if ( bIsIPv6local )
{
pchCloseBracket = strchr ( *ppszText, ']' );
if ( NULL != pchOpenBracket && ( NULL == pchCloseBracket ||
pchCloseBracket < pchOpenBracket ) )
return 0;
}
else
{
if ( NULL == pchDot || ( NULL != pchColon && pchColon < pchDot ) )
return 0;
}
if ( NULL != pbIsIPv6 )
*pbIsIPv6 = bIsIPv6local;
abyAddrLocal = abyAddr;
if ( NULL == abyAddrLocal )
abyAddrLocal = abyDummyAddr;
if ( ! bIsIPv6local )
{
unsigned char* pbyAddrCursor = abyAddrLocal;
unsigned int nVal;
const char* pszTextBefore = *ppszText;
nVal =_parseDecimal ( ppszText );
if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )
return 0;
*(pbyAddrCursor++) = (unsigned char) nVal;
++(*ppszText);
pszTextBefore = *ppszText;
nVal =_parseDecimal ( ppszText );
if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )
return 0;
*(pbyAddrCursor++) = (unsigned char) nVal;
++(*ppszText);
pszTextBefore = *ppszText;
nVal =_parseDecimal ( ppszText );
if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )
return 0;
*(pbyAddrCursor++) = (unsigned char) nVal;
++(*ppszText);
pszTextBefore = *ppszText;
nVal =_parseDecimal ( ppszText );
if ( nVal > 255 || pszTextBefore == *ppszText )
return 0;
*(pbyAddrCursor++) = (unsigned char) nVal;
if ( ':' == **ppszText && NULL != pnPort )
{
unsigned short usPortNetwork;
++(*ppszText);
pszTextBefore = *ppszText;
nVal =_parseDecimal ( ppszText );
if ( nVal > 65535 || pszTextBefore == *ppszText )
return 0;
((unsigned char*)&usPortNetwork)[0] = ( nVal & 0xff00 ) >> 8;
((unsigned char*)&usPortNetwork)[1] = ( nVal & 0xff );
*pnPort = usPortNetwork;
return 1;
}
else
{
if ( NULL != pnPort )
*pnPort = 0;
return 1;
}
}
else
{
unsigned char* pbyAddrCursor;
unsigned char* pbyZerosLoc;
int bIPv4Detected;
int nIdx;
if ( NULL != pchOpenBracket )
*ppszText = pchOpenBracket + 1;
pbyAddrCursor = abyAddrLocal;
pbyZerosLoc = NULL;
bIPv4Detected = 0;
for ( nIdx = 0; nIdx < 8; ++nIdx )
{
const char* pszTextBefore = *ppszText;
unsigned nVal =_parseHex ( ppszText );
if ( pszTextBefore == *ppszText )
{
if ( NULL != pbyZerosLoc )
{
if ( pbyZerosLoc == pbyAddrCursor )
{
--nIdx;
break;
}
return 0;
}
if ( ':' != **ppszText )
return 0;
if ( 0 == nIdx )
{
++(*ppszText);
if ( ':' != **ppszText )
return 0;
}
pbyZerosLoc = pbyAddrCursor;
++(*ppszText);
}
else
{
if ( '.' == **ppszText )
{
const char* pszTextlocal = pszTextBefore;
unsigned char abyAddrlocal[16];
int bIsIPv6local;
int bParseResultlocal = ParseIPv4OrIPv6 ( &pszTextlocal, abyAddrlocal, NULL, &bIsIPv6local );
*ppszText = pszTextlocal;
if ( ! bParseResultlocal || bIsIPv6local )
return 0;
*(pbyAddrCursor++) = abyAddrlocal[0];
*(pbyAddrCursor++) = abyAddrlocal[1];
*(pbyAddrCursor++) = abyAddrlocal[2];
*(pbyAddrCursor++) = abyAddrlocal[3];
++nIdx;
bIPv4Detected = 1;
break;
}
if ( nVal > 65535 )
return 0;
*(pbyAddrCursor++) = nVal >> 8;
*(pbyAddrCursor++) = nVal & 0xff;
if ( ':' == **ppszText )
{
++(*ppszText);
}
else
{
break;
}
}
}
if ( NULL != pbyZerosLoc )
{
int nHead = (int)( pbyZerosLoc - abyAddrLocal );
int nTail = nIdx * 2 - (int)( pbyZerosLoc - abyAddrLocal );
int nZeros = 16 - nTail - nHead;
memmove ( &abyAddrLocal[16-nTail], pbyZerosLoc, nTail );
memset ( pbyZerosLoc, 0, nZeros );
}
if ( bIPv4Detected )
{
static const unsigned char abyPfx[] = { 0,0, 0,0, 0,0, 0,0, 0,0, 0xff,0xff };
if ( 0 != memcmp ( abyAddrLocal, abyPfx, sizeof(abyPfx) ) )
return 0;
}
if ( NULL != pchOpenBracket )
{
if ( ']' != **ppszText )
return 0;
++(*ppszText);
}
if ( ':' == **ppszText && NULL != pnPort )
{
const char* pszTextBefore;
unsigned int nVal;
unsigned short usPortNetwork;
++(*ppszText);
pszTextBefore = *ppszText;
pszTextBefore = *ppszText;
nVal =_parseDecimal ( ppszText );
if ( nVal > 65535 || pszTextBefore == *ppszText )
return 0;
((unsigned char*)&usPortNetwork)[0] = ( nVal & 0xff00 ) >> 8;
((unsigned char*)&usPortNetwork)[1] = ( nVal & 0xff );
*pnPort = usPortNetwork;
return 1;
}
else
{
if ( NULL != pnPort )
*pnPort = 0;
return 1;
}
}
}
int ParseIPv4OrIPv6_2 ( const char* pszText,
unsigned char* abyAddr, int* pnPort, int* pbIsIPv6 )
{
const char* pszTextLocal = pszText;
return ParseIPv4OrIPv6 ( &pszTextLocal, abyAddr, pnPort, pbIsIPv6);
}
| from ipaddress import ip_address
from urllib.parse import urlparse
tests = [
"127.0.0.1",
"127.0.0.1:80",
"::1",
"[::1]:80",
"::192.168.0.1",
"2605:2700:0:3::4713:93e3",
"[2605:2700:0:3::4713:93e3]:80" ]
def parse_ip_port(netloc):
try:
ip = ip_address(netloc)
port = None
except ValueError:
parsed = urlparse('//{}'.format(netloc))
ip = ip_address(parsed.hostname)
port = parsed.port
return ip, port
for address in tests:
ip, port = parse_ip_port(address)
hex_ip = {4:'{:08X}', 6:'{:032X}'}[ip.version].format(int(ip))
print("{:39s} {:>32s} IPv{} port={}".format(
str(ip), hex_ip, ip.version, port ))
|
Port the following code from C to Python with equivalent syntax and logic. |
#include <unistd.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <ncurses.h>
#define ROW_DELAY 40000
int get_rand_in_range(int min, int max)
{
return (rand() % ((max + 1) - min) + min);
}
int main(void)
{
srand(time(NULL));
char chars[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
int total_chars = sizeof(chars);
initscr();
noecho();
curs_set(FALSE);
start_color();
init_pair(1, COLOR_GREEN, COLOR_BLACK);
attron(COLOR_PAIR(1));
int max_x = 0, max_y = 0;
getmaxyx(stdscr, max_y, max_x);
int columns_row[max_x];
int columns_active[max_x];
int i;
for (i = 0; i < max_x; i++)
{
columns_row[i] = -1;
columns_active[i] = 0;
}
while (1)
{
for (i = 0; i < max_x; i++)
{
if (columns_row[i] == -1)
{
columns_row[i] = get_rand_in_range(0, max_y);
columns_active[i] = get_rand_in_range(0, 1);
}
}
for (i = 0; i < max_x; i++)
{
if (columns_active[i] == 1)
{
int char_index = get_rand_in_range(0, total_chars);
mvprintw(columns_row[i], i, "%c", chars[char_index]);
}
else
{
mvprintw(columns_row[i], i, " ");
}
columns_row[i]++;
if (columns_row[i] >= max_y)
{
columns_row[i] = -1;
}
if (get_rand_in_range(0, 1000) == 0)
{
columns_active[i] = (columns_active[i] == 0) ? 1 : 0;
}
}
usleep(ROW_DELAY);
refresh();
}
endwin();
return 0;
}
| import curses
import random
import time
ROW_DELAY=.0001
def get_rand_in_range(min, max):
return random.randrange(min,max+1)
try:
chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
total_chars = len(chars)
stdscr = curses.initscr()
curses.noecho()
curses.curs_set(False)
curses.start_color()
curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)
stdscr.attron(curses.color_pair(1))
max_x = curses.COLS - 1
max_y = curses.LINES - 1
columns_row = []
columns_active = []
for i in range(max_x+1):
columns_row.append(-1)
columns_active.append(0)
while(True):
for i in range(max_x):
if columns_row[i] == -1:
columns_row[i] = get_rand_in_range(0, max_y)
columns_active[i] = get_rand_in_range(0, 1)
for i in range(max_x):
if columns_active[i] == 1:
char_index = get_rand_in_range(0, total_chars-1)
stdscr.addstr(columns_row[i], i, chars[char_index])
else:
stdscr.addstr(columns_row[i], i, " ");
columns_row[i]+=1
if columns_row[i] >= max_y:
columns_row[i] = -1
if get_rand_in_range(0, 1000) == 0:
if columns_active[i] == 0:
columns_active[i] = 1
else:
columns_active[i] = 0
time.sleep(ROW_DELAY)
stdscr.refresh()
except KeyboardInterrupt as err:
curses.endwin()
|
Generate an equivalent Python version of this C code. |
#include <unistd.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <ncurses.h>
#define ROW_DELAY 40000
int get_rand_in_range(int min, int max)
{
return (rand() % ((max + 1) - min) + min);
}
int main(void)
{
srand(time(NULL));
char chars[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
int total_chars = sizeof(chars);
initscr();
noecho();
curs_set(FALSE);
start_color();
init_pair(1, COLOR_GREEN, COLOR_BLACK);
attron(COLOR_PAIR(1));
int max_x = 0, max_y = 0;
getmaxyx(stdscr, max_y, max_x);
int columns_row[max_x];
int columns_active[max_x];
int i;
for (i = 0; i < max_x; i++)
{
columns_row[i] = -1;
columns_active[i] = 0;
}
while (1)
{
for (i = 0; i < max_x; i++)
{
if (columns_row[i] == -1)
{
columns_row[i] = get_rand_in_range(0, max_y);
columns_active[i] = get_rand_in_range(0, 1);
}
}
for (i = 0; i < max_x; i++)
{
if (columns_active[i] == 1)
{
int char_index = get_rand_in_range(0, total_chars);
mvprintw(columns_row[i], i, "%c", chars[char_index]);
}
else
{
mvprintw(columns_row[i], i, " ");
}
columns_row[i]++;
if (columns_row[i] >= max_y)
{
columns_row[i] = -1;
}
if (get_rand_in_range(0, 1000) == 0)
{
columns_active[i] = (columns_active[i] == 0) ? 1 : 0;
}
}
usleep(ROW_DELAY);
refresh();
}
endwin();
return 0;
}
| import curses
import random
import time
ROW_DELAY=.0001
def get_rand_in_range(min, max):
return random.randrange(min,max+1)
try:
chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
total_chars = len(chars)
stdscr = curses.initscr()
curses.noecho()
curses.curs_set(False)
curses.start_color()
curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)
stdscr.attron(curses.color_pair(1))
max_x = curses.COLS - 1
max_y = curses.LINES - 1
columns_row = []
columns_active = []
for i in range(max_x+1):
columns_row.append(-1)
columns_active.append(0)
while(True):
for i in range(max_x):
if columns_row[i] == -1:
columns_row[i] = get_rand_in_range(0, max_y)
columns_active[i] = get_rand_in_range(0, 1)
for i in range(max_x):
if columns_active[i] == 1:
char_index = get_rand_in_range(0, total_chars-1)
stdscr.addstr(columns_row[i], i, chars[char_index])
else:
stdscr.addstr(columns_row[i], i, " ");
columns_row[i]+=1
if columns_row[i] >= max_y:
columns_row[i] = -1
if get_rand_in_range(0, 1000) == 0:
if columns_active[i] == 0:
columns_active[i] = 1
else:
columns_active[i] = 0
time.sleep(ROW_DELAY)
stdscr.refresh()
except KeyboardInterrupt as err:
curses.endwin()
|
Translate this program into Python but keep the logic exactly as in C. | #include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#define SIM_N 5
#define PRINT_DISCARDED 1
#define min(x,y) ((x<y)?(x):(y))
typedef uint8_t card_t;
unsigned int rand_n(unsigned int n) {
unsigned int out, mask = 1;
while (mask < n) mask = mask<<1 | 1;
do {
out = rand() & mask;
} while (out >= n);
return out;
}
card_t rand_card() {
return rand_n(52);
}
void print_card(card_t card) {
static char *suits = "HCDS";
static char *cards[] = {"A","2","3","4","5","6","7","8","9","10","J","Q","K"};
printf(" %s%c", cards[card>>2], suits[card&3]);
}
void shuffle(card_t *pack) {
int card;
card_t temp, randpos;
for (card=0; card<52; card++) {
randpos = rand_card();
temp = pack[card];
pack[card] = pack[randpos];
pack[randpos] = temp;
}
}
int trick() {
card_t pack[52];
card_t blacks[52/4], reds[52/4];
card_t top, x, card;
int blackn=0, redn=0, blacksw=0, redsw=0, result;
for (card=0; card<52; card++) pack[card] = card;
shuffle(pack);
#if PRINT_DISCARDED
printf("Discarded:");
#endif
for (card=0; card<52; card += 2) {
top = pack[card];
if (top & 1) {
blacks[blackn++] = pack[card+1];
} else {
reds[redn++] = pack[card+1];
}
#if PRINT_DISCARDED
print_card(top);
#endif
}
#if PRINT_DISCARDED
printf("\n");
#endif
x = rand_n(min(blackn, redn));
for (card=0; card<x; card++) {
blacksw = rand_n(blackn);
redsw = rand_n(redn);
top = blacks[blacksw];
blacks[blacksw] = reds[redsw];
reds[redsw] = top;
}
result = 0;
for (card=0; card<blackn; card++)
result += (blacks[card] & 1) == 1;
for (card=0; card<redn; card++)
result -= (reds[card] & 1) == 0;
result = !result;
printf("The number of black cards in the 'black' pile"
" %s the number of red cards in the 'red' pile.\n",
result? "equals" : "does not equal");
return result;
}
int main() {
unsigned int seed, i, successes = 0;
FILE *r;
if ((r = fopen("/dev/urandom", "r")) == NULL) {
fprintf(stderr, "cannot open /dev/urandom\n");
return 255;
}
if (fread(&seed, sizeof(unsigned int), 1, r) != 1) {
fprintf(stderr, "failed to read from /dev/urandom\n");
return 255;
}
fclose(r);
srand(seed);
for (i=1; i<=SIM_N; i++) {
printf("Simulation %d\n", i);
successes += trick();
printf("\n");
}
printf("Result: %d successes out of %d simulations\n",
successes, SIM_N);
return 0;
}
| import random
n = 52
Black, Red = 'Black', 'Red'
blacks = [Black] * (n // 2)
reds = [Red] * (n // 2)
pack = blacks + reds
random.shuffle(pack)
black_stack, red_stack, discard = [], [], []
while pack:
top = pack.pop()
if top == Black:
black_stack.append(pack.pop())
else:
red_stack.append(pack.pop())
discard.append(top)
print('(Discards:', ' '.join(d[0] for d in discard), ')\n')
max_swaps = min(len(black_stack), len(red_stack))
swap_count = random.randint(0, max_swaps)
print('Swapping', swap_count)
def random_partition(stack, count):
"Partition the stack into 'count' randomly selected members and the rest"
sample = random.sample(stack, count)
rest = stack[::]
for card in sample:
rest.remove(card)
return rest, sample
black_stack, black_swap = random_partition(black_stack, swap_count)
red_stack, red_swap = random_partition(red_stack, swap_count)
black_stack += red_swap
red_stack += black_swap
if black_stack.count(Black) == red_stack.count(Red):
print('Yeha! The mathematicians assertion is correct.')
else:
print('Whoops - The mathematicians (or my card manipulations) are flakey')
|
Port the provided C code into Python while preserving the original functionality. | #include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#define SIM_N 5
#define PRINT_DISCARDED 1
#define min(x,y) ((x<y)?(x):(y))
typedef uint8_t card_t;
unsigned int rand_n(unsigned int n) {
unsigned int out, mask = 1;
while (mask < n) mask = mask<<1 | 1;
do {
out = rand() & mask;
} while (out >= n);
return out;
}
card_t rand_card() {
return rand_n(52);
}
void print_card(card_t card) {
static char *suits = "HCDS";
static char *cards[] = {"A","2","3","4","5","6","7","8","9","10","J","Q","K"};
printf(" %s%c", cards[card>>2], suits[card&3]);
}
void shuffle(card_t *pack) {
int card;
card_t temp, randpos;
for (card=0; card<52; card++) {
randpos = rand_card();
temp = pack[card];
pack[card] = pack[randpos];
pack[randpos] = temp;
}
}
int trick() {
card_t pack[52];
card_t blacks[52/4], reds[52/4];
card_t top, x, card;
int blackn=0, redn=0, blacksw=0, redsw=0, result;
for (card=0; card<52; card++) pack[card] = card;
shuffle(pack);
#if PRINT_DISCARDED
printf("Discarded:");
#endif
for (card=0; card<52; card += 2) {
top = pack[card];
if (top & 1) {
blacks[blackn++] = pack[card+1];
} else {
reds[redn++] = pack[card+1];
}
#if PRINT_DISCARDED
print_card(top);
#endif
}
#if PRINT_DISCARDED
printf("\n");
#endif
x = rand_n(min(blackn, redn));
for (card=0; card<x; card++) {
blacksw = rand_n(blackn);
redsw = rand_n(redn);
top = blacks[blacksw];
blacks[blacksw] = reds[redsw];
reds[redsw] = top;
}
result = 0;
for (card=0; card<blackn; card++)
result += (blacks[card] & 1) == 1;
for (card=0; card<redn; card++)
result -= (reds[card] & 1) == 0;
result = !result;
printf("The number of black cards in the 'black' pile"
" %s the number of red cards in the 'red' pile.\n",
result? "equals" : "does not equal");
return result;
}
int main() {
unsigned int seed, i, successes = 0;
FILE *r;
if ((r = fopen("/dev/urandom", "r")) == NULL) {
fprintf(stderr, "cannot open /dev/urandom\n");
return 255;
}
if (fread(&seed, sizeof(unsigned int), 1, r) != 1) {
fprintf(stderr, "failed to read from /dev/urandom\n");
return 255;
}
fclose(r);
srand(seed);
for (i=1; i<=SIM_N; i++) {
printf("Simulation %d\n", i);
successes += trick();
printf("\n");
}
printf("Result: %d successes out of %d simulations\n",
successes, SIM_N);
return 0;
}
| import random
n = 52
Black, Red = 'Black', 'Red'
blacks = [Black] * (n // 2)
reds = [Red] * (n // 2)
pack = blacks + reds
random.shuffle(pack)
black_stack, red_stack, discard = [], [], []
while pack:
top = pack.pop()
if top == Black:
black_stack.append(pack.pop())
else:
red_stack.append(pack.pop())
discard.append(top)
print('(Discards:', ' '.join(d[0] for d in discard), ')\n')
max_swaps = min(len(black_stack), len(red_stack))
swap_count = random.randint(0, max_swaps)
print('Swapping', swap_count)
def random_partition(stack, count):
"Partition the stack into 'count' randomly selected members and the rest"
sample = random.sample(stack, count)
rest = stack[::]
for card in sample:
rest.remove(card)
return rest, sample
black_stack, black_swap = random_partition(black_stack, swap_count)
red_stack, red_swap = random_partition(red_stack, swap_count)
black_stack += red_swap
red_stack += black_swap
if black_stack.count(Black) == red_stack.count(Red):
print('Yeha! The mathematicians assertion is correct.')
else:
print('Whoops - The mathematicians (or my card manipulations) are flakey')
|
Convert this C snippet to Python and keep its semantics consistent. | #include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <glib.h>
char text_char(char c) {
switch (c) {
case 'a': case 'b': case 'c':
return '2';
case 'd': case 'e': case 'f':
return '3';
case 'g': case 'h': case 'i':
return '4';
case 'j': case 'k': case 'l':
return '5';
case 'm': case 'n': case 'o':
return '6';
case 'p': case 'q': case 'r': case 's':
return '7';
case 't': case 'u': case 'v':
return '8';
case 'w': case 'x': case 'y': case 'z':
return '9';
default:
return 0;
}
}
bool text_string(const GString* word, GString* text) {
g_string_set_size(text, word->len);
for (size_t i = 0; i < word->len; ++i) {
char c = text_char(g_ascii_tolower(word->str[i]));
if (c == 0)
return false;
text->str[i] = c;
}
return true;
}
typedef struct textonym_tag {
const char* text;
size_t length;
GPtrArray* words;
} textonym_t;
int compare_by_text_length(const void* p1, const void* p2) {
const textonym_t* t1 = p1;
const textonym_t* t2 = p2;
if (t1->length > t2->length)
return -1;
if (t1->length < t2->length)
return 1;
return strcmp(t1->text, t2->text);
}
int compare_by_word_count(const void* p1, const void* p2) {
const textonym_t* t1 = p1;
const textonym_t* t2 = p2;
if (t1->words->len > t2->words->len)
return -1;
if (t1->words->len < t2->words->len)
return 1;
return strcmp(t1->text, t2->text);
}
void print_words(GPtrArray* words) {
for (guint i = 0, n = words->len; i < n; ++i) {
if (i > 0)
printf(", ");
printf("%s", g_ptr_array_index(words, i));
}
printf("\n");
}
void print_top_words(GArray* textonyms, guint top) {
for (guint i = 0; i < top; ++i) {
const textonym_t* t = &g_array_index(textonyms, textonym_t, i);
printf("%s = ", t->text);
print_words(t->words);
}
}
void free_strings(gpointer ptr) {
g_ptr_array_free(ptr, TRUE);
}
bool find_textonyms(const char* filename, GError** error_ptr) {
GError* error = NULL;
GIOChannel* channel = g_io_channel_new_file(filename, "r", &error);
if (channel == NULL) {
g_propagate_error(error_ptr, error);
return false;
}
GHashTable* ht = g_hash_table_new_full(g_str_hash, g_str_equal,
g_free, free_strings);
GString* word = g_string_sized_new(64);
GString* text = g_string_sized_new(64);
guint count = 0;
gsize term_pos;
while (g_io_channel_read_line_string(channel, word, &term_pos,
&error) == G_IO_STATUS_NORMAL) {
g_string_truncate(word, term_pos);
if (!text_string(word, text))
continue;
GPtrArray* words = g_hash_table_lookup(ht, text->str);
if (words == NULL) {
words = g_ptr_array_new_full(1, g_free);
g_hash_table_insert(ht, g_strdup(text->str), words);
}
g_ptr_array_add(words, g_strdup(word->str));
++count;
}
g_io_channel_unref(channel);
g_string_free(word, TRUE);
g_string_free(text, TRUE);
if (error != NULL) {
g_propagate_error(error_ptr, error);
g_hash_table_destroy(ht);
return false;
}
GArray* words = g_array_new(FALSE, FALSE, sizeof(textonym_t));
GHashTableIter iter;
gpointer key, value;
g_hash_table_iter_init(&iter, ht);
while (g_hash_table_iter_next(&iter, &key, &value)) {
GPtrArray* v = value;
if (v->len > 1) {
textonym_t textonym;
textonym.text = key;
textonym.length = strlen(key);
textonym.words = v;
g_array_append_val(words, textonym);
}
}
printf("There are %u words in '%s' which can be represented by the digit key mapping.\n",
count, filename);
guint size = g_hash_table_size(ht);
printf("They require %u digit combinations to represent them.\n", size);
guint textonyms = words->len;
printf("%u digit combinations represent Textonyms.\n", textonyms);
guint top = 5;
if (textonyms < top)
top = textonyms;
printf("\nTop %u by number of words:\n", top);
g_array_sort(words, compare_by_word_count);
print_top_words(words, top);
printf("\nTop %u by length:\n", top);
g_array_sort(words, compare_by_text_length);
print_top_words(words, top);
g_array_free(words, TRUE);
g_hash_table_destroy(ht);
return true;
}
int main(int argc, char** argv) {
if (argc != 2) {
fprintf(stderr, "usage: %s word-list\n", argv[0]);
return EXIT_FAILURE;
}
GError* error = NULL;
if (!find_textonyms(argv[1], &error)) {
if (error != NULL) {
fprintf(stderr, "%s: %s\n", argv[1], error->message);
g_error_free(error);
}
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
| from collections import defaultdict
import urllib.request
CH2NUM = {ch: str(num) for num, chars in enumerate('abc def ghi jkl mno pqrs tuv wxyz'.split(), 2) for ch in chars}
URL = 'http://www.puzzlers.org/pub/wordlists/unixdict.txt'
def getwords(url):
return urllib.request.urlopen(url).read().decode("utf-8").lower().split()
def mapnum2words(words):
number2words = defaultdict(list)
reject = 0
for word in words:
try:
number2words[''.join(CH2NUM[ch] for ch in word)].append(word)
except KeyError:
reject += 1
return dict(number2words), reject
def interactiveconversions():
global inp, ch, num
while True:
inp = input("\nType a number or a word to get the translation and textonyms: ").strip().lower()
if inp:
if all(ch in '23456789' for ch in inp):
if inp in num2words:
print(" Number {0} has the following textonyms in the dictionary: {1}".format(inp, ', '.join(
num2words[inp])))
else:
print(" Number {0} has no textonyms in the dictionary.".format(inp))
elif all(ch in CH2NUM for ch in inp):
num = ''.join(CH2NUM[ch] for ch in inp)
print(" Word {0} is{1} in the dictionary and is number {2} with textonyms: {3}".format(
inp, ('' if inp in wordset else "n't"), num, ', '.join(num2words[num])))
else:
print(" I don't understand %r" % inp)
else:
print("Thank you")
break
if __name__ == '__main__':
words = getwords(URL)
print("Read %i words from %r" % (len(words), URL))
wordset = set(words)
num2words, reject = mapnum2words(words)
morethan1word = sum(1 for w in num2words if len(num2words[w]) > 1)
maxwordpernum = max(len(values) for values in num2words.values())
print(.format(len(words) - reject, URL, len(num2words), morethan1word))
print("\nThe numbers mapping to the most words map to %i words each:" % maxwordpernum)
maxwpn = sorted((key, val) for key, val in num2words.items() if len(val) == maxwordpernum)
for num, wrds in maxwpn:
print(" %s maps to: %s" % (num, ', '.join(wrds)))
interactiveconversions()
|
Port the following code from C to Python with equivalent syntax and logic. | #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <float.h>
#include <iso646.h>
#include <math.h>
#define map_size_rows 10
#define map_size_cols 10
char map[map_size_rows][map_size_cols] = {
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 0, 0, 0, 0, 0, 0, 0, 0, 1},
{1, 0, 0, 0, 0, 0, 0, 0, 0, 1},
{1, 0, 0, 0, 0, 1, 1, 1, 0, 1},
{1, 0, 0, 1, 0, 0, 0, 1, 0, 1},
{1, 0, 0, 1, 0, 0, 0, 1, 0, 1},
{1, 0, 0, 1, 1, 1, 1, 1, 0, 1},
{1, 0, 0, 0, 0, 0, 0, 0, 0, 1},
{1, 0, 0, 0, 0, 0, 0, 0, 0, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1}
};
struct stop {
double col, row;
int * n;
int n_len;
double f, g, h;
int from;
};
int ind[map_size_rows][map_size_cols] = {
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}
};
struct route {
int x;
int y;
double d;
};
int main() {
int i, j, k, l, b, found;
int p_len = 0;
int * path = NULL;
int c_len = 0;
int * closed = NULL;
int o_len = 1;
int * open = (int*)calloc(o_len, sizeof(int));
double min, tempg;
int s;
int e;
int current;
int s_len = 0;
struct stop * stops = NULL;
int r_len = 0;
struct route * routes = NULL;
for (i = 1; i < map_size_rows - 1; i++) {
for (j = 1; j < map_size_cols - 1; j++) {
if (!map[i][j]) {
++s_len;
stops = (struct stop *)realloc(stops, s_len * sizeof(struct stop));
int t = s_len - 1;
stops[t].col = j;
stops[t].row = i;
stops[t].from = -1;
stops[t].g = DBL_MAX;
stops[t].n_len = 0;
stops[t].n = NULL;
ind[i][j] = t;
}
}
}
s = 0;
e = s_len - 1;
for (i = 0; i < s_len; i++) {
stops[i].h = sqrt(pow(stops[e].row - stops[i].row, 2) + pow(stops[e].col - stops[i].col, 2));
}
for (i = 1; i < map_size_rows - 1; i++) {
for (j = 1; j < map_size_cols - 1; j++) {
if (ind[i][j] >= 0) {
for (k = i - 1; k <= i + 1; k++) {
for (l = j - 1; l <= j + 1; l++) {
if ((k == i) and (l == j)) {
continue;
}
if (ind[k][l] >= 0) {
++r_len;
routes = (struct route *)realloc(routes, r_len * sizeof(struct route));
int t = r_len - 1;
routes[t].x = ind[i][j];
routes[t].y = ind[k][l];
routes[t].d = sqrt(pow(stops[routes[t].y].row - stops[routes[t].x].row, 2) + pow(stops[routes[t].y].col - stops[routes[t].x].col, 2));
++stops[routes[t].x].n_len;
stops[routes[t].x].n = (int*)realloc(stops[routes[t].x].n, stops[routes[t].x].n_len * sizeof(int));
stops[routes[t].x].n[stops[routes[t].x].n_len - 1] = t;
}
}
}
}
}
}
open[0] = s;
stops[s].g = 0;
stops[s].f = stops[s].g + stops[s].h;
found = 0;
while (o_len and not found) {
min = DBL_MAX;
for (i = 0; i < o_len; i++) {
if (stops[open[i]].f < min) {
current = open[i];
min = stops[open[i]].f;
}
}
if (current == e) {
found = 1;
++p_len;
path = (int*)realloc(path, p_len * sizeof(int));
path[p_len - 1] = current;
while (stops[current].from >= 0) {
current = stops[current].from;
++p_len;
path = (int*)realloc(path, p_len * sizeof(int));
path[p_len - 1] = current;
}
}
for (i = 0; i < o_len; i++) {
if (open[i] == current) {
if (i not_eq (o_len - 1)) {
for (j = i; j < (o_len - 1); j++) {
open[j] = open[j + 1];
}
}
--o_len;
open = (int*)realloc(open, o_len * sizeof(int));
break;
}
}
++c_len;
closed = (int*)realloc(closed, c_len * sizeof(int));
closed[c_len - 1] = current;
for (i = 0; i < stops[current].n_len; i++) {
b = 0;
for (j = 0; j < c_len; j++) {
if (routes[stops[current].n[i]].y == closed[j]) {
b = 1;
}
}
if (b) {
continue;
}
tempg = stops[current].g + routes[stops[current].n[i]].d;
b = 1;
if (o_len > 0) {
for (j = 0; j < o_len; j++) {
if (routes[stops[current].n[i]].y == open[j]) {
b = 0;
}
}
}
if (b or (tempg < stops[routes[stops[current].n[i]].y].g)) {
stops[routes[stops[current].n[i]].y].from = current;
stops[routes[stops[current].n[i]].y].g = tempg;
stops[routes[stops[current].n[i]].y].f = stops[routes[stops[current].n[i]].y].g + stops[routes[stops[current].n[i]].y].h;
if (b) {
++o_len;
open = (int*)realloc(open, o_len * sizeof(int));
open[o_len - 1] = routes[stops[current].n[i]].y;
}
}
}
}
for (i = 0; i < map_size_rows; i++) {
for (j = 0; j < map_size_cols; j++) {
if (map[i][j]) {
putchar(0xdb);
} else {
b = 0;
for (k = 0; k < p_len; k++) {
if (ind[i][j] == path[k]) {
++b;
}
}
if (b) {
putchar('x');
} else {
putchar('.');
}
}
}
putchar('\n');
}
if (not found) {
puts("IMPOSSIBLE");
} else {
printf("path cost is %d:\n", p_len);
for (i = p_len - 1; i >= 0; i--) {
printf("(%1.0f, %1.0f)\n", stops[path[i]].col, stops[path[i]].row);
}
}
for (i = 0; i < s_len; ++i) {
free(stops[i].n);
}
free(stops);
free(routes);
free(path);
free(open);
free(closed);
return 0;
}
| from __future__ import print_function
import matplotlib.pyplot as plt
class AStarGraph(object):
def __init__(self):
self.barriers = []
self.barriers.append([(2,4),(2,5),(2,6),(3,6),(4,6),(5,6),(5,5),(5,4),(5,3),(5,2),(4,2),(3,2)])
def heuristic(self, start, goal):
D = 1
D2 = 1
dx = abs(start[0] - goal[0])
dy = abs(start[1] - goal[1])
return D * (dx + dy) + (D2 - 2 * D) * min(dx, dy)
def get_vertex_neighbours(self, pos):
n = []
for dx, dy in [(1,0),(-1,0),(0,1),(0,-1),(1,1),(-1,1),(1,-1),(-1,-1)]:
x2 = pos[0] + dx
y2 = pos[1] + dy
if x2 < 0 or x2 > 7 or y2 < 0 or y2 > 7:
continue
n.append((x2, y2))
return n
def move_cost(self, a, b):
for barrier in self.barriers:
if b in barrier:
return 100
return 1
def AStarSearch(start, end, graph):
G = {}
F = {}
G[start] = 0
F[start] = graph.heuristic(start, end)
closedVertices = set()
openVertices = set([start])
cameFrom = {}
while len(openVertices) > 0:
current = None
currentFscore = None
for pos in openVertices:
if current is None or F[pos] < currentFscore:
currentFscore = F[pos]
current = pos
if current == end:
path = [current]
while current in cameFrom:
current = cameFrom[current]
path.append(current)
path.reverse()
return path, F[end]
openVertices.remove(current)
closedVertices.add(current)
for neighbour in graph.get_vertex_neighbours(current):
if neighbour in closedVertices:
continue
candidateG = G[current] + graph.move_cost(current, neighbour)
if neighbour not in openVertices:
openVertices.add(neighbour)
elif candidateG >= G[neighbour]:
continue
cameFrom[neighbour] = current
G[neighbour] = candidateG
H = graph.heuristic(neighbour, end)
F[neighbour] = G[neighbour] + H
raise RuntimeError("A* failed to find a solution")
if __name__=="__main__":
graph = AStarGraph()
result, cost = AStarSearch((0,0), (7,7), graph)
print ("route", result)
print ("cost", cost)
plt.plot([v[0] for v in result], [v[1] for v in result])
for barrier in graph.barriers:
plt.plot([v[0] for v in barrier], [v[1] for v in barrier])
plt.xlim(-1,8)
plt.ylim(-1,8)
plt.show()
|
Change the programming language of this snippet from C to Python without modifying what it does. | #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <float.h>
#include <iso646.h>
#include <math.h>
#define map_size_rows 10
#define map_size_cols 10
char map[map_size_rows][map_size_cols] = {
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 0, 0, 0, 0, 0, 0, 0, 0, 1},
{1, 0, 0, 0, 0, 0, 0, 0, 0, 1},
{1, 0, 0, 0, 0, 1, 1, 1, 0, 1},
{1, 0, 0, 1, 0, 0, 0, 1, 0, 1},
{1, 0, 0, 1, 0, 0, 0, 1, 0, 1},
{1, 0, 0, 1, 1, 1, 1, 1, 0, 1},
{1, 0, 0, 0, 0, 0, 0, 0, 0, 1},
{1, 0, 0, 0, 0, 0, 0, 0, 0, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1}
};
struct stop {
double col, row;
int * n;
int n_len;
double f, g, h;
int from;
};
int ind[map_size_rows][map_size_cols] = {
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}
};
struct route {
int x;
int y;
double d;
};
int main() {
int i, j, k, l, b, found;
int p_len = 0;
int * path = NULL;
int c_len = 0;
int * closed = NULL;
int o_len = 1;
int * open = (int*)calloc(o_len, sizeof(int));
double min, tempg;
int s;
int e;
int current;
int s_len = 0;
struct stop * stops = NULL;
int r_len = 0;
struct route * routes = NULL;
for (i = 1; i < map_size_rows - 1; i++) {
for (j = 1; j < map_size_cols - 1; j++) {
if (!map[i][j]) {
++s_len;
stops = (struct stop *)realloc(stops, s_len * sizeof(struct stop));
int t = s_len - 1;
stops[t].col = j;
stops[t].row = i;
stops[t].from = -1;
stops[t].g = DBL_MAX;
stops[t].n_len = 0;
stops[t].n = NULL;
ind[i][j] = t;
}
}
}
s = 0;
e = s_len - 1;
for (i = 0; i < s_len; i++) {
stops[i].h = sqrt(pow(stops[e].row - stops[i].row, 2) + pow(stops[e].col - stops[i].col, 2));
}
for (i = 1; i < map_size_rows - 1; i++) {
for (j = 1; j < map_size_cols - 1; j++) {
if (ind[i][j] >= 0) {
for (k = i - 1; k <= i + 1; k++) {
for (l = j - 1; l <= j + 1; l++) {
if ((k == i) and (l == j)) {
continue;
}
if (ind[k][l] >= 0) {
++r_len;
routes = (struct route *)realloc(routes, r_len * sizeof(struct route));
int t = r_len - 1;
routes[t].x = ind[i][j];
routes[t].y = ind[k][l];
routes[t].d = sqrt(pow(stops[routes[t].y].row - stops[routes[t].x].row, 2) + pow(stops[routes[t].y].col - stops[routes[t].x].col, 2));
++stops[routes[t].x].n_len;
stops[routes[t].x].n = (int*)realloc(stops[routes[t].x].n, stops[routes[t].x].n_len * sizeof(int));
stops[routes[t].x].n[stops[routes[t].x].n_len - 1] = t;
}
}
}
}
}
}
open[0] = s;
stops[s].g = 0;
stops[s].f = stops[s].g + stops[s].h;
found = 0;
while (o_len and not found) {
min = DBL_MAX;
for (i = 0; i < o_len; i++) {
if (stops[open[i]].f < min) {
current = open[i];
min = stops[open[i]].f;
}
}
if (current == e) {
found = 1;
++p_len;
path = (int*)realloc(path, p_len * sizeof(int));
path[p_len - 1] = current;
while (stops[current].from >= 0) {
current = stops[current].from;
++p_len;
path = (int*)realloc(path, p_len * sizeof(int));
path[p_len - 1] = current;
}
}
for (i = 0; i < o_len; i++) {
if (open[i] == current) {
if (i not_eq (o_len - 1)) {
for (j = i; j < (o_len - 1); j++) {
open[j] = open[j + 1];
}
}
--o_len;
open = (int*)realloc(open, o_len * sizeof(int));
break;
}
}
++c_len;
closed = (int*)realloc(closed, c_len * sizeof(int));
closed[c_len - 1] = current;
for (i = 0; i < stops[current].n_len; i++) {
b = 0;
for (j = 0; j < c_len; j++) {
if (routes[stops[current].n[i]].y == closed[j]) {
b = 1;
}
}
if (b) {
continue;
}
tempg = stops[current].g + routes[stops[current].n[i]].d;
b = 1;
if (o_len > 0) {
for (j = 0; j < o_len; j++) {
if (routes[stops[current].n[i]].y == open[j]) {
b = 0;
}
}
}
if (b or (tempg < stops[routes[stops[current].n[i]].y].g)) {
stops[routes[stops[current].n[i]].y].from = current;
stops[routes[stops[current].n[i]].y].g = tempg;
stops[routes[stops[current].n[i]].y].f = stops[routes[stops[current].n[i]].y].g + stops[routes[stops[current].n[i]].y].h;
if (b) {
++o_len;
open = (int*)realloc(open, o_len * sizeof(int));
open[o_len - 1] = routes[stops[current].n[i]].y;
}
}
}
}
for (i = 0; i < map_size_rows; i++) {
for (j = 0; j < map_size_cols; j++) {
if (map[i][j]) {
putchar(0xdb);
} else {
b = 0;
for (k = 0; k < p_len; k++) {
if (ind[i][j] == path[k]) {
++b;
}
}
if (b) {
putchar('x');
} else {
putchar('.');
}
}
}
putchar('\n');
}
if (not found) {
puts("IMPOSSIBLE");
} else {
printf("path cost is %d:\n", p_len);
for (i = p_len - 1; i >= 0; i--) {
printf("(%1.0f, %1.0f)\n", stops[path[i]].col, stops[path[i]].row);
}
}
for (i = 0; i < s_len; ++i) {
free(stops[i].n);
}
free(stops);
free(routes);
free(path);
free(open);
free(closed);
return 0;
}
| from __future__ import print_function
import matplotlib.pyplot as plt
class AStarGraph(object):
def __init__(self):
self.barriers = []
self.barriers.append([(2,4),(2,5),(2,6),(3,6),(4,6),(5,6),(5,5),(5,4),(5,3),(5,2),(4,2),(3,2)])
def heuristic(self, start, goal):
D = 1
D2 = 1
dx = abs(start[0] - goal[0])
dy = abs(start[1] - goal[1])
return D * (dx + dy) + (D2 - 2 * D) * min(dx, dy)
def get_vertex_neighbours(self, pos):
n = []
for dx, dy in [(1,0),(-1,0),(0,1),(0,-1),(1,1),(-1,1),(1,-1),(-1,-1)]:
x2 = pos[0] + dx
y2 = pos[1] + dy
if x2 < 0 or x2 > 7 or y2 < 0 or y2 > 7:
continue
n.append((x2, y2))
return n
def move_cost(self, a, b):
for barrier in self.barriers:
if b in barrier:
return 100
return 1
def AStarSearch(start, end, graph):
G = {}
F = {}
G[start] = 0
F[start] = graph.heuristic(start, end)
closedVertices = set()
openVertices = set([start])
cameFrom = {}
while len(openVertices) > 0:
current = None
currentFscore = None
for pos in openVertices:
if current is None or F[pos] < currentFscore:
currentFscore = F[pos]
current = pos
if current == end:
path = [current]
while current in cameFrom:
current = cameFrom[current]
path.append(current)
path.reverse()
return path, F[end]
openVertices.remove(current)
closedVertices.add(current)
for neighbour in graph.get_vertex_neighbours(current):
if neighbour in closedVertices:
continue
candidateG = G[current] + graph.move_cost(current, neighbour)
if neighbour not in openVertices:
openVertices.add(neighbour)
elif candidateG >= G[neighbour]:
continue
cameFrom[neighbour] = current
G[neighbour] = candidateG
H = graph.heuristic(neighbour, end)
F[neighbour] = G[neighbour] + H
raise RuntimeError("A* failed to find a solution")
if __name__=="__main__":
graph = AStarGraph()
result, cost = AStarSearch((0,0), (7,7), graph)
print ("route", result)
print ("cost", cost)
plt.plot([v[0] for v in result], [v[1] for v in result])
for barrier in graph.barriers:
plt.plot([v[0] for v in barrier], [v[1] for v in barrier])
plt.xlim(-1,8)
plt.ylim(-1,8)
plt.show()
|
Rewrite the snippet below in Python so it works the same as the original C code. | #include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <glib.h>
int string_compare(gconstpointer p1, gconstpointer p2) {
const char* const* s1 = p1;
const char* const* s2 = p2;
return strcmp(*s1, *s2);
}
GPtrArray* load_dictionary(const char* file, GError** error_ptr) {
GError* error = NULL;
GIOChannel* channel = g_io_channel_new_file(file, "r", &error);
if (channel == NULL) {
g_propagate_error(error_ptr, error);
return NULL;
}
GPtrArray* dict = g_ptr_array_new_full(1024, g_free);
GString* line = g_string_sized_new(64);
gsize term_pos;
while (g_io_channel_read_line_string(channel, line, &term_pos,
&error) == G_IO_STATUS_NORMAL) {
char* word = g_strdup(line->str);
word[term_pos] = '\0';
g_ptr_array_add(dict, word);
}
g_string_free(line, TRUE);
g_io_channel_unref(channel);
if (error != NULL) {
g_propagate_error(error_ptr, error);
g_ptr_array_free(dict, TRUE);
return NULL;
}
g_ptr_array_sort(dict, string_compare);
return dict;
}
void rotate(char* str, size_t len) {
char c = str[0];
memmove(str, str + 1, len - 1);
str[len - 1] = c;
}
char* dictionary_search(const GPtrArray* dictionary, const char* word) {
char** result = bsearch(&word, dictionary->pdata, dictionary->len,
sizeof(char*), string_compare);
return result != NULL ? *result : NULL;
}
void find_teacup_words(GPtrArray* dictionary) {
GHashTable* found = g_hash_table_new(g_str_hash, g_str_equal);
GPtrArray* teacup_words = g_ptr_array_new();
GString* temp = g_string_sized_new(8);
for (size_t i = 0, n = dictionary->len; i < n; ++i) {
char* word = g_ptr_array_index(dictionary, i);
size_t len = strlen(word);
if (len < 3 || g_hash_table_contains(found, word))
continue;
g_ptr_array_set_size(teacup_words, 0);
g_string_assign(temp, word);
bool is_teacup_word = true;
for (size_t i = 0; i < len - 1; ++i) {
rotate(temp->str, len);
char* w = dictionary_search(dictionary, temp->str);
if (w == NULL) {
is_teacup_word = false;
break;
}
if (strcmp(word, w) != 0 && !g_ptr_array_find(teacup_words, w, NULL))
g_ptr_array_add(teacup_words, w);
}
if (is_teacup_word && teacup_words->len > 0) {
printf("%s", word);
g_hash_table_add(found, word);
for (size_t i = 0; i < teacup_words->len; ++i) {
char* teacup_word = g_ptr_array_index(teacup_words, i);
printf(" %s", teacup_word);
g_hash_table_add(found, teacup_word);
}
printf("\n");
}
}
g_string_free(temp, TRUE);
g_ptr_array_free(teacup_words, TRUE);
g_hash_table_destroy(found);
}
int main(int argc, char** argv) {
if (argc != 2) {
fprintf(stderr, "usage: %s dictionary\n", argv[0]);
return EXIT_FAILURE;
}
GError* error = NULL;
GPtrArray* dictionary = load_dictionary(argv[1], &error);
if (dictionary == NULL) {
if (error != NULL) {
fprintf(stderr, "Cannot load dictionary file '%s': %s\n",
argv[1], error->message);
g_error_free(error);
}
return EXIT_FAILURE;
}
find_teacup_words(dictionary);
g_ptr_array_free(dictionary, TRUE);
return EXIT_SUCCESS;
}
|
from itertools import chain, groupby
from os.path import expanduser
from functools import reduce
def main():
print('\n'.join(
concatMap(circularGroup)(
anagrams(3)(
lines(readFile('~/mitWords.txt'))
)
)
))
def anagrams(n):
def go(ws):
def f(xs):
return [
[snd(x) for x in xs]
] if n <= len(xs) >= len(xs[0][0]) else []
return concatMap(f)(groupBy(fst)(sorted(
[(''.join(sorted(w)), w) for w in ws],
key=fst
)))
return go
def circularGroup(ws):
lex = set(ws)
iLast = len(ws) - 1
(i, blnCircular) = until(
lambda tpl: tpl[1] or (tpl[0] > iLast)
)(
lambda tpl: (1 + tpl[0], isCircular(lex)(ws[tpl[0]]))
)(
(0, False)
)
return [' -> '.join(allRotations(ws[i]))] if blnCircular else []
def isCircular(lexicon):
def go(w):
def f(tpl):
(i, _, x) = tpl
return (1 + i, x in lexicon, rotated(x))
iLast = len(w) - 1
return until(
lambda tpl: iLast < tpl[0] or (not tpl[1])
)(f)(
(0, True, rotated(w))
)[1]
return go
def allRotations(w):
return takeIterate(len(w) - 1)(
rotated
)(w)
def concatMap(f):
def go(xs):
return chain.from_iterable(map(f, xs))
return go
def fst(tpl):
return tpl[0]
def groupBy(f):
def go(xs):
return [
list(x[1]) for x in groupby(xs, key=f)
]
return go
def lines(s):
return s.splitlines()
def mapAccumL(f):
def go(a, x):
tpl = f(a[0], x)
return (tpl[0], a[1] + [tpl[1]])
return lambda acc: lambda xs: (
reduce(go, xs, (acc, []))
)
def readFile(fp):
with open(expanduser(fp), 'r', encoding='utf-8') as f:
return f.read()
def rotated(s):
return s[1:] + s[0]
def snd(tpl):
return tpl[1]
def takeIterate(n):
def go(f):
def g(x):
def h(a, i):
v = f(a) if i else x
return (v, v)
return mapAccumL(h)(x)(
range(0, 1 + n)
)[1]
return g
return go
def until(p):
def go(f):
def g(x):
v = x
while not p(v):
v = f(v)
return v
return g
return go
if __name__ == '__main__':
main()
|
Can you help me rewrite this code in Python instead of C, keeping it the same logically? | #include <locale.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
uint64_t digit_sum(uint64_t n, uint64_t sum) {
++sum;
while (n > 0 && n % 10 == 0) {
sum -= 9;
n /= 10;
}
return sum;
}
inline bool divisible(uint64_t n, uint64_t d) {
if ((d & 1) == 0 && (n & 1) == 1)
return false;
return n % d == 0;
}
int main() {
setlocale(LC_ALL, "");
uint64_t previous = 1, gap = 0, sum = 0;
int niven_index = 0, gap_index = 1;
printf("Gap index Gap Niven index Niven number\n");
for (uint64_t niven = 1; gap_index <= 32; ++niven) {
sum = digit_sum(niven, sum);
if (divisible(niven, sum)) {
if (niven > previous + gap) {
gap = niven - previous;
printf("%'9d %'4llu %'14d %'15llu\n", gap_index++,
gap, niven_index, previous);
}
previous = niven;
++niven_index;
}
}
return 0;
}
|
def digit_sum(n, sum):
sum += 1
while n > 0 and n % 10 == 0:
sum -= 9
n /= 10
return sum
previous = 1
gap = 0
sum = 0
niven_index = 0
gap_index = 1
print("Gap index Gap Niven index Niven number")
niven = 1
while gap_index <= 22:
sum = digit_sum(niven, sum)
if niven % sum == 0:
if niven > previous + gap:
gap = niven - previous;
print('{0:9d} {1:4d} {2:13d} {3:11d}'.format(gap_index, gap, niven_index, previous))
gap_index += 1
previous = niven
niven_index += 1
niven += 1
|
Translate this program into Python but keep the logic exactly as in C. | #include <stdio.h>
#define DEBUG_INT(x) printf( #x " at line %d\nresult: %d\n\n", __LINE__, x)
int add(int x, int y) {
int result = x + y;
DEBUG_INT(x);
DEBUG_INT(y);
DEBUG_INT(result);
DEBUG_INT(result+1);
return result;
}
int main() {
add(2, 7);
return 0;
}
| import logging, logging.handlers
LOG_FILENAME = "logdemo.log"
FORMAT_STRING = "%(levelname)s:%(asctime)s:%(name)s:%(funcName)s:line-%(lineno)d: %(message)s"
LOGLEVEL = logging.DEBUG
def print_squares(number):
logger.info("In print_squares")
for i in range(number):
print("square of {0} is {1}".format(i , i*i))
logger.debug(f'square of {i} is {i*i}')
def print_cubes(number):
logger.info("In print_cubes")
for j in range(number):
print("cube of {0} is {1}".format(j, j*j*j))
logger.debug(f'cube of {j} is {j*j*j}')
if __name__ == "__main__":
logger = logging.getLogger("logdemo")
logger.setLevel(LOGLEVEL)
handler = logging.FileHandler(LOG_FILENAME)
handler.setFormatter(logging.Formatter(FORMAT_STRING))
logger.addHandler(handler)
print_squares(10)
print_cubes(10)
logger.info("All done")
|
Please provide an equivalent version of this C code in Python. | #include <stdbool.h>
#include <stdio.h>
bool is_prime(unsigned int n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
for (unsigned int p = 5; p * p <= n; p += 4) {
if (n % p == 0)
return false;
p += 2;
if (n % p == 0)
return false;
}
return true;
}
unsigned int reverse(unsigned int n) {
unsigned int rev = 0;
for (; n > 0; n /= 10)
rev = rev * 10 + n % 10;
return rev;
}
int main() {
unsigned int count = 0;
for (unsigned int n = 1; n < 500; ++n) {
if (is_prime(n) && is_prime(reverse(n)))
printf("%3u%c", n, ++count % 10 == 0 ? '\n' : ' ');
}
printf("\nCount = %u\n", count);
return 0;
}
|
def isPrime(n):
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def isBackPrime(n):
if not isPrime(n):
return False
m = 0
while n:
m *= 10
m += n % 10
n //= 10
return isPrime(m)
if __name__ == '__main__':
for n in range(2, 499):
if isBackPrime(n):
print(n, end=' ');
|
Change the programming language of this snippet from C to Python without modifying what it does. | #include <stdbool.h>
#include <stdio.h>
bool is_prime(unsigned int n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
for (unsigned int p = 5; p * p <= n; p += 4) {
if (n % p == 0)
return false;
p += 2;
if (n % p == 0)
return false;
}
return true;
}
unsigned int reverse(unsigned int n) {
unsigned int rev = 0;
for (; n > 0; n /= 10)
rev = rev * 10 + n % 10;
return rev;
}
int main() {
unsigned int count = 0;
for (unsigned int n = 1; n < 500; ++n) {
if (is_prime(n) && is_prime(reverse(n)))
printf("%3u%c", n, ++count % 10 == 0 ? '\n' : ' ');
}
printf("\nCount = %u\n", count);
return 0;
}
|
def isPrime(n):
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def isBackPrime(n):
if not isPrime(n):
return False
m = 0
while n:
m *= 10
m += n % 10
n //= 10
return isPrime(m)
if __name__ == '__main__':
for n in range(2, 499):
if isBackPrime(n):
print(n, end=' ');
|
Change the programming language of this snippet from C to Python without modifying what it does. | #include <stdbool.h>
#include <stdio.h>
bool is_prime(unsigned int n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
for (unsigned int p = 5; p * p <= n; p += 4) {
if (n % p == 0)
return false;
p += 2;
if (n % p == 0)
return false;
}
return true;
}
unsigned int reverse(unsigned int n) {
unsigned int rev = 0;
for (; n > 0; n /= 10)
rev = rev * 10 + n % 10;
return rev;
}
int main() {
unsigned int count = 0;
for (unsigned int n = 1; n < 500; ++n) {
if (is_prime(n) && is_prime(reverse(n)))
printf("%3u%c", n, ++count % 10 == 0 ? '\n' : ' ');
}
printf("\nCount = %u\n", count);
return 0;
}
|
def isPrime(n):
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def isBackPrime(n):
if not isPrime(n):
return False
m = 0
while n:
m *= 10
m += n % 10
n //= 10
return isPrime(m)
if __name__ == '__main__':
for n in range(2, 499):
if isBackPrime(n):
print(n, end=' ');
|
Produce a functionally identical Python code for the snippet given in C. | #include<graphics.h>
#include<stdio.h>
#include<math.h>
#define pi M_PI
int main(){
double a,b,n,i,incr = 0.0001;
printf("Enter major and minor axes of the SuperEllipse : ");
scanf("%lf%lf",&a,&b);
printf("Enter n : ");
scanf("%lf",&n);
initwindow(500,500,"Superellipse");
for(i=0;i<2*pi;i+=incr){
putpixel(250 + a*pow(fabs(cos(i)),2/n)*(pi/2<i && i<3*pi/2?-1:1),250 + b*pow(fabs(sin(i)),2/n)*(pi<i && i<2*pi?-1:1),15);
}
printf("Done. %lf",i);
getch();
closegraph();
}
|
import matplotlib.pyplot as plt
from math import sin, cos, pi
def sgn(x):
return ((x>0)-(x<0))*1
a,b,n=200,200,2.5
na=2/n
step=100
piece=(pi*2)/step
xp=[];yp=[]
t=0
for t1 in range(step+1):
x=(abs((cos(t)))**na)*a*sgn(cos(t))
y=(abs((sin(t)))**na)*b*sgn(sin(t))
xp.append(x);yp.append(y)
t+=piece
plt.plot(xp,yp)
plt.title("Superellipse with parameter "+str(n))
plt.show()
|
Ensure the translated Python code behaves exactly like the original C snippet. | #include<graphics.h>
#include<stdio.h>
#include<math.h>
#define pi M_PI
int main(){
double a,b,n,i,incr = 0.0001;
printf("Enter major and minor axes of the SuperEllipse : ");
scanf("%lf%lf",&a,&b);
printf("Enter n : ");
scanf("%lf",&n);
initwindow(500,500,"Superellipse");
for(i=0;i<2*pi;i+=incr){
putpixel(250 + a*pow(fabs(cos(i)),2/n)*(pi/2<i && i<3*pi/2?-1:1),250 + b*pow(fabs(sin(i)),2/n)*(pi<i && i<2*pi?-1:1),15);
}
printf("Done. %lf",i);
getch();
closegraph();
}
|
import matplotlib.pyplot as plt
from math import sin, cos, pi
def sgn(x):
return ((x>0)-(x<0))*1
a,b,n=200,200,2.5
na=2/n
step=100
piece=(pi*2)/step
xp=[];yp=[]
t=0
for t1 in range(step+1):
x=(abs((cos(t)))**na)*a*sgn(cos(t))
y=(abs((sin(t)))**na)*b*sgn(sin(t))
xp.append(x);yp.append(y)
t+=piece
plt.plot(xp,yp)
plt.title("Superellipse with parameter "+str(n))
plt.show()
|
Change the programming language of this snippet from C to Python without modifying what it does. | #include <stdio.h>
#include <stdlib.h>
#define SWAP(a,b) do{t=(a);(a)=(b);(b)=t;}while(0)
void _mr_unrank1(int rank, int n, int *vec) {
int t, q, r;
if (n < 1) return;
q = rank / n;
r = rank % n;
SWAP(vec[r], vec[n-1]);
_mr_unrank1(q, n-1, vec);
}
int _mr_rank1(int n, int *vec, int *inv) {
int s, t;
if (n < 2) return 0;
s = vec[n-1];
SWAP(vec[n-1], vec[inv[n-1]]);
SWAP(inv[s], inv[n-1]);
return s + n * _mr_rank1(n-1, vec, inv);
}
void get_permutation(int rank, int n, int *vec) {
int i;
for (i = 0; i < n; ++i) vec[i] = i;
_mr_unrank1(rank, n, vec);
}
int get_rank(int n, int *vec) {
int i, r, *v, *inv;
v = malloc(n * sizeof(int));
inv = malloc(n * sizeof(int));
for (i = 0; i < n; ++i) {
v[i] = vec[i];
inv[vec[i]] = i;
}
r = _mr_rank1(n, v, inv);
free(inv);
free(v);
return r;
}
int main(int argc, char *argv[]) {
int i, r, tv[4];
for (r = 0; r < 24; ++r) {
printf("%3d: ", r);
get_permutation(r, 4, tv);
for (i = 0; i < 4; ++i) {
if (0 == i) printf("[ ");
else printf(", ");
printf("%d", tv[i]);
}
printf(" ] = %d\n", get_rank(4, tv));
}
}
| from math import factorial as fact
from random import randrange
from textwrap import wrap
def identity_perm(n):
return list(range(n))
def unranker1(n, r, pi):
while n > 0:
n1, (rdivn, rmodn) = n-1, divmod(r, n)
pi[n1], pi[rmodn] = pi[rmodn], pi[n1]
n = n1
r = rdivn
return pi
def init_pi1(n, pi):
pi1 = [-1] * n
for i in range(n):
pi1[pi[i]] = i
return pi1
def ranker1(n, pi, pi1):
if n == 1:
return 0
n1 = n-1
s = pi[n1]
pi[n1], pi[pi1[n1]] = pi[pi1[n1]], pi[n1]
pi1[s], pi1[n1] = pi1[n1], pi1[s]
return s + n * ranker1(n1, pi, pi1)
def unranker2(n, r, pi):
while n > 0:
n1 = n-1
s, rmodf = divmod(r, fact(n1))
pi[n1], pi[s] = pi[s], pi[n1]
n = n1
r = rmodf
return pi
def ranker2(n, pi, pi1):
if n == 1:
return 0
n1 = n-1
s = pi[n1]
pi[n1], pi[pi1[n1]] = pi[pi1[n1]], pi[n1]
pi1[s], pi1[n1] = pi1[n1], pi1[s]
return s * fact(n1) + ranker2(n1, pi, pi1)
def get_random_ranks(permsize, samplesize):
perms = fact(permsize)
ranks = set()
while len(ranks) < samplesize:
ranks |= set( randrange(perms)
for r in range(samplesize - len(ranks)) )
return ranks
def test1(comment, unranker, ranker):
n, samplesize, n2 = 3, 4, 12
print(comment)
perms = []
for r in range(fact(n)):
pi = identity_perm(n)
perm = unranker(n, r, pi)
perms.append((r, perm))
for r, pi in perms:
pi1 = init_pi1(n, pi)
print(' From rank %2i to %r back to %2i' % (r, pi, ranker(n, pi[:], pi1)))
print('\n %i random individual samples of %i items:' % (samplesize, n2))
for r in get_random_ranks(n2, samplesize):
pi = identity_perm(n2)
print(' ' + ' '.join('%2i' % i for i in unranker(n2, r, pi)))
print('')
def test2(comment, unranker):
samplesize, n2 = 4, 144
print(comment)
print(' %i random individual samples of %i items:' % (samplesize, n2))
for r in get_random_ranks(n2, samplesize):
pi = identity_perm(n2)
print(' ' + '\n '.join(wrap(repr(unranker(n2, r, pi)))))
print('')
if __name__ == '__main__':
test1('First ordering:', unranker1, ranker1)
test1('Second ordering:', unranker2, ranker2)
test2('First ordering, large number of perms:', unranker1)
|
Port the following code from C to Python with equivalent syntax and logic. | #include <stdio.h>
#include <stdlib.h>
#define SWAP(a,b) do{t=(a);(a)=(b);(b)=t;}while(0)
void _mr_unrank1(int rank, int n, int *vec) {
int t, q, r;
if (n < 1) return;
q = rank / n;
r = rank % n;
SWAP(vec[r], vec[n-1]);
_mr_unrank1(q, n-1, vec);
}
int _mr_rank1(int n, int *vec, int *inv) {
int s, t;
if (n < 2) return 0;
s = vec[n-1];
SWAP(vec[n-1], vec[inv[n-1]]);
SWAP(inv[s], inv[n-1]);
return s + n * _mr_rank1(n-1, vec, inv);
}
void get_permutation(int rank, int n, int *vec) {
int i;
for (i = 0; i < n; ++i) vec[i] = i;
_mr_unrank1(rank, n, vec);
}
int get_rank(int n, int *vec) {
int i, r, *v, *inv;
v = malloc(n * sizeof(int));
inv = malloc(n * sizeof(int));
for (i = 0; i < n; ++i) {
v[i] = vec[i];
inv[vec[i]] = i;
}
r = _mr_rank1(n, v, inv);
free(inv);
free(v);
return r;
}
int main(int argc, char *argv[]) {
int i, r, tv[4];
for (r = 0; r < 24; ++r) {
printf("%3d: ", r);
get_permutation(r, 4, tv);
for (i = 0; i < 4; ++i) {
if (0 == i) printf("[ ");
else printf(", ");
printf("%d", tv[i]);
}
printf(" ] = %d\n", get_rank(4, tv));
}
}
| from math import factorial as fact
from random import randrange
from textwrap import wrap
def identity_perm(n):
return list(range(n))
def unranker1(n, r, pi):
while n > 0:
n1, (rdivn, rmodn) = n-1, divmod(r, n)
pi[n1], pi[rmodn] = pi[rmodn], pi[n1]
n = n1
r = rdivn
return pi
def init_pi1(n, pi):
pi1 = [-1] * n
for i in range(n):
pi1[pi[i]] = i
return pi1
def ranker1(n, pi, pi1):
if n == 1:
return 0
n1 = n-1
s = pi[n1]
pi[n1], pi[pi1[n1]] = pi[pi1[n1]], pi[n1]
pi1[s], pi1[n1] = pi1[n1], pi1[s]
return s + n * ranker1(n1, pi, pi1)
def unranker2(n, r, pi):
while n > 0:
n1 = n-1
s, rmodf = divmod(r, fact(n1))
pi[n1], pi[s] = pi[s], pi[n1]
n = n1
r = rmodf
return pi
def ranker2(n, pi, pi1):
if n == 1:
return 0
n1 = n-1
s = pi[n1]
pi[n1], pi[pi1[n1]] = pi[pi1[n1]], pi[n1]
pi1[s], pi1[n1] = pi1[n1], pi1[s]
return s * fact(n1) + ranker2(n1, pi, pi1)
def get_random_ranks(permsize, samplesize):
perms = fact(permsize)
ranks = set()
while len(ranks) < samplesize:
ranks |= set( randrange(perms)
for r in range(samplesize - len(ranks)) )
return ranks
def test1(comment, unranker, ranker):
n, samplesize, n2 = 3, 4, 12
print(comment)
perms = []
for r in range(fact(n)):
pi = identity_perm(n)
perm = unranker(n, r, pi)
perms.append((r, perm))
for r, pi in perms:
pi1 = init_pi1(n, pi)
print(' From rank %2i to %r back to %2i' % (r, pi, ranker(n, pi[:], pi1)))
print('\n %i random individual samples of %i items:' % (samplesize, n2))
for r in get_random_ranks(n2, samplesize):
pi = identity_perm(n2)
print(' ' + ' '.join('%2i' % i for i in unranker(n2, r, pi)))
print('')
def test2(comment, unranker):
samplesize, n2 = 4, 144
print(comment)
print(' %i random individual samples of %i items:' % (samplesize, n2))
for r in get_random_ranks(n2, samplesize):
pi = identity_perm(n2)
print(' ' + '\n '.join(wrap(repr(unranker(n2, r, pi)))))
print('')
if __name__ == '__main__':
test1('First ordering:', unranker1, ranker1)
test1('Second ordering:', unranker2, ranker2)
test2('First ordering, large number of perms:', unranker1)
|
Change the following C code into Python without altering its purpose. | #include <stdio.h>
#include <stdbool.h>
int main() {
int curr[5][5];
int max_claim[5][5];
int avl[5];
int alloc[5] = {0, 0, 0, 0, 0};
int max_res[5];
int running[5];
int i, j, exec, r, p;
int count = 0;
bool safe = false;
printf("\nEnter the number of resources: ");
scanf("%d", &r);
printf("\nEnter the number of processes: ");
scanf("%d", &p);
for (i = 0; i < p; i++) {
running[i] = 1;
count++;
}
printf("\nEnter Claim Vector: ");
for (i = 0; i < r; i++)
scanf("%d", &max_res[i]);
printf("\nEnter Allocated Resource Table: ");
for (i = 0; i < p; i++) {
for (j = 0; j < r; j++)
scanf("%d", &curr[i][j]);
}
printf("\nEnter Maximum Claim table: ");
for (i = 0; i < p; i++) {
for (j = 0; j < r; j++)
scanf("%d", &max_claim[i][j]);
}
printf("\nThe Claim Vector is: ");
for (i = 0; i < r; i++)
printf("%d ", max_res[i]);
printf("\nThe Allocated Resource Table:\n");
for (i = 0; i < p; i++) {
for (j = 0; j < r; j++)
printf("\t%d", curr[i][j]);
printf("\n");
}
printf("\nThe Maximum Claim Table:\n");
for (i = 0; i < p; i++) {
for (j = 0; j < r; j++)
printf("\t%d", max_claim[i][j]);
printf("\n");
}
for (i = 0; i < p; i++)
for (j = 0; j < r; j++)
alloc[j] += curr[i][j];
printf("\nAllocated resources: ");
for (i = 0; i < r; i++)
printf("%d ", alloc[i]);
for (i = 0; i < r; i++)
avl[i] = max_res[i] - alloc[i];
printf("\nAvailable resources: ");
for (i = 0; i < r; i++)
printf("%d ", avl[i]);
printf("\n");
while (count != 0) {
safe = false;
for (i = 0; i < p; i++) {
if (running[i]) {
exec = 1;
for (j = 0; j < r; j++) {
if (max_claim[i][j] - curr[i][j] > avl[j]) {
exec = 0;
break;
}
}
if (exec) {
printf("\nProcess%d is executing.\n", i + 1);
running[i] = 0;
count--;
safe = true;
for (j = 0; j < r; j++)
avl[j] += curr[i][j];
break;
}
}
}
if (!safe) {
printf("\nThe processes are in unsafe state.");
break;
}
if (safe)
printf("\nThe process is in safe state.");
printf("\nAvailable vector: ");
for (i = 0; i < r; i++)
printf("%d ", avl[i]);
}
return 0;
}
| def main():
resources = int(input("Cantidad de recursos: "))
processes = int(input("Cantidad de procesos: "))
max_resources = [int(i) for i in input("Recursos máximos: ").split()]
print("\n-- recursos asignados para cada proceso --")
currently_allocated = [[int(i) for i in input(f"proceso {j + 1}: ").split()] for j in range(processes)]
print("\n--- recursos máximos para cada proceso ---")
max_need = [[int(i) for i in input(f"proceso {j + 1}: ").split()] for j in range(processes)]
allocated = [0] * resources
for i in range(processes):
for j in range(resources):
allocated[j] += currently_allocated[i][j]
print(f"\nRecursos totales asignados : {allocated}")
available = [max_resources[i] - allocated[i] for i in range(resources)]
print(f"Recursos totales disponibles: {available}\n")
running = [True] * processes
count = processes
while count != 0:
safe = False
for i in range(processes):
if running[i]:
executing = True
for j in range(resources):
if max_need[i][j] - currently_allocated[i][j] > available[j]:
executing = False
break
if executing:
print(f"proceso {i + 1} ejecutándose")
running[i] = False
count -= 1
safe = True
for j in range(resources):
available[j] += currently_allocated[i][j]
break
if not safe:
print("El proceso está en un estado inseguro.")
break
print(f"El proceso está en un estado seguro.\nRecursos disponibles: {available}\n")
if __name__ == '__main__':
main()
|
Maintain the same structure and functionality when rewriting this code in Python. | #include <stdio.h>
#include <stdlib.h>
size_t rprint(char *s, int *x, int len)
{
#define sep (a > s ? "," : "")
#define ol (s ? 100 : 0)
int i, j;
char *a = s;
for (i = j = 0; i < len; i = ++j) {
for (; j < len - 1 && x[j + 1] == x[j] + 1; j++);
if (i + 1 < j)
a += snprintf(s?a:s, ol, "%s%d-%d", sep, x[i], x[j]);
else
while (i <= j)
a += snprintf(s?a:s, ol, "%s%d", sep, x[i++]);
}
return a - s;
#undef sep
#undef ol
}
int main()
{
int x[] = { 0, 1, 2, 4, 6, 7, 8, 11, 12, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 27, 28, 29, 30, 31, 32, 33, 35, 36,
37, 38, 39 };
char *s = malloc(rprint(0, x, sizeof(x) / sizeof(int)) + 1);
rprint(s, x, sizeof(x) / sizeof(int));
printf("%s\n", s);
return 0;
}
| def range_extract(lst):
'Yield 2-tuple ranges or 1-tuple single elements from list of increasing ints'
lenlst = len(lst)
i = 0
while i< lenlst:
low = lst[i]
while i <lenlst-1 and lst[i]+1 == lst[i+1]: i +=1
hi = lst[i]
if hi - low >= 2:
yield (low, hi)
elif hi - low == 1:
yield (low,)
yield (hi,)
else:
yield (low,)
i += 1
def printr(ranges):
print( ','.join( (('%i-%i' % r) if len(r) == 2 else '%i' % r)
for r in ranges ) )
if __name__ == '__main__':
for lst in [[-8, -7, -6, -3, -2, -1, 0, 1, 3, 4, 5, 7,
8, 9, 10, 11, 14, 15, 17, 18, 19, 20],
[0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22,
23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39]]:
printr(range_extract(lst))
|
Change the following C code into Python without altering its purpose. | #include <stdio.h>
#include <sys/mman.h>
#include <string.h>
int test (int a, int b)
{
char code[] = {0x8B, 0x44, 0x24, 0x4, 0x3, 0x44, 0x24, 0x8, 0xC3};
void *buf;
int c;
buf = mmap (0,sizeof(code),PROT_READ|PROT_WRITE|PROT_EXEC,
MAP_PRIVATE|MAP_ANON,-1,0);
memcpy (buf, code, sizeof(code));
c = ((int (*) (int, int))buf)(a, b);
munmap (buf, sizeof(code));
return c;
}
int main ()
{
printf("%d\n", test(7,12));
return 0;
}
| import ctypes
import os
from ctypes import c_ubyte, c_int
code = bytes([0x8b, 0x44, 0x24, 0x04, 0x03, 0x44, 0x24, 0x08, 0xc3])
code_size = len(code)
if (os.name == 'posix'):
import mmap
executable_map = mmap.mmap(-1, code_size, mmap.MAP_PRIVATE | mmap.MAP_ANON, mmap.PROT_READ | mmap.PROT_WRITE | mmap.PROT_EXEC)
executable_map.write(code)
func_address = ctypes.addressof(c_ubyte.from_buffer(executable_map))
elif (os.name == 'nt'):
code_buffer = ctypes.create_string_buffer(code)
PAGE_EXECUTE_READWRITE = 0x40
MEM_COMMIT = 0x1000
executable_buffer_address = ctypes.windll.kernel32.VirtualAlloc(0, code_size, MEM_COMMIT, PAGE_EXECUTE_READWRITE)
if (executable_buffer_address == 0):
print('Warning: Failed to enable code execution, call will likely cause a protection fault.')
func_address = ctypes.addressof(code_buffer)
else:
ctypes.memmove(executable_buffer_address, code_buffer, code_size)
func_address = executable_buffer_address
else:
code_buffer = ctypes.create_string_buffer(code)
func_address = ctypes.addressof(code_buffer)
prototype = ctypes.CFUNCTYPE(c_int, c_ubyte, c_ubyte)
func = prototype(func_address)
res = func(7,12)
print(res)
|
Generate an equivalent Python version of this C code. | #include <stdio.h>
#include <math.h>
#define max(x,y) ((x) > (y) ? (x) : (y))
int tri[] = {
55,
94, 48,
95, 30, 96,
77, 71, 26, 67,
97, 13, 76, 38, 45,
7, 36, 79, 16, 37, 68,
48, 7, 9, 18, 70, 26, 6,
18, 72, 79, 46, 59, 79, 29, 90,
20, 76, 87, 11, 32, 7, 7, 49, 18,
27, 83, 58, 35, 71, 11, 25, 57, 29, 85,
14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55,
2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23,
92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42,
56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72,
44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36,
85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52,
6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15,
27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93
};
int main(void)
{
const int len = sizeof(tri) / sizeof(tri[0]);
const int base = (sqrt(8*len + 1) - 1) / 2;
int step = base - 1;
int stepc = 0;
int i;
for (i = len - base - 1; i >= 0; --i) {
tri[i] += max(tri[i + step], tri[i + step + 1]);
if (++stepc == step) {
step--;
stepc = 0;
}
}
printf("%d\n", tri[0]);
return 0;
}
| fun maxpathsum(t):
let a = val t
for i in a.length-1..-1..1, c in linearindices a[r]:
a[r, c] += max(a[r+1, c], a[r=1, c+1])
return a[1, 1]
let test = [
[55],
[94, 48],
[95, 30, 96],
[77, 71, 26, 67],
[97, 13, 76, 38, 45],
[07, 36, 79, 16, 37, 68],
[48, 07, 09, 18, 70, 26, 06],
[18, 72, 79, 46, 59, 79, 29, 90],
[20, 76, 87, 11, 32, 07, 07, 49, 18],
[27, 83, 58, 35, 71, 11, 25, 57, 29, 85],
[14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55],
[02, 90, 03, 60, 48, 49, 41, 46, 33, 36, 47, 23],
[92, 50, 48, 02, 36, 59, 42, 79, 72, 20, 82, 77, 42],
[56, 78, 38, 80, 39, 75, 02, 71, 66, 66, 01, 03, 55, 72],
[44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36],
[85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 01, 01, 99, 89, 52],
[06, 71, 28, 75, 94, 48, 37, 10, 23, 51, 06, 48, 53, 18, 74, 98, 15],
[27, 02, 92, 23, 08, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93]
]
@print maxpathsum test
|
Rewrite this program in Python while keeping its functionality equivalent to the C version. | #include <stdio.h>
#include <math.h>
#define max(x,y) ((x) > (y) ? (x) : (y))
int tri[] = {
55,
94, 48,
95, 30, 96,
77, 71, 26, 67,
97, 13, 76, 38, 45,
7, 36, 79, 16, 37, 68,
48, 7, 9, 18, 70, 26, 6,
18, 72, 79, 46, 59, 79, 29, 90,
20, 76, 87, 11, 32, 7, 7, 49, 18,
27, 83, 58, 35, 71, 11, 25, 57, 29, 85,
14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55,
2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23,
92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42,
56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72,
44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36,
85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52,
6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15,
27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93
};
int main(void)
{
const int len = sizeof(tri) / sizeof(tri[0]);
const int base = (sqrt(8*len + 1) - 1) / 2;
int step = base - 1;
int stepc = 0;
int i;
for (i = len - base - 1; i >= 0; --i) {
tri[i] += max(tri[i + step], tri[i + step + 1]);
if (++stepc == step) {
step--;
stepc = 0;
}
}
printf("%d\n", tri[0]);
return 0;
}
| fun maxpathsum(t):
let a = val t
for i in a.length-1..-1..1, c in linearindices a[r]:
a[r, c] += max(a[r+1, c], a[r=1, c+1])
return a[1, 1]
let test = [
[55],
[94, 48],
[95, 30, 96],
[77, 71, 26, 67],
[97, 13, 76, 38, 45],
[07, 36, 79, 16, 37, 68],
[48, 07, 09, 18, 70, 26, 06],
[18, 72, 79, 46, 59, 79, 29, 90],
[20, 76, 87, 11, 32, 07, 07, 49, 18],
[27, 83, 58, 35, 71, 11, 25, 57, 29, 85],
[14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55],
[02, 90, 03, 60, 48, 49, 41, 46, 33, 36, 47, 23],
[92, 50, 48, 02, 36, 59, 42, 79, 72, 20, 82, 77, 42],
[56, 78, 38, 80, 39, 75, 02, 71, 66, 66, 01, 03, 55, 72],
[44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36],
[85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 01, 01, 99, 89, 52],
[06, 71, 28, 75, 94, 48, 37, 10, 23, 51, 06, 48, 53, 18, 74, 98, 15],
[27, 02, 92, 23, 08, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93]
]
@print maxpathsum test
|
Ensure the translated Python code behaves exactly like the original C snippet. | #include<stdlib.h>
#include<stdio.h>
char** imageMatrix;
char blankPixel,imagePixel;
typedef struct{
int row,col;
}pixel;
int getBlackNeighbours(int row,int col){
int i,j,sum = 0;
for(i=-1;i<=1;i++){
for(j=-1;j<=1;j++){
if(i!=0 || j!=0)
sum+= (imageMatrix[row+i][col+j]==imagePixel);
}
}
return sum;
}
int getBWTransitions(int row,int col){
return ((imageMatrix[row-1][col]==blankPixel && imageMatrix[row-1][col+1]==imagePixel)
+(imageMatrix[row-1][col+1]==blankPixel && imageMatrix[row][col+1]==imagePixel)
+(imageMatrix[row][col+1]==blankPixel && imageMatrix[row+1][col+1]==imagePixel)
+(imageMatrix[row+1][col+1]==blankPixel && imageMatrix[row+1][col]==imagePixel)
+(imageMatrix[row+1][col]==blankPixel && imageMatrix[row+1][col-1]==imagePixel)
+(imageMatrix[row+1][col-1]==blankPixel && imageMatrix[row][col-1]==imagePixel)
+(imageMatrix[row][col-1]==blankPixel && imageMatrix[row-1][col-1]==imagePixel)
+(imageMatrix[row-1][col-1]==blankPixel && imageMatrix[row-1][col]==imagePixel));
}
int zhangSuenTest1(int row,int col){
int neighbours = getBlackNeighbours(row,col);
return ((neighbours>=2 && neighbours<=6)
&& (getBWTransitions(row,col)==1)
&& (imageMatrix[row-1][col]==blankPixel||imageMatrix[row][col+1]==blankPixel||imageMatrix[row+1][col]==blankPixel)
&& (imageMatrix[row][col+1]==blankPixel||imageMatrix[row+1][col]==blankPixel||imageMatrix[row][col-1]==blankPixel));
}
int zhangSuenTest2(int row,int col){
int neighbours = getBlackNeighbours(row,col);
return ((neighbours>=2 && neighbours<=6)
&& (getBWTransitions(row,col)==1)
&& (imageMatrix[row-1][col]==blankPixel||imageMatrix[row][col+1]==blankPixel||imageMatrix[row][col-1]==blankPixel)
&& (imageMatrix[row-1][col]==blankPixel||imageMatrix[row+1][col]==blankPixel||imageMatrix[row][col+1]==blankPixel));
}
void zhangSuen(char* inputFile, char* outputFile){
int startRow = 1,startCol = 1,endRow,endCol,i,j,count,rows,cols,processed;
pixel* markers;
FILE* inputP = fopen(inputFile,"r");
fscanf(inputP,"%d%d",&rows,&cols);
fscanf(inputP,"%d%d",&blankPixel,&imagePixel);
blankPixel<=9?blankPixel+='0':blankPixel;
imagePixel<=9?imagePixel+='0':imagePixel;
printf("\nPrinting original image :\n");
imageMatrix = (char**)malloc(rows*sizeof(char*));
for(i=0;i<rows;i++){
imageMatrix[i] = (char*)malloc((cols+1)*sizeof(char));
fscanf(inputP,"%s\n",imageMatrix[i]);
printf("\n%s",imageMatrix[i]);
}
fclose(inputP);
endRow = rows-2;
endCol = cols-2;
do{
markers = (pixel*)malloc((endRow-startRow+1)*(endCol-startCol+1)*sizeof(pixel));
count = 0;
for(i=startRow;i<=endRow;i++){
for(j=startCol;j<=endCol;j++){
if(imageMatrix[i][j]==imagePixel && zhangSuenTest1(i,j)==1){
markers[count].row = i;
markers[count].col = j;
count++;
}
}
}
processed = (count>0);
for(i=0;i<count;i++){
imageMatrix[markers[i].row][markers[i].col] = blankPixel;
}
free(markers);
markers = (pixel*)malloc((endRow-startRow+1)*(endCol-startCol+1)*sizeof(pixel));
count = 0;
for(i=startRow;i<=endRow;i++){
for(j=startCol;j<=endCol;j++){
if(imageMatrix[i][j]==imagePixel && zhangSuenTest2(i,j)==1){
markers[count].row = i;
markers[count].col = j;
count++;
}
}
}
if(processed==0)
processed = (count>0);
for(i=0;i<count;i++){
imageMatrix[markers[i].row][markers[i].col] = blankPixel;
}
free(markers);
}while(processed==1);
FILE* outputP = fopen(outputFile,"w");
printf("\n\n\nPrinting image after applying Zhang Suen Thinning Algorithm : \n\n\n");
for(i=0;i<rows;i++){
for(j=0;j<cols;j++){
printf("%c",imageMatrix[i][j]);
fprintf(outputP,"%c",imageMatrix[i][j]);
}
printf("\n");
fprintf(outputP,"\n");
}
fclose(outputP);
printf("\nImage also written to : %s",outputFile);
}
int main()
{
char inputFile[100],outputFile[100];
printf("Enter full path of input image file : ");
scanf("%s",inputFile);
printf("Enter full path of output image file : ");
scanf("%s",outputFile);
zhangSuen(inputFile,outputFile);
return 0;
}
|
beforeTxt =
smallrc01 =
rc01 =
def intarray(binstring):
return [[1 if ch == '1' else 0 for ch in line]
for line in binstring.strip().split()]
def chararray(intmatrix):
return '\n'.join(''.join(str(p) for p in row) for row in intmatrix)
def toTxt(intmatrix):
Return 8-neighbours of point p1 of picture, in order'''
i = image
x1, y1, x_1, y_1 = x+1, y-1, x-1, y+1
return [i[y1][x], i[y1][x1], i[y][x1], i[y_1][x1],
i[y_1][x], i[y_1][x_1], i[y][x_1], i[y1][x_1]]
def transitions(neighbours):
n = neighbours + neighbours[0:1]
return sum((n1, n2) == (0, 1) for n1, n2 in zip(n, n[1:]))
def zhangSuen(image):
changing1 = changing2 = [(-1, -1)]
while changing1 or changing2:
changing1 = []
for y in range(1, len(image) - 1):
for x in range(1, len(image[0]) - 1):
P2,P3,P4,P5,P6,P7,P8,P9 = n = neighbours(x, y, image)
if (image[y][x] == 1 and
P4 * P6 * P8 == 0 and
P2 * P4 * P6 == 0 and
transitions(n) == 1 and
2 <= sum(n) <= 6):
changing1.append((x,y))
for x, y in changing1: image[y][x] = 0
changing2 = []
for y in range(1, len(image) - 1):
for x in range(1, len(image[0]) - 1):
P2,P3,P4,P5,P6,P7,P8,P9 = n = neighbours(x, y, image)
if (image[y][x] == 1 and
P2 * P6 * P8 == 0 and
P2 * P4 * P8 == 0 and
transitions(n) == 1 and
2 <= sum(n) <= 6):
changing2.append((x,y))
for x, y in changing2: image[y][x] = 0
return image
if __name__ == '__main__':
for picture in (beforeTxt, smallrc01, rc01):
image = intarray(picture)
print('\nFrom:\n%s' % toTxt(image))
after = zhangSuen(image)
print('\nTo thinned:\n%s' % toTxt(after))
|
Rewrite this program in Python while keeping its functionality equivalent to the C version. | #include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <ctype.h>
#include <string.h>
typedef struct { unsigned char r, g, b; } rgb_t;
typedef struct {
int w, h;
rgb_t **pix;
} image_t, *image;
typedef struct {
int r[256], g[256], b[256];
int n;
} color_histo_t;
int write_ppm(image im, char *fn)
{
FILE *fp = fopen(fn, "w");
if (!fp) return 0;
fprintf(fp, "P6\n%d %d\n255\n", im->w, im->h);
fwrite(im->pix[0], 1, sizeof(rgb_t) * im->w * im->h, fp);
fclose(fp);
return 1;
}
image img_new(int w, int h)
{
int i;
image im = malloc(sizeof(image_t) + h * sizeof(rgb_t*)
+ sizeof(rgb_t) * w * h);
im->w = w; im->h = h;
im->pix = (rgb_t**)(im + 1);
for (im->pix[0] = (rgb_t*)(im->pix + h), i = 1; i < h; i++)
im->pix[i] = im->pix[i - 1] + w;
return im;
}
int read_num(FILE *f)
{
int n;
while (!fscanf(f, "%d ", &n)) {
if ((n = fgetc(f)) == '#') {
while ((n = fgetc(f)) != '\n')
if (n == EOF) break;
if (n == '\n') continue;
} else return 0;
}
return n;
}
image read_ppm(char *fn)
{
FILE *fp = fopen(fn, "r");
int w, h, maxval;
image im = 0;
if (!fp) return 0;
if (fgetc(fp) != 'P' || fgetc(fp) != '6' || !isspace(fgetc(fp)))
goto bail;
w = read_num(fp);
h = read_num(fp);
maxval = read_num(fp);
if (!w || !h || !maxval) goto bail;
im = img_new(w, h);
fread(im->pix[0], 1, sizeof(rgb_t) * w * h, fp);
bail:
if (fp) fclose(fp);
return im;
}
void del_pixels(image im, int row, int col, int size, color_histo_t *h)
{
int i;
rgb_t *pix;
if (col < 0 || col >= im->w) return;
for (i = row - size; i <= row + size && i < im->h; i++) {
if (i < 0) continue;
pix = im->pix[i] + col;
h->r[pix->r]--;
h->g[pix->g]--;
h->b[pix->b]--;
h->n--;
}
}
void add_pixels(image im, int row, int col, int size, color_histo_t *h)
{
int i;
rgb_t *pix;
if (col < 0 || col >= im->w) return;
for (i = row - size; i <= row + size && i < im->h; i++) {
if (i < 0) continue;
pix = im->pix[i] + col;
h->r[pix->r]++;
h->g[pix->g]++;
h->b[pix->b]++;
h->n++;
}
}
void init_histo(image im, int row, int size, color_histo_t*h)
{
int j;
memset(h, 0, sizeof(color_histo_t));
for (j = 0; j < size && j < im->w; j++)
add_pixels(im, row, j, size, h);
}
int median(const int *x, int n)
{
int i;
for (n /= 2, i = 0; i < 256 && (n -= x[i]) > 0; i++);
return i;
}
void median_color(rgb_t *pix, const color_histo_t *h)
{
pix->r = median(h->r, h->n);
pix->g = median(h->g, h->n);
pix->b = median(h->b, h->n);
}
image median_filter(image in, int size)
{
int row, col;
image out = img_new(in->w, in->h);
color_histo_t h;
for (row = 0; row < in->h; row ++) {
for (col = 0; col < in->w; col++) {
if (!col) init_histo(in, row, size, &h);
else {
del_pixels(in, row, col - size, size, &h);
add_pixels(in, row, col + size, size, &h);
}
median_color(out->pix[row] + col, &h);
}
}
return out;
}
int main(int c, char **v)
{
int size;
image in, out;
if (c <= 3) {
printf("Usage: %s size ppm_in ppm_out\n", v[0]);
return 0;
}
size = atoi(v[1]);
printf("filter size %d\n", size);
if (size < 0) size = 1;
in = read_ppm(v[2]);
out = median_filter(in, size);
write_ppm(out, v[3]);
free(in);
free(out);
return 0;
}
| import Image, ImageFilter
im = Image.open('image.ppm')
median = im.filter(ImageFilter.MedianFilter(3))
median.save('image2.ppm')
|
Translate this program into Python but keep the logic exactly as in C. | #include <err.h>
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <syslog.h>
#include <time.h>
#include <unistd.h>
int
main(int argc, char **argv)
{
extern char *__progname;
time_t clock;
int fd;
if (argc != 2) {
fprintf(stderr, "usage: %s file\n", __progname);
exit(1);
}
fd = open(argv[1], O_WRONLY | O_APPEND | O_CREAT, 0666);
if (fd < 0)
err(1, argv[1]);
if (daemon(0, 0) < 0)
err(1, "daemon");
if (dup2(fd, STDOUT_FILENO) < 0) {
syslog(LOG_ERR, "dup2: %s", strerror(errno));
exit(1);
}
close(fd);
for (;;) {
time(&clock);
fputs(ctime(&clock), stdout);
if (fflush(stdout) == EOF) {
syslog(LOG_ERR, "%s: %s", argv[1], strerror(errno));
exit(1);
}
sleep(1);
}
}
|
import posix
import os
import sys
pid = posix.fork()
if pid != 0:
print("Child process detached with pid %s" % pid)
sys.exit(0)
old_stdin = sys.stdin
old_stdout = sys.stdout
old_stderr = sys.stderr
sys.stdin = open('/dev/null', 'rt')
sys.stdout = open('/tmp/dmn.log', 'wt')
sys.stderr = sys.stdout
old_stdin.close()
old_stdout.close()
old_stderr.close()
posix.setsid()
import time
t = time.time()
while time.time() < t + 10:
print("timer running, %s seconds" % str(time.time() - t))
time.sleep(1)
|
Keep all operations the same but rewrite the snippet in Python. | #include <err.h>
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <syslog.h>
#include <time.h>
#include <unistd.h>
int
main(int argc, char **argv)
{
extern char *__progname;
time_t clock;
int fd;
if (argc != 2) {
fprintf(stderr, "usage: %s file\n", __progname);
exit(1);
}
fd = open(argv[1], O_WRONLY | O_APPEND | O_CREAT, 0666);
if (fd < 0)
err(1, argv[1]);
if (daemon(0, 0) < 0)
err(1, "daemon");
if (dup2(fd, STDOUT_FILENO) < 0) {
syslog(LOG_ERR, "dup2: %s", strerror(errno));
exit(1);
}
close(fd);
for (;;) {
time(&clock);
fputs(ctime(&clock), stdout);
if (fflush(stdout) == EOF) {
syslog(LOG_ERR, "%s: %s", argv[1], strerror(errno));
exit(1);
}
sleep(1);
}
}
|
import posix
import os
import sys
pid = posix.fork()
if pid != 0:
print("Child process detached with pid %s" % pid)
sys.exit(0)
old_stdin = sys.stdin
old_stdout = sys.stdout
old_stderr = sys.stderr
sys.stdin = open('/dev/null', 'rt')
sys.stdout = open('/tmp/dmn.log', 'wt')
sys.stderr = sys.stdout
old_stdin.close()
old_stdout.close()
old_stderr.close()
posix.setsid()
import time
t = time.time()
while time.time() < t + 10:
print("timer running, %s seconds" % str(time.time() - t))
time.sleep(1)
|
Change the programming language of this snippet from C to Python without modifying what it does. |
#include <stdio.h>
int Gcd(int v1, int v2)
{
int a, b, r;
if (v1 < v2)
{
a = v2;
b = v1;
}
else
{
a = v1;
b = v2;
}
do
{
r = a % b;
if (r == 0)
{
break;
}
else
{
a = b;
b = r;
}
} while (1 == 1);
return b;
}
int NotInList(int num, int numtrip, int *tripletslist)
{
for (int i = 0; i < numtrip; i++)
{
if (num == tripletslist[i])
{
return 0;
}
}
return 1;
}
int main()
{
int coprime[50];
int gcd1, gcd2;
int ntrip = 2;
int n = 3;
coprime[0] = 1;
coprime[1] = 2;
while ( n < 50)
{
gcd1 = Gcd(n, coprime[ntrip-1]);
gcd2 = Gcd(n, coprime[ntrip-2]);
if (gcd1 == 1 && gcd2 == 1 && NotInList(n, ntrip, coprime))
{
coprime[ntrip++] = n;
n = 3;
}
else
{
n++;
}
}
printf("\n");
for (int i = 0; i < ntrip; i++)
{
printf("%2d ", coprime[i]);
if ((i+1) % 10 == 0)
{
printf("\n");
}
}
printf("\n\nNumber of elements in coprime triplets: %d\n\n", ntrip);
return 0;
}
|
def Gcd(v1, v2):
a, b = v1, v2
if (a < b):
a, b = v2, v1
r = 1
while (r != 0):
r = a % b
if (r != 0):
a = b
b = r
return b
a = [1, 2]
n = 3
while (n < 50):
gcd1 = Gcd(n, a[-1])
gcd2 = Gcd(n, a[-2])
if (gcd1 == 1 and gcd2 == 1 and not(n in a)):
a.append(n)
n = 3
else:
n += 1
for i in range(0, len(a)):
if (i % 10 == 0):
print('')
print("%4d" % a[i], end = '');
print("\n\nNumber of elements in coprime triplets = " + str(len(a)), end = "\n")
|
Preserve the algorithm and functionality while converting the code from C to Python. |
#include <stdio.h>
int Gcd(int v1, int v2)
{
int a, b, r;
if (v1 < v2)
{
a = v2;
b = v1;
}
else
{
a = v1;
b = v2;
}
do
{
r = a % b;
if (r == 0)
{
break;
}
else
{
a = b;
b = r;
}
} while (1 == 1);
return b;
}
int NotInList(int num, int numtrip, int *tripletslist)
{
for (int i = 0; i < numtrip; i++)
{
if (num == tripletslist[i])
{
return 0;
}
}
return 1;
}
int main()
{
int coprime[50];
int gcd1, gcd2;
int ntrip = 2;
int n = 3;
coprime[0] = 1;
coprime[1] = 2;
while ( n < 50)
{
gcd1 = Gcd(n, coprime[ntrip-1]);
gcd2 = Gcd(n, coprime[ntrip-2]);
if (gcd1 == 1 && gcd2 == 1 && NotInList(n, ntrip, coprime))
{
coprime[ntrip++] = n;
n = 3;
}
else
{
n++;
}
}
printf("\n");
for (int i = 0; i < ntrip; i++)
{
printf("%2d ", coprime[i]);
if ((i+1) % 10 == 0)
{
printf("\n");
}
}
printf("\n\nNumber of elements in coprime triplets: %d\n\n", ntrip);
return 0;
}
|
def Gcd(v1, v2):
a, b = v1, v2
if (a < b):
a, b = v2, v1
r = 1
while (r != 0):
r = a % b
if (r != 0):
a = b
b = r
return b
a = [1, 2]
n = 3
while (n < 50):
gcd1 = Gcd(n, a[-1])
gcd2 = Gcd(n, a[-2])
if (gcd1 == 1 and gcd2 == 1 and not(n in a)):
a.append(n)
n = 3
else:
n += 1
for i in range(0, len(a)):
if (i % 10 == 0):
print('')
print("%4d" % a[i], end = '');
print("\n\nNumber of elements in coprime triplets = " + str(len(a)), end = "\n")
|
Produce a functionally identical Python code for the snippet given in C. |
#include <stdio.h>
int Gcd(int v1, int v2)
{
int a, b, r;
if (v1 < v2)
{
a = v2;
b = v1;
}
else
{
a = v1;
b = v2;
}
do
{
r = a % b;
if (r == 0)
{
break;
}
else
{
a = b;
b = r;
}
} while (1 == 1);
return b;
}
int NotInList(int num, int numtrip, int *tripletslist)
{
for (int i = 0; i < numtrip; i++)
{
if (num == tripletslist[i])
{
return 0;
}
}
return 1;
}
int main()
{
int coprime[50];
int gcd1, gcd2;
int ntrip = 2;
int n = 3;
coprime[0] = 1;
coprime[1] = 2;
while ( n < 50)
{
gcd1 = Gcd(n, coprime[ntrip-1]);
gcd2 = Gcd(n, coprime[ntrip-2]);
if (gcd1 == 1 && gcd2 == 1 && NotInList(n, ntrip, coprime))
{
coprime[ntrip++] = n;
n = 3;
}
else
{
n++;
}
}
printf("\n");
for (int i = 0; i < ntrip; i++)
{
printf("%2d ", coprime[i]);
if ((i+1) % 10 == 0)
{
printf("\n");
}
}
printf("\n\nNumber of elements in coprime triplets: %d\n\n", ntrip);
return 0;
}
|
def Gcd(v1, v2):
a, b = v1, v2
if (a < b):
a, b = v2, v1
r = 1
while (r != 0):
r = a % b
if (r != 0):
a = b
b = r
return b
a = [1, 2]
n = 3
while (n < 50):
gcd1 = Gcd(n, a[-1])
gcd2 = Gcd(n, a[-2])
if (gcd1 == 1 and gcd2 == 1 and not(n in a)):
a.append(n)
n = 3
else:
n += 1
for i in range(0, len(a)):
if (i % 10 == 0):
print('')
print("%4d" % a[i], end = '');
print("\n\nNumber of elements in coprime triplets = " + str(len(a)), end = "\n")
|
Convert this C snippet to Python and keep its semantics consistent. | #include <stdio.h>
int main() {
int i, gprev = 0;
int s[7] = {1, 2, 2, 3, 4, 4, 5};
for (i = 0; i < 7; ++i) {
int curr = s[i];
int prev = 0;
if (i > 0 && curr == prev) printf("%d\n", i);
prev = curr;
}
for (i = 0; i < 7; ++i) {
int curr = s[i];
if (i > 0 && curr == gprev) printf("%d\n", i);
gprev = curr;
}
return 0;
}
| s = [1, 2, 2, 3, 4, 4, 5]
for i in range(len(s)):
curr = s[i]
if i > 0 and curr == prev:
print(i)
prev = curr
|
Write the same algorithm in Python as shown in this C implementation. | #include <curl/curl.h>
#include <string.h>
#include <stdio.h>
size_t write_data(void *ptr, size_t size, size_t nmeb, void *stream){
return fwrite(ptr,size,nmeb,stream);
}
size_t read_data(void *ptr, size_t size, size_t nmeb, void *stream){
return fread(ptr,size,nmeb,stream);
}
void callSOAP(char* URL, char * inFile, char * outFile) {
FILE * rfp = fopen(inFile, "r");
if(!rfp)
perror("Read File Open:");
FILE * wfp = fopen(outFile, "w+");
if(!wfp)
perror("Write File Open:");
struct curl_slist *header = NULL;
header = curl_slist_append (header, "Content-Type:text/xml");
header = curl_slist_append (header, "SOAPAction: rsc");
header = curl_slist_append (header, "Transfer-Encoding: chunked");
header = curl_slist_append (header, "Expect:");
CURL *curl;
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, URL);
curl_easy_setopt(curl, CURLOPT_POST, 1L);
curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_data);
curl_easy_setopt(curl, CURLOPT_READDATA, rfp);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, wfp);
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, header);
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE_LARGE, (curl_off_t)-1);
curl_easy_setopt(curl, CURLOPT_VERBOSE,1L);
curl_easy_perform(curl);
curl_easy_cleanup(curl);
}
}
int main(int argC,char* argV[])
{
if(argC!=4)
printf("Usage : %s <URL of WSDL> <Input file path> <Output File Path>",argV[0]);
else
callSOAP(argV[1],argV[2],argV[3]);
return 0;
}
| from SOAPpy import WSDL
proxy = WSDL.Proxy("http://example.com/soap/wsdl")
result = proxy.soapFunc("hello")
result = proxy.anotherSoapFunc(34234)
|
Translate this program into Python but keep the logic exactly as in C. | #include <curl/curl.h>
#include <string.h>
#include <stdio.h>
size_t write_data(void *ptr, size_t size, size_t nmeb, void *stream){
return fwrite(ptr,size,nmeb,stream);
}
size_t read_data(void *ptr, size_t size, size_t nmeb, void *stream){
return fread(ptr,size,nmeb,stream);
}
void callSOAP(char* URL, char * inFile, char * outFile) {
FILE * rfp = fopen(inFile, "r");
if(!rfp)
perror("Read File Open:");
FILE * wfp = fopen(outFile, "w+");
if(!wfp)
perror("Write File Open:");
struct curl_slist *header = NULL;
header = curl_slist_append (header, "Content-Type:text/xml");
header = curl_slist_append (header, "SOAPAction: rsc");
header = curl_slist_append (header, "Transfer-Encoding: chunked");
header = curl_slist_append (header, "Expect:");
CURL *curl;
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, URL);
curl_easy_setopt(curl, CURLOPT_POST, 1L);
curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_data);
curl_easy_setopt(curl, CURLOPT_READDATA, rfp);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, wfp);
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, header);
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE_LARGE, (curl_off_t)-1);
curl_easy_setopt(curl, CURLOPT_VERBOSE,1L);
curl_easy_perform(curl);
curl_easy_cleanup(curl);
}
}
int main(int argC,char* argV[])
{
if(argC!=4)
printf("Usage : %s <URL of WSDL> <Input file path> <Output File Path>",argV[0]);
else
callSOAP(argV[1],argV[2],argV[3]);
return 0;
}
| from SOAPpy import WSDL
proxy = WSDL.Proxy("http://example.com/soap/wsdl")
result = proxy.soapFunc("hello")
result = proxy.anotherSoapFunc(34234)
|
Change the programming language of this snippet from C to Python without modifying what it does. |
#include<stdio.h>
#define Hi printf("Hi There.");
#define start int main(){
#define end return 0;}
start
Hi
#warning "Don't you have anything better to do ?"
#ifdef __unix__
#warning "What are you doing still working on Unix ?"
printf("\nThis is an Unix system.");
#elif _WIN32
#warning "You couldn't afford a 64 bit ?"
printf("\nThis is a 32 bit Windows system.");
#elif _WIN64
#warning "You couldn't afford an Apple ?"
printf("\nThis is a 64 bit Windows system.");
#endif
end
| Python 3.2 (r32:88445, Feb 20 2011, 21:30:00) [MSC v.1500 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import __future__
>>> __future__.all_feature_names
['nested_scopes', 'generators', 'division', 'absolute_import', 'with_statement', 'print_function', 'unicode_literals', 'barry_as_FLUFL']
>>>
|
Maintain the same structure and functionality when rewriting this code in Python. | #include <stdio.h>
#include <stdint.h>
uint32_t msb32(uint32_t n)
{
uint32_t b = 1;
if (!n) return 0;
#define step(x) if (n >= ((uint32_t)1) << x) b <<= x, n >>= x
step(16); step(8); step(4); step(2); step(1);
#undef step
return b;
}
int msb32_idx(uint32_t n)
{
int b = 0;
if (!n) return -1;
#define step(x) if (n >= ((uint32_t)1) << x) b += x, n >>= x
step(16); step(8); step(4); step(2); step(1);
#undef step
return b;
}
#define lsb32(n) ( (uint32_t)(n) & -(int32_t)(n) )
inline int lsb32_idx(uint32_t n) { return msb32_idx(lsb32(n)); }
int main()
{
int32_t n;
int i;
for (i = 0, n = 1; ; i++, n *= 42) {
printf("42**%d = %10d(x%08x): M x%08x(%2d) L x%03x(%2d)\n",
i, n, n,
msb32(n), msb32_idx(n),
lsb32(n), lsb32_idx(n));
if (n >= INT32_MAX / 42) break;
}
return 0;
}
| def msb(x):
return x.bit_length() - 1
def lsb(x):
return msb(x & -x)
for i in range(6):
x = 42 ** i
print("%10d MSB: %2d LSB: %2d" % (x, msb(x), lsb(x)))
for i in range(6):
x = 1302 ** i
print("%20d MSB: %2d LSB: %2d" % (x, msb(x), lsb(x)))
|
Maintain the same structure and functionality when rewriting this code in Python. | #include <stdio.h>
#include <stdint.h>
uint32_t msb32(uint32_t n)
{
uint32_t b = 1;
if (!n) return 0;
#define step(x) if (n >= ((uint32_t)1) << x) b <<= x, n >>= x
step(16); step(8); step(4); step(2); step(1);
#undef step
return b;
}
int msb32_idx(uint32_t n)
{
int b = 0;
if (!n) return -1;
#define step(x) if (n >= ((uint32_t)1) << x) b += x, n >>= x
step(16); step(8); step(4); step(2); step(1);
#undef step
return b;
}
#define lsb32(n) ( (uint32_t)(n) & -(int32_t)(n) )
inline int lsb32_idx(uint32_t n) { return msb32_idx(lsb32(n)); }
int main()
{
int32_t n;
int i;
for (i = 0, n = 1; ; i++, n *= 42) {
printf("42**%d = %10d(x%08x): M x%08x(%2d) L x%03x(%2d)\n",
i, n, n,
msb32(n), msb32_idx(n),
lsb32(n), lsb32_idx(n));
if (n >= INT32_MAX / 42) break;
}
return 0;
}
| def msb(x):
return x.bit_length() - 1
def lsb(x):
return msb(x & -x)
for i in range(6):
x = 42 ** i
print("%10d MSB: %2d LSB: %2d" % (x, msb(x), lsb(x)))
for i in range(6):
x = 1302 ** i
print("%20d MSB: %2d LSB: %2d" % (x, msb(x), lsb(x)))
|
Preserve the algorithm and functionality while converting the code from C to Python. | #include <stdio.h>
int riseEqFall(int num) {
int rdigit = num % 10;
int netHeight = 0;
while (num /= 10) {
netHeight += ((num % 10) > rdigit) - ((num % 10) < rdigit);
rdigit = num % 10;
}
return netHeight == 0;
}
int nextNum() {
static int num = 0;
do {num++;} while (!riseEqFall(num));
return num;
}
int main(void) {
int total, num;
printf("The first 200 numbers are: \n");
for (total = 0; total < 200; total++)
printf("%d ", nextNum());
printf("\n\nThe 10,000,000th number is: ");
for (; total < 10000000; total++) num = nextNum();
printf("%d\n", num);
return 0;
}
| import itertools
def riseEqFall(num):
height = 0
d1 = num % 10
num //= 10
while num:
d2 = num % 10
height += (d1<d2) - (d1>d2)
d1 = d2
num //= 10
return height == 0
def sequence(start, fn):
num=start-1
while True:
num += 1
while not fn(num): num += 1
yield num
a296712 = sequence(1, riseEqFall)
print("The first 200 numbers are:")
print(*itertools.islice(a296712, 200))
print("The 10,000,000th number is:")
print(*itertools.islice(a296712, 10000000-200-1, 10000000-200))
|
Transform the following C implementation into Python, maintaining the same output and logic. | #include<conio.h>
#include<dos.h>
char *strings[] = {"The cursor will move one position to the left",
"The cursor will move one position to the right",
"The cursor will move vetically up one line",
"The cursor will move vertically down one line",
"The cursor will move to the beginning of the line",
"The cursor will move to the end of the line",
"The cursor will move to the top left corner of the screen",
"The cursor will move to the bottom right corner of the screen"};
int main()
{
int i,j,MAXROW,MAXCOL;
struct text_info tInfo;
gettextinfo(&tInfo);
MAXROW = tInfo.screenheight;
MAXCOL = tInfo.screenwidth;
clrscr();
cprintf("This is a demonstration of cursor control using gotoxy(). Press any key to continue.");
getch();
for(i=0;i<8;i++)
{
clrscr();
gotoxy(5,MAXROW/2);
cprintf("%s",strings[i]);
getch();
switch(i){
case 0:gotoxy(wherex()-1,wherey());
break;
case 1:gotoxy(wherex()+1,wherey());
break;
case 2:gotoxy(wherex(),wherey()-1);
break;
case 3:gotoxy(wherex(),wherey()+1);
break;
case 4:for(j=0;j<strlen(strings[i]);j++){
gotoxy(wherex()-1,wherey());
delay(100);
}
break;
case 5:gotoxy(wherex()-strlen(strings[i]),wherey());
for(j=0;j<strlen(strings[i]);j++){
gotoxy(wherex()+1,wherey());
delay(100);
}
break;
case 6:while(wherex()!=1)
{
gotoxy(wherex()-1,wherey());
delay(100);
}
while(wherey()!=1)
{
gotoxy(wherex(),wherey()-1);
delay(100);
}
break;
case 7:while(wherex()!=MAXCOL)
{
gotoxy(wherex()+1,wherey());
delay(100);
}
while(wherey()!=MAXROW)
{
gotoxy(wherex(),wherey()+1);
delay(100);
}
break;
};
getch();
}
clrscr();
cprintf("End of demonstration.");
getch();
return 0;
}
| import curses
scr = curses.initscr()
def move_left():
y,x = curses.getyx()
curses.move(y,x-1)
def move_right():
y,x = curses.getyx()
curses.move(y,x+1)
def move_up():
y,x = curses.getyx()
curses.move(y-1,x)
def move_down():
y,x = curses.getyx()
curses.move(y+1,x)
def move_line_home()
y,x = curses.getyx()
curses.move(y,0)
def move_line_end()
y,x = curses.getyx()
maxy,maxx = scr.getmaxyx()
curses.move(y,maxx)
def move_page_home():
curses.move(0,0)
def move_page_end():
y,x = scr.getmaxyx()
curses.move(y,x)
|
Ensure the translated Python code behaves exactly like the original C snippet. | #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 main( void ) {
int p;
long int s = 2;
for(p=3;p<2000000;p+=2) {
if(isprime(p)) s+=p;
}
printf( "%ld\n", s );
return 0;
}
|
def isPrime(n):
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
if __name__ == '__main__':
suma = 2
n = 1
for i in range(3, 2000000, 2):
if isPrime(i):
suma += i
n+=1
print(suma)
|
Port the provided C code into Python while preserving the original functionality. | #include<graphics.h>
#include<stdlib.h>
#include<stdio.h>
#include<math.h>
#define pi M_PI
typedef struct{
double x,y;
}point;
void kochCurve(point p1,point p2,int times){
point p3,p4,p5;
double theta = pi/3;
if(times>0){
p3 = (point){(2*p1.x+p2.x)/3,(2*p1.y+p2.y)/3};
p5 = (point){(2*p2.x+p1.x)/3,(2*p2.y+p1.y)/3};
p4 = (point){p3.x + (p5.x - p3.x)*cos(theta) + (p5.y - p3.y)*sin(theta),p3.y - (p5.x - p3.x)*sin(theta) + (p5.y - p3.y)*cos(theta)};
kochCurve(p1,p3,times-1);
kochCurve(p3,p4,times-1);
kochCurve(p4,p5,times-1);
kochCurve(p5,p2,times-1);
}
else{
line(p1.x,p1.y,p2.x,p2.y);
}
}
int main(int argC, char** argV)
{
int w,h,r;
point p1,p2;
if(argC!=4){
printf("Usage : %s <window width> <window height> <recursion level>",argV[0]);
}
else{
w = atoi(argV[1]);
h = atoi(argV[2]);
r = atoi(argV[3]);
initwindow(w,h,"Koch Curve");
p1 = (point){10,h-10};
p2 = (point){w-10,h-10};
kochCurve(p1,p2,r);
getch();
closegraph();
}
return 0;
}
| l = 300
def setup():
size(400, 400)
background(0, 0, 255)
stroke(255)
translate(width / 2.0, height / 2.0)
translate(-l / 2.0, l * sqrt(3) / 6.0)
for i in range(4):
kcurve(0, l)
rotate(radians(120))
translate(-l, 0)
def kcurve(x1, x2):
s = (x2 - x1) / 3.0
if s < 5:
pushMatrix()
translate(x1, 0)
line(0, 0, s, 0)
line(2 * s, 0, 3 * s, 0)
translate(s, 0)
rotate(radians(60))
line(0, 0, s, 0)
translate(s, 0)
rotate(radians(-120))
line(0, 0, s, 0)
popMatrix()
return
pushMatrix()
translate(x1, 0)
kcurve(0, s)
kcurve(2 * s, 3 * s)
translate(s, 0)
rotate(radians(60))
kcurve(0, s)
translate(s, 0)
rotate(radians(-120))
kcurve(0, s)
popMatrix()
|
Translate this program into Python but keep the logic exactly as in C. | #include<graphics.h>
#include<stdlib.h>
#include<time.h>
int main()
{
srand(time(NULL));
initwindow(640,480,"Yellow Random Pixel");
putpixel(rand()%640,rand()%480,YELLOW);
getch();
return 0;
}
| import Tkinter,random
def draw_pixel_2 ( sizex=640,sizey=480 ):
pos = random.randint( 0,sizex-1 ),random.randint( 0,sizey-1 )
root = Tkinter.Tk()
can = Tkinter.Canvas( root,width=sizex,height=sizey,bg='black' )
can.create_rectangle( pos*2,outline='yellow' )
can.pack()
root.title('press ESCAPE to quit')
root.bind('<Escape>',lambda e : root.quit())
root.mainloop()
draw_pixel_2()
|
Convert the following code from C to Python, ensuring the logic remains intact. |
#include <stdio.h>
char vowels[] = {'a','e','i','o','u','\n'};
int len(char * str) {
int i = 0;
while (str[i] != '\n') i++;
return i;
}
int isvowel(char c){
int b = 0;
int v = len(vowels);
for(int i = 0; i < v;i++) {
if(c == vowels[i]) {
b = 1;
break;
}
}
return b;
}
int isletter(char c){
return ((c >= 'a') && (c <= 'z') || (c >= 'A') && (c <= 'Z'));
}
int isconsonant(char c){
return isletter(c) && !isvowel(c);
}
int cVowels(char * str) {
int i = 0;
int count = 0;
while (str[i] != '\n') {
if (isvowel(str[i])) {
count++;;
}
i++;
}
return count;
}
int cConsonants(char * str ) {
int i = 0;
int count = 0;
while (str[i] != '\n') {
if (isconsonant(str[i])) {
count++;
}
i++;
}
return count;
}
int main() {
char buff[] = "This is 1 string\n";
printf("%4d, %4d, %4d, %s\n", cVowels(buff), cConsonants(buff), len(buff), buff);
char buff2[] = "This is a second string\n";
printf("%4d, %4d, %4d, %s\n", cVowels(buff2), cConsonants(buff2), len(buff2), buff2);
printf("a: %d\n", isvowel('a'));
printf("b: %d\n", isvowel('b'));
printf("Z: %d\n", isconsonant('Z'));
printf("1: %d\n", isletter('1'));
}
| def isvowel(c):
return c in ['a', 'e', 'i', 'o', 'u', 'A', 'E', "I", 'O', 'U']
def isletter(c):
return 'a' <= c <= 'z' or 'A' <= c <= 'Z'
def isconsonant(c):
return not isvowel(c) and isletter(c)
def vccounts(s):
a = list(s.lower())
au = set(a)
return sum([isvowel(c) for c in a]), sum([isconsonant(c) for c in a]), \
sum([isvowel(c) for c in au]), sum([isconsonant(c) for c in au])
def testvccount():
teststrings = [
"Forever Python programming language",
"Now is the time for all good men to come to the aid of their country."]
for s in teststrings:
vcnt, ccnt, vu, cu = vccounts(s)
print(f"String: {s}\n Vowels: {vcnt} (distinct {vu})\n Consonants: {ccnt} (distinct {cu})\n")
testvccount()
|
Port the following code from C to Python with equivalent syntax and logic. |
#include <stdio.h>
char vowels[] = {'a','e','i','o','u','\n'};
int len(char * str) {
int i = 0;
while (str[i] != '\n') i++;
return i;
}
int isvowel(char c){
int b = 0;
int v = len(vowels);
for(int i = 0; i < v;i++) {
if(c == vowels[i]) {
b = 1;
break;
}
}
return b;
}
int isletter(char c){
return ((c >= 'a') && (c <= 'z') || (c >= 'A') && (c <= 'Z'));
}
int isconsonant(char c){
return isletter(c) && !isvowel(c);
}
int cVowels(char * str) {
int i = 0;
int count = 0;
while (str[i] != '\n') {
if (isvowel(str[i])) {
count++;;
}
i++;
}
return count;
}
int cConsonants(char * str ) {
int i = 0;
int count = 0;
while (str[i] != '\n') {
if (isconsonant(str[i])) {
count++;
}
i++;
}
return count;
}
int main() {
char buff[] = "This is 1 string\n";
printf("%4d, %4d, %4d, %s\n", cVowels(buff), cConsonants(buff), len(buff), buff);
char buff2[] = "This is a second string\n";
printf("%4d, %4d, %4d, %s\n", cVowels(buff2), cConsonants(buff2), len(buff2), buff2);
printf("a: %d\n", isvowel('a'));
printf("b: %d\n", isvowel('b'));
printf("Z: %d\n", isconsonant('Z'));
printf("1: %d\n", isletter('1'));
}
| def isvowel(c):
return c in ['a', 'e', 'i', 'o', 'u', 'A', 'E', "I", 'O', 'U']
def isletter(c):
return 'a' <= c <= 'z' or 'A' <= c <= 'Z'
def isconsonant(c):
return not isvowel(c) and isletter(c)
def vccounts(s):
a = list(s.lower())
au = set(a)
return sum([isvowel(c) for c in a]), sum([isconsonant(c) for c in a]), \
sum([isvowel(c) for c in au]), sum([isconsonant(c) for c in au])
def testvccount():
teststrings = [
"Forever Python programming language",
"Now is the time for all good men to come to the aid of their country."]
for s in teststrings:
vcnt, ccnt, vu, cu = vccounts(s)
print(f"String: {s}\n Vowels: {vcnt} (distinct {vu})\n Consonants: {ccnt} (distinct {cu})\n")
testvccount()
|
Change the following C code into Python without altering its purpose. | count = 1;
while (count < 10) {
print("count is: ", count, "\n");
count = count + 1;
}
| def expr(p)
if tok is "("
x = paren_expr()
elif tok in ["-", "+", "!"]
gettok()
y = expr(precedence of operator)
if operator was "+"
x = y
else
x = make_node(operator, y)
elif tok is an Identifier
x = make_leaf(Identifier, variable name)
gettok()
elif tok is an Integer constant
x = make_leaf(Integer, integer value)
gettok()
else
error()
while tok is a binary operator and precedence of tok >= p
save_tok = tok
gettok()
q = precedence of save_tok
if save_tok is not right associative
q += 1
x = make_node(Operator save_tok represents, x, expr(q))
return x
def paren_expr()
expect("(")
x = expr(0)
expect(")")
return x
def stmt()
t = NULL
if accept("if")
e = paren_expr()
s = stmt()
t = make_node(If, e, make_node(If, s, accept("else") ? stmt() : NULL))
elif accept("putc")
t = make_node(Prtc, paren_expr())
expect(";")
elif accept("print")
expect("(")
repeat
if tok is a string
e = make_node(Prts, make_leaf(String, the string))
gettok()
else
e = make_node(Prti, expr(0))
t = make_node(Sequence, t, e)
until not accept(",")
expect(")")
expect(";")
elif tok is ";"
gettok()
elif tok is an Identifier
v = make_leaf(Identifier, variable name)
gettok()
expect("=")
t = make_node(Assign, v, expr(0))
expect(";")
elif accept("while")
e = paren_expr()
t = make_node(While, e, stmt()
elif accept("{")
while tok not equal "}" and tok not equal end-of-file
t = make_node(Sequence, t, stmt())
expect("}")
elif tok is end-of-file
pass
else
error()
return t
def parse()
t = NULL
gettok()
repeat
t = make_node(Sequence, t, stmt())
until tok is end-of-file
return t
|
Transform the following C implementation into Python, maintaining the same output and logic. | count = 1;
while (count < 10) {
print("count is: ", count, "\n");
count = count + 1;
}
| def expr(p)
if tok is "("
x = paren_expr()
elif tok in ["-", "+", "!"]
gettok()
y = expr(precedence of operator)
if operator was "+"
x = y
else
x = make_node(operator, y)
elif tok is an Identifier
x = make_leaf(Identifier, variable name)
gettok()
elif tok is an Integer constant
x = make_leaf(Integer, integer value)
gettok()
else
error()
while tok is a binary operator and precedence of tok >= p
save_tok = tok
gettok()
q = precedence of save_tok
if save_tok is not right associative
q += 1
x = make_node(Operator save_tok represents, x, expr(q))
return x
def paren_expr()
expect("(")
x = expr(0)
expect(")")
return x
def stmt()
t = NULL
if accept("if")
e = paren_expr()
s = stmt()
t = make_node(If, e, make_node(If, s, accept("else") ? stmt() : NULL))
elif accept("putc")
t = make_node(Prtc, paren_expr())
expect(";")
elif accept("print")
expect("(")
repeat
if tok is a string
e = make_node(Prts, make_leaf(String, the string))
gettok()
else
e = make_node(Prti, expr(0))
t = make_node(Sequence, t, e)
until not accept(",")
expect(")")
expect(";")
elif tok is ";"
gettok()
elif tok is an Identifier
v = make_leaf(Identifier, variable name)
gettok()
expect("=")
t = make_node(Assign, v, expr(0))
expect(";")
elif accept("while")
e = paren_expr()
t = make_node(While, e, stmt()
elif accept("{")
while tok not equal "}" and tok not equal end-of-file
t = make_node(Sequence, t, stmt())
expect("}")
elif tok is end-of-file
pass
else
error()
return t
def parse()
t = NULL
gettok()
repeat
t = make_node(Sequence, t, stmt())
until tok is end-of-file
return t
|
Preserve the algorithm and functionality while converting the code from C to Python. | count = 1;
while (count < 10) {
print("count is: ", count, "\n");
count = count + 1;
}
| def expr(p)
if tok is "("
x = paren_expr()
elif tok in ["-", "+", "!"]
gettok()
y = expr(precedence of operator)
if operator was "+"
x = y
else
x = make_node(operator, y)
elif tok is an Identifier
x = make_leaf(Identifier, variable name)
gettok()
elif tok is an Integer constant
x = make_leaf(Integer, integer value)
gettok()
else
error()
while tok is a binary operator and precedence of tok >= p
save_tok = tok
gettok()
q = precedence of save_tok
if save_tok is not right associative
q += 1
x = make_node(Operator save_tok represents, x, expr(q))
return x
def paren_expr()
expect("(")
x = expr(0)
expect(")")
return x
def stmt()
t = NULL
if accept("if")
e = paren_expr()
s = stmt()
t = make_node(If, e, make_node(If, s, accept("else") ? stmt() : NULL))
elif accept("putc")
t = make_node(Prtc, paren_expr())
expect(";")
elif accept("print")
expect("(")
repeat
if tok is a string
e = make_node(Prts, make_leaf(String, the string))
gettok()
else
e = make_node(Prti, expr(0))
t = make_node(Sequence, t, e)
until not accept(",")
expect(")")
expect(";")
elif tok is ";"
gettok()
elif tok is an Identifier
v = make_leaf(Identifier, variable name)
gettok()
expect("=")
t = make_node(Assign, v, expr(0))
expect(";")
elif accept("while")
e = paren_expr()
t = make_node(While, e, stmt()
elif accept("{")
while tok not equal "}" and tok not equal end-of-file
t = make_node(Sequence, t, stmt())
expect("}")
elif tok is end-of-file
pass
else
error()
return t
def parse()
t = NULL
gettok()
repeat
t = make_node(Sequence, t, stmt())
until tok is end-of-file
return t
|
Preserve the algorithm and functionality while converting the code from C to Python. | #include<graphics.h>
int main()
{
initwindow(320,240,"Red Pixel");
putpixel(100,100,RED);
getch();
return 0;
}
| from PIL import Image
img = Image.new('RGB', (320, 240))
pixels = img.load()
pixels[100,100] = (255,0,0)
img.show()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.