Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Write the same code in C as shown below in Python.
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', ...
Change the following Python code into C without altering its purpose.
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.appen...
#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 =...
Rewrite this program in C while keeping its functionality equivalent to the Python version.
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.appen...
#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 =...
Write the same code in C as shown below in Python.
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(...
#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': ...
Write the same code in C as shown below in Python.
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] -...
#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},...
Generate a C translation of this Python snippet without changing its computational steps.
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] -...
#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},...
Produce a functionally identical C code for the snippet given in Python.
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): ...
#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 = N...
Port the provided Python code into C while preserving the original functionality.
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) ...
#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...
Convert the following code from Python to C, ensuring the logic remains intact.
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(...
#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; }
Rewrite this program in C while keeping its functionality equivalent to the Python version.
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__':...
#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; ...
Translate the given Python code snippet into C without altering its behavior.
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__':...
#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; ...
Generate an equivalent C version of this Python code.
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__':...
#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; ...
Write the same algorithm in C as shown in this Python implementation.
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.plo...
#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){ p...
Convert this Python snippet to C and keep its semantics consistent.
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.plo...
#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){ p...
Can you help me rewrite this code in C instead of Python, keeping it the same logically?
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 ...
#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) { ...
Convert the following code from Python to C, ensuring the logic remains intact.
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 ...
#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) { ...
Change the following Python code into C without altering its purpose.
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}:...
#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(...
Can you help me rewrite this code in C instead of Python, keeping it the same logically?
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) ...
#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...
Preserve the algorithm and functionality while converting the code from Python to C.
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_EX...
#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...
Ensure the translated C code behaves exactly like the original Python snippet.
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, ...
#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...
Write a version of this Python function in C with identical behavior.
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, ...
#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...
Produce a language-to-language conversion: from Python to C, same semantics.
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-neighb...
#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...
Convert the following code from Python to C, ensuring the logic remains intact.
import Image, ImageFilter im = Image.open('image.ppm') median = im.filter(ImageFilter.MedianFilter(3)) median.save('image2.ppm')
#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...
Translate the given Python code snippet into C without altering its behavior.
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...
#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", __prog...
Change the programming language of this snippet from Python to C without modifying what it does.
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...
#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", __prog...
Rewrite the snippet below in C so it works the same as the original Python code.
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 a...
#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...
Write the same algorithm in C as shown in this Python implementation.
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 a...
#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...
Change the following Python code into C without altering its purpose.
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 a...
#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...
Translate this program into C but keep the logic exactly as in Python.
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
#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]; ...
Change the programming language of this snippet from Python to C without modifying what it does.
from SOAPpy import WSDL proxy = WSDL.Proxy("http://example.com/soap/wsdl") result = proxy.soapFunc("hello") result = proxy.anotherSoapFunc(34234)
#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 *...
Change the following Python code into C without altering its purpose.
from SOAPpy import WSDL proxy = WSDL.Proxy("http://example.com/soap/wsdl") result = proxy.soapFunc("hello") result = proxy.anotherSoapFunc(34234)
#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 *...
Generate a C translation of this Python snippet without changing its computational steps.
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'...
#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 ...
Port the following code from Python to C with equivalent syntax and logic.
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)))
#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...
Transform the following Python implementation into C, maintaining the same output and logic.
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)))
#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...
Write the same algorithm in C as shown in this Python implementation.
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...
#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 (!ris...
Write a version of this Python function in C with identical behavior.
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...
#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 th...
Rewrite the snippet below in C so it works the same as the original Python code.
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)
#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; } p...
Ensure the translated C code behaves exactly like the original Python snippet.
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...
#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+p...
Port the following code from Python to C with equivalent syntax and logic.
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 ...
#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; }
Rewrite this program in C while keeping its functionality equivalent to the Python version.
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 ...
#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){ ret...
Generate a C translation of this Python snippet without changing its computational steps.
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 ...
#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){ ret...
Convert the following code from Python to C, ensuring the logic remains intact.
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...
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 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...
count = 1; while (count < 10) { print("count is: ", count, "\n"); count = count + 1; }
Produce a functionally identical C code for the snippet given in Python.
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...
count = 1; while (count < 10) { print("count is: ", count, "\n"); count = count + 1; }
Translate the given Python code snippet into C without altering its behavior.
from PIL import Image img = Image.new('RGB', (320, 240)) pixels = img.load() pixels[100,100] = (255,0,0) img.show()
#include<graphics.h> int main() { initwindow(320,240,"Red Pixel"); putpixel(100,100,RED); getch(); return 0; }
Change the following Python code into C without altering its purpose.
def digitSumsPrime(n): def go(bases): return all( isPrime(digitSum(b)(n)) for b in bases ) return go def digitSum(base): def go(n): q, r = divmod(n, base) return go(q) + r if n else 0 return go def main(): xs = [ ...
#include <stdio.h> #include <stdint.h> uint8_t prime(uint8_t n) { uint8_t f; if (n < 2) return 0; for (f = 2; f < n; f++) { if (n % f == 0) return 0; } return 1; } uint8_t digit_sum(uint8_t n, uint8_t base) { uint8_t s = 0; do {s += n % base;} while (n /= base); return s; } ...
Write a version of this Python function in C with identical behavior.
def digitSumsPrime(n): def go(bases): return all( isPrime(digitSum(b)(n)) for b in bases ) return go def digitSum(base): def go(n): q, r = divmod(n, base) return go(q) + r if n else 0 return go def main(): xs = [ ...
#include <stdio.h> #include <stdint.h> uint8_t prime(uint8_t n) { uint8_t f; if (n < 2) return 0; for (f = 2; f < n; f++) { if (n % f == 0) return 0; } return 1; } uint8_t digit_sum(uint8_t n, uint8_t base) { uint8_t s = 0; do {s += n % base;} while (n /= base); return s; } ...
Port the provided Python code into C while preserving the original functionality.
import urllib.request from collections import Counter urllib.request.urlretrieve("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt", "unixdict.txt") dictionary = open("unixdict.txt","r") wordList = dictionary.read().split('\n') dictionary.close() filteredWords = [chosenWord for chosenWord in wordList if ...
#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_WORD_SIZE 80 #define MIN_LENGTH 9 #define WORD_SIZE (MIN_LENGTH + 1) 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("O...
Convert this Python block to C, preserving its control flow and logic.
from functools import reduce from operator import mul def p(n): digits = [int(c) for c in str(n)] return not 0 in digits and ( 0 != (n % reduce(mul, digits, 1)) ) and all(0 == n % d for d in digits) def main(): xs = [ str(n) for n in range(1, 1000) if p(n) ...
#include <stdio.h> int divisible(int n) { int p = 1; int c, d; for (c=n; c; c /= 10) { d = c % 10; if (!d || n % d) return 0; p *= d; } return n % p; } int main() { int n, c=0; for (n=1; n<1000; n++) { if (divisible(n)) { printf("%...
Write the same algorithm in C as shown in this Python implementation.
from functools import reduce from operator import mul def p(n): digits = [int(c) for c in str(n)] return not 0 in digits and ( 0 != (n % reduce(mul, digits, 1)) ) and all(0 == n % d for d in digits) def main(): xs = [ str(n) for n in range(1, 1000) if p(n) ...
#include <stdio.h> int divisible(int n) { int p = 1; int c, d; for (c=n; c; c /= 10) { d = c % 10; if (!d || n % d) return 0; p *= d; } return n % p; } int main() { int n, c=0; for (n=1; n<1000; n++) { if (divisible(n)) { printf("%...
Preserve the algorithm and functionality while converting the code from Python to C.
from myhdl import * @block def NOTgate( a, q ): @always_comb def NOTgateLogic(): q.next = not a return NOTgateLogic @block def ANDgate( a, b, q ): @always_comb def ANDgateLogic(): q.next = a and b return ANDgateLogic @block def ORgate( a, b, q ): @...
#include <stdio.h> typedef char pin_t; #define IN const pin_t * #define OUT pin_t * #define PIN(X) pin_t _##X; pin_t *X = & _##X; #define V(X) (*(X)) #define NOT(X) (~(X)&1) #define XOR(X,Y) ((NOT(X)&(Y)) | ((X)&NOT(Y))) void halfadder(IN a, IN b, OUT s, OUT c) { V(s) = XOR(V(a), V(b)); V(c) = V(a) & V(b); } ...
Produce a language-to-language conversion: from Python to C, same semantics.
from myhdl import * @block def NOTgate( a, q ): @always_comb def NOTgateLogic(): q.next = not a return NOTgateLogic @block def ANDgate( a, b, q ): @always_comb def ANDgateLogic(): q.next = a and b return ANDgateLogic @block def ORgate( a, b, q ): @...
#include <stdio.h> typedef char pin_t; #define IN const pin_t * #define OUT pin_t * #define PIN(X) pin_t _##X; pin_t *X = & _##X; #define V(X) (*(X)) #define NOT(X) (~(X)&1) #define XOR(X,Y) ((NOT(X)&(Y)) | ((X)&NOT(Y))) void halfadder(IN a, IN b, OUT s, OUT c) { V(s) = XOR(V(a), V(b)); V(c) = V(a) & V(b); } ...
Write a version of this Python function in C with identical behavior.
from myhdl import * @block def NOTgate( a, q ): @always_comb def NOTgateLogic(): q.next = not a return NOTgateLogic @block def ANDgate( a, b, q ): @always_comb def ANDgateLogic(): q.next = a and b return ANDgateLogic @block def ORgate( a, b, q ): @...
#include <stdio.h> typedef char pin_t; #define IN const pin_t * #define OUT pin_t * #define PIN(X) pin_t _##X; pin_t *X = & _##X; #define V(X) (*(X)) #define NOT(X) (~(X)&1) #define XOR(X,Y) ((NOT(X)&(Y)) | ((X)&NOT(Y))) void halfadder(IN a, IN b, OUT s, OUT c) { V(s) = XOR(V(a), V(b)); V(c) = V(a) & V(b); } ...
Generate a C translation of this Python snippet without changing its computational steps.
import math from sys import stdout LOG_10 = 2.302585092994 def build_oms(s): if s % 2 == 0: s += 1 q = [[0 for j in range(s)] for i in range(s)] p = 1 i = s // 2 j = 0 while p <= (s * s): q[i][j] = p ti = i + 1 if ti >= s: ti = 0 tj = j - 1 if ...
#include<stdlib.h> #include<ctype.h> #include<stdio.h> int** oddMagicSquare(int n) { if (n < 3 || n % 2 == 0) return NULL; int value = 0; int squareSize = n * n; int c = n / 2, r = 0,i; int** result = (int**)malloc(n*sizeof(int*)); for(i=0;i<n...
Convert this Python block to C, preserving its control flow and logic.
>>> from itertools import permutations >>> pieces = 'KQRrBbNN' >>> starts = {''.join(p).upper() for p in permutations(pieces) if p.index('B') % 2 != p.index('b') % 2 and ( p.index('r') < p.index('K') < p.index('R') or p.index('R') < p.index('K') <...
#include<stdlib.h> #include<locale.h> #include<wchar.h> #include<stdio.h> #include<time.h> char rank[9]; int pos[8]; void swap(int i,int j){ int temp = pos[i]; pos[i] = pos[j]; pos[j] = temp; } void generateFirstRank(){ int kPos,qPos,bPos1,bPos2,rPos1,rPos2,nPos1,nPos2,i; for(i=0;i<8;i++){ rank[i] = 'e...
Can you help me rewrite this code in C instead of Python, keeping it the same logically?
def meaning_of_life(): return 42 if __name__ == "__main__": print("Main: The meaning of life is %s" % meaning_of_life())
int meaning_of_life();
Write a version of this Python function in C with identical behavior.
def meaning_of_life(): return 42 if __name__ == "__main__": print("Main: The meaning of life is %s" % meaning_of_life())
int meaning_of_life();
Write the same algorithm in C as shown in this Python implementation.
import math def perlin_noise(x, y, z): X = math.floor(x) & 255 Y = math.floor(y) & 255 Z = math.floor(z) & 255 x -= math.floor(x) y -= math.floor(y) z -= math.floor(z) u = fade(x) ...
#include<stdlib.h> #include<stdio.h> #include<math.h> int p[512]; double fade(double t) { return t * t * t * (t * (t * 6 - 15) + 10); } double lerp(double t, double a, double b) { return a + t * (b - a); } double grad(int hash, double x, double y, double z) { int h = hash & 15; doubl...
Port the following code from Python to C with equivalent syntax and logic.
import sys, os from collections import Counter def dodir(path): global h for name in os.listdir(path): p = os.path.join(path, name) if os.path.islink(p): pass elif os.path.isfile(p): h[os.stat(p).st_size] += 1 elif os.path.isdir(p): dodir(p)...
#include<windows.h> #include<string.h> #include<stdio.h> #define MAXORDER 25 int main(int argC, char* argV[]) { char str[MAXORDER],commandString[1000],*startPath; long int* fileSizeLog = (long int*)calloc(sizeof(long int),MAXORDER),max; int i,j,len; double scale; FILE* fp; if(argC==1) printf("Usage : %s <fol...
Convert the following code from Python to C, ensuring the logic remains intact.
>>> import os >>> print('\n'.join(sorted(os.listdir('.')))) DLLs Doc LICENSE.txt Lib NEWS.txt README.txt Scripts Tools include libs python.exe pythonw.exe tcl >>>
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> #include <sys/types.h> #include <dirent.h> #include <unistd.h> int cmpstr(const void *a, const void *b) { return strcmp(*(const char**)a, *(const char**)b); } int main(void) { DIR *basedir; char path[PATH_MAX]; struct diren...
Maintain the same structure and functionality when rewriting this code in C.
from __future__ import annotations import asyncio import sys from typing import Optional from typing import TextIO class OutOfInkError(Exception): class Printer: def __init__(self, name: str, backup: Optional[Printer]): self.name = name self.backup = backup self.ink_level: int =...
#include <stdlib.h> #include <stdio.h> #include <pthread.h> typedef struct rendezvous { pthread_mutex_t lock; pthread_cond_t cv_entering; pthread_cond_t cv_accepting; pthread_cond_t cv_done; int (*accept_func)(void*); int entering; int accepting; ...
Port the provided Python code into C while preserving the original functionality.
environments = [{'cnt':0, 'seq':i+1} for i in range(12)] code = while any(env['seq'] > 1 for env in environments): for env in environments: exec(code, globals(), env) print() print('Counts') for env in environments: print('% 4d' % env['cnt'], end='') print()
#include <stdio.h> #define JOBS 12 #define jobs(a) for (switch_to(a = 0); a < JOBS || !printf("\n"); switch_to(++a)) typedef struct { int seq, cnt; } env_t; env_t env[JOBS] = {{0, 0}}; int *seq, *cnt; void hail() { printf("% 4d", *seq); if (*seq == 1) return; ++*cnt; *seq = (*seq & 1) ? 3 * *seq + 1 : *seq / 2; ...
Port the following code from Python to C with equivalent syntax and logic.
from unicodedata import name def unicode_code(ch): return 'U+{:04x}'.format(ord(ch)) def utf8hex(ch): return " ".join([hex(c)[2:] for c in ch.encode('utf8')]).upper() if __name__ == "__main__": print('{:<11} {:<36} {:<15} {:<15}'.format('Character', 'Name', 'Unicode', 'UTF-8 encoding (hex)')) cha...
#include <stdio.h> #include <stdlib.h> #include <inttypes.h> typedef struct { char mask; char lead; uint32_t beg; uint32_t end; int bits_stored; }utf_t; utf_t * utf[] = { [0] = &(utf_t){0b00111111, 0b10000000, 0, 0, 6 }, [1] = &(utf_t){0b01111111, 0b00000000, 0000, 0177, 7 ...
Generate a C translation of this Python snippet without changing its computational steps.
from __future__ import division import sys from PIL import Image def _fpart(x): return x - int(x) def _rfpart(x): return 1 - _fpart(x) def putpixel(img, xy, color, alpha=1): compose_color = lambda bg, fg: int(round(alpha * fg + (1-alpha) * bg)) c = compose_color(img.getpixel(xy), color) i...
void draw_line_antialias( image img, unsigned int x0, unsigned int y0, unsigned int x1, unsigned int y1, color_component r, color_component g, color_component b );
Rewrite the snippet below in C so it works the same as the original Python code.
import curses def print_message(): stdscr.addstr('This is the message.\n') stdscr = curses.initscr() curses.noecho() curses.cbreak() stdscr.keypad(1) stdscr.addstr('CTRL+P for message or q to quit.\n') while True: c = stdscr.getch() if c == 16: print_message() elif c == ord('q'): break curses.nocbr...
#include <stdio.h> #include <stdlib.h> #include <X11/Xlib.h> #include <X11/keysym.h> int main() { Display *d; XEvent event; d = XOpenDisplay(NULL); if ( d != NULL ) { XGrabKey(d, XKeysymToKeycode(d, XStringToKeysym("F7")), Mod1Mask, DefaultRootWindow(d), True, GrabModeAsy...
Generate an equivalent C version of this Python code.
>>> from itertools import product >>> nuggets = set(range(101)) >>> for s, n, t in product(range(100//6+1), range(100//9+1), range(100//20+1)): nuggets.discard(6*s + 9*n + 20*t) >>> max(nuggets) 43 >>>
#include <stdio.h> int main() { int max = 0, i = 0, sixes, nines, twenties; loopstart: while (i < 100) { for (sixes = 0; sixes*6 < i; sixes++) { if (sixes*6 == i) { i++; goto loopstart; } for (nines = 0; nines*9 < i; nines++) { ...
Translate this program into C but keep the logic exactly as in Python.
>>> from itertools import product >>> nuggets = set(range(101)) >>> for s, n, t in product(range(100//6+1), range(100//9+1), range(100//20+1)): nuggets.discard(6*s + 9*n + 20*t) >>> max(nuggets) 43 >>>
#include <stdio.h> int main() { int max = 0, i = 0, sixes, nines, twenties; loopstart: while (i < 100) { for (sixes = 0; sixes*6 < i; sixes++) { if (sixes*6 == i) { i++; goto loopstart; } for (nines = 0; nines*9 < i; nines++) { ...
Write a version of this Python function in C with identical behavior.
def MagicSquareDoublyEven(order): sq = [range(1+n*order,order + (n*order)+1) for n in range(order) ] n1 = order/4 for r in range(n1): r1 = sq[r][n1:-n1] r2 = sq[order -r - 1][n1:-n1] r1.reverse() r2.reverse() sq[r][n1:-n1] = r2 sq[order -r - 1][n1:-n1] = r1 ...
#include<stdlib.h> #include<ctype.h> #include<stdio.h> int** doublyEvenMagicSquare(int n) { if (n < 4 || n % 4 != 0) return NULL; int bits = 38505; int size = n * n; int mult = n / 4,i,r,c,bitPos; int** result = (int**)malloc(n*sizeof(int*)); for(i=0;i<n;i++) result[i] = (int*)malloc(n*sizeof(int)); fo...
Ensure the translated C code behaves exactly like the original Python snippet.
>>> >>> inf = 1e234 * 1e234 >>> _inf = 1e234 * -1e234 >>> _zero = 1 / _inf >>> nan = inf + _inf >>> inf, _inf, _zero, nan (inf, -inf, -0.0, nan) >>> >>> for value in (inf, _inf, _zero, nan): print (value) inf -inf -0.0 nan >>> >>> float('nan') nan >>> float('inf') inf >>> float('-inf') -inf >>> -0. -0.0 >>> >>> na...
#include <stdio.h> int main() { double inf = 1/0.0; double minus_inf = -1/0.0; double minus_zero = -1/ inf ; double nan = 0.0/0.0; printf("positive infinity: %f\n",inf); printf("negative infinity: %f\n",minus_inf); printf("negative zero: %f\n",minus_zero); printf("not a number: %f\n",n...
Keep all operations the same but rewrite the snippet in C.
>>> >>> inf = 1e234 * 1e234 >>> _inf = 1e234 * -1e234 >>> _zero = 1 / _inf >>> nan = inf + _inf >>> inf, _inf, _zero, nan (inf, -inf, -0.0, nan) >>> >>> for value in (inf, _inf, _zero, nan): print (value) inf -inf -0.0 nan >>> >>> float('nan') nan >>> float('inf') inf >>> float('-inf') -inf >>> -0. -0.0 >>> >>> na...
#include <stdio.h> int main() { double inf = 1/0.0; double minus_inf = -1/0.0; double minus_zero = -1/ inf ; double nan = 0.0/0.0; printf("positive infinity: %f\n",inf); printf("negative infinity: %f\n",minus_inf); printf("negative zero: %f\n",minus_zero); printf("not a number: %f\n",n...
Change the following Python code into C without altering its purpose.
mask64 = (1 << 64) - 1 mask32 = (1 << 32) - 1 const = 0x2545F4914F6CDD1D class Xorshift_star(): def __init__(self, seed=0): self.state = seed & mask64 def seed(self, num): self.state = num & mask64 def next_int(self): "return random int between 0 and 2**32" x =...
#include <math.h> #include <stdint.h> #include <stdio.h> static uint64_t state; static const uint64_t STATE_MAGIC = 0x2545F4914F6CDD1D; void seed(uint64_t num) { state = num; } uint32_t next_int() { uint64_t x; uint32_t answer; x = state; x = x ^ (x >> 12); x = x ^ (x << 25); x = x ^ (x ...
Ensure the translated C code behaves exactly like the original Python snippet.
import inflect def count_letters(word): count = 0 for letter in word: if letter != ',' and letter !='-' and letter !=' ': count += 1 return count def split_with_spaces(sentence): sentence_list = [] curr_word = "" for c in sentence: if...
#include <ctype.h> #include <locale.h> #include <stdbool.h> #include <stdio.h> #include <stdint.h> #include <glib.h> typedef uint64_t integer; typedef struct number_names_tag { const char* cardinal; const char* ordinal; } number_names; const number_names small[] = { { "zero", "zeroth" }, { "one", "first"...
Please provide an equivalent version of this Python code in C.
def validate(diagram): rawlines = diagram.splitlines() lines = [] for line in rawlines: if line != '': lines.append(line) if len(lines) == 0: print('diagram has no non-empty lines!') return None width = len(line...
#include <stdlib.h> #include <stdio.h> #include <string.h> enum { MAX_ROWS=14, MAX_NAMES=20, NAME_SZ=80 }; char *Lines[MAX_ROWS] = { " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+", " | ID |", " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+", " |QR| ...
Write the same code in C as shown below in Python.
from difflib import ndiff def levenshtein(str1, str2): result = "" pos, removed = 0, 0 for x in ndiff(str1, str2): if pos<len(str1) and str1[pos] == x[2]: pos += 1 result += x[2] if x[0] == "-": removed += 1 continue else: if r...
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct edit_s edit_t, *edit; struct edit_s { char c1, c2; int n; edit next; }; void leven(char *a, char *b) { int i, j, la = strlen(a), lb = strlen(b); edit *tbl = malloc(sizeof(edit) * (1 + la)); tbl[0] = calloc((1 + la) * (1 + lb), sizeof(edit...
Port the provided Python code into C while preserving the original functionality.
def builtinsort(x): x.sort() def partition(seq, pivot): low, middle, up = [], [], [] for x in seq: if x < pivot: low.append(x) elif x == pivot: middle.append(x) else: up.append(x) return low, middle, up import random def qsortranpart(seq): size = le...
#ifndef _CSEQUENCE_H #define _CSEQUENCE_H #include <stdlib.h> void setfillconst(double c); void fillwithconst(double *v, int n); void fillwithrrange(double *v, int n); void shuffledrange(double *v, int n); #endif
Write a version of this Python function in C with identical behavior.
def builtinsort(x): x.sort() def partition(seq, pivot): low, middle, up = [], [], [] for x in seq: if x < pivot: low.append(x) elif x == pivot: middle.append(x) else: up.append(x) return low, middle, up import random def qsortranpart(seq): size = le...
#ifndef _CSEQUENCE_H #define _CSEQUENCE_H #include <stdlib.h> void setfillconst(double c); void fillwithconst(double *v, int n); void fillwithrrange(double *v, int n); void shuffledrange(double *v, int n); #endif
Write the same code in C as shown below in Python.
try: from itertools import zip_longest as izip_longest except: from itertools import izip_longest def fringe(tree): for node1 in tree: if isinstance(node1, tuple): for node2 in fringe(node1): yield node2 else: yield node1 def sa...
#include <stdio.h> #include <stdlib.h> #include <ucontext.h> typedef struct { ucontext_t caller, callee; char stack[8192]; void *in, *out; } co_t; co_t * co_new(void(*f)(), void *data) { co_t * c = malloc(sizeof(*c)); getcontext(&c->callee); c->in = data; c->callee.uc_stack.ss_sp = c->stack; c->callee.uc_sta...
Write the same code in C as shown below in Python.
from optparse import OptionParser [...] parser = OptionParser() parser.add_option("-f", "--file", dest="filename", help="write report to FILE", metavar="FILE") parser.add_option("-q", "--quiet", action="store_false", dest="verbose", default=True, help="don't print s...
#include <stdio.h> int main(int argc, char **argv){ int i; const char *commands[]={"-c", "-p", "-t", "-d", "-a", NULL}; enum {CREATE,PRINT,TITLE,DATE,AUTH}; if (argc<2) { usage: printf ("Usage: %s [commands]\n" "-c Create new entry.\n" "-p Print the latest entry.\n" ...
Produce a language-to-language conversion: from Python to C, same semantics.
from optparse import OptionParser [...] parser = OptionParser() parser.add_option("-f", "--file", dest="filename", help="write report to FILE", metavar="FILE") parser.add_option("-q", "--quiet", action="store_false", dest="verbose", default=True, help="don't print s...
#include <stdio.h> int main(int argc, char **argv){ int i; const char *commands[]={"-c", "-p", "-t", "-d", "-a", NULL}; enum {CREATE,PRINT,TITLE,DATE,AUTH}; if (argc<2) { usage: printf ("Usage: %s [commands]\n" "-c Create new entry.\n" "-p Print the latest entry.\n" ...
Convert this Python snippet to C and keep its semantics consistent.
[print("( " + "1"*i + "3 ) ^ 2 = " + str(int("1"*i + "3")**2)) for i in range(0,8)]
#include <stdio.h> #include <stdint.h> uint64_t ones_plus_three(uint64_t ones) { uint64_t r = 0; while (ones--) r = r*10 + 1; return r*10 + 3; } int main() { uint64_t n; for (n=0; n<8; n++) { uint64_t x = ones_plus_three(n); printf("%8lu^2 = %15lu\n", x, x*x); } return 0; }...
Write the same algorithm in C as shown in this Python implementation.
[print("( " + "1"*i + "3 ) ^ 2 = " + str(int("1"*i + "3")**2)) for i in range(0,8)]
#include <stdio.h> #include <stdint.h> uint64_t ones_plus_three(uint64_t ones) { uint64_t r = 0; while (ones--) r = r*10 + 1; return r*10 + 3; } int main() { uint64_t n; for (n=0; n<8; n++) { uint64_t x = ones_plus_three(n); printf("%8lu^2 = %15lu\n", x, x*x); } return 0; }...
Write a version of this Python function in C with identical behavior.
import autopy autopy.key.type_string("Hello, world!") autopy.key.type_string("Hello, world!", wpm=60) autopy.key.tap(autopy.key.Code.RETURN) autopy.key.tap(autopy.key.Code.F1) autopy.key.tap(autopy.key.Code.LEFT_ARROW)
#include <stdio.h> #include <stdlib.h> #include <X11/Xlib.h> #include <X11/Xutil.h> int main(int argc, char *argv[]) { Display *dpy; Window win; GC gc; int scr; Atom WM_DELETE_WINDOW; XEvent ev; XEvent ev2; KeySym keysym; int loop; dpy = XOpenDisplay(NULL); if (dpy == NULL) { fputs("Canno...
Write a version of this Python function in C with identical behavior.
from itertools import combinations, product, count from functools import lru_cache, reduce _bbullet, _wbullet = '\u2022\u25E6' _or = set.__or__ def place(m, n): "Place m black and white queens, peacefully, on an n-by-n board" board = set(product(range(n), repeat=2)) placements = {frozenset(c) for c in ...
#include <math.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> enum Piece { Empty, Black, White, }; typedef struct Position_t { int x, y; } Position; struct Node_t { Position pos; struct Node_t *next; }; void releaseNode(struct Node_t *head) { if (head == NULL) return; ...
Ensure the translated C code behaves exactly like the original Python snippet.
from macropy.core.macros import * from macropy.core.quotes import macros, q, ast, u macros = Macros() @macros.expr def expand(tree, **kw): addition = 10 return q[lambda x: x * ast[tree] + u[addition]]
#define STATIC_ASSERT(COND,MSG) typedef char static_assertion_##MSG[(!!(COND))*2-1] #define COMPILE_TIME_ASSERT3(X,L) STATIC_ASSERT(X,static_assertion_at_line_##L) #define COMPILE_TIME_ASSERT2(X,L) COMPILE_TIME_ASSERT3(X,L) #define COMPILE_TIME_ASSERT(X) COMPILE_TIME_ASSERT2(X,__LINE__) COMPILE_TIME_ASSERT(sizeof...
Please provide an equivalent version of this Python code in C.
col = 0 for i in range(100000): if set(str(i)) == set(hex(i)[2:]): col += 1 print("{:7}".format(i), end='\n'[:col % 10 == 0]) print()
#include <stdio.h> #define LIMIT 100000 int digitset(int num, int base) { int set; for (set = 0; num; num /= base) set |= 1 << num % base; return set; } int main() { int i, c = 0; for (i = 0; i < LIMIT; i++) if (digitset(i,10) == digitset(i,16)) printf("%6d%c", i, ++c%1...
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__': n = 600851475143 j = 3 while not isPrime(n): if n % j == 0: n /= j j += 2 print(n);
#include <stdio.h> #include <stdlib.h> int isprime( long int n ) { int i=3; if(!(n%2)) return 0; while( i*i < n ) { if(!(n%i)) return 0; i+=2; } return 1; } int main(void) { long int n=600851475143, j=3; while(!isprime(n)) { if(!(n%j)) n/=j; j+=2; } ...
Convert this Python snippet to C and keep its semantics consistent.
def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True if __name__ == '__main__': n = 600851475143 j = 3 while not isPrime(n): if n % j == 0: n /= j j += 2 print(n);
#include <stdio.h> #include <stdlib.h> int isprime( long int n ) { int i=3; if(!(n%2)) return 0; while( i*i < n ) { if(!(n%i)) return 0; i+=2; } return 1; } int main(void) { long int n=600851475143, j=3; while(!isprime(n)) { if(!(n%j)) n/=j; j+=2; } ...
Rewrite the snippet below in C so it works the same as the original Python code.
def lpd(n): for i in range(n-1,0,-1): if n%i==0: return i return 1 for i in range(1,101): print("{:3}".format(lpd(i)), end=i%10==0 and '\n' or '')
#include <stdio.h> unsigned int lpd(unsigned int n) { if (n<=1) return 1; int i; for (i=n-1; i>0; i--) if (n%i == 0) return i; } int main() { int i; for (i=1; i<=100; i++) { printf("%3d", lpd(i)); if (i % 10 == 0) printf("\n"); } return 0; }
Port the provided Python code into C while preserving the original functionality.
from __future__ import print_function from string import ascii_lowercase SYMBOLTABLE = list(ascii_lowercase) def move2front_encode(strng, symboltable): sequence, pad = [], symboltable[::] for char in strng: indx = pad.index(char) sequence.append(indx) pad = [pad.pop(indx)] + pad re...
#include<stdio.h> #include<stdlib.h> #include<string.h> #define MAX_SIZE 100 int move_to_front(char *str,char c) { char *q,*p; int shift=0; p=(char *)malloc(strlen(str)+1); strcpy(p,str); q=strchr(p,c); shift=q-p; strncpy(str+1,p,shift); str[0]=c; free(p); return shif...
Produce a language-to-language conversion: from Python to C, same semantics.
Import-Module ActiveDirectory $searchData = "user name" $searchBase = "DC=example,DC=com" get-aduser -Filter((DistinguishedName -eq $searchdata) -or (UserPrincipalName -eq $searchdata) -or (SamAccountName -eq $searchdata)) -SearchBase $searchBase
#include <ldap.h> char *name, *password; ... LDAP *ld = ldap_init("ldap.somewhere.com", 389); ldap_simple_bind_s(ld, name, password); LDAPMessage **result; ldap_search_s(ld, "dc=somewhere,dc=com", LDAP_SCOPE_SUBTREE, "(&(objectclass=person)(|(cn=joe*)(cn=shmoe*)))", NULL, 0, result); ldap_msgfree(*resul...
Change the programming language of this snippet from Python to C without modifying what it does.
from numpy import * A = matrix([[3, 0], [4, 5]]) U, Sigma, VT = linalg.svd(A) print(U) print(Sigma) print(VT)
#include <stdio.h> #include <gsl/gsl_linalg.h> void gsl_matrix_print(const gsl_matrix *M) { int rows = M->size1; int cols = M->size2; for (int i = 0; i < rows; i++) { printf("|"); for (int j = 0; j < cols; j++) { printf("% 12.10f ", gsl_matrix_get(M, i, j)); } p...
Convert this Python snippet to C and keep its semantics consistent.
def main(): fila = 0 lenCubos = 51 print("Suma de N cubos para n = [0..49]\n") for n in range(1, lenCubos): sumCubos = 0 for m in range(1, n): sumCubos = sumCubos + (m ** 3) fila += 1 print(f'{sumCubos:7} ', end='') if fila % 5 == 0: ...
#include <stdio.h> int main() { for (int i = 0, sum = 0; i < 50; ++i) { sum += i * i * i; printf("%7d%c", sum, (i + 1) % 5 == 0 ? '\n' : ' '); } return 0; }
Change the programming language of this snippet from Python to C without modifying what it does.
>>> def isint(f): return complex(f).imag == 0 and complex(f).real.is_integer() >>> [isint(f) for f in (1.0, 2, (3.0+0.0j), 4.1, (3+4j), (5.6+0j))] [True, True, True, False, False, False] >>> ... >>> isint(25.000000) True >>> isint(24.999999) False >>> isint(25.000100) False >>> isint(-2.1e120) True >>> isint(-5...
#include <stdio.h> #include <complex.h> #include <math.h> #define FMTSPEC(arg) _Generic((arg), \ float: "%f", double: "%f", \ long double: "%Lf", unsigned int: "%u", \ unsigned long: "%lu", unsigned long long: "%llu", \ int: "%d", long: "%ld", long long: "%lld", \ default: "(invalid type (%p)") #...
Port the following code from Python to C with equivalent syntax and logic.
import os exit_code = os.system('ls') output = os.popen('ls').read()
#include <stdlib.h> int main() { system("ls"); return 0; }
Generate a C translation of this Python snippet without changing its computational steps.
from __future__ import print_function import lxml from lxml import etree if __name__=="__main__": parser = etree.XMLParser(dtd_validation=True) schema_root = etree.XML() schema = etree.XMLSchema(schema_root) parser = etree.XMLParser(schema = schema) try: root = etree.fromstring("<a>5</a>", parser) print ...
#include <libxml/xmlschemastypes.h> int main(int argC, char** argV) { if (argC <= 2) { printf("Usage: %s <XML Document Name> <XSD Document Name>\n", argV[0]); return 0; } xmlDocPtr doc; xmlSchemaPtr schema = NULL; xmlSchemaParserCtxtPtr ctxt; char *XMLFileName = argV[1]; char *XSDFileName = argV[2]; int ...
Write the same algorithm in C as shown in this Python implementation.
def longest_increasing_subsequence(X): N = len(X) P = [0] * N M = [0] * (N+1) L = 0 for i in range(N): lo = 1 hi = L while lo <= hi: mid = (lo+hi)//2 if (X[M[mid]] < X[i]): lo = mid+1 else: hi = mid-1 ...
#include <stdio.h> #include <stdlib.h> struct node { int val, len; struct node *next; }; void lis(int *v, int len) { int i; struct node *p, *n = calloc(len, sizeof *n); for (i = 0; i < len; i++) n[i].val = v[i]; for (i = len; i--; ) { for (p = n + i; p++ < n + len; ) { if (p->val > n[i].val && p->len...
Produce a language-to-language conversion: from Python to C, same semantics.
import sys, math, collections Sphere = collections.namedtuple("Sphere", "cx cy cz r") V3 = collections.namedtuple("V3", "x y z") def normalize((x, y, z)): len = math.sqrt(x**2 + y**2 + z**2) return V3(x / len, y / len, z / len) def dot(v1, v2): d = v1.x*v2.x + v1.y*v2.y + v1.z*v2.z return -d if d < 0...
#include <stdio.h> #include <math.h> #include <unistd.h> const char *shades = ".:!*oe&#%@"; double light[3] = { -50, 0, 50 }; void normalize(double * v) { double len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]); v[0] /= len; v[1] /= len; v[2] /= len; } double dot(double *x, double *y) { double d = x[0]*y[0] + x[1]*y...
Generate a C translation of this Python snippet without changing its computational steps.
from __future__ import print_function def lgen(even=False, nmax=1000000): start = 2 if even else 1 n, lst = 1, list(range(start, nmax + 1, 2)) lenlst = len(lst) yield lst[0] while n < lenlst and lst[n] < lenlst: yield lst[n] n, lst = n + 1, [j for i,j in enumerate(lst, 1) if i % lst...
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> #define LUCKY_SIZE 60000 int luckyOdd[LUCKY_SIZE]; int luckyEven[LUCKY_SIZE]; void compactLucky(int luckyArray[]) { int i, j, k; for (i = 0; i < LUCKY_SIZE; i++) { if (luckyArray[i] == 0) { j = i; break; } ...
Convert the following code from Python to C, ensuring the logic remains intact.
>>> x="From global scope" >>> def outerfunc(): x = "From scope at outerfunc" def scoped_local(): x = "scope local" return "scoped_local scope gives x = " + x print(scoped_local()) def scoped_nonlocal(): nonlocal x return "scoped_nonlocal scope gives x = " + x print(...
int a; static int p; extern float v; int code(int arg) { int myp; static int myc; } static void code2(void) { v = v * 1.02; }
Preserve the algorithm and functionality while converting the code from Python to C.
import argparse from argparse import Namespace import datetime import shlex def parse_args(): 'Set up, parse, and return arguments' parser = argparse.ArgumentParser(epilog=globals()['__doc__']) parser.add_argument('command', choices='add pl plc pa'.split(), help=) par...
#include <stdio.h> #include <stdlib.h> #include <string.h> #define _XOPEN_SOURCE #define __USE_XOPEN #include <time.h> #define DB "database.csv" #define TRY(a) if (!(a)) {perror(#a);exit(1);} #define TRY2(a) if((a)<0) {perror(#a);exit(1);} #define FREE(a) if(a) {free(a);a=NULL;} #define sort_by(foo) \ static int b...