Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Convert this Python snippet to C and keep its semantics consistent.
import os from math import pi, sin au_header = bytearray( [46, 115, 110, 100, 0, 0, 0, 24, 255, 255, 255, 255, 0, 0, 0, 3, 0, 0, 172, 68, 0, 0, 0, 1]) def f(x, freq): "Compute sine wave as 16-bi...
#include <stdio.h> #include <math.h> #include <stdlib.h> int header[] = {46, 115, 110, 100, 0, 0, 0, 24, 255, 255, 255, 255, 0, 0, 0, 3, 0, 0, 172, 68, 0, 0, 0, 1}; int main(int argc, char *argv[]){ float freq, dur; long i, v; if (argc < 3) { p...
Rewrite this program in C while keeping its functionality equivalent to the Python version.
def load_ast() line = readline() line_list = tokenize the line, respecting double quotes text = line_list[0] if text == ";" return None node_type = text if len(line_list) > 1 return make_leaf(node_type, line_list[1]) left = load_ast() right = lo...
count = 1; while (count < 10) { print("count is: ", count, "\n"); count = count + 1; }
Rewrite the snippet below in C so it works the same as the original Python code.
def load_ast() line = readline() line_list = tokenize the line, respecting double quotes text = line_list[0] if text == ";" return None node_type = text if len(line_list) > 1 return make_leaf(node_type, line_list[1]) left = load_ast() right = lo...
count = 1; while (count < 10) { print("count is: ", count, "\n"); count = count + 1; }
Write a version of this Python function in C with identical behavior.
def load_ast() line = readline() line_list = tokenize the line, respecting double quotes text = line_list[0] if text == ";" return None node_type = text if len(line_list) > 1 return make_leaf(node_type, line_list[1]) left = load_ast() right = lo...
count = 1; while (count < 10) { print("count is: ", count, "\n"); count = count + 1; }
Produce a language-to-language conversion: from Python to C, same semantics.
def stern_brocot(predicate=lambda series: len(series) < 20): sb, i = [1, 1], 0 while predicate(sb): sb += [sum(sb[i:i + 2]), sb[i + 1]] i += 1 return sb if __name__ == '__main__': from fractions import gcd n_first = 15 print('The first %i values:\n ' % n_first, ...
k=2; i=1; j=2; while(k<nn); k++; sb[k]=sb[k-i]+sb[k-j]; k++; sb[k]=sb[k-j]; i++; j++; }
Write the same algorithm in C as shown in this Python implementation.
from collections import namedtuple import math class I(namedtuple('Imprecise', 'value, delta')): 'Imprecise type: I(value=0.0, delta=0.0)' __slots__ = () def __new__(_cls, value=0.0, delta=0.0): 'Defaults to 0.0 ± delta' return super().__new__(_cls, float(value), abs(float(delta))) ...
#include <stdlib.h> #include <string.h> #include <stdio.h> #include <math.h> typedef struct{ double value; double delta; }imprecise; #define SQR(x) ((x) * (x)) imprecise imprecise_add(imprecise a, imprecise b) { imprecise ret; ret.value = a.value + b.value; ret.delta = sqrt(SQR(a.delta) + SQR(b....
Translate this program into C but keep the logic exactly as in Python.
from itertools import groupby def soundex(word): codes = ("bfpv","cgjkqsxz", "dt", "l", "mn", "r") soundDict = dict((ch, str(ix+1)) for ix,cod in enumerate(codes) for ch in cod) cmap2 = lambda kar: soundDict.get(kar, '9') sdx = ''.join(cmap2(kar) for kar in word.lower()) sdx2 = word[0].upper() + ''.joi...
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> static char code[128] = { 0 }; void add_code(const char *s, int c) { while (*s) { code[(int)*s] = code[0x20 ^ (int)*s] = c; s++; } } void init() { static const char *cls[] = { "AEIOU", "", "BFPV", "CGJKQSXZ", "DT", "L", "MN", "R",...
Port the following code from Python to C with equivalent syntax and logic.
def bags(n,cache={}): if not n: return [(0, "")] upto = sum([bags(x) for x in range(n-1, 0, -1)], []) return [(c+1, '('+s+')') for c,s in bagchain((0, ""), n-1, upto)] def bagchain(x, n, bb, start=0): if not n: return [x] out = [] for i in range(start, len(bb)): c,s = bb[i] if c <= n: out += bagchain((x[0]...
#include <stdio.h> #include <stdlib.h> typedef unsigned int uint; typedef unsigned long long tree; #define B(x) (1ULL<<(x)) tree *list = 0; uint cap = 0, len = 0; uint offset[32] = {0, 1, 0}; void append(tree t) { if (len == cap) { cap = cap ? cap*2 : 2; list = realloc(list, cap*sizeof(tree)); } list[len++] =...
Convert the following code from Python to C, ensuring the logic remains intact.
class Doc(object): def method(self, num): pass
int add(int a, int b) { return a + b; }
Preserve the algorithm and functionality while converting the code from Python to C.
>>> import sqlite3 >>> conn = sqlite3.connect(':memory:') >>> c = conn.cursor() >>> c.execute() <sqlite3.Cursor object at 0x013263B0> >>> c.execute() <sqlite3.Cursor object at 0x013263B0> >>> for t in [('2006-03-28', 'BUY', 'IBM', 1000, 45.00), ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00), ('2006-0...
#include <sqlite3.h> #include <stdlib.h> #include <stdio.h> int main() { sqlite3 *db = NULL; char *errmsg; const char *code = "CREATE TABLE employee (\n" " empID INTEGER PRIMARY KEY AUTOINCREMENT,\n" " firstName TEXT NOT NULL,\n" " lastName TEXT NOT NULL,\n" " AGE INTEGER NOT NULL,\n" " DOB DATE...
Please provide an equivalent version of this Python code in C.
>>> import sqlite3 >>> conn = sqlite3.connect(':memory:') >>> c = conn.cursor() >>> c.execute() <sqlite3.Cursor object at 0x013263B0> >>> c.execute() <sqlite3.Cursor object at 0x013263B0> >>> for t in [('2006-03-28', 'BUY', 'IBM', 1000, 45.00), ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00), ('2006-0...
#include <sqlite3.h> #include <stdlib.h> #include <stdio.h> int main() { sqlite3 *db = NULL; char *errmsg; const char *code = "CREATE TABLE employee (\n" " empID INTEGER PRIMARY KEY AUTOINCREMENT,\n" " firstName TEXT NOT NULL,\n" " lastName TEXT NOT NULL,\n" " AGE INTEGER NOT NULL,\n" " DOB DATE...
Write the same algorithm in C as shown in this Python implementation.
from collections import namedtuple import math Circle = namedtuple('Circle', 'x, y, r') def solveApollonius(c1, c2, c3, s1, s2, s3): x1, y1, r1 = c1 x2, y2, r2 = c2 x3, y3, r3 = c3 v11 = 2*x2 - 2*x1 v12 = 2*y2 - 2*y1 v13 = x1*x1 - x2*x2 + y1*y1 - y2*y2 - r1*r1 + r2*r2 v14 = 2*s2*r2 ...
#include <stdio.h> #include <tgmath.h> #define VERBOSE 0 #define for3 for(int i = 0; i < 3; i++) typedef complex double vec; typedef struct { vec c; double r; } circ; #define re(x) creal(x) #define im(x) cimag(x) #define cp(x) re(x), im(x) #define CPLX "(%6.3f,%6.3f)" #define CPLX3 CPLX" "CPLX" "CPLX double cross(v...
Preserve the algorithm and functionality while converting the code from Python to C.
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9] list2 = [10, 11, 12, 13, 14, 15, 16, 17, 18] list3 = [19, 20, 21, 22, 23, 24, 25, 26, 27] print([ ''.join(str(n) for n in z) for z in zip(list1, list2, list3) ])
#include<stdio.h> #include<stdlib.h> int main(void) { int list[3][9], i; for(i=0;i<27;i++) list[i/9][i%9]=1+i; for(i=0;i<9;i++) printf( "%d%d%d ", list[0][i], list[1][i], list[2][i] ); return 0; }
Translate the given Python code snippet into C without altering its behavior.
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9] list2 = [10, 11, 12, 13, 14, 15, 16, 17, 18] list3 = [19, 20, 21, 22, 23, 24, 25, 26, 27] print([ ''.join(str(n) for n in z) for z in zip(list1, list2, list3) ])
#include<stdio.h> #include<stdlib.h> int main(void) { int list[3][9], i; for(i=0;i<27;i++) list[i/9][i%9]=1+i; for(i=0;i<9;i++) printf( "%d%d%d ", list[0][i], list[1][i], list[2][i] ); return 0; }
Maintain the same structure and functionality when rewriting this code in C.
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9] list2 = [10, 11, 12, 13, 14, 15, 16, 17, 18] list3 = [19, 20, 21, 22, 23, 24, 25, 26, 27] print([ ''.join(str(n) for n in z) for z in zip(list1, list2, list3) ])
#include<stdio.h> #include<stdlib.h> int main(void) { int list[3][9], i; for(i=0;i<27;i++) list[i/9][i%9]=1+i; for(i=0;i<9;i++) printf( "%d%d%d ", list[0][i], list[1][i], list[2][i] ); return 0; }
Maintain the same structure and functionality when rewriting this code in C.
from itertools import takewhile from functools import reduce def longestCommonSuffix(xs): def allSame(cs): h = cs[0] return all(h == c for c in cs[1:]) def firstCharPrepended(s, cs): return cs[0] + s return reduce( firstCharPrepended, takewhile( ...
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct node_t { char *elem; int length; struct node_t *next; } node; node *make_node(char *s) { node *t = malloc(sizeof(node)); t->elem = s; t->length = strlen(s); t->next = NULL; return t; } void append_node(node *hea...
Ensure the translated C code behaves exactly like the original Python snippet.
from itertools import takewhile from functools import reduce def longestCommonSuffix(xs): def allSame(cs): h = cs[0] return all(h == c for c in cs[1:]) def firstCharPrepended(s, cs): return cs[0] + s return reduce( firstCharPrepended, takewhile( ...
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct node_t { char *elem; int length; struct node_t *next; } node; node *make_node(char *s) { node *t = malloc(sizeof(node)); t->elem = s; t->length = strlen(s); t->next = NULL; return t; } void append_node(node *hea...
Port the provided Python code into C while preserving the original functionality.
import socket import thread import time HOST = "" PORT = 4004 def accept(conn): def threaded(): while True: conn.send("Please enter your name: ") try: name = conn.recv(1024).strip() except socket.error: continue if name...
#include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <sys/select.h> #include <netinet/in.h> #include <netinet/ip.h> int tsocket; struct sockaddr_in tsockinfo; fd_set status, current; void ClientText(int handle, char *buf, int buf_len); struct client { char buffer[4096]; int pos; char na...
Produce a functionally identical C code for the snippet given in Python.
classes = (str.isupper, str.islower, str.isalnum, str.isalpha, str.isdecimal, str.isdigit, str.isidentifier, str.isnumeric, str.isprintable, str.isspace, str.istitle) for stringclass in classes: chars = ''.join(chr(i) for i in range(0x10FFFF+1) if stringclass(chr(i))) print('\nString clas...
#include <stdio.h> int main(int argc, char const *argv[]) { for (char c = 0x41; c < 0x5b; c ++) putchar(c); putchar('\n'); for (char c = 0x61; c < 0x7b; c ++) putchar(c); putchar('\n'); return 0; }
Change the programming language of this snippet from Python to C without modifying what it does.
from numpy import array, tril, sum A = [[1,3,7,8,10], [2,4,16,14,4], [3,1,9,18,11], [12,14,17,18,20], [7,1,3,9,5]] print(sum(tril(A, -1)))
#include<stdlib.h> #include<stdio.h> typedef struct{ int rows,cols; int** dataSet; }matrix; matrix readMatrix(char* dataFile){ FILE* fp = fopen(dataFile,"r"); matrix rosetta; int i,j; fscanf(fp,"%d%d",&rosetta.rows,&rosetta.cols); rosetta.dataSet = (int**)malloc(rosetta.rows*sizeof(int*)); for(i=0;i<ros...
Produce a language-to-language conversion: from Python to C, same semantics.
import datetime import re import urllib.request import sys def get(url): with urllib.request.urlopen(url) as response: html = response.read().decode('utf-8') if re.match(r'<!Doctype HTML[\s\S]*<Title>URL Not Found</Title>', html): return None return html def main(): template = 'http://...
#include<curl/curl.h> #include<string.h> #include<stdio.h> #define MAX_LEN 1000 void searchChatLogs(char* searchString){ char* baseURL = "http: time_t t; struct tm* currentDate; char dateString[30],dateStringFile[30],lineData[MAX_LEN],targetURL[100]; int i,flag; FILE *fp; CURL *curl; CURLcode res; time(&...
Preserve the algorithm and functionality while converting the code from Python to C.
import requests URL = "http://rosettacode.org/mw/api.php" PARAMS = { "action": "query", "format": "json", "formatversion": 2, "generator": "categorymembers", "gcmtitle": "Category:Language users", "gcmlimit": 500, "prop": "categoryinfo", } def fetch_data(): counts = {} contin...
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <curl/curl.h> #include "wren.h" struct MemoryStruct { char *memory; size_t size; }; static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) { size_t realsize = size * nmemb; struct MemoryStruct *m...
Write the same algorithm in C as shown in this Python implementation.
import requests URL = "http://rosettacode.org/mw/api.php" PARAMS = { "action": "query", "format": "json", "formatversion": 2, "generator": "categorymembers", "gcmtitle": "Category:Language users", "gcmlimit": 500, "prop": "categoryinfo", } def fetch_data(): counts = {} contin...
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <curl/curl.h> #include "wren.h" struct MemoryStruct { char *memory; size_t size; }; static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) { size_t realsize = size * nmemb; struct MemoryStruct *m...
Translate this program into C but keep the logic exactly as in Python.
from math import sqrt from numpy import array from mpmath import mpf class AdditionChains: def __init__(self): self.chains, self.idx, self.pos = [[1]], 0, 0 self.pat, self.lvl = {1: 0}, [[1]] def add_chain(self): newchain = self.chains[self.idx].copy() ...
#include <stdio.h> #include "achain.c" typedef struct {double u, v;} cplx; inline cplx c_mul(cplx a, cplx b) { cplx c; c.u = a.u * b.u - a.v * b.v; c.v = a.u * b.v + a.v * b.u; return c; } cplx chain_expo(cplx x, int n) { int i, j, k, l, e[32]; cplx v[32]; l = seq(n, 0, e); puts("Exponents:"); for (i =...
Convert this Python snippet to C and keep its semantics consistent.
from math import sqrt from numpy import array from mpmath import mpf class AdditionChains: def __init__(self): self.chains, self.idx, self.pos = [[1]], 0, 0 self.pat, self.lvl = {1: 0}, [[1]] def add_chain(self): newchain = self.chains[self.idx].copy() ...
#include <stdio.h> #include "achain.c" typedef struct {double u, v;} cplx; inline cplx c_mul(cplx a, cplx b) { cplx c; c.u = a.u * b.u - a.v * b.v; c.v = a.u * b.v + a.v * b.u; return c; } cplx chain_expo(cplx x, int n) { int i, j, k, l, e[32]; cplx v[32]; l = seq(n, 0, e); puts("Exponents:"); for (i =...
Convert this Python block to C, preserving its control flow and logic.
import sys if "UTF-8" in sys.stdout.encoding: print("△") else: raise Exception("Terminal can't handle UTF-8")
#include<stdlib.h> #include<stdio.h> int main () { int i; char *str = getenv ("LANG"); for (i = 0; str[i + 2] != 00; i++) { if ((str[i] == 'u' && str[i + 1] == 't' && str[i + 2] == 'f') || (str[i] == 'U' && str[i + 1] == 'T' && str[i + 2] == 'F')) { printf ("Uni...
Port the following code from Python to C with equivalent syntax and logic.
import sys if "UTF-8" in sys.stdout.encoding: print("△") else: raise Exception("Terminal can't handle UTF-8")
#include<stdlib.h> #include<stdio.h> int main () { int i; char *str = getenv ("LANG"); for (i = 0; str[i + 2] != 00; i++) { if ((str[i] == 'u' && str[i + 1] == 't' && str[i + 2] == 'f') || (str[i] == 'U' && str[i + 1] == 'T' && str[i + 2] == 'F')) { printf ("Uni...
Generate an equivalent C version of this Python code.
import math print("working...") limit = 1000000 Primes = [] oldPrime = 0 newPrime = 0 x = 0 def isPrime(n): for i in range(2,int(n**0.5)+1): if n%i==0: return False return True def issquare(x): for n in range(x): if (x == n*n): return 1 return 0 for n in range(limit): if isPrim...
#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)); r...
Convert this Python snippet to C and keep its semantics consistent.
import math print("working...") limit = 1000000 Primes = [] oldPrime = 0 newPrime = 0 x = 0 def isPrime(n): for i in range(2,int(n**0.5)+1): if n%i==0: return False return True def issquare(x): for n in range(x): if (x == n*n): return 1 return 0 for n in range(limit): if isPrim...
#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)); r...
Translate the given Python code snippet into C without altering its behavior.
def truncate_file(name, length): if not os.path.isfile(name): return False if length >= os.path.getsize(name): return False with open(name, 'ab') as f: f.truncate(length) return True
#include <windows.h> #include <stdio.h> #include <wchar.h> void oops(const wchar_t *message) { wchar_t *buf; DWORD error; buf = NULL; error = GetLastError(); FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, error, 0, (wchar_t *)&buf, 0, ...
Write a version of this Python function in C with identical behavior.
def truncate_file(name, length): if not os.path.isfile(name): return False if length >= os.path.getsize(name): return False with open(name, 'ab') as f: f.truncate(length) return True
#include <windows.h> #include <stdio.h> #include <wchar.h> void oops(const wchar_t *message) { wchar_t *buf; DWORD error; buf = NULL; error = GetLastError(); FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, error, 0, (wchar_t *)&buf, 0, ...
Change the following Python code into C without altering its purpose.
def truncate_file(name, length): if not os.path.isfile(name): return False if length >= os.path.getsize(name): return False with open(name, 'ab') as f: f.truncate(length) return True
#include <windows.h> #include <stdio.h> #include <wchar.h> void oops(const wchar_t *message) { wchar_t *buf; DWORD error; buf = NULL; error = GetLastError(); FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, error, 0, (wchar_t *)&buf, 0, ...
Convert this Python block to C, preserving its control flow and logic.
import win32api import win32con import pywintypes devmode=pywintypes.DEVMODEType() devmode.PelsWidth=640 devmode.PelsHeight=480 devmode.Fields=win32con.DM_PELSWIDTH | win32con.DM_PELSHEIGHT win32api.ChangeDisplaySettings(devmode,0)
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include "wren.h" void C_xrandr(WrenVM* vm) { const char *arg = wrenGetSlotString(vm, 1); char command[strlen(arg) + 8]; strcpy(command, "xrandr "); strcat(command, arg); system(command); } void C_usleep(WrenVM* vm...
Generate an equivalent C version of this Python code.
import win32api import win32con import pywintypes devmode=pywintypes.DEVMODEType() devmode.PelsWidth=640 devmode.PelsHeight=480 devmode.Fields=win32con.DM_PELSWIDTH | win32con.DM_PELSHEIGHT win32api.ChangeDisplaySettings(devmode,0)
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include "wren.h" void C_xrandr(WrenVM* vm) { const char *arg = wrenGetSlotString(vm, 1); char command[strlen(arg) + 8]; strcpy(command, "xrandr "); strcat(command, arg); system(command); } void C_usleep(WrenVM* vm...
Convert this Python snippet to C and keep its semantics consistent.
def flush_input(): try: import msvcrt while msvcrt.kbhit(): msvcrt.getch() except ImportError: import sys, termios termios.tcflush(sys.stdin, termios.TCIOFLUSH)
#include <stdio.h> #include <stdlib.h> int main(int argc, char* argv[]) { char text[256]; getchar(); fseek(stdin, 0, SEEK_END); fgets(text, sizeof(text), stdin); puts(text); return EXIT_SUCCESS; }
Generate a C translation of this Python snippet without changing its computational steps.
import math import collections triple = collections.namedtuple('triple', 'm fm simp') def _quad_simpsons_mem(f: callable, a: float , fa: float, b: float, fb: float)->tuple: m = a + (b - a) / 2 fm = f(m) simp = abs(b - a) / 6 * (fa + 4*fm + fb) return triple(m, fm, simp,) def _quad_asr(f: ca...
#include <stdio.h> #include <math.h> typedef struct { double m; double fm; double simp; } triple; triple _quad_simpsons_mem(double (*f)(double), double a, double fa, double b, double fb) { double m = (a + b) / 2; double fm = f(m); double simp = fabs(b - a) / 6 * (fa + 4*fm + fb); triple t = {m, ...
Generate a C translation of this Python snippet without changing its computational steps.
import math import collections triple = collections.namedtuple('triple', 'm fm simp') def _quad_simpsons_mem(f: callable, a: float , fa: float, b: float, fb: float)->tuple: m = a + (b - a) / 2 fm = f(m) simp = abs(b - a) / 6 * (fa + 4*fm + fb) return triple(m, fm, simp,) def _quad_asr(f: ca...
#include <stdio.h> #include <math.h> typedef struct { double m; double fm; double simp; } triple; triple _quad_simpsons_mem(double (*f)(double), double a, double fa, double b, double fb) { double m = (a + b) / 2; double fm = f(m); double simp = fabs(b - a) / 6 * (fa + 4*fm + fb); triple t = {m, ...
Rewrite the snippet below in C so it works the same as the original Python code.
import io FASTA= infile = io.StringIO(FASTA) def fasta_parse(infile): key = '' for line in infile: if line.startswith('>'): if key: yield key, val key, val = line[1:].rstrip().split()[0], '' elif key: val += line.rstrip() if key: ...
#include <stdio.h> #include <stdlib.h> #include <string.h> void main() { FILE * fp; char * line = NULL; size_t len = 0; ssize_t read; fp = fopen("fasta.txt", "r"); if (fp == NULL) exit(EXIT_FAILURE); int state = 0; while ((read = getline(&line, &len, fp)) != -1) { if (line[read - 1] == '\n') line[r...
Rewrite the snippet below in C so it works the same as the original Python code.
from itertools import chain, takewhile def cousinPrimes(): def go(x): n = 4 + x return [(x, n)] if isPrime(n) else [] return chain.from_iterable( map(go, primes()) ) def main(): pairs = list( takewhile( lambda ab: 1000 > ab[1], ...
#include <stdio.h> #include <string.h> #define LIMIT 1000 void sieve(int max, char *s) { int p, k; memset(s, 0, max); for (p=2; p*p<=max; p++) if (!s[p]) for (k=p*p; k<=max; k+=p) s[k]=1; } int main(void) { char primes[LIMIT+1]; int p, count=0; sieve...
Convert this Python snippet to C and keep its semantics consistent.
from itertools import chain, takewhile def cousinPrimes(): def go(x): n = 4 + x return [(x, n)] if isPrime(n) else [] return chain.from_iterable( map(go, primes()) ) def main(): pairs = list( takewhile( lambda ab: 1000 > ab[1], ...
#include <stdio.h> #include <string.h> #define LIMIT 1000 void sieve(int max, char *s) { int p, k; memset(s, 0, max); for (p=2; p*p<=max; p++) if (!s[p]) for (k=p*p; k<=max; k+=p) s[k]=1; } int main(void) { char primes[LIMIT+1]; int p, count=0; sieve...
Convert this Python block to C, preserving its control flow and logic.
from itertools import islice digits = "0123456789abcdefghijklmnopqrstuvwxyz" def baseN(num,b): if num == 0: return "0" result = "" while num != 0: num, d = divmod(num, b) result += digits[d] return result[::-1] def pal2(num): if num == 0 or num == 1: return True based = bin(num)[2:] retu...
#include <stdio.h> typedef unsigned long long xint; int is_palin2(xint n) { xint x = 0; if (!(n&1)) return !n; while (x < n) x = x<<1 | (n&1), n >>= 1; return n == x || n == x>>1; } xint reverse3(xint n) { xint x = 0; while (n) x = x*3 + (n%3), n /= 3; return x; } void print(xint n, xint base) { putchar(' ')...
Change the following Python code into C without altering its purpose.
from itertools import islice digits = "0123456789abcdefghijklmnopqrstuvwxyz" def baseN(num,b): if num == 0: return "0" result = "" while num != 0: num, d = divmod(num, b) result += digits[d] return result[::-1] def pal2(num): if num == 0 or num == 1: return True based = bin(num)[2:] retu...
#include <stdio.h> typedef unsigned long long xint; int is_palin2(xint n) { xint x = 0; if (!(n&1)) return !n; while (x < n) x = x<<1 | (n&1), n >>= 1; return n == x || n == x>>1; } xint reverse3(xint n) { xint x = 0; while (n) x = x*3 + (n%3), n /= 3; return x; } void print(xint n, xint base) { putchar(' ')...
Change the programming language of this snippet from Python to C without modifying what it does.
from sys import stdin if stdin.isatty(): print("Input comes from tty.") else: print("Input doesn't come from tty.")
#include <unistd.h> #include <stdio.h> int main(void) { puts(isatty(fileno(stdin)) ? "stdin is tty" : "stdin is not tty"); return 0; }
Write a version of this Python function in C with identical behavior.
from sys import stdin if stdin.isatty(): print("Input comes from tty.") else: print("Input doesn't come from tty.")
#include <unistd.h> #include <stdio.h> int main(void) { puts(isatty(fileno(stdin)) ? "stdin is tty" : "stdin is not tty"); return 0; }
Convert this Python block to C, preserving its control flow and logic.
from Xlib import X, display class Window: def __init__(self, display, msg): self.display = display self.msg = msg self.screen = self.display.screen() self.window = self.screen.root.create_window( 10, 10, 100, 100, 1, self.screen.root_depth, ...
'--- added a flush to exit cleanly PRAGMA LDFLAGS `pkg-config --cflags --libs x11` PRAGMA INCLUDE <X11/Xlib.h> PRAGMA INCLUDE <X11/Xutil.h> OPTION PARSE FALSE '---XLIB is so ugly ALIAS XNextEvent TO EVENT ALIAS XOpenDisplay TO DISPLAY ALIAS DefaultScreen TO SCREEN ALIAS XCreateSimpleWindow TO CREATE ALIAS XCloseD...
Maintain the same structure and functionality when rewriting this code in C.
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())])
#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++...
Preserve the algorithm and functionality while converting the code from Python to C.
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, watt...
#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...
Please provide an equivalent version of this Python code in C.
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'...
#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...
Port the provided Python code into C while preserving the original functionality.
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):...
#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*leastWi...
Ensure the translated C code behaves exactly like the original Python snippet.
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()))
#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 a...
Generate a C translation of this Python snippet without changing its computational steps.
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)
#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...
Translate the given Python code snippet into C without altering its behavior.
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 (a...
#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) { ...
Convert this Python block to C, preserving its control flow and logic.
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 (a...
#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) { ...
Convert the following code from Python to C, ensuring the logic remains intact.
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.i...
#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) >> 2...
Produce a language-to-language conversion: from Python to C, same semantics.
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 ...
#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 ...
Produce a functionally identical C code for the snippet given in Python.
from PIL import Image im = Image.open("boxes_1.ppm") im.save("boxes_1.jpg")
void print_jpg(image img, int qual);
Please provide an equivalent version of this Python code in C.
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('ri...
#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 ...
Convert this Python block to C, preserving its control flow and logic.
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('ri...
#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 ...
Ensure the translated C code behaves exactly like the original Python snippet.
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_e...
#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' ) ...
Change the following Python code into C without altering its purpose.
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_e...
#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' ) ...
Write a version of this Python function in C with identical behavior.
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",...
#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; ...
Convert this Python snippet to C and keep its semantics consistent.
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",...
#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; ...
Translate this program into C but keep the logic exactly as in Python.
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...
#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...
Can you help me rewrite this code in C instead of Python, keeping it the same logically?
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)) ...
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);
Ensure the translated C code behaves exactly like the original Python snippet.
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()) fo...
#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()...
Generate an equivalent C version of this Python code.
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 p...
HANDLE hMutex = CreateMutex(NULL, FALSE, NULL);
Rewrite this program in C while keeping its functionality equivalent to the Python version.
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()
#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....
Rewrite this program in C while keeping its functionality equivalent to the Python version.
import sys print " ".join(sys.argv[1:])
#!/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 ...
Maintain the same structure and functionality when rewriting this code in C.
import sys print " ".join(sys.argv[1:])
#!/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 ...
Generate an equivalent C version of this Python code.
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 =...
#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) { ...
Change the programming language of this snippet from Python to C without modifying what it does.
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....
#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", "0010010...
Write the same algorithm in C as shown in this Python implementation.
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"
#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; }
Write the same code in C as shown below in Python.
'c' == "c" 'text' == "text" ' " ' " ' " '\x20' == ' ' u'unicode string' u'\u05d0'
char ch = 'z';
Convert the following code from Python to C, ensuring the logic remains intact.
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...
#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); ...
Ensure the translated C code behaves exactly like the original Python snippet.
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...
#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); ...
Produce a language-to-language conversion: from Python to C, same semantics.
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...
#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: PostQuitM...
Write the same algorithm in C as shown in this Python implementation.
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...
#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); re...
Convert this Python block to C, preserving its control flow and logic.
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() prin...
#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 ...
Rewrite the snippet below in C so it works the same as the original Python code.
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() prin...
#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 ...
Rewrite this program in C while keeping its functionality equivalent to the Python version.
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() prin...
#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 ...
Generate a C translation of this Python snippet without changing its computational steps.
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 +...
#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 tru...
Convert the following code from Python to C, ensuring the logic remains intact.
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 +...
#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 tru...
Rewrite the snippet below in C so it works the same as the original Python code.
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 ['Θ'] ...
#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; ...
Generate an equivalent C version of this Python code.
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 ['Θ'] ...
#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; ...
Keep all operations the same but rewrite the snippet in C.
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...
#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; } ...
Transform the following Python implementation into C, maintaining the same output and logic.
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__": ...
#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)); r...
Write the same code in C as shown below in Python.
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__": ...
#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)); r...
Translate this program into C but keep the logic exactly as in Python.
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]) retur...
#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 = ...
Port the following code from Python to C with equivalent syntax and logic.
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()
#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; }
Write the same algorithm in C as shown in this Python implementation.
print "\033[7mReversed\033[m Normal"
#include <stdio.h> int main() { printf("\033[7mReversed\033[m Normal\n"); return 0; }
Generate an equivalent C version of this Python code.
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: 's...
#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", 10...
Port the provided Python code into C while preserving the original functionality.
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]:
#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++...
Ensure the translated C code behaves exactly like the original Python snippet.
>>> 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 P...
enum fruits { apple, banana, cherry }; enum fruits { apple = 0, banana = 1, cherry = 2 };
Translate the given Python code snippet into C without altering its behavior.
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 ...
#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; } ...
Ensure the translated C code behaves exactly like the original Python snippet.
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 ...
#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; } ...
Please provide an equivalent version of this Python code in C.
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:"...
#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); ...
Please provide an equivalent version of this Python code in C.
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()
#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 stro...
Produce a language-to-language conversion: from Python to C, same semantics.
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()
#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 stro...
Change the programming language of this snippet from Python to C without modifying what it does.
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 = Non...
#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...
Preserve the algorithm and functionality while converting the code from Python to C.
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...
#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', ...