Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Write a version of this C function in Python with identical behavior.
#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; } int main() { uint8_t n, s = 0; for (n = 0; n < 200; n++) { if (prime(digit_sum(n,2)) && prime(digit_sum(n,3))) { printf("%4d",n); if (++s>=10) { printf("\n"); s=0; } } } printf("\n"); return 0; }
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 = [ str(n) for n in range(1, 200) if digitSumsPrime(n)([2, 3]) ] print(f'{len(xs)} matches in [1..199]\n') print(table(10)(xs)) def chunksOf(n): def go(xs): return ( xs[i:n + i] for i in range(0, len(xs), n) ) if 0 < n else None return go def isPrime(n): if n in (2, 3): return True if 2 > n or 0 == n % 2: return False if 9 > n: return True if 0 == n % 3: return False def p(x): return 0 == n % x or 0 == n % (2 + x) return not any(map(p, range(5, 1 + int(n ** 0.5), 6))) def table(n): def go(xs): w = len(xs[-1]) return '\n'.join( ' '.join(row) for row in chunksOf(n)([ s.rjust(w, ' ') for s in xs ]) ) return go if __name__ == '__main__': main()
Port the following code from C to Python with equivalent syntax and logic.
#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; } int main() { uint8_t n, s = 0; for (n = 0; n < 200; n++) { if (prime(digit_sum(n,2)) && prime(digit_sum(n,3))) { printf("%4d",n); if (++s>=10) { printf("\n"); s=0; } } } printf("\n"); return 0; }
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 = [ str(n) for n in range(1, 200) if digitSumsPrime(n)([2, 3]) ] print(f'{len(xs)} matches in [1..199]\n') print(table(10)(xs)) def chunksOf(n): def go(xs): return ( xs[i:n + i] for i in range(0, len(xs), n) ) if 0 < n else None return go def isPrime(n): if n in (2, 3): return True if 2 > n or 0 == n % 2: return False if 9 > n: return True if 0 == n % 3: return False def p(x): return 0 == n % x or 0 == n % (2 + x) return not any(map(p, range(5, 1 + int(n ** 0.5), 6))) def table(n): def go(xs): w = len(xs[-1]) return '\n'.join( ' '.join(row) for row in chunksOf(n)([ s.rjust(w, ' ') for s in xs ]) ) return go if __name__ == '__main__': main()
Keep all operations the same but rewrite the snippet in Python.
#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("Out of memory"); return ptr; } void* xrealloc(void* p, size_t n) { void* ptr = realloc(p, n); if (ptr == NULL) fatal("Out of memory"); return ptr; } int word_compare(const void* p1, const void* p2) { return memcmp(p1, p2, WORD_SIZE); } int main(int argc, char** argv) { const char* filename = argc < 2 ? "unixdict.txt" : argv[1]; FILE* in = fopen(filename, "r"); if (!in) { perror(filename); return EXIT_FAILURE; } char line[MAX_WORD_SIZE]; size_t size = 0, capacity = 1024; char* words = xmalloc(WORD_SIZE * capacity); while (fgets(line, sizeof(line), in)) { size_t len = strlen(line) - 1; if (len < MIN_LENGTH) continue; line[len] = '\0'; if (size == capacity) { capacity *= 2; words = xrealloc(words, WORD_SIZE * capacity); } memcpy(&words[size * WORD_SIZE], line, WORD_SIZE); ++size; } fclose(in); qsort(words, size, WORD_SIZE, word_compare); int count = 0; char prev_word[WORD_SIZE] = { 0 }; for (size_t i = 0; i + MIN_LENGTH <= size; ++i) { char word[WORD_SIZE] = { 0 }; for (size_t j = 0; j < MIN_LENGTH; ++j) word[j] = words[(i + j) * WORD_SIZE + j]; if (word_compare(word, prev_word) == 0) continue; if (bsearch(word, words, size, WORD_SIZE, word_compare)) printf("%2d. %s\n", ++count, word); memcpy(prev_word, word, WORD_SIZE); } free(words); return EXIT_SUCCESS; }
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 len(chosenWord)>=9] for word in filteredWords[:-9]: position = filteredWords.index(word) newWord = "".join([filteredWords[position+i][i] for i in range(0,9)]) if newWord in filteredWords: print(newWord)
Translate this program into Python but keep the logic exactly as in C.
#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("%5d", n); if (!(++c % 10)) printf("\n"); } } printf("\n"); return 0; }
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) ] w = len(xs[-1]) print(f'{len(xs)} matching numbers:\n') print('\n'.join( ' '.join(cell.rjust(w, ' ') for cell in row) for row in chunksOf(10)(xs) )) def chunksOf(n): def go(xs): return ( xs[i:n + i] for i in range(0, len(xs), n) ) if 0 < n else None return go if __name__ == '__main__': main()
Translate the given C code snippet into Python without altering its behavior.
#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("%5d", n); if (!(++c % 10)) printf("\n"); } } printf("\n"); return 0; }
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) ] w = len(xs[-1]) print(f'{len(xs)} matching numbers:\n') print('\n'.join( ' '.join(cell.rjust(w, ' ') for cell in row) for row in chunksOf(10)(xs) )) def chunksOf(n): def go(xs): return ( xs[i:n + i] for i in range(0, len(xs), n) ) if 0 < n else None return go if __name__ == '__main__': main()
Translate the given C code snippet into Python without altering its behavior.
#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); } void fulladder(IN a, IN b, IN ic, OUT s, OUT oc) { PIN(ps); PIN(pc); PIN(tc); halfadder(a, b, ps, pc); halfadder(ps, ic, s, tc); V(oc) = V(tc) | V(pc); } void fourbitsadder(IN a0, IN a1, IN a2, IN a3, IN b0, IN b1, IN b2, IN b3, OUT o0, OUT o1, OUT o2, OUT o3, OUT overflow) { PIN(zero); V(zero) = 0; PIN(tc0); PIN(tc1); PIN(tc2); fulladder(a0, b0, zero, o0, tc0); fulladder(a1, b1, tc0, o1, tc1); fulladder(a2, b2, tc1, o2, tc2); fulladder(a3, b3, tc2, o3, overflow); } int main() { PIN(a0); PIN(a1); PIN(a2); PIN(a3); PIN(b0); PIN(b1); PIN(b2); PIN(b3); PIN(s0); PIN(s1); PIN(s2); PIN(s3); PIN(overflow); V(a3) = 0; V(b3) = 1; V(a2) = 0; V(b2) = 1; V(a1) = 1; V(b1) = 1; V(a0) = 0; V(b0) = 0; fourbitsadder(a0, a1, a2, a3, b0, b1, b2, b3, s0, s1, s2, s3, overflow); printf("%d%d%d%d + %d%d%d%d = %d%d%d%d, overflow = %d\n", V(a3), V(a2), V(a1), V(a0), V(b3), V(b2), V(b1), V(b0), V(s3), V(s2), V(s1), V(s0), V(overflow)); return 0; }
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 ): @always_comb def ORgateLogic(): q.next = a or b return ORgateLogic @block def XORgate( a, b, q ): nota, notb, annotb, bnnota = [Signal(bool(0)) for i in range(4)] inv0 = NOTgate( a, nota ) inv1 = NOTgate( b, notb ) and2a = ANDgate( a, notb, annotb ) and2b = ANDgate( b, nota, bnnota ) or2a = ORgate( annotb, bnnota, q ) return inv0, inv1, and2a, and2b, or2a @block def HalfAdder( in_a, in_b, summ, carry ): and2a = ANDgate(in_a, in_b, carry) xor2a = XORgate(in_a, in_b, summ) return and2a, xor2a @block def FullAdder( fa_c0, fa_a, fa_b, fa_s, fa_c1 ): ha1_s, ha1_c1, ha2_c1 = [Signal(bool(0)) for i in range(3)] HalfAdder01 = HalfAdder( fa_c0, fa_a, ha1_s, ha1_c1 ) HalfAdder02 = HalfAdder( ha1_s, fa_b, fa_s, ha2_c1 ) or2a = ORgate(ha1_c1, ha2_c1, fa_c1) return HalfAdder01, HalfAdder02, or2a @block def Adder4b( ina, inb, cOut, sum4): cl = [Signal(bool()) for i in range(0,4)] sl = [Signal(bool()) for i in range(4)] HalfAdder0 = HalfAdder( ina(0), inb(0), sl[0], cl[1] ) FullAdder1 = FullAdder( cl[1], ina(1), inb(1), sl[1], cl[2] ) FullAdder2 = FullAdder( cl[2], ina(2), inb(2), sl[2], cl[3] ) FullAdder3 = FullAdder( cl[3], ina(3), inb(3), sl[3], cOut ) sc = ConcatSignal(*reversed(sl)) @always_comb def list2intbv(): sum4.next = sc return HalfAdder0, FullAdder1, FullAdder2, FullAdder3, list2intbv t_co, t_s, t_a, t_b, dbug = [Signal(bool(0)) for i in range(5)] ina4, inb4, sum4 = [Signal(intbv(0)[4:]) for i in range(3)] from random import randrange @block def Test_Adder4b(): dut = Adder4b( ina4, inb4, t_co, sum4 ) @instance def check(): print( "\n b a | c1 s \n -------------------" ) for i in range(15): ina4.next, inb4.next = randrange(2**4), randrange(2**4) yield delay(5) print( " %2d %2d | %2d %2d " \ % (ina4,inb4, t_co,sum4) ) assert t_co * 16 + sum4 == ina4 + inb4 print() return dut, check def main(): simInst = Test_Adder4b() simInst.name = "mySimInst" simInst.config_sim(trace=True) simInst.run_sim(duration=None) inst = Adder4b( ina4, inb4, t_co, sum4 ) inst.convert(hdl='VHDL') inst.convert(hdl='Verilog') if __name__ == '__main__': main()
Write a version of this C function in Python with identical behavior.
#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); } void fulladder(IN a, IN b, IN ic, OUT s, OUT oc) { PIN(ps); PIN(pc); PIN(tc); halfadder(a, b, ps, pc); halfadder(ps, ic, s, tc); V(oc) = V(tc) | V(pc); } void fourbitsadder(IN a0, IN a1, IN a2, IN a3, IN b0, IN b1, IN b2, IN b3, OUT o0, OUT o1, OUT o2, OUT o3, OUT overflow) { PIN(zero); V(zero) = 0; PIN(tc0); PIN(tc1); PIN(tc2); fulladder(a0, b0, zero, o0, tc0); fulladder(a1, b1, tc0, o1, tc1); fulladder(a2, b2, tc1, o2, tc2); fulladder(a3, b3, tc2, o3, overflow); } int main() { PIN(a0); PIN(a1); PIN(a2); PIN(a3); PIN(b0); PIN(b1); PIN(b2); PIN(b3); PIN(s0); PIN(s1); PIN(s2); PIN(s3); PIN(overflow); V(a3) = 0; V(b3) = 1; V(a2) = 0; V(b2) = 1; V(a1) = 1; V(b1) = 1; V(a0) = 0; V(b0) = 0; fourbitsadder(a0, a1, a2, a3, b0, b1, b2, b3, s0, s1, s2, s3, overflow); printf("%d%d%d%d + %d%d%d%d = %d%d%d%d, overflow = %d\n", V(a3), V(a2), V(a1), V(a0), V(b3), V(b2), V(b1), V(b0), V(s3), V(s2), V(s1), V(s0), V(overflow)); return 0; }
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 ): @always_comb def ORgateLogic(): q.next = a or b return ORgateLogic @block def XORgate( a, b, q ): nota, notb, annotb, bnnota = [Signal(bool(0)) for i in range(4)] inv0 = NOTgate( a, nota ) inv1 = NOTgate( b, notb ) and2a = ANDgate( a, notb, annotb ) and2b = ANDgate( b, nota, bnnota ) or2a = ORgate( annotb, bnnota, q ) return inv0, inv1, and2a, and2b, or2a @block def HalfAdder( in_a, in_b, summ, carry ): and2a = ANDgate(in_a, in_b, carry) xor2a = XORgate(in_a, in_b, summ) return and2a, xor2a @block def FullAdder( fa_c0, fa_a, fa_b, fa_s, fa_c1 ): ha1_s, ha1_c1, ha2_c1 = [Signal(bool(0)) for i in range(3)] HalfAdder01 = HalfAdder( fa_c0, fa_a, ha1_s, ha1_c1 ) HalfAdder02 = HalfAdder( ha1_s, fa_b, fa_s, ha2_c1 ) or2a = ORgate(ha1_c1, ha2_c1, fa_c1) return HalfAdder01, HalfAdder02, or2a @block def Adder4b( ina, inb, cOut, sum4): cl = [Signal(bool()) for i in range(0,4)] sl = [Signal(bool()) for i in range(4)] HalfAdder0 = HalfAdder( ina(0), inb(0), sl[0], cl[1] ) FullAdder1 = FullAdder( cl[1], ina(1), inb(1), sl[1], cl[2] ) FullAdder2 = FullAdder( cl[2], ina(2), inb(2), sl[2], cl[3] ) FullAdder3 = FullAdder( cl[3], ina(3), inb(3), sl[3], cOut ) sc = ConcatSignal(*reversed(sl)) @always_comb def list2intbv(): sum4.next = sc return HalfAdder0, FullAdder1, FullAdder2, FullAdder3, list2intbv t_co, t_s, t_a, t_b, dbug = [Signal(bool(0)) for i in range(5)] ina4, inb4, sum4 = [Signal(intbv(0)[4:]) for i in range(3)] from random import randrange @block def Test_Adder4b(): dut = Adder4b( ina4, inb4, t_co, sum4 ) @instance def check(): print( "\n b a | c1 s \n -------------------" ) for i in range(15): ina4.next, inb4.next = randrange(2**4), randrange(2**4) yield delay(5) print( " %2d %2d | %2d %2d " \ % (ina4,inb4, t_co,sum4) ) assert t_co * 16 + sum4 == ina4 + inb4 print() return dut, check def main(): simInst = Test_Adder4b() simInst.name = "mySimInst" simInst.config_sim(trace=True) simInst.run_sim(duration=None) inst = Adder4b( ina4, inb4, t_co, sum4 ) inst.convert(hdl='VHDL') inst.convert(hdl='Verilog') if __name__ == '__main__': main()
Transform the following C implementation into Python, maintaining the same output and logic.
#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); } void fulladder(IN a, IN b, IN ic, OUT s, OUT oc) { PIN(ps); PIN(pc); PIN(tc); halfadder(a, b, ps, pc); halfadder(ps, ic, s, tc); V(oc) = V(tc) | V(pc); } void fourbitsadder(IN a0, IN a1, IN a2, IN a3, IN b0, IN b1, IN b2, IN b3, OUT o0, OUT o1, OUT o2, OUT o3, OUT overflow) { PIN(zero); V(zero) = 0; PIN(tc0); PIN(tc1); PIN(tc2); fulladder(a0, b0, zero, o0, tc0); fulladder(a1, b1, tc0, o1, tc1); fulladder(a2, b2, tc1, o2, tc2); fulladder(a3, b3, tc2, o3, overflow); } int main() { PIN(a0); PIN(a1); PIN(a2); PIN(a3); PIN(b0); PIN(b1); PIN(b2); PIN(b3); PIN(s0); PIN(s1); PIN(s2); PIN(s3); PIN(overflow); V(a3) = 0; V(b3) = 1; V(a2) = 0; V(b2) = 1; V(a1) = 1; V(b1) = 1; V(a0) = 0; V(b0) = 0; fourbitsadder(a0, a1, a2, a3, b0, b1, b2, b3, s0, s1, s2, s3, overflow); printf("%d%d%d%d + %d%d%d%d = %d%d%d%d, overflow = %d\n", V(a3), V(a2), V(a1), V(a0), V(b3), V(b2), V(b1), V(b0), V(s3), V(s2), V(s1), V(s0), V(overflow)); return 0; }
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 ): @always_comb def ORgateLogic(): q.next = a or b return ORgateLogic @block def XORgate( a, b, q ): nota, notb, annotb, bnnota = [Signal(bool(0)) for i in range(4)] inv0 = NOTgate( a, nota ) inv1 = NOTgate( b, notb ) and2a = ANDgate( a, notb, annotb ) and2b = ANDgate( b, nota, bnnota ) or2a = ORgate( annotb, bnnota, q ) return inv0, inv1, and2a, and2b, or2a @block def HalfAdder( in_a, in_b, summ, carry ): and2a = ANDgate(in_a, in_b, carry) xor2a = XORgate(in_a, in_b, summ) return and2a, xor2a @block def FullAdder( fa_c0, fa_a, fa_b, fa_s, fa_c1 ): ha1_s, ha1_c1, ha2_c1 = [Signal(bool(0)) for i in range(3)] HalfAdder01 = HalfAdder( fa_c0, fa_a, ha1_s, ha1_c1 ) HalfAdder02 = HalfAdder( ha1_s, fa_b, fa_s, ha2_c1 ) or2a = ORgate(ha1_c1, ha2_c1, fa_c1) return HalfAdder01, HalfAdder02, or2a @block def Adder4b( ina, inb, cOut, sum4): cl = [Signal(bool()) for i in range(0,4)] sl = [Signal(bool()) for i in range(4)] HalfAdder0 = HalfAdder( ina(0), inb(0), sl[0], cl[1] ) FullAdder1 = FullAdder( cl[1], ina(1), inb(1), sl[1], cl[2] ) FullAdder2 = FullAdder( cl[2], ina(2), inb(2), sl[2], cl[3] ) FullAdder3 = FullAdder( cl[3], ina(3), inb(3), sl[3], cOut ) sc = ConcatSignal(*reversed(sl)) @always_comb def list2intbv(): sum4.next = sc return HalfAdder0, FullAdder1, FullAdder2, FullAdder3, list2intbv t_co, t_s, t_a, t_b, dbug = [Signal(bool(0)) for i in range(5)] ina4, inb4, sum4 = [Signal(intbv(0)[4:]) for i in range(3)] from random import randrange @block def Test_Adder4b(): dut = Adder4b( ina4, inb4, t_co, sum4 ) @instance def check(): print( "\n b a | c1 s \n -------------------" ) for i in range(15): ina4.next, inb4.next = randrange(2**4), randrange(2**4) yield delay(5) print( " %2d %2d | %2d %2d " \ % (ina4,inb4, t_co,sum4) ) assert t_co * 16 + sum4 == ina4 + inb4 print() return dut, check def main(): simInst = Test_Adder4b() simInst.name = "mySimInst" simInst.config_sim(trace=True) simInst.run_sim(duration=None) inst = Adder4b( ina4, inb4, t_co, sum4 ) inst.convert(hdl='VHDL') inst.convert(hdl='Verilog') if __name__ == '__main__': main()
Please provide an equivalent version of this C code in Python.
#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;i++) result[i] = (int*)malloc(n*sizeof(int)); while (++value <= squareSize) { result[r][c] = value; if (r == 0) { if (c == n - 1) { r++; } else { r = n - 1; c++; } } else if (c == n - 1) { r--; c = 0; } else if (result[r - 1][c + 1] == 0) { r--; c++; } else { r++; } } return result; } int** singlyEvenMagicSquare(int n) { if (n < 6 || (n - 2) % 4 != 0) return NULL; int size = n * n; int halfN = n / 2; int subGridSize = size / 4, i; int** subGrid = oddMagicSquare(halfN); int gridFactors[] = {0, 2, 3, 1}; int** result = (int**)malloc(n*sizeof(int*)); for(i=0;i<n;i++) result[i] = (int*)malloc(n*sizeof(int)); for (int r = 0; r < n; r++) { for (int c = 0; c < n; c++) { int grid = (r / halfN) * 2 + (c / halfN); result[r][c] = subGrid[r % halfN][c % halfN]; result[r][c] += gridFactors[grid] * subGridSize; } } int nColsLeft = halfN / 2; int nColsRight = nColsLeft - 1; for (int r = 0; r < halfN; r++) for (int c = 0; c < n; c++) { if (c < nColsLeft || c >= n - nColsRight || (c == nColsLeft && r == nColsLeft)) { if (c == 0 && r == nColsLeft) continue; int tmp = result[r][c]; result[r][c] = result[r + halfN][c]; result[r + halfN][c] = tmp; } } return result; } int numDigits(int n){ int count = 1; while(n>=10){ n /= 10; count++; } return count; } void printMagicSquare(int** square,int rows){ int i,j; for(i=0;i<rows;i++){ for(j=0;j<rows;j++){ printf("%*s%d",rows - numDigits(square[i][j]),"",square[i][j]); } printf("\n"); } printf("\nMagic constant: %d ", (rows * rows + 1) * rows / 2); } int main(int argC,char* argV[]) { int n; if(argC!=2||isdigit(argV[1][0])==0) printf("Usage : %s <integer specifying rows in magic square>",argV[0]); else{ n = atoi(argV[1]); printMagicSquare(singlyEvenMagicSquare(n),n); } return 0; }
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 tj < 0: tj = s - 1 if q[ti][tj] != 0: ti = i tj = j + 1 i = ti j = tj p = p + 1 return q, s def build_sems(s): if s % 2 == 1: s += 1 while s % 4 == 0: s += 2 q = [[0 for j in range(s)] for i in range(s)] z = s // 2 b = z * z c = 2 * b d = 3 * b o = build_oms(z) for j in range(0, z): for i in range(0, z): a = o[0][i][j] q[i][j] = a q[i + z][j + z] = a + b q[i + z][j] = a + c q[i][j + z] = a + d lc = z // 2 rc = lc for j in range(0, z): for i in range(0, s): if i < lc or i > s - rc or (i == lc and j == lc): if not (i == 0 and j == lc): t = q[i][j] q[i][j] = q[i][j + z] q[i][j + z] = t return q, s def format_sqr(s, l): for i in range(0, l - len(s)): s = "0" + s return s + " " def display(q): s = q[1] print(" - {0} x {1}\n".format(s, s)) k = 1 + math.floor(math.log(s * s) / LOG_10) for j in range(0, s): for i in range(0, s): stdout.write(format_sqr("{0}".format(q[0][i][j]), k)) print() print("Magic sum: {0}\n".format(s * ((s * s) + 1) // 2)) stdout.write("Singly Even Magic Square") display(build_sems(6))
Ensure the translated Python code behaves exactly like the original C snippet.
#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'; pos[i] = i; } do{ kPos = rand()%8; rPos1 = rand()%8; rPos2 = rand()%8; }while((rPos1-kPos<=0 && rPos2-kPos<=0)||(rPos1-kPos>=0 && rPos2-kPos>=0)||(rPos1==rPos2 || kPos==rPos1 || kPos==rPos2)); rank[pos[rPos1]] = 'R'; rank[pos[kPos]] = 'K'; rank[pos[rPos2]] = 'R'; swap(rPos1,7); swap(rPos2,6); swap(kPos,5); do{ bPos1 = rand()%5; bPos2 = rand()%5; }while(((pos[bPos1]-pos[bPos2])%2==0)||(bPos1==bPos2)); rank[pos[bPos1]] = 'B'; rank[pos[bPos2]] = 'B'; swap(bPos1,4); swap(bPos2,3); do{ qPos = rand()%3; nPos1 = rand()%3; }while(qPos==nPos1); rank[pos[qPos]] = 'Q'; rank[pos[nPos1]] = 'N'; for(i=0;i<8;i++) if(rank[i]=='e'){ rank[i] = 'N'; break; } } void printRank(){ int i; #ifdef _WIN32 printf("%s\n",rank); #else { setlocale(LC_ALL,""); printf("\n"); for(i=0;i<8;i++){ if(rank[i]=='K') printf("%lc",(wint_t)9812); else if(rank[i]=='Q') printf("%lc",(wint_t)9813); else if(rank[i]=='R') printf("%lc",(wint_t)9814); else if(rank[i]=='B') printf("%lc",(wint_t)9815); if(rank[i]=='N') printf("%lc",(wint_t)9816); } } #endif } int main() { int i; srand((unsigned)time(NULL)); for(i=0;i<9;i++){ generateFirstRank(); printRank(); } return 0; }
>>> 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') < p.index('r') ) } >>> len(starts) 960 >>> starts.pop() 'QNBRNKRB' >>>
Change the programming language of this snippet from C to Python without modifying what it does.
int meaning_of_life();
def meaning_of_life(): return 42 if __name__ == "__main__": print("Main: The meaning of life is %s" % meaning_of_life())
Translate this program into Python but keep the logic exactly as in C.
int meaning_of_life();
def meaning_of_life(): return 42 if __name__ == "__main__": print("Main: The meaning of life is %s" % meaning_of_life())
Translate the given C code snippet into Python without altering its behavior.
#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; double u = h<8 ? x : y, v = h<4 ? y : h==12||h==14 ? x : z; return ((h&1) == 0 ? u : -u) + ((h&2) == 0 ? v : -v); } double noise(double x, double y, double z) { int X = (int)floor(x) & 255, Y = (int)floor(y) & 255, Z = (int)floor(z) & 255; x -= floor(x); y -= floor(y); z -= floor(z); double u = fade(x), v = fade(y), w = fade(z); int A = p[X ]+Y, AA = p[A]+Z, AB = p[A+1]+Z, B = p[X+1]+Y, BA = p[B]+Z, BB = p[B+1]+Z; return lerp(w, lerp(v, lerp(u, grad(p[AA ], x , y , z ), grad(p[BA ], x-1, y , z )), lerp(u, grad(p[AB ], x , y-1, z ), grad(p[BB ], x-1, y-1, z ))), lerp(v, lerp(u, grad(p[AA+1], x , y , z-1 ), grad(p[BA+1], x-1, y , z-1 )), lerp(u, grad(p[AB+1], x , y-1, z-1 ), grad(p[BB+1], x-1, y-1, z-1 )))); } void loadPermutation(char* fileName){ FILE* fp = fopen(fileName,"r"); int permutation[256],i; for(i=0;i<256;i++) fscanf(fp,"%d",&permutation[i]); fclose(fp); for (int i=0; i < 256 ; i++) p[256+i] = p[i] = permutation[i]; } int main(int argC,char* argV[]) { if(argC!=5) printf("Usage : %s <permutation data file> <x,y,z co-ordinates separated by space>"); else{ loadPermutation(argV[1]); printf("Perlin Noise for (%s,%s,%s) is %.17lf",argV[2],argV[3],argV[4],noise(strtod(argV[2],NULL),strtod(argV[3],NULL),strtod(argV[4],NULL))); } return 0; }
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) v = fade(y) w = fade(z) A = p[X ]+Y; AA = p[A]+Z; AB = p[A+1]+Z B = p[X+1]+Y; BA = p[B]+Z; BB = p[B+1]+Z return lerp(w, lerp(v, lerp(u, grad(p[AA ], x , y , z ), grad(p[BA ], x-1, y , z )), lerp(u, grad(p[AB ], x , y-1, z ), grad(p[BB ], x-1, y-1, z ))), lerp(v, lerp(u, grad(p[AA+1], x , y , z-1 ), grad(p[BA+1], x-1, y , z-1 )), lerp(u, grad(p[AB+1], x , y-1, z-1 ), grad(p[BB+1], x-1, y-1, z-1 )))) def fade(t): return t ** 3 * (t * (t * 6 - 15) + 10) def lerp(t, a, b): return a + t * (b - a) def grad(hash, x, y, z): h = hash & 15 u = x if h<8 else y v = y if h<4 else (x if h in (12, 14) else z) return (u if (h&1) == 0 else -u) + (v if (h&2) == 0 else -v) p = [None] * 512 permutation = [151,160,137,91,90,15, 131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23, 190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33, 88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166, 77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244, 102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196, 135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123, 5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42, 223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9, 129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228, 251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107, 49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254, 138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180] for i in range(256): p[256+i] = p[i] = permutation[i] if __name__ == '__main__': print("%1.17f" % perlin_noise(3.14, 42, 7))
Port the provided C code into Python while preserving the original functionality.
#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 <followed by directory to start search from(. for current dir), followed by \n optional parameters (T or G) to show text or graph output>",argV[0]); else{ if(strchr(argV[1],' ')!=NULL){ len = strlen(argV[1]); startPath = (char*)malloc((len+2)*sizeof(char)); startPath[0] = '\"'; startPath[len+1]='\"'; strncpy(startPath+1,argV[1],len); startPath[len+2] = argV[1][len]; sprintf(commandString,"forfiles /p %s /s /c \"cmd /c echo @fsize\" 2>&1",startPath); } else if(strlen(argV[1])==1 && argV[1][0]=='.') strcpy(commandString,"forfiles /s /c \"cmd /c echo @fsize\" 2>&1"); else sprintf(commandString,"forfiles /p %s /s /c \"cmd /c echo @fsize\" 2>&1",argV[1]); fp = popen(commandString,"r"); while(fgets(str,100,fp)!=NULL){ if(str[0]=='0') fileSizeLog[0]++; else fileSizeLog[strlen(str)]++; } if(argC==2 || (argC==3 && (argV[2][0]=='t'||argV[2][0]=='T'))){ for(i=0;i<MAXORDER;i++){ printf("\nSize Order < 10^%2d bytes : %Ld",i,fileSizeLog[i]); } } else if(argC==3 && (argV[2][0]=='g'||argV[2][0]=='G')){ CONSOLE_SCREEN_BUFFER_INFO csbi; int val = GetConsoleScreenBufferInfo(GetStdHandle( STD_OUTPUT_HANDLE ),&csbi); if(val) { max = fileSizeLog[0]; for(i=1;i<MAXORDER;i++) (fileSizeLog[i]>max)?max=fileSizeLog[i]:max; (max < csbi.dwSize.X)?(scale=1):(scale=(1.0*(csbi.dwSize.X-50))/max); for(i=0;i<MAXORDER;i++){ printf("\nSize Order < 10^%2d bytes |",i); for(j=0;j<(int)(scale*fileSizeLog[i]);j++) printf("%c",219); printf("%Ld",fileSizeLog[i]); } } } return 0; } }
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) else: pass def main(arg): global h h = Counter() for dir in arg: dodir(dir) s = n = 0 for k, v in sorted(h.items()): print("Size %d -> %d file(s)" % (k, v)) n += v s += k * v print("Total %d bytes for %d files" % (s, n)) main(sys.argv[1:])
Write the same algorithm in Python as shown in this C implementation.
#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 dirent *entry; char **dirnames; int diralloc = 128; int dirsize = 0; if (!(dirnames = malloc(diralloc * sizeof(char*)))) { perror("malloc error:"); return 1; } if (!getcwd(path, PATH_MAX)) { perror("getcwd error:"); return 1; } if (!(basedir = opendir(path))) { perror("opendir error:"); return 1; } while ((entry = readdir(basedir))) { if (dirsize >= diralloc) { diralloc *= 2; if (!(dirnames = realloc(dirnames, diralloc * sizeof(char*)))) { perror("realloc error:"); return 1; } } dirnames[dirsize++] = strdup(entry->d_name); } qsort(dirnames, dirsize, sizeof(char*), cmpstr); int i; for (i = 0; i < dirsize; ++i) { if (dirnames[i][0] != '.') { printf("%s\n", dirnames[i]); } } for (i = 0; i < dirsize; ++i) free(dirnames[i]); free(dirnames); closedir(basedir); return 0; }
>>> 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 >>>
Generate an equivalent Python version of this C code.
#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; int done; } rendezvous_t; #define RENDEZVOUS_INITILIZER(accept_function) { \ .lock = PTHREAD_MUTEX_INITIALIZER, \ .cv_entering = PTHREAD_COND_INITIALIZER, \ .cv_accepting = PTHREAD_COND_INITIALIZER, \ .cv_done = PTHREAD_COND_INITIALIZER, \ .accept_func = accept_function, \ .entering = 0, \ .accepting = 0, \ .done = 0, \ } int enter_rendezvous(rendezvous_t *rv, void* data) { pthread_mutex_lock(&rv->lock); rv->entering++; pthread_cond_signal(&rv->cv_entering); while (!rv->accepting) { pthread_cond_wait(&rv->cv_accepting, &rv->lock); } int ret = rv->accept_func(data); rv->done = 1; pthread_cond_signal(&rv->cv_done); rv->entering--; rv->accepting = 0; pthread_mutex_unlock(&rv->lock); return ret; } void accept_rendezvous(rendezvous_t *rv) { pthread_mutex_lock(&rv->lock); rv->accepting = 1; while (!rv->entering) { pthread_cond_wait(&rv->cv_entering, &rv->lock); } pthread_cond_signal(&rv->cv_accepting); while (!rv->done) { pthread_cond_wait(&rv->cv_done, &rv->lock); } rv->done = 0; rv->accepting = 0; pthread_mutex_unlock(&rv->lock); } typedef struct printer { rendezvous_t rv; struct printer *backup; int id; int remaining_lines; } printer_t; typedef struct print_args { struct printer *printer; const char* line; } print_args_t; int print_line(printer_t *printer, const char* line) { print_args_t args; args.printer = printer; args.line = line; return enter_rendezvous(&printer->rv, &args); } int accept_print(void* data) { print_args_t *args = (print_args_t*)data; printer_t *printer = args->printer; const char* line = args->line; if (printer->remaining_lines) { printf("%d: ", printer->id); while (*line != '\0') { putchar(*line++); } putchar('\n'); printer->remaining_lines--; return 1; } else if (printer->backup) { return print_line(printer->backup, line); } else { return -1; } } printer_t backup_printer = { .rv = RENDEZVOUS_INITILIZER(accept_print), .backup = NULL, .id = 2, .remaining_lines = 5, }; printer_t main_printer = { .rv = RENDEZVOUS_INITILIZER(accept_print), .backup = &backup_printer, .id = 1, .remaining_lines = 5, }; void* printer_thread(void* thread_data) { printer_t *printer = (printer_t*) thread_data; while (1) { accept_rendezvous(&printer->rv); } } typedef struct poem { char* name; char* lines[]; } poem_t; poem_t humpty_dumpty = { .name = "Humpty Dumpty", .lines = { "Humpty Dumpty sat on a wall.", "Humpty Dumpty had a great fall.", "All the king's horses and all the king's men", "Couldn't put Humpty together again.", "" }, }; poem_t mother_goose = { .name = "Mother Goose", .lines = { "Old Mother Goose", "When she wanted to wander,", "Would ride through the air", "On a very fine gander.", "Jack's mother came in,", "And caught the goose soon,", "And mounting its back,", "Flew up to the moon.", "" }, }; void* poem_thread(void* thread_data) { poem_t *poem = (poem_t*)thread_data; for (unsigned i = 0; poem->lines[i] != ""; i++) { int ret = print_line(&main_printer, poem->lines[i]); if (ret < 0) { printf(" %s out of ink!\n", poem->name); exit(1); } } return NULL; } int main(void) { pthread_t threads[4]; pthread_create(&threads[0], NULL, poem_thread, &humpty_dumpty); pthread_create(&threads[1], NULL, poem_thread, &mother_goose); pthread_create(&threads[2], NULL, printer_thread, &main_printer); pthread_create(&threads[3], NULL, printer_thread, &backup_printer); pthread_join(threads[0], NULL); pthread_join(threads[1], NULL); pthread_cancel(threads[2]); pthread_cancel(threads[3]); return 0; }
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 = 5 self.output_stream: TextIO = sys.stdout async def print(self, msg): if self.ink_level <= 0: if self.backup: await self.backup.print(msg) else: raise OutOfInkError(self.name) else: self.ink_level -= 1 self.output_stream.write(f"({self.name}): {msg}\n") async def main(): reserve = Printer("reserve", None) main = Printer("main", reserve) humpty_lines = [ "Humpty Dumpty sat on a wall.", "Humpty Dumpty had a great fall.", "All the king's horses and all the king's men,", "Couldn't put Humpty together again.", ] goose_lines = [ "Old Mother Goose,", "When she wanted to wander,", "Would ride through the air,", "On a very fine gander.", "Jack's mother came in,", "And caught the goose soon,", "And mounting its back,", "Flew up to the moon.", ] async def print_humpty(): for line in humpty_lines: try: task = asyncio.Task(main.print(line)) await task except OutOfInkError: print("\t Humpty Dumpty out of ink!") break async def print_goose(): for line in goose_lines: try: task = asyncio.Task(main.print(line)) await task except OutOfInkError: print("\t Mother Goose out of ink!") break await asyncio.gather(print_goose(), print_humpty()) if __name__ == "__main__": asyncio.run(main(), debug=True)
Write the same code in Python as shown below in C.
#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; } void switch_to(int id) { seq = &env[id].seq; cnt = &env[id].cnt; } int main() { int i; jobs(i) { env[i].seq = i + 1; } again: jobs(i) { hail(); } jobs(i) { if (1 != *seq) goto again; } printf("COUNTS:\n"); jobs(i) { printf("% 4d", *cnt); } return 0; }
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()
Write a version of this C function in Python with identical behavior.
#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 }, [2] = &(utf_t){0b00011111, 0b11000000, 0200, 03777, 5 }, [3] = &(utf_t){0b00001111, 0b11100000, 04000, 0177777, 4 }, [4] = &(utf_t){0b00000111, 0b11110000, 0200000, 04177777, 3 }, &(utf_t){0}, }; int codepoint_len(const uint32_t cp); int utf8_len(const char ch); char *to_utf8(const uint32_t cp); uint32_t to_cp(const char chr[4]); int codepoint_len(const uint32_t cp) { int len = 0; for(utf_t **u = utf; *u; ++u) { if((cp >= (*u)->beg) && (cp <= (*u)->end)) { break; } ++len; } if(len > 4) exit(1); return len; } int utf8_len(const char ch) { int len = 0; for(utf_t **u = utf; *u; ++u) { if((ch & ~(*u)->mask) == (*u)->lead) { break; } ++len; } if(len > 4) { exit(1); } return len; } char *to_utf8(const uint32_t cp) { static char ret[5]; const int bytes = codepoint_len(cp); int shift = utf[0]->bits_stored * (bytes - 1); ret[0] = (cp >> shift & utf[bytes]->mask) | utf[bytes]->lead; shift -= utf[0]->bits_stored; for(int i = 1; i < bytes; ++i) { ret[i] = (cp >> shift & utf[0]->mask) | utf[0]->lead; shift -= utf[0]->bits_stored; } ret[bytes] = '\0'; return ret; } uint32_t to_cp(const char chr[4]) { int bytes = utf8_len(*chr); int shift = utf[0]->bits_stored * (bytes - 1); uint32_t codep = (*chr++ & utf[bytes]->mask) << shift; for(int i = 1; i < bytes; ++i, ++chr) { shift -= utf[0]->bits_stored; codep |= ((char)*chr & utf[0]->mask) << shift; } return codep; } int main(void) { const uint32_t *in, input[] = {0x0041, 0x00f6, 0x0416, 0x20ac, 0x1d11e, 0x0}; printf("Character Unicode UTF-8 encoding (hex)\n"); printf("----------------------------------------\n"); char *utf8; uint32_t codepoint; for(in = input; *in; ++in) { utf8 = to_utf8(*in); codepoint = to_cp(utf8); printf("%s U+%-7.4x", utf8, codepoint); for(int i = 0; utf8[i] && i < 4; ++i) { printf("%hhx ", utf8[i]); } printf("\n"); } return 0; }
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)')) chars = ['A', 'ö', 'Ж', '€', '𝄞'] for char in chars: print('{:<11} {:<36} {:<15} {:<15}'.format(char, name(char), unicode_code(char), utf8hex(char)))
Generate a Python translation of this C snippet without changing its computational steps.
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 );
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) img.putpixel(xy, c) def draw_line(img, p1, p2, color): x1, y1 = p1 x2, y2 = p2 dx, dy = x2-x1, y2-y1 steep = abs(dx) < abs(dy) p = lambda px, py: ((px,py), (py,px))[steep] if steep: x1, y1, x2, y2, dx, dy = y1, x1, y2, x2, dy, dx if x2 < x1: x1, x2, y1, y2 = x2, x1, y2, y1 grad = dy/dx intery = y1 + _rfpart(x1) * grad def draw_endpoint(pt): x, y = pt xend = round(x) yend = y + grad * (xend - x) xgap = _rfpart(x + 0.5) px, py = int(xend), int(yend) putpixel(img, p(px, py), color, _rfpart(yend) * xgap) putpixel(img, p(px, py+1), color, _fpart(yend) * xgap) return px xstart = draw_endpoint(p(*p1)) + 1 xend = draw_endpoint(p(*p2)) for x in range(xstart, xend): y = int(intery) putpixel(img, p(x, y), color, _rfpart(intery)) putpixel(img, p(x, y+1), color, _fpart(intery)) intery += grad if __name__ == '__main__': if len(sys.argv) != 2: print 'usage: python xiaolinwu.py [output-file]' sys.exit(-1) blue = (0, 0, 255) yellow = (255, 255, 0) img = Image.new("RGB", (500,500), blue) for a in range(10, 431, 60): draw_line(img, (10, 10), (490, a), yellow) draw_line(img, (10, 10), (a, 490), yellow) draw_line(img, (10, 10), (490, 490), yellow) filename = sys.argv[1] img.save(filename) print 'image saved to', filename
Transform the following C implementation into Python, maintaining the same output and logic.
#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, GrabModeAsync, GrabModeAsync); XGrabKey(d, XKeysymToKeycode(d, XStringToKeysym("F6")), Mod1Mask, DefaultRootWindow(d), True, GrabModeAsync, GrabModeAsync); for(;;) { XNextEvent(d, &event); if ( event.type == KeyPress ) { KeySym s = XLookupKeysym(&event.xkey, 0); if ( s == XK_F7 ) { printf("something's happened\n"); } else if ( s == XK_F6 ) { break; } } } XUngrabKey(d, XKeysymToKeycode(d, XStringToKeysym("F7")), Mod1Mask, DefaultRootWindow(d)); XUngrabKey(d, XKeysymToKeycode(d, XStringToKeysym("F6")), Mod1Mask, DefaultRootWindow(d)); } return EXIT_SUCCESS; }
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.nocbreak() stdscr.keypad(0) curses.echo() curses.endwin()
Change the programming language of this snippet from C to Python without modifying what it does.
#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++) { if (sixes*6 + nines*9 == i) { i++; goto loopstart; } for (twenties = 0; twenties*20 < i; twenties++) { if (sixes*6 + nines*9 + twenties*20 == i) { i++; goto loopstart; } } } } max = i; i++; } printf("Maximum non-McNuggets number is %d\n", max); return 0; }
>>> 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 >>>
Write the same code in Python as shown below in C.
#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++) { if (sixes*6 + nines*9 == i) { i++; goto loopstart; } for (twenties = 0; twenties*20 < i; twenties++) { if (sixes*6 + nines*9 + twenties*20 == i) { i++; goto loopstart; } } } } max = i; i++; } printf("Maximum non-McNuggets number is %d\n", max); return 0; }
>>> 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 >>>
Preserve the algorithm and functionality while converting the code from C to Python.
#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)); for (r = 0, i = 0; r < n; r++) { for (c = 0; c < n; c++, i++) { bitPos = c / mult + (r / mult) * 4; result[r][c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i; } } return result; } int numDigits(int n){ int count = 1; while(n>=10){ n /= 10; count++; } return count; } void printMagicSquare(int** square,int rows){ int i,j,baseWidth = numDigits(rows*rows) + 3; printf("Doubly Magic Square of Order : %d and Magic Constant : %d\n\n",rows,(rows * rows + 1) * rows / 2); for(i=0;i<rows;i++){ for(j=0;j<rows;j++){ printf("%*s%d",baseWidth - numDigits(square[i][j]),"",square[i][j]); } printf("\n"); } } int main(int argC,char* argV[]) { int n; if(argC!=2||isdigit(argV[1][0])==0) printf("Usage : %s <integer specifying rows in magic square>",argV[0]); else{ n = atoi(argV[1]); printMagicSquare(doublyEvenMagicSquare(n),n); } return 0; }
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 for r in range(n1, order-n1): r1 = sq[r][:n1] r2 = sq[order -r - 1][order-n1:] r1.reverse() r2.reverse() sq[r][:n1] = r2 sq[order -r - 1][order-n1:] = r1 return sq def printsq(s): n = len(s) bl = len(str(n**2))+1 for i in range(n): print ''.join( [ ("%"+str(bl)+"s")%(str(x)) for x in s[i]] ) print "\nMagic constant = %d"%sum(s[0]) printsq(MagicSquareDoublyEven(8))
Preserve the algorithm and functionality while converting the code from C to Python.
#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",nan); printf("+inf + 2.0 = %f\n",inf + 2.0); printf("+inf - 10.1 = %f\n",inf - 10.1); printf("+inf + -inf = %f\n",inf + minus_inf); printf("0.0 * +inf = %f\n",0.0 * inf); printf("1.0/-0.0 = %f\n",1.0/minus_zero); printf("NaN + 1.0 = %f\n",nan + 1.0); printf("NaN + NaN = %f\n",nan + nan); printf("NaN == NaN = %s\n",nan == nan ? "true" : "false"); printf("0.0 == -0.0 = %s\n",0.0 == minus_zero ? "true" : "false"); return 0; }
>>> >>> 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 >>> >>> nan == nan False >>> nan is nan True >>> 0. == -0. True >>> 0. is -0. False >>> inf + _inf nan >>> 0.0 * nan nan >>> nan * 0.0 nan >>> 0.0 * inf nan >>> inf * 0.0 nan
Produce a functionally identical Python code for the snippet given in C.
#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",nan); printf("+inf + 2.0 = %f\n",inf + 2.0); printf("+inf - 10.1 = %f\n",inf - 10.1); printf("+inf + -inf = %f\n",inf + minus_inf); printf("0.0 * +inf = %f\n",0.0 * inf); printf("1.0/-0.0 = %f\n",1.0/minus_zero); printf("NaN + 1.0 = %f\n",nan + 1.0); printf("NaN + NaN = %f\n",nan + nan); printf("NaN == NaN = %s\n",nan == nan ? "true" : "false"); printf("0.0 == -0.0 = %s\n",0.0 == minus_zero ? "true" : "false"); return 0; }
>>> >>> 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 >>> >>> nan == nan False >>> nan is nan True >>> 0. == -0. True >>> 0. is -0. False >>> inf + _inf nan >>> 0.0 * nan nan >>> nan * 0.0 nan >>> 0.0 * inf nan >>> inf * 0.0 nan
Preserve the algorithm and functionality while converting the code from C to Python.
#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 >> 27); state = x; answer = ((x * STATE_MAGIC) >> 32); return answer; } float next_float() { return (float)next_int() / (1LL << 32); } int main() { int counts[5] = { 0, 0, 0, 0, 0 }; int i; seed(1234567); printf("%u\n", next_int()); printf("%u\n", next_int()); printf("%u\n", next_int()); printf("%u\n", next_int()); printf("%u\n", next_int()); printf("\n"); seed(987654321); for (i = 0; i < 100000; i++) { int j = (int)floor(next_float() * 5.0); counts[j]++; } for (i = 0; i < 5; i++) { printf("%d: %d\n", i, counts[i]); } return 0; }
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 = self.state x = (x ^ (x >> 12)) & mask64 x = (x ^ (x << 25)) & mask64 x = (x ^ (x >> 27)) & mask64 self.state = x answer = (((x * const) & mask64) >> 32) & mask32 return answer def next_float(self): "return random float between 0 and 1" return self.next_int() / (1 << 32) if __name__ == '__main__': random_gen = Xorshift_star() random_gen.seed(1234567) for i in range(5): print(random_gen.next_int()) random_gen.seed(987654321) hist = {i:0 for i in range(5)} for i in range(100_000): hist[int(random_gen.next_float() *5)] += 1 print(hist)
Translate the given C code snippet into Python without altering its behavior.
#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" }, { "two", "second" }, { "three", "third" }, { "four", "fourth" }, { "five", "fifth" }, { "six", "sixth" }, { "seven", "seventh" }, { "eight", "eighth" }, { "nine", "ninth" }, { "ten", "tenth" }, { "eleven", "eleventh" }, { "twelve", "twelfth" }, { "thirteen", "thirteenth" }, { "fourteen", "fourteenth" }, { "fifteen", "fifteenth" }, { "sixteen", "sixteenth" }, { "seventeen", "seventeenth" }, { "eighteen", "eighteenth" }, { "nineteen", "nineteenth" } }; const number_names tens[] = { { "twenty", "twentieth" }, { "thirty", "thirtieth" }, { "forty", "fortieth" }, { "fifty", "fiftieth" }, { "sixty", "sixtieth" }, { "seventy", "seventieth" }, { "eighty", "eightieth" }, { "ninety", "ninetieth" } }; typedef struct named_number_tag { const char* cardinal; const char* ordinal; integer number; } named_number; const named_number named_numbers[] = { { "hundred", "hundredth", 100 }, { "thousand", "thousandth", 1000 }, { "million", "millionth", 1000000 }, { "billion", "biliionth", 1000000000 }, { "trillion", "trillionth", 1000000000000 }, { "quadrillion", "quadrillionth", 1000000000000000ULL }, { "quintillion", "quintillionth", 1000000000000000000ULL } }; const char* get_small_name(const number_names* n, bool ordinal) { return ordinal ? n->ordinal : n->cardinal; } const char* get_big_name(const named_number* n, bool ordinal) { return ordinal ? n->ordinal : n->cardinal; } const named_number* get_named_number(integer n) { const size_t names_len = sizeof(named_numbers)/sizeof(named_numbers[0]); for (size_t i = 0; i + 1 < names_len; ++i) { if (n < named_numbers[i + 1].number) return &named_numbers[i]; } return &named_numbers[names_len - 1]; } typedef struct word_tag { size_t offset; size_t length; } word_t; typedef struct word_list_tag { GArray* words; GString* str; } word_list; void word_list_create(word_list* words) { words->words = g_array_new(FALSE, FALSE, sizeof(word_t)); words->str = g_string_new(NULL); } void word_list_destroy(word_list* words) { g_string_free(words->str, TRUE); g_array_free(words->words, TRUE); } void word_list_clear(word_list* words) { g_string_truncate(words->str, 0); g_array_set_size(words->words, 0); } void word_list_append(word_list* words, const char* str) { size_t offset = words->str->len; size_t len = strlen(str); g_string_append_len(words->str, str, len); word_t word; word.offset = offset; word.length = len; g_array_append_val(words->words, word); } word_t* word_list_get(word_list* words, size_t index) { return &g_array_index(words->words, word_t, index); } void word_list_extend(word_list* words, const char* str) { word_t* word = word_list_get(words, words->words->len - 1); size_t len = strlen(str); word->length += len; g_string_append_len(words->str, str, len); } size_t append_number_name(word_list* words, integer n, bool ordinal) { size_t count = 0; if (n < 20) { word_list_append(words, get_small_name(&small[n], ordinal)); count = 1; } else if (n < 100) { if (n % 10 == 0) { word_list_append(words, get_small_name(&tens[n/10 - 2], ordinal)); } else { word_list_append(words, get_small_name(&tens[n/10 - 2], false)); word_list_extend(words, "-"); word_list_extend(words, get_small_name(&small[n % 10], ordinal)); } count = 1; } else { const named_number* num = get_named_number(n); integer p = num->number; count += append_number_name(words, n/p, false); if (n % p == 0) { word_list_append(words, get_big_name(num, ordinal)); ++count; } else { word_list_append(words, get_big_name(num, false)); ++count; count += append_number_name(words, n % p, ordinal); } } return count; } size_t count_letters(word_list* words, size_t index) { const word_t* word = word_list_get(words, index); size_t letters = 0; const char* s = words->str->str + word->offset; for (size_t i = 0, n = word->length; i < n; ++i) { if (isalpha((unsigned char)s[i])) ++letters; } return letters; } void sentence(word_list* result, size_t count) { static const char* words[] = { "Four", "is", "the", "number", "of", "letters", "in", "the", "first", "word", "of", "this", "sentence," }; word_list_clear(result); size_t n = sizeof(words)/sizeof(words[0]); for (size_t i = 0; i < n; ++i) word_list_append(result, words[i]); for (size_t i = 1; count > n; ++i) { n += append_number_name(result, count_letters(result, i), false); word_list_append(result, "in"); word_list_append(result, "the"); n += 2; n += append_number_name(result, i + 1, true); word_list_extend(result, ","); } } size_t sentence_length(const word_list* words) { size_t n = words->words->len; if (n == 0) return 0; return words->str->len + n - 1; } int main() { setlocale(LC_ALL, ""); size_t n = 201; word_list result = { 0 }; word_list_create(&result); sentence(&result, n); printf("Number of letters in first %'lu words in the sequence:\n", n); for (size_t i = 0; i < n; ++i) { if (i != 0) printf("%c", i % 25 == 0 ? '\n' : ' '); printf("%'2lu", count_letters(&result, i)); } printf("\nSentence length: %'lu\n", sentence_length(&result)); for (n = 1000; n <= 10000000; n *= 10) { sentence(&result, n); const word_t* word = word_list_get(&result, n - 1); const char* s = result.str->str + word->offset; printf("The %'luth word is '%.*s' and has %lu letters. ", n, (int)word->length, s, count_letters(&result, n - 1)); printf("Sentence length: %'lu\n" , sentence_length(&result)); } word_list_destroy(&result); return 0; }
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 c == " " and curr_word != "": sentence_list.append(curr_word+" ") curr_word = "" else: curr_word += c if len(curr_word) > 0: sentence_list.append(curr_word) return sentence_list def my_num_to_words(p, my_number): number_string_list = p.number_to_words(my_number, wantlist=True, andword='') number_string = number_string_list[0] for i in range(1,len(number_string_list)): number_string += " " + number_string_list[i] return number_string def build_sentence(p, max_words): sentence_list = split_with_spaces("Four is the number of letters in the first word of this sentence,") num_words = 13 word_number = 2 while num_words < max_words: ordinal_string = my_num_to_words(p, p.ordinal(word_number)) word_number_string = my_num_to_words(p, count_letters(sentence_list[word_number - 1])) new_string = " "+word_number_string+" in the "+ordinal_string+"," new_list = split_with_spaces(new_string) sentence_list += new_list num_words += len(new_list) word_number += 1 return sentence_list, num_words def word_and_counts(word_num): sentence_list, num_words = build_sentence(p, word_num) word_str = sentence_list[word_num - 1].strip(' ,') num_letters = len(word_str) num_characters = 0 for word in sentence_list: num_characters += len(word) print('Word {0:8d} is "{1}", with {2} letters. Length of the sentence so far: {3} '.format(word_num,word_str,num_letters,num_characters)) p = inflect.engine() sentence_list, num_words = build_sentence(p, 201) print(" ") print("The lengths of the first 201 words are:") print(" ") print('{0:3d}: '.format(1),end='') total_characters = 0 for word_index in range(201): word_length = count_letters(sentence_list[word_index]) total_characters += len(sentence_list[word_index]) print('{0:2d}'.format(word_length),end='') if (word_index+1) % 20 == 0: print(" ") print('{0:3d}: '.format(word_index + 2),end='') else: print(" ",end='') print(" ") print(" ") print("Length of the sentence so far: "+str(total_characters)) print(" ") word_and_counts(1000) word_and_counts(10000) word_and_counts(100000) word_and_counts(1000000) word_and_counts(10000000)
Port the provided C code into Python while preserving the original functionality.
#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| Opcode |AA|TC|RD|RA| Z | RCODE |", " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+", " | QDCOUNT |", " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+", " | ANCOUNT |", " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+", " | NSCOUNT |", " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+", " | ARCOUNT |", " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" }; typedef struct { unsigned bit3s; unsigned mask; unsigned data; char A[NAME_SZ+2]; }NAME_T; NAME_T names[MAX_NAMES]; unsigned idx_name; enum{ID,BITS,QDCOUNT,ANCOUNT,NSCOUNT,ARCOUNT,MAX_HDR}; unsigned header[MAX_HDR]; unsigned idx_hdr; int bit_hdr(char *pLine); int bit_names(char *pLine); void dump_names(void); void make_test_hdr(void); int main(void){ char *p1; int rv; printf("Extract meta-data from bit-encoded text form\n"); make_test_hdr(); idx_name = 0; for( int i=0; i<MAX_ROWS;i++ ){ p1 = Lines[i]; if( p1==NULL ) break; if( rv = bit_hdr(Lines[i]), rv>0) continue; if( rv = bit_names(Lines[i]),rv>0) continue; } dump_names(); } int bit_hdr(char *pLine){ char *p1 = strchr(pLine,'+'); if( p1==NULL ) return 0; int numbits=0; for( int i=0; i<strlen(p1)-1; i+=3 ){ if( p1[i] != '+' || p1[i+1] != '-' || p1[i+2] != '-' ) return 0; numbits++; } return numbits; } int bit_names(char *pLine){ char *p1,*p2 = pLine, tmp[80]; unsigned sz=0, maskbitcount = 15; while(1){ p1 = strchr(p2,'|'); if( p1==NULL ) break; p1++; p2 = strchr(p1,'|'); if( p2==NULL ) break; sz = p2-p1; tmp[sz] = 0; int k=0; for(int j=0; j<sz;j++){ if( p1[j] > ' ') tmp[k++] = p1[j]; } tmp[k]= 0; sz++; NAME_T *pn = &names[idx_name++]; strcpy(&pn->A[0], &tmp[0]); pn->bit3s = sz/3; if( pn->bit3s < 16 ){ for( int i=0; i<pn->bit3s; i++){ pn->mask |= 1 << maskbitcount--; } pn->data = header[idx_hdr] & pn->mask; unsigned m2 = pn->mask; while( (m2 & 1)==0 ){ m2>>=1; pn->data >>= 1; } if( pn->mask == 0xf ) idx_hdr++; } else{ pn->data = header[idx_hdr++]; } } return sz; } void dump_names(void){ NAME_T *pn; printf("-name-bits-mask-data-\n"); for( int i=0; i<MAX_NAMES; i++ ){ pn = &names[i]; if( pn->bit3s < 1 ) break; printf("%10s %2d X%04x = %u\n",pn->A, pn->bit3s, pn->mask, pn->data); } puts("bye.."); } void make_test_hdr(void){ header[ID] = 1024; header[QDCOUNT] = 12; header[ANCOUNT] = 34; header[NSCOUNT] = 56; header[ARCOUNT] = 78; header[BITS] = 0xB50A; }
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(lines[0]) cols = (width - 1) // 3 if cols not in [8, 16, 32, 64]: print('number of columns should be 8, 16, 32 or 64') return None if len(lines)%2 == 0: print('number of non-empty lines should be odd') return None if lines[0] != (('+--' * cols)+'+'): print('incorrect header line') return None for i in range(len(lines)): line=lines[i] if i == 0: continue elif i%2 == 0: if line != lines[0]: print('incorrect separator line') return None elif len(line) != width: print('inconsistent line widths') return None elif line[0] != '|' or line[width-1] != '|': print("non-separator lines must begin and end with '|'") return None return lines def decode(lines): print("Name Bits Start End") print("======= ==== ===== ===") startbit = 0 results = [] for line in lines: infield=False for c in line: if not infield and c == '|': infield = True spaces = 0 name = '' elif infield: if c == ' ': spaces += 1 elif c != '|': name += c else: bits = (spaces + len(name) + 1) // 3 endbit = startbit + bits - 1 print('{0:7} {1:2d} {2:2d} {3:2d}'.format(name, bits, startbit, endbit)) reslist = [name, bits, startbit, endbit] results.append(reslist) spaces = 0 name = '' startbit += bits return results def unpack(results, hex): print("\nTest string in hex:") print(hex) print("\nTest string in binary:") bin = f'{int(hex, 16):0>{4*len(hex)}b}' print(bin) print("\nUnpacked:\n") print("Name Size Bit pattern") print("======= ==== ================") for r in results: name = r[0] size = r[1] startbit = r[2] endbit = r[3] bitpattern = bin[startbit:endbit+1] print('{0:7} {1:2d} {2:16}'.format(name, size, bitpattern)) diagram = lines = validate(diagram) if lines == None: print("No lines returned") else: print(" ") print("Diagram after trimming whitespace and removal of blank lines:") print(" ") for line in lines: print(line) print(" ") print("Decoded:") print(" ") results = decode(lines) hex = "78477bbf5496e12e1bf169a4" unpack(results, hex)
Preserve the algorithm and functionality while converting the code from C to Python.
#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_t)); for (i = 1; i <= la; i++) tbl[i] = tbl[i-1] + (1+lb); for (i = la; i >= 0; i--) { char *aa = a + i; for (j = lb; j >= 0; j--) { char *bb = b + j; if (!*aa && !*bb) continue; edit e = &tbl[i][j]; edit repl = &tbl[i+1][j+1]; edit dela = &tbl[i+1][j]; edit delb = &tbl[i][j+1]; e->c1 = *aa; e->c2 = *bb; if (!*aa) { e->next = delb; e->n = e->next->n + 1; continue; } if (!*bb) { e->next = dela; e->n = e->next->n + 1; continue; } e->next = repl; if (*aa == *bb) { e->n = e->next->n; continue; } if (e->next->n > delb->n) { e->next = delb; e->c1 = 0; } if (e->next->n > dela->n) { e->next = dela; e->c1 = *aa; e->c2 = 0; } e->n = e->next->n + 1; } } edit p = tbl[0]; printf("%s -> %s: %d edits\n", a, b, p->n); while (p->next) { if (p->c1 == p->c2) printf("%c", p->c1); else { putchar('('); if (p->c1) putchar(p->c1); putchar(','); if (p->c2) putchar(p->c2); putchar(')'); } p = p->next; } putchar('\n'); free(tbl[0]); free(tbl); } int main(void) { leven("raisethysword", "rosettacode"); return 0; }
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 removed > 0: removed -=1 else: result += "-" print(result) levenshtein("place","palace") levenshtein("rosettacode","raisethysword")
Ensure the translated Python code behaves exactly like the original C snippet.
#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
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 = len(seq) if size < 2: return seq low, middle, up = partition(seq, random.choice(seq)) return qsortranpart(low) + middle + qsortranpart(up)
Convert this C block to Python, preserving its control flow and logic.
#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
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 = len(seq) if size < 2: return seq low, middle, up = partition(seq, random.choice(seq)) return qsortranpart(low) + middle + qsortranpart(up)
Translate this program into Python but keep the logic exactly as in C.
#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_stack.ss_size = sizeof(c->stack); c->callee.uc_link = &c->caller; makecontext(&c->callee, f, 1, (int)c); return c; } void co_del(co_t *c) { free(c); } inline void co_yield(co_t *c, void *data) { c->out = data; swapcontext(&c->callee, &c->caller); } inline void * co_collect(co_t *c) { c->out = 0; swapcontext(&c->caller, &c->callee); return c->out; } typedef struct node node; struct node { int v; node *left, *right; }; node *newnode(int v) { node *n = malloc(sizeof(node)); n->left = n->right = 0; n->v = v; return n; } void tree_insert(node **root, node *n) { while (*root) root = ((*root)->v > n->v) ? &(*root)->left : &(*root)->right; *root = n; } void tree_trav(int x) { co_t *c = (co_t *) x; void trav(node *root) { if (!root) return; trav(root->left); co_yield(c, root); trav(root->right); } trav(c->in); } int tree_eq(node *t1, node *t2) { co_t *c1 = co_new(tree_trav, t1); co_t *c2 = co_new(tree_trav, t2); node *p = 0, *q = 0; do { p = co_collect(c1); q = co_collect(c2); } while (p && q && (p->v == q->v)); co_del(c1); co_del(c2); return !p && !q; } int main() { int x[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1 }; int y[] = { 2, 5, 7, 1, 9, 0, 6, 4, 8, 3, -1 }; int z[] = { 0, 1, 2, 3, 4, 5, 6, 8, 9, -1 }; node *t1 = 0, *t2 = 0, *t3 = 0; void mktree(int *buf, node **root) { int i; for (i = 0; buf[i] >= 0; i++) tree_insert(root, newnode(buf[i])); } mktree(x, &t1); mktree(y, &t2); mktree(z, &t3); printf("t1 == t2: %s\n", tree_eq(t1, t2) ? "yes" : "no"); printf("t1 == t3: %s\n", tree_eq(t1, t3) ? "yes" : "no"); return 0; }
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 same_fringe(tree1, tree2): return all(node1 == node2 for node1, node2 in izip_longest(fringe(tree1), fringe(tree2))) if __name__ == '__main__': a = 1, 2, 3, 4, 5, 6, 7, 8 b = 1, (( 2, 3 ), (4, (5, ((6, 7), 8)))) c = (((1, 2), 3), 4), 5, 6, 7, 8 x = 1, 2, 3, 4, 5, 6, 7, 8, 9 y = 0, 2, 3, 4, 5, 6, 7, 8 z = 1, 2, (4, 3), 5, 6, 7, 8 assert same_fringe(a, a) assert same_fringe(a, b) assert same_fringe(a, c) assert not same_fringe(a, x) assert not same_fringe(a, y) assert not same_fringe(a, z)
Ensure the translated Python code behaves exactly like the original C snippet.
#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" "-t Sort by title.\n" "-d Sort by date.\n" "-a Sort by author.\n",argv[0]); return 0; } for (i=0;commands[i]&&strcmp(argv[1],commands[i]);i++); switch (i) { case CREATE: ... break; case PRINT: ... break; ... ... default: printf ("Unknown command..." ...); goto usage; } return 0; }
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 status messages to stdout") (options, args) = parser.parse_args() example: <yourscript> --file=outfile -q
Ensure the translated Python code behaves exactly like the original C snippet.
#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" "-t Sort by title.\n" "-d Sort by date.\n" "-a Sort by author.\n",argv[0]); return 0; } for (i=0;commands[i]&&strcmp(argv[1],commands[i]);i++); switch (i) { case CREATE: ... break; case PRINT: ... break; ... ... default: printf ("Unknown command..." ...); goto usage; } return 0; }
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 status messages to stdout") (options, args) = parser.parse_args() example: <yourscript> --file=outfile -q
Change the programming language of this snippet from C to Python without modifying what it does.
#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; }
[print("( " + "1"*i + "3 ) ^ 2 = " + str(int("1"*i + "3")**2)) for i in range(0,8)]
Transform the following C implementation into Python, maintaining the same output and logic.
#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; }
[print("( " + "1"*i + "3 ) ^ 2 = " + str(int("1"*i + "3")**2)) for i in range(0,8)]
Generate a Python translation of this C snippet without changing its computational steps.
#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("Cannot open display", stderr); exit(1); } scr = XDefaultScreen(dpy); win = XCreateSimpleWindow(dpy, XRootWindow(dpy, scr), 10, 10, 300, 200, 1, XBlackPixel(dpy, scr), XWhitePixel(dpy, scr)); XStoreName(dpy, win, argv[0]); XSelectInput(dpy, win, ExposureMask | KeyPressMask | ButtonPressMask); XMapWindow(dpy, win); XFlush(dpy); gc = XDefaultGC(dpy, scr); WM_DELETE_WINDOW = XInternAtom(dpy, "WM_DELETE_WINDOW", True); XSetWMProtocols(dpy, win, &WM_DELETE_WINDOW, 1); loop = 1; while (loop) { XNextEvent(dpy, &ev); switch (ev.type) { case Expose: { char msg1[] = "Clic in the window to generate"; char msg2[] = "a key press event"; XDrawString(dpy, win, gc, 10, 20, msg1, sizeof(msg1)-1); XDrawString(dpy, win, gc, 10, 35, msg2, sizeof(msg2)-1); } break; case ButtonPress: puts("ButtonPress event received"); ev2.type = KeyPress; ev2.xkey.state = ShiftMask; ev2.xkey.keycode = 24 + (rand() % 33); ev2.xkey.same_screen = True; XSendEvent(dpy, win, True, KeyPressMask, &ev2); break; case ClientMessage: if (ev.xclient.data.l[0] == WM_DELETE_WINDOW) loop = 0; break; case KeyPress: puts("KeyPress event received"); printf("> keycode: %d\n", ev.xkey.keycode); keysym = XLookupKeysym(&(ev.xkey), 0); if (keysym == XK_q || keysym == XK_Escape) { loop = 0; } else { char buffer[] = " "; int nchars = XLookupString( &(ev.xkey), buffer, 2, &keysym, NULL ); if (nchars == 1) printf("> Key '%c' pressed\n", buffer[0]); } break; } } XDestroyWindow(dpy, win); XCloseDisplay(dpy); return 1; }
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)
Port the following code from C to Python with equivalent syntax and logic.
#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; releaseNode(head->next); head->next = NULL; free(head); } typedef struct List_t { struct Node_t *head; struct Node_t *tail; size_t length; } List; List makeList() { return (List) { NULL, NULL, 0 }; } void releaseList(List *lst) { if (lst == NULL) return; releaseNode(lst->head); lst->head = NULL; lst->tail = NULL; } void addNode(List *lst, Position pos) { struct Node_t *newNode; if (lst == NULL) { exit(EXIT_FAILURE); } newNode = malloc(sizeof(struct Node_t)); if (newNode == NULL) { exit(EXIT_FAILURE); } newNode->next = NULL; newNode->pos = pos; if (lst->head == NULL) { lst->head = lst->tail = newNode; } else { lst->tail->next = newNode; lst->tail = newNode; } lst->length++; } void removeAt(List *lst, size_t pos) { if (lst == NULL) return; if (pos == 0) { struct Node_t *temp = lst->head; if (lst->tail == lst->head) { lst->tail = NULL; } lst->head = lst->head->next; temp->next = NULL; free(temp); lst->length--; } else { struct Node_t *temp = lst->head; struct Node_t *rem; size_t i = pos; while (i-- > 1) { temp = temp->next; } rem = temp->next; if (rem == lst->tail) { lst->tail = temp; } temp->next = rem->next; rem->next = NULL; free(rem); lst->length--; } } bool isAttacking(Position queen, Position pos) { return queen.x == pos.x || queen.y == pos.y || abs(queen.x - pos.x) == abs(queen.y - pos.y); } bool place(int m, int n, List *pBlackQueens, List *pWhiteQueens) { struct Node_t *queenNode; bool placingBlack = true; int i, j; if (pBlackQueens == NULL || pWhiteQueens == NULL) { exit(EXIT_FAILURE); } if (m == 0) return true; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { Position pos = { i, j }; queenNode = pBlackQueens->head; while (queenNode != NULL) { if ((queenNode->pos.x == pos.x && queenNode->pos.y == pos.y) || !placingBlack && isAttacking(queenNode->pos, pos)) { goto inner; } queenNode = queenNode->next; } queenNode = pWhiteQueens->head; while (queenNode != NULL) { if ((queenNode->pos.x == pos.x && queenNode->pos.y == pos.y) || placingBlack && isAttacking(queenNode->pos, pos)) { goto inner; } queenNode = queenNode->next; } if (placingBlack) { addNode(pBlackQueens, pos); placingBlack = false; } else { addNode(pWhiteQueens, pos); if (place(m - 1, n, pBlackQueens, pWhiteQueens)) { return true; } removeAt(pBlackQueens, pBlackQueens->length - 1); removeAt(pWhiteQueens, pWhiteQueens->length - 1); placingBlack = true; } inner: {} } } if (!placingBlack) { removeAt(pBlackQueens, pBlackQueens->length - 1); } return false; } void printBoard(int n, List *pBlackQueens, List *pWhiteQueens) { size_t length = n * n; struct Node_t *queenNode; char *board; size_t i, j, k; if (pBlackQueens == NULL || pWhiteQueens == NULL) { exit(EXIT_FAILURE); } board = calloc(length, sizeof(char)); if (board == NULL) { exit(EXIT_FAILURE); } queenNode = pBlackQueens->head; while (queenNode != NULL) { board[queenNode->pos.x * n + queenNode->pos.y] = Black; queenNode = queenNode->next; } queenNode = pWhiteQueens->head; while (queenNode != NULL) { board[queenNode->pos.x * n + queenNode->pos.y] = White; queenNode = queenNode->next; } for (i = 0; i < length; i++) { if (i != 0 && i % n == 0) { printf("\n"); } switch (board[i]) { case Black: printf("B "); break; case White: printf("W "); break; default: j = i / n; k = i - j * n; if (j % 2 == k % 2) { printf(" "); } else { printf("# "); } break; } } printf("\n\n"); } void test(int n, int q) { List blackQueens = makeList(); List whiteQueens = makeList(); printf("%d black and %d white queens on a %d x %d board:\n", q, q, n, n); if (place(q, n, &blackQueens, &whiteQueens)) { printBoard(n, &blackQueens, &whiteQueens); } else { printf("No solution exists.\n\n"); } releaseList(&blackQueens); releaseList(&whiteQueens); } int main() { test(2, 1); test(3, 1); test(3, 2); test(4, 1); test(4, 2); test(4, 3); test(5, 1); test(5, 2); test(5, 3); test(5, 4); test(5, 5); test(6, 1); test(6, 2); test(6, 3); test(6, 4); test(6, 5); test(6, 6); test(7, 1); test(7, 2); test(7, 3); test(7, 4); test(7, 5); test(7, 6); test(7, 7); return EXIT_SUCCESS; }
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 combinations(board, m)} for blacks in placements: black_attacks = reduce(_or, (queen_attacks_from(pos, n) for pos in blacks), set()) for whites in {frozenset(c) for c in combinations(board - black_attacks, m)}: if not black_attacks & whites: return blacks, whites return set(), set() @lru_cache(maxsize=None) def queen_attacks_from(pos, n): x0, y0 = pos a = set([pos]) a.update((x, y0) for x in range(n)) a.update((x0, y) for y in range(n)) for x1 in range(n): y1 = y0 -x0 +x1 if 0 <= y1 < n: a.add((x1, y1)) y1 = y0 +x0 -x1 if 0 <= y1 < n: a.add((x1, y1)) return a def pboard(black_white, n): "Print board" if black_white is None: blk, wht = set(), set() else: blk, wht = black_white print(f" f"on a {n}-by-{n} board:", end='') for x, y in product(range(n), repeat=2): if y == 0: print() xy = (x, y) ch = ('?' if xy in blk and xy in wht else 'B' if xy in blk else 'W' if xy in wht else _bbullet if (x + y)%2 else _wbullet) print('%s' % ch, end='') print() if __name__ == '__main__': n=2 for n in range(2, 7): print() for m in count(1): ans = place(m, n) if ans[0]: pboard(ans, n) else: print (f" break print('\n') m, n = 5, 7 ans = place(m, n) pboard(ans, n)
Write the same code in Python as shown below in C.
#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(long)==8); int main() { COMPILE_TIME_ASSERT(sizeof(int)==4); }
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]]
Produce a functionally identical Python code for the snippet given in C.
#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%10 ? ' ' : '\n'); printf("\n"); return 0; }
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()
Maintain the same structure and functionality when rewriting this code in Python.
#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; } printf( "%ld\n", n ); return 0; }
def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True if __name__ == '__main__': n = 600851475143 j = 3 while not isPrime(n): if n % j == 0: n /= j j += 2 print(n);
Rewrite this program in Python while keeping its functionality equivalent to the C version.
#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; } printf( "%ld\n", n ); return 0; }
def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True if __name__ == '__main__': n = 600851475143 j = 3 while not isPrime(n): if n % j == 0: n /= j j += 2 print(n);
Change the programming language of this snippet from C to Python without modifying what it does.
#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; }
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 '')
Generate an equivalent Python version of this C code.
#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 shift; } void decode(int* pass,int size,char *sym) { int i,index; char c; char table[]="abcdefghijklmnopqrstuvwxyz"; for(i=0;i<size;i++) { c=table[pass[i]]; index=move_to_front(table,c); if(pass[i]!=index) printf("there is an error"); sym[i]=c; } sym[size]='\0'; } void encode(char *sym,int size,int *pass) { int i=0; char c; char table[]="abcdefghijklmnopqrstuvwxyz"; for(i=0;i<size;i++) { c=sym[i]; pass[i]=move_to_front(table,c); } } int check(char *sym,int size,int *pass) { int *pass2=malloc(sizeof(int)*size); char *sym2=malloc(sizeof(char)*size); int i,val=1; encode(sym,size,pass2); i=0; while(i<size && pass[i]==pass2[i])i++; if(i!=size)val=0; decode(pass,size,sym2); if(strcmp(sym,sym2)!=0)val=0; free(sym2); free(pass2); return val; } int main() { char sym[3][MAX_SIZE]={"broood","bananaaa","hiphophiphop"}; int pass[MAX_SIZE]={0}; int i,len,j; for(i=0;i<3;i++) { len=strlen(sym[i]); encode(sym[i],len,pass); printf("%s : [",sym[i]); for(j=0;j<len;j++) printf("%d ",pass[j]); printf("]\n"); if(check(sym[i],len,pass)) printf("Correct :)\n"); else printf("Incorrect :(\n"); } return 0; }
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 return sequence def move2front_decode(sequence, symboltable): chars, pad = [], symboltable[::] for indx in sequence: char = pad[indx] chars.append(char) pad = [pad.pop(indx)] + pad return ''.join(chars) if __name__ == '__main__': for s in ['broood', 'bananaaa', 'hiphophiphop']: encode = move2front_encode(s, SYMBOLTABLE) print('%14r encodes to %r' % (s, encode), end=', ') decode = move2front_decode(encode, SYMBOLTABLE) print('which decodes back to %r' % decode) assert s == decode, 'Whoops!'
Produce a functionally identical Python code for the snippet given in C.
#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(*result); ldap_unbind(ld);
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
Rewrite the snippet below in Python so it works the same as the original C code.
#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)); } printf("\b|\n"); } printf("\n"); } int main(){ double a[] = {3, 0, 4, 5}; gsl_matrix_view A = gsl_matrix_view_array(a, 2, 2); gsl_matrix *V = gsl_matrix_alloc(2, 2); gsl_vector *S = gsl_vector_alloc(2); gsl_vector *work = gsl_vector_alloc(2); gsl_linalg_SV_decomp(&A.matrix, V, S, work); gsl_matrix_transpose(V); double s[] = {S->data[0], 0, 0, S->data[1]}; gsl_matrix_view SM = gsl_matrix_view_array(s, 2, 2); printf("U:\n"); gsl_matrix_print(&A.matrix); printf("S:\n"); gsl_matrix_print(&SM.matrix); printf("VT:\n"); gsl_matrix_print(V); gsl_matrix_free(V); gsl_vector_free(S); gsl_vector_free(work); return 0; }
from numpy import * A = matrix([[3, 0], [4, 5]]) U, Sigma, VT = linalg.svd(A) print(U) print(Sigma) print(VT)
Can you help me rewrite this code in Python instead of C, keeping it the same logically?
#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; }
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: print(" ") print(f"\nEncontrados {fila} cubos.") if __name__ == '__main__': main()
Change the following C code into Python without altering its purpose.
#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)") #define CMPPARTS(x, y) ((long double complex)((long double)(x) + \ I * (long double)(y))) #define TEST_CMPL(i, j)\ printf(FMTSPEC(i), i), printf(" + "), printf(FMTSPEC(j), j), \ printf("i = %s\n", (isint(CMPPARTS(i, j)) ? "true" : "false")) #define TEST_REAL(i)\ printf(FMTSPEC(i), i), printf(" = %s\n", (isint(i) ? "true" : "false")) static inline int isint(long double complex n) { return cimagl(n) == 0 && nearbyintl(creall(n)) == creall(n); } int main(void) { TEST_REAL(0); TEST_REAL(-0); TEST_REAL(-2); TEST_REAL(-2.00000000000001); TEST_REAL(5); TEST_REAL(7.3333333333333); TEST_REAL(3.141592653589); TEST_REAL(-9.223372036854776e18); TEST_REAL(5e-324); TEST_REAL(NAN); TEST_CMPL(6, 0); TEST_CMPL(0, 1); TEST_CMPL(0, 0); TEST_CMPL(3.4, 0); double complex test1 = 5 + 0*I, test2 = 3.4f, test3 = 3, test4 = 0 + 1.2*I; printf("Test 1 (5+i) = %s\n", isint(test1) ? "true" : "false"); printf("Test 2 (3.4+0i) = %s\n", isint(test2) ? "true" : "false"); printf("Test 3 (3+0i) = %s\n", isint(test3) ? "true" : "false"); printf("Test 4 (0+1.2i) = %s\n", isint(test4) ? "true" : "false"); }
>>> 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(-5e-2) False >>> isint(float('nan')) False >>> isint(float('inf')) False >>> isint(5.0+0.0j) True >>> isint(5-5j) False
Convert this C snippet to Python and keep its semantics consistent.
#include <stdlib.h> int main() { system("ls"); return 0; }
import os exit_code = os.system('ls') output = os.popen('ls').read()
Translate the given C code snippet into Python without altering its behavior.
#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 ret; xmlLineNumbersDefault(1); ctxt = xmlSchemaNewParserCtxt(XSDFileName); xmlSchemaSetParserErrors(ctxt, (xmlSchemaValidityErrorFunc) fprintf, (xmlSchemaValidityWarningFunc) fprintf, stderr); schema = xmlSchemaParse(ctxt); xmlSchemaFreeParserCtxt(ctxt); doc = xmlReadFile(XMLFileName, NULL, 0); if (doc == NULL){ fprintf(stderr, "Could not parse %s\n", XMLFileName); } else{ xmlSchemaValidCtxtPtr ctxt; ctxt = xmlSchemaNewValidCtxt(schema); xmlSchemaSetValidErrors(ctxt, (xmlSchemaValidityErrorFunc) fprintf, (xmlSchemaValidityWarningFunc) fprintf, stderr); ret = xmlSchemaValidateDoc(ctxt, doc); if (ret == 0){ printf("%s validates\n", XMLFileName); } else if (ret > 0){ printf("%s fails to validate\n", XMLFileName); } else{ printf("%s validation generated an internal error\n", XMLFileName); } xmlSchemaFreeValidCtxt(ctxt); xmlFreeDoc(doc); } if(schema != NULL) xmlSchemaFree(schema); xmlSchemaCleanupTypes(); xmlCleanupParser(); xmlMemoryDump(); return 0; }
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 ("Finished validating good xml") except lxml.etree.XMLSyntaxError as err: print (err) parser = etree.XMLParser(schema = schema) try: root = etree.fromstring("<a>5<b>foobar</b></a>", parser) except lxml.etree.XMLSyntaxError as err: print (err)
Convert the following code from C to Python, ensuring the logic remains intact.
#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 >= n[i].len) { n[i].next = p; n[i].len = p->len + 1; } } } for (i = 0, p = n; i < len; i++) if (n[i].len > p->len) p = n + i; do printf(" %d", p->val); while ((p = p->next)); putchar('\n'); free(n); } int main(void) { int x[] = { 3, 2, 6, 4, 5, 1 }; int y[] = { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 }; lis(x, sizeof(x) / sizeof(int)); lis(y, sizeof(y) / sizeof(int)); return 0; }
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 newL = lo P[i] = M[newL-1] M[newL] = i if (newL > L): L = newL S = [] k = M[L] for i in range(L-1, -1, -1): S.append(X[k]) k = P[k] return S[::-1] if __name__ == '__main__': for d in [[3,2,6,4,5,1], [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]]: print('a L.I.S. of %s is %s' % (d, longest_increasing_subsequence(d)))
Change the following C code into Python without altering its purpose.
#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[1] + x[2]*y[2]; return d < 0 ? -d : 0; } typedef struct { double cx, cy, cz, r; } sphere_t; sphere_t pos = { 20, 20, 0, 20 }, neg = { 1, 1, -6, 20 }; int hit_sphere(sphere_t *sph, double x, double y, double *z1, double *z2) { double zsq; x -= sph->cx; y -= sph->cy; zsq = sph->r * sph->r - (x * x + y * y); if (zsq < 0) return 0; zsq = sqrt(zsq); *z1 = sph->cz - zsq; *z2 = sph->cz + zsq; return 1; } void draw_sphere(double k, double ambient) { int i, j, intensity, hit_result; double b; double vec[3], x, y, zb1, zb2, zs1, zs2; for (i = floor(pos.cy - pos.r); i <= ceil(pos.cy + pos.r); i++) { y = i + .5; for (j = floor(pos.cx - 2 * pos.r); j <= ceil(pos.cx + 2 * pos.r); j++) { x = (j - pos.cx) / 2. + .5 + pos.cx; if (!hit_sphere(&pos, x, y, &zb1, &zb2)) hit_result = 0; else if (!hit_sphere(&neg, x, y, &zs1, &zs2)) hit_result = 1; else if (zs1 > zb1) hit_result = 1; else if (zs2 > zb2) hit_result = 0; else if (zs2 > zb1) hit_result = 2; else hit_result = 1; switch(hit_result) { case 0: putchar('+'); continue; case 1: vec[0] = x - pos.cx; vec[1] = y - pos.cy; vec[2] = zb1 - pos.cz; break; default: vec[0] = neg.cx - x; vec[1] = neg.cy - y; vec[2] = neg.cz - zs2; } normalize(vec); b = pow(dot(light, vec), k) + ambient; intensity = (1 - b) * (sizeof(shades) - 1); if (intensity < 0) intensity = 0; if (intensity >= sizeof(shades) - 1) intensity = sizeof(shades) - 2; putchar(shades[intensity]); } putchar('\n'); } } int main() { double ang = 0; while (1) { printf("\033[H"); light[1] = cos(ang * 2); light[2] = cos(ang); light[0] = sin(ang); normalize(light); ang += .05; draw_sphere(2, .3); usleep(100000); } return 0; }
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 else 0.0 def hit_sphere(sph, x0, y0): x = x0 - sph.cx y = y0 - sph.cy zsq = sph.r ** 2 - (x ** 2 + y ** 2) if zsq < 0: return (False, 0, 0) szsq = math.sqrt(zsq) return (True, sph.cz - szsq, sph.cz + szsq) def draw_sphere(k, ambient, light): shades = ".:!*oe& pos = Sphere(20.0, 20.0, 0.0, 20.0) neg = Sphere(1.0, 1.0, -6.0, 20.0) for i in xrange(int(math.floor(pos.cy - pos.r)), int(math.ceil(pos.cy + pos.r) + 1)): y = i + 0.5 for j in xrange(int(math.floor(pos.cx - 2 * pos.r)), int(math.ceil(pos.cx + 2 * pos.r) + 1)): x = (j - pos.cx) / 2.0 + 0.5 + pos.cx (h, zb1, zb2) = hit_sphere(pos, x, y) if not h: hit_result = 0 else: (h, zs1, zs2) = hit_sphere(neg, x, y) if not h: hit_result = 1 elif zs1 > zb1: hit_result = 1 elif zs2 > zb2: hit_result = 0 elif zs2 > zb1: hit_result = 2 else: hit_result = 1 if hit_result == 0: sys.stdout.write(' ') continue elif hit_result == 1: vec = V3(x - pos.cx, y - pos.cy, zb1 - pos.cz) elif hit_result == 2: vec = V3(neg.cx-x, neg.cy-y, neg.cz-zs2) vec = normalize(vec) b = dot(light, vec) ** k + ambient intensity = int((1 - b) * len(shades)) intensity = min(len(shades), max(0, intensity)) sys.stdout.write(shades[intensity]) print light = normalize(V3(-50, 30, 50)) draw_sphere(2, 0.5, light)
Write the same code in Python as shown below in C.
#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; } } for (j = i + 1; j < LUCKY_SIZE; j++) { if (luckyArray[j] > 0) { luckyArray[i++] = luckyArray[j]; } } for (; i < LUCKY_SIZE; i++) { luckyArray[i] = 0; } } void initialize() { int i, j; for (i = 0; i < LUCKY_SIZE; i++) { luckyEven[i] = 2 * i + 2; luckyOdd[i] = 2 * i + 1; } for (i = 1; i < LUCKY_SIZE; i++) { if (luckyOdd[i] > 0) { for (j = luckyOdd[i] - 1; j < LUCKY_SIZE; j += luckyOdd[i]) { luckyOdd[j] = 0; } compactLucky(luckyOdd); } } for (i = 1; i < LUCKY_SIZE; i++) { if (luckyEven[i] > 0) { for (j = luckyEven[i] - 1; j < LUCKY_SIZE; j += luckyEven[i]) { luckyEven[j] = 0; } compactLucky(luckyEven); } } } void printBetween(size_t j, size_t k, bool even) { int i; if (even) { if (luckyEven[j] == 0 || luckyEven[k] == 0) { fprintf(stderr, "At least one argument is too large\n"); exit(EXIT_FAILURE); } printf("Lucky even numbers between %d and %d are:", j, k); for (i = 0; luckyEven[i] != 0; i++) { if (luckyEven[i] > k) { break; } if (luckyEven[i] > j) { printf(" %d", luckyEven[i]); } } } else { if (luckyOdd[j] == 0 || luckyOdd[k] == 0) { fprintf(stderr, "At least one argument is too large\n"); exit(EXIT_FAILURE); } printf("Lucky numbers between %d and %d are:", j, k); for (i = 0; luckyOdd[i] != 0; i++) { if (luckyOdd[i] > k) { break; } if (luckyOdd[i] > j) { printf(" %d", luckyOdd[i]); } } } printf("\n"); } void printRange(size_t j, size_t k, bool even) { int i; if (even) { if (luckyEven[k] == 0) { fprintf(stderr, "The argument is too large\n"); exit(EXIT_FAILURE); } printf("Lucky even numbers %d to %d are:", j, k); for (i = j - 1; i < k; i++) { printf(" %d", luckyEven[i]); } } else { if (luckyOdd[k] == 0) { fprintf(stderr, "The argument is too large\n"); exit(EXIT_FAILURE); } printf("Lucky numbers %d to %d are:", j, k); for (i = j - 1; i < k; i++) { printf(" %d", luckyOdd[i]); } } printf("\n"); } void printSingle(size_t j, bool even) { if (even) { if (luckyEven[j] == 0) { fprintf(stderr, "The argument is too large\n"); exit(EXIT_FAILURE); } printf("Lucky even number %d=%d\n", j, luckyEven[j - 1]); } else { if (luckyOdd[j] == 0) { fprintf(stderr, "The argument is too large\n"); exit(EXIT_FAILURE); } printf("Lucky number %d=%d\n", j, luckyOdd[j - 1]); } } void help() { printf("./lucky j [k] [--lucky|--evenLucky]\n"); printf("\n"); printf(" argument(s) | what is displayed\n"); printf("==============================================\n"); printf("-j=m | mth lucky number\n"); printf("-j=m --lucky | mth lucky number\n"); printf("-j=m --evenLucky | mth even lucky number\n"); printf("-j=m -k=n | mth through nth (inclusive) lucky numbers\n"); printf("-j=m -k=n --lucky | mth through nth (inclusive) lucky numbers\n"); printf("-j=m -k=n --evenLucky | mth through nth (inclusive) even lucky numbers\n"); printf("-j=m -k=-n | all lucky numbers in the range [m, n]\n"); printf("-j=m -k=-n --lucky | all lucky numbers in the range [m, n]\n"); printf("-j=m -k=-n --evenLucky | all even lucky numbers in the range [m, n]\n"); } void process(int argc, char *argv[]) { bool evenLucky = false; int j = 0; int k = 0; bool good = false; int i; for (i = 1; i < argc; ++i) { if ('-' == argv[i][0]) { if ('-' == argv[i][1]) { if (0 == strcmp("--lucky", argv[i])) { evenLucky = false; } else if (0 == strcmp("--evenLucky", argv[i])) { evenLucky = true; } else { fprintf(stderr, "Unknown long argument: [%s]\n", argv[i]); exit(EXIT_FAILURE); } } else { if ('j' == argv[i][1] && '=' == argv[i][2] && argv[i][3] != 0) { good = true; j = atoi(&argv[i][3]); } else if ('k' == argv[i][1] && '=' == argv[i][2]) { k = atoi(&argv[i][3]); } else { fprintf(stderr, "Unknown short argument: [%s]\n", argv[i]); exit(EXIT_FAILURE); } } } else { fprintf(stderr, "Unknown argument: [%s]\n", argv[i]); exit(EXIT_FAILURE); } } if (!good) { help(); exit(EXIT_FAILURE); } if (k > 0) { printRange(j, k, evenLucky); } else if (k < 0) { printBetween(j, -k, evenLucky); } else { printSingle(j, evenLucky); } } void test() { printRange(1, 20, false); printRange(1, 20, true); printBetween(6000, 6100, false); printBetween(6000, 6100, true); printSingle(10000, false); printSingle(10000, true); } int main(int argc, char *argv[]) { initialize(); if (argc < 2) { help(); return 1; } process(argc, argv); return 0; }
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[n]] lenlst = len(lst) for i in lst[n:]: yield i
Transform the following C implementation into Python, maintaining the same output and logic.
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; }
>>> 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(scoped_nonlocal()) def scoped_global(): global x return "scoped_global scope gives x = " + x print(scoped_global()) def scoped_notdefinedlocally(): return "scoped_notdefinedlocally scope gives x = " + x print(scoped_notdefinedlocally()) >>> outerfunc() scoped_local scope gives x = scope local scoped_nonlocal scope gives x = From scope at outerfunc scoped_global scope gives x = From global scope scoped_notdefinedlocally scope gives x = From global scope >>>
Produce a language-to-language conversion: from C to Python, same semantics.
#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 by_##foo (const void*p1, const void*p2) { \ return strcmp ((*(const pdb_t*)p1)->foo, (*(const pdb_t*)p2)->foo); } typedef struct db { char title[26]; char first_name[26]; char last_name[26]; time_t date; char publ[100]; struct db *next; } db_t,*pdb_t; typedef int (sort)(const void*, const void*); enum {CREATE,PRINT,TITLE,DATE,AUTH,READLINE,READ,SORT,DESTROY}; static pdb_t dao (int cmd, FILE *f, pdb_t db, sort sortby); static char *time2str (time_t *time); static time_t str2time (char *date); sort_by(last_name); sort_by(title); static int by_date(pdb_t *p1, pdb_t *p2); int main (int argc, char **argv) { char buf[100]; const char *commands[]={"-c", "-p", "-t", "-d", "-a", NULL}; db_t db; db.next=NULL; pdb_t dblist; int i; FILE *f; TRY (f=fopen(DB,"a+")); if (argc<2) { usage: printf ("Usage: %s [commands]\n" "-c Create new entry.\n" "-p Print the latest entry.\n" "-t Print all entries sorted by title.\n" "-d Print all entries sorted by date.\n" "-a Print all entries sorted by author.\n",argv[0]); fclose (f); return 0; } for (i=0;commands[i]&&strcmp(argv[1],commands[i]);i++); switch (i) { case CREATE: printf("-c Create a new entry.\n"); printf("Title  :");if((scanf(" %25[^\n]",db.title ))<0)break; printf("Author Firstname:");if((scanf(" %25[^\n]",db.first_name))<0)break; printf("Author Lastname :");if((scanf(" %25[^\n]",db.last_name ))<0)break; printf("Date 10-12-2000 :");if((scanf(" %10[^\n]",buf ))<0)break; printf("Publication  :");if((scanf(" %99[^\n]",db.publ ))<0)break; db.date=str2time (buf); dao (CREATE,f,&db,NULL); break; case PRINT: printf ("-p Print the latest entry.\n"); while (!feof(f)) dao (READLINE,f,&db,NULL); dao (PRINT,f,&db,NULL); break; case TITLE: printf ("-t Print all entries sorted by title.\n"); dblist = dao (READ,f,&db,NULL); dblist = dao (SORT,f,dblist,by_title); dao (PRINT,f,dblist,NULL); dao (DESTROY,f,dblist,NULL); break; case DATE: printf ("-d Print all entries sorted by date.\n"); dblist = dao (READ,f,&db,NULL); dblist = dao (SORT,f,dblist,(int (*)(const void *,const void *)) by_date); dao (PRINT,f,dblist,NULL); dao (DESTROY,f,dblist,NULL); break; case AUTH: printf ("-a Print all entries sorted by author.\n"); dblist = dao (READ,f,&db,NULL); dblist = dao (SORT,f,dblist,by_last_name); dao (PRINT,f,dblist,NULL); dao (DESTROY,f,dblist,NULL); break; default: { printf ("Unknown command: %s.\n",strlen(argv[1])<10?argv[1]:""); goto usage; } } fclose (f); return 0; } static pdb_t dao (int cmd, FILE *f, pdb_t in_db, sort sortby) { pdb_t *pdb=NULL,rec=NULL,hd=NULL; int i=0,ret; char buf[100]; switch (cmd) { case CREATE: fprintf (f,"\"%s\",",in_db->title); fprintf (f,"\"%s\",",in_db->first_name); fprintf (f,"\"%s\",",in_db->last_name); fprintf (f,"\"%s\",",time2str(&in_db->date)); fprintf (f,"\"%s\" \n",in_db->publ); break; case PRINT: for (;in_db;i++) { printf ("Title  : %s\n", in_db->title); printf ("Author  : %s %s\n", in_db->first_name, in_db->last_name); printf ("Date  : %s\n", time2str(&in_db->date)); printf ("Publication : %s\n\n", in_db->publ); if (!((i+1)%3)) { printf ("Press Enter to continue.\n"); ret = scanf ("%*[^\n]"); if (ret<0) return rec; else getchar(); } in_db=in_db->next; } break; case READLINE: if((fscanf(f," \"%[^\"]\",",in_db->title ))<0)break; if((fscanf(f," \"%[^\"]\",",in_db->first_name))<0)break; if((fscanf(f," \"%[^\"]\",",in_db->last_name ))<0)break; if((fscanf(f," \"%[^\"]\",",buf ))<0)break; if((fscanf(f," \"%[^\"]\" ",in_db->publ ))<0)break; in_db->date=str2time (buf); break; case READ: while (!feof(f)) { dao (READLINE,f,in_db,NULL); TRY (rec=malloc(sizeof(db_t))); *rec=*in_db; rec->next=hd; hd=rec;i++; } if (i<2) { puts ("Empty database. Please create some entries."); fclose (f); exit (0); } break; case SORT: rec=in_db; for (;in_db;i++) in_db=in_db->next; TRY (pdb=malloc(i*sizeof(pdb_t))); in_db=rec; for (i=0;in_db;i++) { pdb[i]=in_db; in_db=in_db->next; } qsort (pdb,i,sizeof in_db,sortby); pdb[i-1]->next=NULL; for (i=i-1;i;i--) { pdb[i-1]->next=pdb[i]; } rec=pdb[0]; FREE (pdb); pdb=NULL; break; case DESTROY: { while ((rec=in_db)) { in_db=in_db->next; FREE (rec); } } } return rec; } static char *time2str (time_t *time) { static char buf[255]; struct tm *ptm; ptm=localtime (time); strftime(buf, 255, "%m-%d-%Y", ptm); return buf; } static time_t str2time (char *date) { struct tm tm; memset (&tm, 0, sizeof(struct tm)); strptime(date, "%m-%d-%Y", &tm); return mktime(&tm); } static int by_date (pdb_t *p1, pdb_t *p2) { if ((*p1)->date < (*p2)->date) { return -1; } else return ((*p1)->date > (*p2)->date); }
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=) parser.add_argument('-d', '--description', help='A description of the item. (e.g., title, name)') parser.add_argument('-t', '--tag', help=( )) parser.add_argument('-f', '--field', nargs=2, action='append', help='Other optional fields with value (can be repeated)') return parser def do_add(args, dbname): 'Add a new entry' if args.description is None: args.description = '' if args.tag is None: args.tag = '' del args.command print('Writing record to %s' % dbname) with open(dbname, 'a') as db: db.write('%r\n' % args) def do_pl(args, dbname): 'Print the latest entry' print('Getting last record from %s' % dbname) with open(dbname, 'r') as db: for line in db: pass record = eval(line) del record._date print(str(record)) def do_plc(args, dbname): 'Print the latest entry for each category/tag' print('Getting latest record for each tag from %s' % dbname) with open(dbname, 'r') as db: records = [eval(line) for line in db] tags = set(record.tag for record in records) records.reverse() for record in records: if record.tag in tags: del record._date print(str(record)) tags.discard(record.tag) if not tags: break def do_pa(args, dbname): 'Print all entries sorted by a date' print('Getting all records by date from %s' % dbname) with open(dbname, 'r') as db: records = [eval(line) for line in db] for record in records: del record._date print(str(record)) def test(): import time parser = parse_args() for cmdline in [ , , , , , ]: args = parser.parse_args(shlex.split(cmdline)) now = datetime.datetime.utcnow() args._date = now.isoformat() do_command[args.command](args, dbname) time.sleep(0.5) do_command = dict(add=do_add, pl=do_pl, plc=do_plc, pa=do_pa) dbname = '_simple_db_db.py' if __name__ == '__main__': if 0: test() else: parser = parse_args() args = parser.parse_args() now = datetime.datetime.utcnow() args._date = now.isoformat() do_command[args.command](args, dbname)
Write the same code in Python as shown below in C.
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #include <stdbool.h> typedef double Fp; typedef struct { Fp x, y, r; } Circle; Circle circles[] = { { 1.6417233788, 1.6121789534, 0.0848270516}, {-1.4944608174, 1.2077959613, 1.1039549836}, { 0.6110294452, -0.6907087527, 0.9089162485}, { 0.3844862411, 0.2923344616, 0.2375743054}, {-0.2495892950, -0.3832854473, 1.0845181219}, { 1.7813504266, 1.6178237031, 0.8162655711}, {-0.1985249206, -0.8343333301, 0.0538864941}, {-1.7011985145, -0.1263820964, 0.4776976918}, {-0.4319462812, 1.4104420482, 0.7886291537}, { 0.2178372997, -0.9499557344, 0.0357871187}, {-0.6294854565, -1.3078893852, 0.7653357688}, { 1.7952608455, 0.6281269104, 0.2727652452}, { 1.4168575317, 1.0683357171, 1.1016025378}, { 1.4637371396, 0.9463877418, 1.1846214562}, {-0.5263668798, 1.7315156631, 1.4428514068}, {-1.2197352481, 0.9144146579, 1.0727263474}, {-0.1389358881, 0.1092805780, 0.7350208828}, { 1.5293954595, 0.0030278255, 1.2472867347}, {-0.5258728625, 1.3782633069, 1.3495508831}, {-0.1403562064, 0.2437382535, 1.3804956588}, { 0.8055826339, -0.0482092025, 0.3327165165}, {-0.6311979224, 0.7184578971, 0.2491045282}, { 1.4685857879, -0.8347049536, 1.3670667538}, {-0.6855727502, 1.6465021616, 1.0593087096}, { 0.0152957411, 0.0638919221, 0.9771215985}}; const size_t n_circles = sizeof(circles) / sizeof(Circle); static inline Fp min(const Fp a, const Fp b) { return a <= b ? a : b; } static inline Fp max(const Fp a, const Fp b) { return a >= b ? a : b; } static inline Fp sq(const Fp a) { return a * a; } static inline double uniform(const double a, const double b) { const double r01 = rand() / (double)RAND_MAX; return a + (b - a) * r01; } static inline bool is_inside_circles(const Fp x, const Fp y) { for (size_t i = 0; i < n_circles; i++) if (sq(x - circles[i].x) + sq(y - circles[i].y) < circles[i].r) return true; return false; } int main() { Fp x_min = INFINITY, x_max = -INFINITY; Fp y_min = x_min, y_max = x_max; for (size_t i = 0; i < n_circles; i++) { Circle *c = &circles[i]; x_min = min(x_min, c->x - c->r); x_max = max(x_max, c->x + c->r); y_min = min(y_min, c->y - c->r); y_max = max(y_max, c->y + c->r); c->r *= c->r; } const Fp bbox_area = (x_max - x_min) * (y_max - y_min); srand(time(0)); size_t to_try = 1U << 16; size_t n_tries = 0; size_t n_hits = 0; while (true) { n_hits += is_inside_circles(uniform(x_min, x_max), uniform(y_min, y_max)); n_tries++; if (n_tries == to_try) { const Fp area = bbox_area * n_hits / n_tries; const Fp r = (Fp)n_hits / n_tries; const Fp s = area * sqrt(r * (1 - r) / n_tries); printf("%.4f +/- %.4f (%zd samples)\n", area, s, n_tries); if (s * 3 <= 1e-3) break; to_try *= 2; } } return 0; }
from collections import namedtuple Circle = namedtuple("Circle", "x y r") circles = [ Circle( 1.6417233788, 1.6121789534, 0.0848270516), Circle(-1.4944608174, 1.2077959613, 1.1039549836), Circle( 0.6110294452, -0.6907087527, 0.9089162485), Circle( 0.3844862411, 0.2923344616, 0.2375743054), Circle(-0.2495892950, -0.3832854473, 1.0845181219), Circle( 1.7813504266, 1.6178237031, 0.8162655711), Circle(-0.1985249206, -0.8343333301, 0.0538864941), Circle(-1.7011985145, -0.1263820964, 0.4776976918), Circle(-0.4319462812, 1.4104420482, 0.7886291537), Circle( 0.2178372997, -0.9499557344, 0.0357871187), Circle(-0.6294854565, -1.3078893852, 0.7653357688), Circle( 1.7952608455, 0.6281269104, 0.2727652452), Circle( 1.4168575317, 1.0683357171, 1.1016025378), Circle( 1.4637371396, 0.9463877418, 1.1846214562), Circle(-0.5263668798, 1.7315156631, 1.4428514068), Circle(-1.2197352481, 0.9144146579, 1.0727263474), Circle(-0.1389358881, 0.1092805780, 0.7350208828), Circle( 1.5293954595, 0.0030278255, 1.2472867347), Circle(-0.5258728625, 1.3782633069, 1.3495508831), Circle(-0.1403562064, 0.2437382535, 1.3804956588), Circle( 0.8055826339, -0.0482092025, 0.3327165165), Circle(-0.6311979224, 0.7184578971, 0.2491045282), Circle( 1.4685857879, -0.8347049536, 1.3670667538), Circle(-0.6855727502, 1.6465021616, 1.0593087096), Circle( 0.0152957411, 0.0638919221, 0.9771215985)] def main(): x_min = min(c.x - c.r for c in circles) x_max = max(c.x + c.r for c in circles) y_min = min(c.y - c.r for c in circles) y_max = max(c.y + c.r for c in circles) box_side = 500 dx = (x_max - x_min) / box_side dy = (y_max - y_min) / box_side count = 0 for r in xrange(box_side): y = y_min + r * dy for c in xrange(box_side): x = x_min + c * dx if any((x-circle.x)**2 + (y-circle.y)**2 <= (circle.r ** 2) for circle in circles): count += 1 print "Approximated area:", count * dx * dy main()
Port the provided C code into Python while preserving the original functionality.
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #include <stdbool.h> typedef double Fp; typedef struct { Fp x, y, r; } Circle; Circle circles[] = { { 1.6417233788, 1.6121789534, 0.0848270516}, {-1.4944608174, 1.2077959613, 1.1039549836}, { 0.6110294452, -0.6907087527, 0.9089162485}, { 0.3844862411, 0.2923344616, 0.2375743054}, {-0.2495892950, -0.3832854473, 1.0845181219}, { 1.7813504266, 1.6178237031, 0.8162655711}, {-0.1985249206, -0.8343333301, 0.0538864941}, {-1.7011985145, -0.1263820964, 0.4776976918}, {-0.4319462812, 1.4104420482, 0.7886291537}, { 0.2178372997, -0.9499557344, 0.0357871187}, {-0.6294854565, -1.3078893852, 0.7653357688}, { 1.7952608455, 0.6281269104, 0.2727652452}, { 1.4168575317, 1.0683357171, 1.1016025378}, { 1.4637371396, 0.9463877418, 1.1846214562}, {-0.5263668798, 1.7315156631, 1.4428514068}, {-1.2197352481, 0.9144146579, 1.0727263474}, {-0.1389358881, 0.1092805780, 0.7350208828}, { 1.5293954595, 0.0030278255, 1.2472867347}, {-0.5258728625, 1.3782633069, 1.3495508831}, {-0.1403562064, 0.2437382535, 1.3804956588}, { 0.8055826339, -0.0482092025, 0.3327165165}, {-0.6311979224, 0.7184578971, 0.2491045282}, { 1.4685857879, -0.8347049536, 1.3670667538}, {-0.6855727502, 1.6465021616, 1.0593087096}, { 0.0152957411, 0.0638919221, 0.9771215985}}; const size_t n_circles = sizeof(circles) / sizeof(Circle); static inline Fp min(const Fp a, const Fp b) { return a <= b ? a : b; } static inline Fp max(const Fp a, const Fp b) { return a >= b ? a : b; } static inline Fp sq(const Fp a) { return a * a; } static inline double uniform(const double a, const double b) { const double r01 = rand() / (double)RAND_MAX; return a + (b - a) * r01; } static inline bool is_inside_circles(const Fp x, const Fp y) { for (size_t i = 0; i < n_circles; i++) if (sq(x - circles[i].x) + sq(y - circles[i].y) < circles[i].r) return true; return false; } int main() { Fp x_min = INFINITY, x_max = -INFINITY; Fp y_min = x_min, y_max = x_max; for (size_t i = 0; i < n_circles; i++) { Circle *c = &circles[i]; x_min = min(x_min, c->x - c->r); x_max = max(x_max, c->x + c->r); y_min = min(y_min, c->y - c->r); y_max = max(y_max, c->y + c->r); c->r *= c->r; } const Fp bbox_area = (x_max - x_min) * (y_max - y_min); srand(time(0)); size_t to_try = 1U << 16; size_t n_tries = 0; size_t n_hits = 0; while (true) { n_hits += is_inside_circles(uniform(x_min, x_max), uniform(y_min, y_max)); n_tries++; if (n_tries == to_try) { const Fp area = bbox_area * n_hits / n_tries; const Fp r = (Fp)n_hits / n_tries; const Fp s = area * sqrt(r * (1 - r) / n_tries); printf("%.4f +/- %.4f (%zd samples)\n", area, s, n_tries); if (s * 3 <= 1e-3) break; to_try *= 2; } } return 0; }
from collections import namedtuple Circle = namedtuple("Circle", "x y r") circles = [ Circle( 1.6417233788, 1.6121789534, 0.0848270516), Circle(-1.4944608174, 1.2077959613, 1.1039549836), Circle( 0.6110294452, -0.6907087527, 0.9089162485), Circle( 0.3844862411, 0.2923344616, 0.2375743054), Circle(-0.2495892950, -0.3832854473, 1.0845181219), Circle( 1.7813504266, 1.6178237031, 0.8162655711), Circle(-0.1985249206, -0.8343333301, 0.0538864941), Circle(-1.7011985145, -0.1263820964, 0.4776976918), Circle(-0.4319462812, 1.4104420482, 0.7886291537), Circle( 0.2178372997, -0.9499557344, 0.0357871187), Circle(-0.6294854565, -1.3078893852, 0.7653357688), Circle( 1.7952608455, 0.6281269104, 0.2727652452), Circle( 1.4168575317, 1.0683357171, 1.1016025378), Circle( 1.4637371396, 0.9463877418, 1.1846214562), Circle(-0.5263668798, 1.7315156631, 1.4428514068), Circle(-1.2197352481, 0.9144146579, 1.0727263474), Circle(-0.1389358881, 0.1092805780, 0.7350208828), Circle( 1.5293954595, 0.0030278255, 1.2472867347), Circle(-0.5258728625, 1.3782633069, 1.3495508831), Circle(-0.1403562064, 0.2437382535, 1.3804956588), Circle( 0.8055826339, -0.0482092025, 0.3327165165), Circle(-0.6311979224, 0.7184578971, 0.2491045282), Circle( 1.4685857879, -0.8347049536, 1.3670667538), Circle(-0.6855727502, 1.6465021616, 1.0593087096), Circle( 0.0152957411, 0.0638919221, 0.9771215985)] def main(): x_min = min(c.x - c.r for c in circles) x_max = max(c.x + c.r for c in circles) y_min = min(c.y - c.r for c in circles) y_max = max(c.y + c.r for c in circles) box_side = 500 dx = (x_max - x_min) / box_side dy = (y_max - y_min) / box_side count = 0 for r in xrange(box_side): y = y_min + r * dy for c in xrange(box_side): x = x_min + c * dx if any((x-circle.x)**2 + (y-circle.y)**2 <= (circle.r ** 2) for circle in circles): count += 1 print "Approximated area:", count * dx * dy main()
Preserve the algorithm and functionality while converting the code from C to Python.
#include "SL_Generated.h" #include "CImg.h" using namespace cimg_library; int main( int argc, char** argv ) { string fileName = "Pentagon.bmp"; if(argc > 1) fileName = argv[1]; int thetaAxisSize = 640; if(argc > 2) thetaAxisSize = atoi(argv[2]); int rAxisSize = 480; if(argc > 3) rAxisSize = atoi(argv[3]); int minContrast = 64; if(argc > 4) minContrast = atoi(argv[4]); int threads = 0; if(argc > 5) threads = atoi(argv[5]); char titleBuffer[200]; SLTimer t; CImg<int> image(fileName.c_str()); int imageDimensions[] = {image.height(), image.width(), 0}; Sequence<Sequence<int> > imageSeq((void*) image.data(), imageDimensions); Sequence< Sequence<int> > result; sl_init(threads); t.start(); sl_hough(imageSeq, thetaAxisSize, rAxisSize, minContrast, threads, result); t.stop(); CImg<int> resultImage(result[1].size(), result.size()); for(int y = 0; y < result.size(); y++) for(int x = 0; x < result[y+1].size(); x++) resultImage(x,result.size() - 1 - y) = result[y+1][x+1]; sprintf(titleBuffer, "SequenceL Hough Transformation: %d X %d Image to %d X %d Result | %d Cores | Processed in %f sec\0", image.width(), image.height(), resultImage.width(), resultImage.height(), threads, t.getTime()); resultImage.display(titleBuffer); sl_done(); return 0; }
from math import hypot, pi, cos, sin from PIL import Image def hough(im, ntx=460, mry=360): "Calculate Hough transform." pim = im.load() nimx, mimy = im.size mry = int(mry/2)*2 him = Image.new("L", (ntx, mry), 255) phim = him.load() rmax = hypot(nimx, mimy) dr = rmax / (mry/2) dth = pi / ntx for jx in xrange(nimx): for iy in xrange(mimy): col = pim[jx, iy] if col == 255: continue for jtx in xrange(ntx): th = dth * jtx r = jx*cos(th) + iy*sin(th) iry = mry/2 + int(r/dr+0.5) phim[jtx, iry] -= 1 return him def test(): "Test Hough transform with pentagon." im = Image.open("pentagon.png").convert("L") him = hough(im) him.save("ho5.bmp") if __name__ == "__main__": test()
Keep all operations the same but rewrite the snippet in Python.
#include <stdlib.h> #include <stdio.h> #include <math.h> #ifndef M_PI #define M_PI 3.14159265358979323846 #endif typedef double (* Ifctn)( double t); double Simpson3_8( Ifctn f, double a, double b, int N) { int j; double l1; double h = (b-a)/N; double h1 = h/3.0; double sum = f(a) + f(b); for (j=3*N-1; j>0; j--) { l1 = (j%3)? 3.0 : 2.0; sum += l1*f(a+h1*j) ; } return h*sum/8.0; } #define A 12 double Gamma_Spouge( double z ) { int k; static double cspace[A]; static double *coefs = NULL; double accum; double a = A; if (!coefs) { double k1_factrl = 1.0; coefs = cspace; coefs[0] = sqrt(2.0*M_PI); for(k=1; k<A; k++) { coefs[k] = exp(a-k) * pow(a-k,k-0.5) / k1_factrl; k1_factrl *= -k; } } accum = coefs[0]; for (k=1; k<A; k++) { accum += coefs[k]/(z+k); } accum *= exp(-(z+a)) * pow(z+a, z+0.5); return accum/z; } double aa1; double f0( double t) { return pow(t, aa1)*exp(-t); } double GammaIncomplete_Q( double a, double x) { double y, h = 1.5e-2; y = aa1 = a-1; while((f0(y) * (x-y) > 2.0e-8) && (y < x)) y += .4; if (y>x) y=x; return 1.0 - Simpson3_8( &f0, 0, y, (int)(y/h))/Gamma_Spouge(a); }
import math import random def GammaInc_Q( a, x): a1 = a-1 a2 = a-2 def f0( t ): return t**a1*math.exp(-t) def df0(t): return (a1-t)*t**a2*math.exp(-t) y = a1 while f0(y)*(x-y) >2.0e-8 and y < x: y += .3 if y > x: y = x h = 3.0e-4 n = int(y/h) h = y/n hh = 0.5*h gamax = h * sum( f0(t)+hh*df0(t) for t in ( h*j for j in xrange(n-1, -1, -1))) return gamax/gamma_spounge(a) c = None def gamma_spounge( z): global c a = 12 if c is None: k1_factrl = 1.0 c = [] c.append(math.sqrt(2.0*math.pi)) for k in range(1,a): c.append( math.exp(a-k) * (a-k)**(k-0.5) / k1_factrl ) k1_factrl *= -k accm = c[0] for k in range(1,a): accm += c[k] / (z+k) accm *= math.exp( -(z+a)) * (z+a)**(z+0.5) return accm/z; def chi2UniformDistance( dataSet ): expected = sum(dataSet)*1.0/len(dataSet) cntrd = (d-expected for d in dataSet) return sum(x*x for x in cntrd)/expected def chi2Probability(dof, distance): return 1.0 - GammaInc_Q( 0.5*dof, 0.5*distance) def chi2IsUniform(dataSet, significance): dof = len(dataSet)-1 dist = chi2UniformDistance(dataSet) return chi2Probability( dof, dist ) > significance dset1 = [ 199809, 200665, 199607, 200270, 199649 ] dset2 = [ 522573, 244456, 139979, 71531, 21461 ] for ds in (dset1, dset2): print "Data set:", ds dof = len(ds)-1 distance =chi2UniformDistance(ds) print "dof: %d distance: %.4f" % (dof, distance), prob = chi2Probability( dof, distance) print "probability: %.4f"%prob, print "uniform? ", "Yes"if chi2IsUniform(ds,0.05) else "No"
Maintain the same structure and functionality when rewriting this code in Python.
#include <stdio.h> #include <math.h> #include <stdlib.h> double Pvalue (const double *restrict ARRAY1, const size_t ARRAY1_SIZE, const double *restrict ARRAY2, const size_t ARRAY2_SIZE) { if (ARRAY1_SIZE <= 1) { return 1.0; } else if (ARRAY2_SIZE <= 1) { return 1.0; } double fmean1 = 0.0, fmean2 = 0.0; for (size_t x = 0; x < ARRAY1_SIZE; x++) { if (isfinite(ARRAY1[x]) == 0) { puts("Got a non-finite number in 1st array, can't calculate P-value."); exit(EXIT_FAILURE); } fmean1 += ARRAY1[x]; } fmean1 /= ARRAY1_SIZE; for (size_t x = 0; x < ARRAY2_SIZE; x++) { if (isfinite(ARRAY2[x]) == 0) { puts("Got a non-finite number in 2nd array, can't calculate P-value."); exit(EXIT_FAILURE); } fmean2 += ARRAY2[x]; } fmean2 /= ARRAY2_SIZE; if (fmean1 == fmean2) { return 1.0; } double unbiased_sample_variance1 = 0.0, unbiased_sample_variance2 = 0.0; for (size_t x = 0; x < ARRAY1_SIZE; x++) { unbiased_sample_variance1 += (ARRAY1[x]-fmean1)*(ARRAY1[x]-fmean1); } for (size_t x = 0; x < ARRAY2_SIZE; x++) { unbiased_sample_variance2 += (ARRAY2[x]-fmean2)*(ARRAY2[x]-fmean2); } unbiased_sample_variance1 = unbiased_sample_variance1/(ARRAY1_SIZE-1); unbiased_sample_variance2 = unbiased_sample_variance2/(ARRAY2_SIZE-1); const double WELCH_T_STATISTIC = (fmean1-fmean2)/sqrt(unbiased_sample_variance1/ARRAY1_SIZE+unbiased_sample_variance2/ARRAY2_SIZE); const double DEGREES_OF_FREEDOM = pow((unbiased_sample_variance1/ARRAY1_SIZE+unbiased_sample_variance2/ARRAY2_SIZE),2.0) / ( (unbiased_sample_variance1*unbiased_sample_variance1)/(ARRAY1_SIZE*ARRAY1_SIZE*(ARRAY1_SIZE-1))+ (unbiased_sample_variance2*unbiased_sample_variance2)/(ARRAY2_SIZE*ARRAY2_SIZE*(ARRAY2_SIZE-1)) ); const double a = DEGREES_OF_FREEDOM/2; double value = DEGREES_OF_FREEDOM/(WELCH_T_STATISTIC*WELCH_T_STATISTIC+DEGREES_OF_FREEDOM); if ((isinf(value) != 0) || (isnan(value) != 0)) { return 1.0; } if ((isinf(value) != 0) || (isnan(value) != 0)) { return 1.0; } const double beta = lgammal(a)+0.57236494292470009-lgammal(a+0.5); const double acu = 0.1E-14; double ai; double cx; int indx; int ns; double pp; double psq; double qq; double rx; double temp; double term; double xx; if ( (a <= 0.0)) { } if ( value < 0.0 || 1.0 < value ) { return value; } if ( value == 0.0 || value == 1.0 ) { return value; } psq = a + 0.5; cx = 1.0 - value; if ( a < psq * value ) { xx = cx; cx = value; pp = 0.5; qq = a; indx = 1; } else { xx = value; pp = a; qq = 0.5; indx = 0; } term = 1.0; ai = 1.0; value = 1.0; ns = ( int ) ( qq + cx * psq ); rx = xx / cx; temp = qq - ai; if ( ns == 0 ) { rx = xx; } for ( ; ; ) { term = term * temp * rx / ( pp + ai ); value = value + term;; temp = fabs ( term ); if ( temp <= acu && temp <= acu * value ) { value = value * exp ( pp * log ( xx ) + ( qq - 1.0 ) * log ( cx ) - beta ) / pp; if ( indx ) { value = 1.0 - value; } break; } ai = ai + 1.0; ns = ns - 1; if ( 0 <= ns ) { temp = qq - ai; if ( ns == 0 ) { rx = xx; } } else { temp = psq; psq = psq + 1.0; } } return value; } int main(void) { const double d1[] = {27.5,21.0,19.0,23.6,17.0,17.9,16.9,20.1,21.9,22.6,23.1,19.6,19.0,21.7,21.4}; const double d2[] = {27.1,22.0,20.8,23.4,23.4,23.5,25.8,22.0,24.8,20.2,21.9,22.1,22.9,20.5,24.4}; const double d3[] = {17.2,20.9,22.6,18.1,21.7,21.4,23.5,24.2,14.7,21.8}; const double d4[] = {21.5,22.8,21.0,23.0,21.6,23.6,22.5,20.7,23.4,21.8,20.7,21.7,21.5,22.5,23.6,21.5,22.5,23.5,21.5,21.8}; const double d5[] = {19.8,20.4,19.6,17.8,18.5,18.9,18.3,18.9,19.5,22.0}; const double d6[] = {28.2,26.6,20.1,23.3,25.2,22.1,17.7,27.6,20.6,13.7,23.2,17.5,20.6,18.0,23.9,21.6,24.3,20.4,24.0,13.2}; const double d7[] = {30.02,29.99,30.11,29.97,30.01,29.99}; const double d8[] = {29.89,29.93,29.72,29.98,30.02,29.98}; const double x[] = {3.0,4.0,1.0,2.1}; const double y[] = {490.2,340.0,433.9}; const double v1[] = {0.010268,0.000167,0.000167}; const double v2[] = {0.159258,0.136278,0.122389}; const double s1[] = {1.0/15,10.0/62.0}; const double s2[] = {1.0/10,2/50.0}; const double z1[] = {9/23.0,21/45.0,0/38.0}; const double z2[] = {0/44.0,42/94.0,0/22.0}; const double CORRECT_ANSWERS[] = {0.021378001462867, 0.148841696605327, 0.0359722710297968, 0.090773324285671, 0.0107515611497845, 0.00339907162713746, 0.52726574965384, 0.545266866977794}; double pvalue = Pvalue(d1,sizeof(d1)/sizeof(*d1),d2,sizeof(d2)/sizeof(*d2)); double error = fabs(pvalue - CORRECT_ANSWERS[0]); printf("Test sets 1 p-value = %g\n", pvalue); pvalue = Pvalue(d3,sizeof(d3)/sizeof(*d3),d4,sizeof(d4)/sizeof(*d4)); error += fabs(pvalue - CORRECT_ANSWERS[1]); printf("Test sets 2 p-value = %g\n",pvalue); pvalue = Pvalue(d5,sizeof(d5)/sizeof(*d5),d6,sizeof(d6)/sizeof(*d6)); error += fabs(pvalue - CORRECT_ANSWERS[2]); printf("Test sets 3 p-value = %g\n", pvalue); pvalue = Pvalue(d7,sizeof(d7)/sizeof(*d7),d8,sizeof(d8)/sizeof(*d8)); printf("Test sets 4 p-value = %g\n", pvalue); error += fabs(pvalue - CORRECT_ANSWERS[3]); pvalue = Pvalue(x,sizeof(x)/sizeof(*x),y,sizeof(y)/sizeof(*y)); error += fabs(pvalue - CORRECT_ANSWERS[4]); printf("Test sets 5 p-value = %g\n", pvalue); pvalue = Pvalue(v1,sizeof(v1)/sizeof(*v1),v2,sizeof(v2)/sizeof(*v2)); error += fabs(pvalue - CORRECT_ANSWERS[5]); printf("Test sets 6 p-value = %g\n", pvalue); pvalue = Pvalue(s1,sizeof(s1)/sizeof(*s1),s2,sizeof(s2)/sizeof(*s2)); error += fabs(pvalue - CORRECT_ANSWERS[6]); printf("Test sets 7 p-value = %g\n", pvalue); pvalue = Pvalue(z1, 3, z2, 3); error += fabs(pvalue - CORRECT_ANSWERS[7]); printf("Test sets z p-value = %g\n", pvalue); printf("the cumulative error is %g\n", error); return 0; }
import numpy as np import scipy as sp import scipy.stats def welch_ttest(x1, x2): n1 = x1.size n2 = x2.size m1 = np.mean(x1) m2 = np.mean(x2) v1 = np.var(x1, ddof=1) v2 = np.var(x2, ddof=1) t = (m1 - m2) / np.sqrt(v1 / n1 + v2 / n2) df = (v1 / n1 + v2 / n2)**2 / (v1**2 / (n1**2 * (n1 - 1)) + v2**2 / (n2**2 * (n2 - 1))) p = 2 * sp.stats.t.cdf(-abs(t), df) return t, df, p welch_ttest(np.array([3.0, 4.0, 1.0, 2.1]), np.array([490.2, 340.0, 433.9])) (-9.559497721932658, 2.0008523488562844, 0.01075156114978449)
Generate an equivalent Python version of this C code.
#include <stdio.h> #include <math.h> #include <stdlib.h> double Pvalue (const double *restrict ARRAY1, const size_t ARRAY1_SIZE, const double *restrict ARRAY2, const size_t ARRAY2_SIZE) { if (ARRAY1_SIZE <= 1) { return 1.0; } else if (ARRAY2_SIZE <= 1) { return 1.0; } double fmean1 = 0.0, fmean2 = 0.0; for (size_t x = 0; x < ARRAY1_SIZE; x++) { if (isfinite(ARRAY1[x]) == 0) { puts("Got a non-finite number in 1st array, can't calculate P-value."); exit(EXIT_FAILURE); } fmean1 += ARRAY1[x]; } fmean1 /= ARRAY1_SIZE; for (size_t x = 0; x < ARRAY2_SIZE; x++) { if (isfinite(ARRAY2[x]) == 0) { puts("Got a non-finite number in 2nd array, can't calculate P-value."); exit(EXIT_FAILURE); } fmean2 += ARRAY2[x]; } fmean2 /= ARRAY2_SIZE; if (fmean1 == fmean2) { return 1.0; } double unbiased_sample_variance1 = 0.0, unbiased_sample_variance2 = 0.0; for (size_t x = 0; x < ARRAY1_SIZE; x++) { unbiased_sample_variance1 += (ARRAY1[x]-fmean1)*(ARRAY1[x]-fmean1); } for (size_t x = 0; x < ARRAY2_SIZE; x++) { unbiased_sample_variance2 += (ARRAY2[x]-fmean2)*(ARRAY2[x]-fmean2); } unbiased_sample_variance1 = unbiased_sample_variance1/(ARRAY1_SIZE-1); unbiased_sample_variance2 = unbiased_sample_variance2/(ARRAY2_SIZE-1); const double WELCH_T_STATISTIC = (fmean1-fmean2)/sqrt(unbiased_sample_variance1/ARRAY1_SIZE+unbiased_sample_variance2/ARRAY2_SIZE); const double DEGREES_OF_FREEDOM = pow((unbiased_sample_variance1/ARRAY1_SIZE+unbiased_sample_variance2/ARRAY2_SIZE),2.0) / ( (unbiased_sample_variance1*unbiased_sample_variance1)/(ARRAY1_SIZE*ARRAY1_SIZE*(ARRAY1_SIZE-1))+ (unbiased_sample_variance2*unbiased_sample_variance2)/(ARRAY2_SIZE*ARRAY2_SIZE*(ARRAY2_SIZE-1)) ); const double a = DEGREES_OF_FREEDOM/2; double value = DEGREES_OF_FREEDOM/(WELCH_T_STATISTIC*WELCH_T_STATISTIC+DEGREES_OF_FREEDOM); if ((isinf(value) != 0) || (isnan(value) != 0)) { return 1.0; } if ((isinf(value) != 0) || (isnan(value) != 0)) { return 1.0; } const double beta = lgammal(a)+0.57236494292470009-lgammal(a+0.5); const double acu = 0.1E-14; double ai; double cx; int indx; int ns; double pp; double psq; double qq; double rx; double temp; double term; double xx; if ( (a <= 0.0)) { } if ( value < 0.0 || 1.0 < value ) { return value; } if ( value == 0.0 || value == 1.0 ) { return value; } psq = a + 0.5; cx = 1.0 - value; if ( a < psq * value ) { xx = cx; cx = value; pp = 0.5; qq = a; indx = 1; } else { xx = value; pp = a; qq = 0.5; indx = 0; } term = 1.0; ai = 1.0; value = 1.0; ns = ( int ) ( qq + cx * psq ); rx = xx / cx; temp = qq - ai; if ( ns == 0 ) { rx = xx; } for ( ; ; ) { term = term * temp * rx / ( pp + ai ); value = value + term;; temp = fabs ( term ); if ( temp <= acu && temp <= acu * value ) { value = value * exp ( pp * log ( xx ) + ( qq - 1.0 ) * log ( cx ) - beta ) / pp; if ( indx ) { value = 1.0 - value; } break; } ai = ai + 1.0; ns = ns - 1; if ( 0 <= ns ) { temp = qq - ai; if ( ns == 0 ) { rx = xx; } } else { temp = psq; psq = psq + 1.0; } } return value; } int main(void) { const double d1[] = {27.5,21.0,19.0,23.6,17.0,17.9,16.9,20.1,21.9,22.6,23.1,19.6,19.0,21.7,21.4}; const double d2[] = {27.1,22.0,20.8,23.4,23.4,23.5,25.8,22.0,24.8,20.2,21.9,22.1,22.9,20.5,24.4}; const double d3[] = {17.2,20.9,22.6,18.1,21.7,21.4,23.5,24.2,14.7,21.8}; const double d4[] = {21.5,22.8,21.0,23.0,21.6,23.6,22.5,20.7,23.4,21.8,20.7,21.7,21.5,22.5,23.6,21.5,22.5,23.5,21.5,21.8}; const double d5[] = {19.8,20.4,19.6,17.8,18.5,18.9,18.3,18.9,19.5,22.0}; const double d6[] = {28.2,26.6,20.1,23.3,25.2,22.1,17.7,27.6,20.6,13.7,23.2,17.5,20.6,18.0,23.9,21.6,24.3,20.4,24.0,13.2}; const double d7[] = {30.02,29.99,30.11,29.97,30.01,29.99}; const double d8[] = {29.89,29.93,29.72,29.98,30.02,29.98}; const double x[] = {3.0,4.0,1.0,2.1}; const double y[] = {490.2,340.0,433.9}; const double v1[] = {0.010268,0.000167,0.000167}; const double v2[] = {0.159258,0.136278,0.122389}; const double s1[] = {1.0/15,10.0/62.0}; const double s2[] = {1.0/10,2/50.0}; const double z1[] = {9/23.0,21/45.0,0/38.0}; const double z2[] = {0/44.0,42/94.0,0/22.0}; const double CORRECT_ANSWERS[] = {0.021378001462867, 0.148841696605327, 0.0359722710297968, 0.090773324285671, 0.0107515611497845, 0.00339907162713746, 0.52726574965384, 0.545266866977794}; double pvalue = Pvalue(d1,sizeof(d1)/sizeof(*d1),d2,sizeof(d2)/sizeof(*d2)); double error = fabs(pvalue - CORRECT_ANSWERS[0]); printf("Test sets 1 p-value = %g\n", pvalue); pvalue = Pvalue(d3,sizeof(d3)/sizeof(*d3),d4,sizeof(d4)/sizeof(*d4)); error += fabs(pvalue - CORRECT_ANSWERS[1]); printf("Test sets 2 p-value = %g\n",pvalue); pvalue = Pvalue(d5,sizeof(d5)/sizeof(*d5),d6,sizeof(d6)/sizeof(*d6)); error += fabs(pvalue - CORRECT_ANSWERS[2]); printf("Test sets 3 p-value = %g\n", pvalue); pvalue = Pvalue(d7,sizeof(d7)/sizeof(*d7),d8,sizeof(d8)/sizeof(*d8)); printf("Test sets 4 p-value = %g\n", pvalue); error += fabs(pvalue - CORRECT_ANSWERS[3]); pvalue = Pvalue(x,sizeof(x)/sizeof(*x),y,sizeof(y)/sizeof(*y)); error += fabs(pvalue - CORRECT_ANSWERS[4]); printf("Test sets 5 p-value = %g\n", pvalue); pvalue = Pvalue(v1,sizeof(v1)/sizeof(*v1),v2,sizeof(v2)/sizeof(*v2)); error += fabs(pvalue - CORRECT_ANSWERS[5]); printf("Test sets 6 p-value = %g\n", pvalue); pvalue = Pvalue(s1,sizeof(s1)/sizeof(*s1),s2,sizeof(s2)/sizeof(*s2)); error += fabs(pvalue - CORRECT_ANSWERS[6]); printf("Test sets 7 p-value = %g\n", pvalue); pvalue = Pvalue(z1, 3, z2, 3); error += fabs(pvalue - CORRECT_ANSWERS[7]); printf("Test sets z p-value = %g\n", pvalue); printf("the cumulative error is %g\n", error); return 0; }
import numpy as np import scipy as sp import scipy.stats def welch_ttest(x1, x2): n1 = x1.size n2 = x2.size m1 = np.mean(x1) m2 = np.mean(x2) v1 = np.var(x1, ddof=1) v2 = np.var(x2, ddof=1) t = (m1 - m2) / np.sqrt(v1 / n1 + v2 / n2) df = (v1 / n1 + v2 / n2)**2 / (v1**2 / (n1**2 * (n1 - 1)) + v2**2 / (n2**2 * (n2 - 1))) p = 2 * sp.stats.t.cdf(-abs(t), df) return t, df, p welch_ttest(np.array([3.0, 4.0, 1.0, 2.1]), np.array([490.2, 340.0, 433.9])) (-9.559497721932658, 2.0008523488562844, 0.01075156114978449)
Change the following C code into Python without altering its purpose.
char input[] = "top1 des1 ip1 ip2\n" "top2 des1 ip2 ip3\n" "ip1 extra1 ip1a ipcommon\n" "ip2 ip2a ip2b ip2c ipcommon\n" "des1 des1a des1b des1c\n" "des1a des1a1 des1a2\n" "des1c des1c1 extra1\n"; ... int find_name(item base, int len, const char *name) { int i; for (i = 0; i < len; i++) if (!strcmp(base[i].name, name)) return i; return -1; } int depends_on(item base, int n1, int n2) { int i; if (n1 == n2) return 1; for (i = 0; i < base[n1].n_deps; i++) if (depends_on(base, base[n1].deps[i], n2)) return 1; return 0; } void compile_order(item base, int n_items, int *top, int n_top) { int i, j, lvl; int d = 0; printf("Compile order for:"); for (i = 0; i < n_top; i++) { printf(" %s", base[top[i]].name); if (base[top[i]].depth > d) d = base[top[i]].depth; } printf("\n"); for (lvl = 1; lvl <= d; lvl ++) { printf("level %d:", lvl); for (i = 0; i < n_items; i++) { if (base[i].depth != lvl) continue; for (j = 0; j < n_top; j++) { if (depends_on(base, top[j], i)) { printf(" %s", base[i].name); break; } } } printf("\n"); } printf("\n"); } int main() { int i, n, bad = -1; item items; n = parse_input(&items); for (i = 0; i < n; i++) if (!items[i].depth && get_depth(items, i, bad) < 0) bad--; int top[3]; top[0] = find_name(items, n, "top1"); top[1] = find_name(items, n, "top2"); top[2] = find_name(items, n, "ip1"); compile_order(items, n, top, 1); compile_order(items, n, top + 1, 1); compile_order(items, n, top, 2); compile_order(items, n, top + 2, 1); return 0; }
try: from functools import reduce except: pass def topx(data, tops=None): 'Extract the set of top-level(s) in topological order' for k, v in data.items(): v.discard(k) if tops is None: tops = toplevels(data) return _topx(data, tops, [], set()) def _topx(data, tops, _sofar, _sofar_set): 'Recursive topological extractor' _sofar += [tops] _sofar_set.union(tops) depends = reduce(set.union, (data.get(top, set()) for top in tops)) if depends: _topx(data, depends, _sofar, _sofar_set) ordered, accum = [], set() for s in _sofar[::-1]: ordered += [sorted(s - accum)] accum |= s return ordered def printorder(order): 'Prettyprint topological ordering' if order: print("First: " + ', '.join(str(s) for s in order[0])) for o in order[1:]: print(" Then: " + ', '.join(str(s) for s in o)) def toplevels(data): for k, v in data.items(): v.discard(k) dependents = reduce(set.union, data.values()) return set(data.keys()) - dependents if __name__ == '__main__': data = dict( top1 = set('ip1 des1 ip2'.split()), top2 = set('ip2 des1 ip3'.split()), des1 = set('des1a des1b des1c'.split()), des1a = set('des1a1 des1a2'.split()), des1c = set('des1c1 extra1'.split()), ip2 = set('ip2a ip2b ip2c ipcommon'.split()), ip1 = set('ip1a ipcommon extra1'.split()), ) tops = toplevels(data) print("The top levels of the dependency graph are: " + ' '.join(tops)) for t in sorted(tops): print("\nThe compile order for top level: %s is..." % t) printorder(topx(data, set([t]))) if len(tops) > 1: print("\nThe compile order for top levels: %s is..." % ' and '.join(str(s) for s in sorted(tops)) ) printorder(topx(data, tops))
Maintain the same structure and functionality when rewriting this code in Python.
char input[] = "top1 des1 ip1 ip2\n" "top2 des1 ip2 ip3\n" "ip1 extra1 ip1a ipcommon\n" "ip2 ip2a ip2b ip2c ipcommon\n" "des1 des1a des1b des1c\n" "des1a des1a1 des1a2\n" "des1c des1c1 extra1\n"; ... int find_name(item base, int len, const char *name) { int i; for (i = 0; i < len; i++) if (!strcmp(base[i].name, name)) return i; return -1; } int depends_on(item base, int n1, int n2) { int i; if (n1 == n2) return 1; for (i = 0; i < base[n1].n_deps; i++) if (depends_on(base, base[n1].deps[i], n2)) return 1; return 0; } void compile_order(item base, int n_items, int *top, int n_top) { int i, j, lvl; int d = 0; printf("Compile order for:"); for (i = 0; i < n_top; i++) { printf(" %s", base[top[i]].name); if (base[top[i]].depth > d) d = base[top[i]].depth; } printf("\n"); for (lvl = 1; lvl <= d; lvl ++) { printf("level %d:", lvl); for (i = 0; i < n_items; i++) { if (base[i].depth != lvl) continue; for (j = 0; j < n_top; j++) { if (depends_on(base, top[j], i)) { printf(" %s", base[i].name); break; } } } printf("\n"); } printf("\n"); } int main() { int i, n, bad = -1; item items; n = parse_input(&items); for (i = 0; i < n; i++) if (!items[i].depth && get_depth(items, i, bad) < 0) bad--; int top[3]; top[0] = find_name(items, n, "top1"); top[1] = find_name(items, n, "top2"); top[2] = find_name(items, n, "ip1"); compile_order(items, n, top, 1); compile_order(items, n, top + 1, 1); compile_order(items, n, top, 2); compile_order(items, n, top + 2, 1); return 0; }
try: from functools import reduce except: pass def topx(data, tops=None): 'Extract the set of top-level(s) in topological order' for k, v in data.items(): v.discard(k) if tops is None: tops = toplevels(data) return _topx(data, tops, [], set()) def _topx(data, tops, _sofar, _sofar_set): 'Recursive topological extractor' _sofar += [tops] _sofar_set.union(tops) depends = reduce(set.union, (data.get(top, set()) for top in tops)) if depends: _topx(data, depends, _sofar, _sofar_set) ordered, accum = [], set() for s in _sofar[::-1]: ordered += [sorted(s - accum)] accum |= s return ordered def printorder(order): 'Prettyprint topological ordering' if order: print("First: " + ', '.join(str(s) for s in order[0])) for o in order[1:]: print(" Then: " + ', '.join(str(s) for s in o)) def toplevels(data): for k, v in data.items(): v.discard(k) dependents = reduce(set.union, data.values()) return set(data.keys()) - dependents if __name__ == '__main__': data = dict( top1 = set('ip1 des1 ip2'.split()), top2 = set('ip2 des1 ip3'.split()), des1 = set('des1a des1b des1c'.split()), des1a = set('des1a1 des1a2'.split()), des1c = set('des1c1 extra1'.split()), ip2 = set('ip2a ip2b ip2c ipcommon'.split()), ip1 = set('ip1a ipcommon extra1'.split()), ) tops = toplevels(data) print("The top levels of the dependency graph are: " + ' '.join(tops)) for t in sorted(tops): print("\nThe compile order for top level: %s is..." % t) printorder(topx(data, set([t]))) if len(tops) > 1: print("\nThe compile order for top levels: %s is..." % ' and '.join(str(s) for s in sorted(tops)) ) printorder(topx(data, tops))
Convert this C snippet to Python and keep its semantics consistent.
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define BUFFER_SIZE 128 typedef unsigned char character; typedef character *string; typedef struct node_t node; struct node_t { enum tag_t { NODE_LEAF, NODE_TREE, NODE_SEQ, } tag; union { string str; node *root; } data; node *next; }; node *allocate_node(enum tag_t tag) { node *n = malloc(sizeof(node)); if (n == NULL) { fprintf(stderr, "Failed to allocate node for tag: %d\n", tag); exit(1); } n->tag = tag; n->next = NULL; return n; } node *make_leaf(string str) { node *n = allocate_node(NODE_LEAF); n->data.str = str; return n; } node *make_tree() { node *n = allocate_node(NODE_TREE); n->data.root = NULL; return n; } node *make_seq() { node *n = allocate_node(NODE_SEQ); n->data.root = NULL; return n; } void deallocate_node(node *n) { if (n == NULL) { return; } deallocate_node(n->next); n->next = NULL; if (n->tag == NODE_LEAF) { free(n->data.str); n->data.str = NULL; } else if (n->tag == NODE_TREE || n->tag == NODE_SEQ) { deallocate_node(n->data.root); n->data.root = NULL; } else { fprintf(stderr, "Cannot deallocate node with tag: %d\n", n->tag); exit(1); } free(n); } void append(node *root, node *elem) { if (root == NULL) { fprintf(stderr, "Cannot append to uninitialized node."); exit(1); } if (elem == NULL) { return; } if (root->tag == NODE_SEQ || root->tag == NODE_TREE) { if (root->data.root == NULL) { root->data.root = elem; } else { node *it = root->data.root; while (it->next != NULL) { it = it->next; } it->next = elem; } } else { fprintf(stderr, "Cannot append to node with tag: %d\n", root->tag); exit(1); } } size_t count(node *n) { if (n == NULL) { return 0; } if (n->tag == NODE_LEAF) { return 1; } if (n->tag == NODE_TREE) { size_t sum = 0; node *it = n->data.root; while (it != NULL) { sum += count(it); it = it->next; } return sum; } if (n->tag == NODE_SEQ) { size_t prod = 1; node *it = n->data.root; while (it != NULL) { prod *= count(it); it = it->next; } return prod; } fprintf(stderr, "Cannot count node with tag: %d\n", n->tag); exit(1); } void expand(node *n, size_t pos) { if (n == NULL) { return; } if (n->tag == NODE_LEAF) { printf(n->data.str); } else if (n->tag == NODE_TREE) { node *it = n->data.root; while (true) { size_t cnt = count(it); if (pos < cnt) { expand(it, pos); break; } pos -= cnt; it = it->next; } } else if (n->tag == NODE_SEQ) { size_t prod = pos; node *it = n->data.root; while (it != NULL) { size_t cnt = count(it); size_t rem = prod % cnt; expand(it, rem); it = it->next; } } else { fprintf(stderr, "Cannot expand node with tag: %d\n", n->tag); exit(1); } } string allocate_string(string src) { size_t len = strlen(src); string out = calloc(len + 1, sizeof(character)); if (out == NULL) { fprintf(stderr, "Failed to allocate a copy of the string."); exit(1); } strcpy(out, src); return out; } node *parse_seq(string input, size_t *pos); node *parse_tree(string input, size_t *pos) { node *root = make_tree(); character buffer[BUFFER_SIZE] = { 0 }; size_t bufpos = 0; size_t depth = 0; bool asSeq = false; bool allow = false; while (input[*pos] != 0) { character c = input[(*pos)++]; if (c == '\\') { c = input[(*pos)++]; if (c == 0) { break; } buffer[bufpos++] = '\\'; buffer[bufpos++] = c; buffer[bufpos] = 0; } else if (c == '{') { buffer[bufpos++] = c; buffer[bufpos] = 0; asSeq = true; depth++; } else if (c == '}') { if (depth-- > 0) { buffer[bufpos++] = c; buffer[bufpos] = 0; } else { if (asSeq) { size_t new_pos = 0; node *seq = parse_seq(buffer, &new_pos); append(root, seq); } else { append(root, make_leaf(allocate_string(buffer))); } break; } } else if (c == ',') { if (depth == 0) { if (asSeq) { size_t new_pos = 0; node *seq = parse_seq(buffer, &new_pos); append(root, seq); bufpos = 0; buffer[bufpos] = 0; asSeq = false; } else { append(root, make_leaf(allocate_string(buffer))); bufpos = 0; buffer[bufpos] = 0; } } else { buffer[bufpos++] = c; buffer[bufpos] = 0; } } else { buffer[bufpos++] = c; buffer[bufpos] = 0; } } return root; } node *parse_seq(string input, size_t *pos) { node *root = make_seq(); character buffer[BUFFER_SIZE] = { 0 }; size_t bufpos = 0; while (input[*pos] != 0) { character c = input[(*pos)++]; if (c == '\\') { c = input[(*pos)++]; if (c == 0) { break; } buffer[bufpos++] = c; buffer[bufpos] = 0; } else if (c == '{') { node *tree = parse_tree(input, pos); if (bufpos > 0) { append(root, make_leaf(allocate_string(buffer))); bufpos = 0; buffer[bufpos] = 0; } append(root, tree); } else { buffer[bufpos++] = c; buffer[bufpos] = 0; } } if (bufpos > 0) { append(root, make_leaf(allocate_string(buffer))); bufpos = 0; buffer[bufpos] = 0; } return root; } void test(string input) { size_t pos = 0; node *n = parse_seq(input, &pos); size_t cnt = count(n); size_t i; printf("Pattern: %s\n", input); for (i = 0; i < cnt; i++) { expand(n, i); printf("\n"); } printf("\n"); deallocate_node(n); } int main() { test("~/{Downloads,Pictures}/*.{jpg,gif,png}"); test("It{{em,alic}iz,erat}e{d,}, please."); test("{,{,gotta have{ ,\\, again\\, }}more }cowbell!"); return 0; }
def getitem(s, depth=0): out = [""] while s: c = s[0] if depth and (c == ',' or c == '}'): return out,s if c == '{': x = getgroup(s[1:], depth+1) if x: out,s = [a+b for a in out for b in x[0]], x[1] continue if c == '\\' and len(s) > 1: s, c = s[1:], c + s[1] out, s = [a+c for a in out], s[1:] return out,s def getgroup(s, depth): out, comma = [], False while s: g,s = getitem(s, depth) if not s: break out += g if s[0] == '}': if comma: return out, s[1:] return ['{' + a + '}' for a in out], s[1:] if s[0] == ',': comma,s = True, s[1:] return None for s in .split('\n'): print "\n\t".join([s] + getitem(s)[0]) + "\n"
Generate an equivalent Python version of this C code.
f(); g(1, 2, 3); int op_arg(); int main() { op_arg(1); op_arg(1, 2); op_arg(1, 2, 3); return 0; } int op_arg(int a, int b) { printf("%d %d %d\n", a, b, (&b)[1]); return a; } void h(int a, ...) { va_list ap; va_start(ap); ... } h(1, 2, 3, 4, "abcd", (void*)0); struct v_args { int arg1; int arg2; char _sentinel; }; void _v(struct v_args args) { printf("%d, %d\n", args.arg1, args.arg2); } #define v(...) _v((struct v_args){__VA_ARGS__}) v(.arg2 = 5, .arg1 = 17); v(.arg2=1); v(); printf("%p", f); double a = asin(1);
def no_args(): pass no_args() def fixed_args(x, y): print('x=%r, y=%r' % (x, y)) fixed_args(1, 2) fixed_args(y=2, x=1) myargs=(1,2) fixed_args(*myargs) def opt_args(x=1): print(x) opt_args() opt_args(3.141) def var_args(*v): print(v) var_args(1, 2, 3) var_args(1, (2,3)) var_args() fixed_args(y=2, x=1) if 1: no_args() assert no_args() is None def return_something(): return 1 x = return_something() def is_builtin(x): print(x.__name__ in dir(__builtins__)) is_builtin(pow) is_builtin(is_builtin) def takes_anything(*args, **kwargs): for each in args: print(each) for key, value in sorted(kwargs.items()): print("%s:%s" % (key, value)) wrapped_fn(*args, **kwargs)
Preserve the algorithm and functionality while converting the code from C to Python.
f(); g(1, 2, 3); int op_arg(); int main() { op_arg(1); op_arg(1, 2); op_arg(1, 2, 3); return 0; } int op_arg(int a, int b) { printf("%d %d %d\n", a, b, (&b)[1]); return a; } void h(int a, ...) { va_list ap; va_start(ap); ... } h(1, 2, 3, 4, "abcd", (void*)0); struct v_args { int arg1; int arg2; char _sentinel; }; void _v(struct v_args args) { printf("%d, %d\n", args.arg1, args.arg2); } #define v(...) _v((struct v_args){__VA_ARGS__}) v(.arg2 = 5, .arg1 = 17); v(.arg2=1); v(); printf("%p", f); double a = asin(1);
def no_args(): pass no_args() def fixed_args(x, y): print('x=%r, y=%r' % (x, y)) fixed_args(1, 2) fixed_args(y=2, x=1) myargs=(1,2) fixed_args(*myargs) def opt_args(x=1): print(x) opt_args() opt_args(3.141) def var_args(*v): print(v) var_args(1, 2, 3) var_args(1, (2,3)) var_args() fixed_args(y=2, x=1) if 1: no_args() assert no_args() is None def return_something(): return 1 x = return_something() def is_builtin(x): print(x.__name__ in dir(__builtins__)) is_builtin(pow) is_builtin(is_builtin) def takes_anything(*args, **kwargs): for each in args: print(each) for key, value in sorted(kwargs.items()): print("%s:%s" % (key, value)) wrapped_fn(*args, **kwargs)
Write the same code in Python as shown below in C.
#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX 12 char *super = 0; int pos, cnt[MAX]; int fact_sum(int n) { int s, x, f; for (s = 0, x = 0, f = 1; x < n; f *= ++x, s += f); return s; } int r(int n) { if (!n) return 0; char c = super[pos - n]; if (!--cnt[n]) { cnt[n] = n; if (!r(n-1)) return 0; } super[pos++] = c; return 1; } void superperm(int n) { int i, len; pos = n; len = fact_sum(n); super = realloc(super, len + 1); super[len] = '\0'; for (i = 0; i <= n; i++) cnt[i] = i; for (i = 1; i <= n; i++) super[i - 1] = i + '0'; while (r(n)); } int main(void) { int n; for (n = 0; n < MAX; n++) { printf("superperm(%2d) ", n); superperm(n); printf("len = %d", (int)strlen(super)); putchar('\n'); } return 0; }
"Generate a short Superpermutation of n characters A... as a string using various algorithms." from __future__ import print_function, division from itertools import permutations from math import factorial import string import datetime import gc MAXN = 7 def s_perm0(n): allchars = string.ascii_uppercase[:n] allperms = [''.join(p) for p in permutations(allchars)] sp, tofind = allperms[0], set(allperms[1:]) while tofind: for skip in range(1, n): for trial_add in (''.join(p) for p in permutations(sp[-n:][:skip])): trial_perm = (sp + trial_add)[-n:] if trial_perm in tofind: sp += trial_add tofind.discard(trial_perm) trial_add = None break if trial_add is None: break assert all(perm in sp for perm in allperms) return sp def s_perm1(n): allchars = string.ascii_uppercase[:n] allperms = [''.join(p) for p in sorted(permutations(allchars))] perms, sp = allperms[::], '' while perms: nxt = perms.pop() if nxt not in sp: sp += nxt assert all(perm in sp for perm in allperms) return sp def s_perm2(n): allchars = string.ascii_uppercase[:n] allperms = [''.join(p) for p in sorted(permutations(allchars))] perms, sp = allperms[::], '' while perms: nxt = perms.pop(0) if nxt not in sp: sp += nxt if perms: nxt = perms.pop(-1) if nxt not in sp: sp += nxt assert all(perm in sp for perm in allperms) return sp def _s_perm3(n, cmp): allchars = string.ascii_uppercase[:n] allperms = [''.join(p) for p in sorted(permutations(allchars))] perms, sp = allperms[::], '' while perms: lastn = sp[-n:] nxt = cmp(perms, key=lambda pm: sum((ch1 == ch2) for ch1, ch2 in zip(pm, lastn))) perms.remove(nxt) if nxt not in sp: sp += nxt assert all(perm in sp for perm in allperms) return sp def s_perm3_max(n): return _s_perm3(n, max) def s_perm3_min(n): return _s_perm3(n, min) longest = [factorial(n) * n for n in range(MAXN + 1)] weight, runtime = {}, {} print(__doc__) for algo in [s_perm0, s_perm1, s_perm2, s_perm3_max, s_perm3_min]: print('\n print(algo.__doc__) weight[algo.__name__], runtime[algo.__name__] = 1, datetime.timedelta(0) for n in range(1, MAXN + 1): gc.collect() gc.disable() t = datetime.datetime.now() sp = algo(n) t = datetime.datetime.now() - t gc.enable() runtime[algo.__name__] += t lensp = len(sp) wt = (lensp / longest[n]) ** 2 print(' For N=%i: SP length %5i Max: %5i Weight: %5.2f' % (n, lensp, longest[n], wt)) weight[algo.__name__] *= wt weight[algo.__name__] **= 1 / n weight[algo.__name__] = 1 / weight[algo.__name__] print('%*s Overall Weight: %5.2f in %.1f seconds.' % (29, '', weight[algo.__name__], runtime[algo.__name__].total_seconds())) print('\n print('\n'.join('%12s (%.3f)' % kv for kv in sorted(weight.items(), key=lambda keyvalue: -keyvalue[1]))) print('\n print('\n'.join('%12s (%.3f)' % (k, v.total_seconds()) for k, v in sorted(runtime.items(), key=lambda keyvalue: keyvalue[1])))
Change the following C code into Python without altering its purpose.
#include <windows.h> #include "resource.h" BOOL CALLBACK DlgProc( HWND hwnd, UINT msg, WPARAM wPar, LPARAM lPar ) { switch( msg ) { case WM_INITDIALOG: srand( GetTickCount() ); SetDlgItemInt( hwnd, IDC_INPUT, 0, FALSE ); break; case WM_COMMAND: switch( LOWORD(wPar) ) { case IDC_INCREMENT: { UINT n = GetDlgItemInt( hwnd, IDC_INPUT, NULL, FALSE ); SetDlgItemInt( hwnd, IDC_INPUT, ++n, FALSE ); } break; case IDC_RANDOM: { int reply = MessageBox( hwnd, "Do you really want to\nget a random number?", "Random input confirmation", MB_ICONQUESTION|MB_YESNO ); if( reply == IDYES ) SetDlgItemInt( hwnd, IDC_INPUT, rand(), FALSE ); } break; case IDC_QUIT: SendMessage( hwnd, WM_CLOSE, 0, 0 ); break; default: ; } break; case WM_CLOSE: { int reply = MessageBox( hwnd, "Do you really want to quit?", "Quit confirmation", MB_ICONQUESTION|MB_YESNO ); if( reply == IDYES ) EndDialog( hwnd, 0 ); } break; default: ; } return 0; } int WINAPI WinMain( HINSTANCE hInst, HINSTANCE hPInst, LPSTR cmdLn, int show ) { return DialogBox( hInst, MAKEINTRESOURCE(IDD_DLG), NULL, DlgProc ); }
import random, tkMessageBox from Tkinter import * window = Tk() window.geometry("300x50+100+100") options = { "padx":5, "pady":5} s=StringVar() s.set(1) def increase(): s.set(int(s.get())+1) def rand(): if tkMessageBox.askyesno("Confirmation", "Reset to random value ?"): s.set(random.randrange(0,5000)) def update(e): if not e.char.isdigit(): tkMessageBox.showerror('Error', 'Invalid input !') return "break" e = Entry(text=s) e.grid(column=0, row=0, **options) e.bind('<Key>', update) b1 = Button(text="Increase", command=increase, **options ) b1.grid(column=1, row=0, **options) b2 = Button(text="Random", command=rand, **options) b2.grid(column=2, row=0, **options) mainloop()
Produce a language-to-language conversion: from C to Python, same semantics.
#include <stdio.h> #include <stdlib.h> inline int irand(int n) { int r, randmax = RAND_MAX/n * n; while ((r = rand()) >= randmax); return r / (randmax / n); } inline int one_of_n(int n) { int i, r = 0; for (i = 1; i < n; i++) if (!irand(i + 1)) r = i; return r; } int main(void) { int i, r[10] = {0}; for (i = 0; i < 1000000; i++, r[one_of_n(10)]++); for (i = 0; i < 10; i++) printf("%d%c", r[i], i == 9 ? '\n':' '); return 0; }
from random import randrange try: range = xrange except: pass def one_of_n(lines): choice = None for i, line in enumerate(lines): if randrange(i+1) == 0: choice = line return choice def one_of_n_test(n=10, trials=1000000): bins = [0] * n if n: for i in range(trials): bins[one_of_n(range(n))] += 1 return bins print(one_of_n_test())
Change the programming language of this snippet from C to Python without modifying what it does.
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct rec_t rec_t; struct rec_t { int depth; rec_t * p[10]; }; rec_t root = {0, {0}}; #define USE_POOL_ALLOC #ifdef USE_POOL_ALLOC rec_t *tail = 0, *head = 0; #define POOL_SIZE (1 << 20) inline rec_t *new_rec() { if (head == tail) { head = calloc(sizeof(rec_t), POOL_SIZE); tail = head + POOL_SIZE; } return head++; } #else #define new_rec() calloc(sizeof(rec_t), 1) #endif rec_t *find_rec(char *s) { int i; rec_t *r = &root; while (*s) { i = *s++ - '0'; if (!r->p[i]) r->p[i] = new_rec(); r = r->p[i]; } return r; } char number[100][4]; void init() { int i; for (i = 0; i < 100; i++) sprintf(number[i], "%d", i); } void count(char *buf) { int i, c[10] = {0}; char *s; for (s = buf; *s; c[*s++ - '0']++); for (i = 9; i >= 0; i--) { if (!c[i]) continue; s = number[c[i]]; *buf++ = s[0]; if ((*buf = s[1])) buf++; *buf++ = i + '0'; } *buf = '\0'; } int depth(char *in, int d) { rec_t *r = find_rec(in); if (r->depth > 0) return r->depth; d++; if (!r->depth) r->depth = -d; else r->depth += d; count(in); d = depth(in, d); if (r->depth <= 0) r->depth = d + 1; return r->depth; } int main(void) { char a[100]; int i, d, best_len = 0, n_best = 0; int best_ints[32]; rec_t *r; init(); for (i = 0; i < 1000000; i++) { sprintf(a, "%d", i); d = depth(a, 0); if (d < best_len) continue; if (d > best_len) { n_best = 0; best_len = d; } if (d == best_len) best_ints[n_best++] = i; } printf("longest length: %d\n", best_len); for (i = 0; i < n_best; i++) { printf("%d\n", best_ints[i]); sprintf(a, "%d", best_ints[i]); for (d = 0; d <= best_len; d++) { r = find_rec(a); printf("%3d: %s\n", r->depth, a); count(a); } putchar('\n'); } return 0; }
from itertools import groupby, permutations def A036058(number): return ''.join( str(len(list(g))) + k for k,g in groupby(sorted(str(number), reverse=True)) ) def A036058_length(numberstring='0', printit=False): iterations, last_three, queue_index = 1, ([None] * 3), 0 def A036058(number): return ''.join( str(len(list(g))) + k for k,g in groupby(number) ) while True: if printit: print(" %2i %s" % (iterations, numberstring)) numberstring = ''.join(sorted(numberstring, reverse=True)) if numberstring in last_three: break assert iterations < 1000000 last_three[queue_index], numberstring = numberstring, A036058(numberstring) iterations += 1 queue_index +=1 queue_index %=3 return iterations def max_A036058_length( start_range=range(11) ): already_done = set() max_len = (-1, []) for n in start_range: sn = str(n) sns = tuple(sorted(sn, reverse=True)) if sns not in already_done: already_done.add(sns) size = A036058_length(sns) if size > max_len[0]: max_len = (size, [n]) elif size == max_len[0]: max_len[1].append(n) return max_len lenmax, starts = max_A036058_length( range(1000000) ) allstarts = [] for n in starts: allstarts += [int(''.join(x)) for x in set(k for k in permutations(str(n), 4) if k[0] != '0')] allstarts = [x for x in sorted(allstarts) if x < 1000000] print ( % (lenmax, allstarts) ) print ( ) for n in starts: print() A036058_length(str(n), printit=True)
Maintain the same structure and functionality when rewriting this code in Python.
#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" }, { "two", "second" }, { "three", "third" }, { "four", "fourth" }, { "five", "fifth" }, { "six", "sixth" }, { "seven", "seventh" }, { "eight", "eighth" }, { "nine", "ninth" }, { "ten", "tenth" }, { "eleven", "eleventh" }, { "twelve", "twelfth" }, { "thirteen", "thirteenth" }, { "fourteen", "fourteenth" }, { "fifteen", "fifteenth" }, { "sixteen", "sixteenth" }, { "seventeen", "seventeenth" }, { "eighteen", "eighteenth" }, { "nineteen", "nineteenth" } }; const number_names tens[] = { { "twenty", "twentieth" }, { "thirty", "thirtieth" }, { "forty", "fortieth" }, { "fifty", "fiftieth" }, { "sixty", "sixtieth" }, { "seventy", "seventieth" }, { "eighty", "eightieth" }, { "ninety", "ninetieth" } }; typedef struct named_number_tag { const char* cardinal; const char* ordinal; integer number; } named_number; const named_number named_numbers[] = { { "hundred", "hundredth", 100 }, { "thousand", "thousandth", 1000 }, { "million", "millionth", 1000000 }, { "billion", "billionth", 1000000000 }, { "trillion", "trillionth", 1000000000000 }, { "quadrillion", "quadrillionth", 1000000000000000ULL }, { "quintillion", "quintillionth", 1000000000000000000ULL } }; const char* get_small_name(const number_names* n, bool ordinal) { return ordinal ? n->ordinal : n->cardinal; } const char* get_big_name(const named_number* n, bool ordinal) { return ordinal ? n->ordinal : n->cardinal; } const named_number* get_named_number(integer n) { const size_t names_len = sizeof(named_numbers)/sizeof(named_numbers[0]); for (size_t i = 0; i + 1 < names_len; ++i) { if (n < named_numbers[i + 1].number) return &named_numbers[i]; } return &named_numbers[names_len - 1]; } void append_number_name(GString* gstr, integer n, bool ordinal) { if (n < 20) g_string_append(gstr, get_small_name(&small[n], ordinal)); else if (n < 100) { if (n % 10 == 0) { g_string_append(gstr, get_small_name(&tens[n/10 - 2], ordinal)); } else { g_string_append(gstr, get_small_name(&tens[n/10 - 2], false)); g_string_append_c(gstr, '-'); g_string_append(gstr, get_small_name(&small[n % 10], ordinal)); } } else { const named_number* num = get_named_number(n); integer p = num->number; append_number_name(gstr, n/p, false); g_string_append_c(gstr, ' '); if (n % p == 0) { g_string_append(gstr, get_big_name(num, ordinal)); } else { g_string_append(gstr, get_big_name(num, false)); g_string_append_c(gstr, ' '); append_number_name(gstr, n % p, ordinal); } } } GString* number_name(integer n, bool ordinal) { GString* result = g_string_sized_new(8); append_number_name(result, n, ordinal); return result; } void test_ordinal(integer n) { GString* name = number_name(n, true); printf("%llu: %s\n", n, name->str); g_string_free(name, TRUE); } int main() { test_ordinal(1); test_ordinal(2); test_ordinal(3); test_ordinal(4); test_ordinal(5); test_ordinal(11); test_ordinal(15); test_ordinal(21); test_ordinal(42); test_ordinal(65); test_ordinal(98); test_ordinal(100); test_ordinal(101); test_ordinal(272); test_ordinal(300); test_ordinal(750); test_ordinal(23456); test_ordinal(7891233); test_ordinal(8007006005004003LL); return 0; }
irregularOrdinals = { "one": "first", "two": "second", "three": "third", "five": "fifth", "eight": "eighth", "nine": "ninth", "twelve": "twelfth", } def num2ordinal(n): conversion = int(float(n)) num = spell_integer(conversion) hyphen = num.rsplit("-", 1) num = num.rsplit(" ", 1) delim = " " if len(num[-1]) > len(hyphen[-1]): num = hyphen delim = "-" if num[-1] in irregularOrdinals: num[-1] = delim + irregularOrdinals[num[-1]] elif num[-1].endswith("y"): num[-1] = delim + num[-1][:-1] + "ieth" else: num[-1] = delim + num[-1] + "th" return "".join(num) if __name__ == "__main__": tests = "1 2 3 4 5 11 65 100 101 272 23456 8007006005004003 123 00123.0 1.23e2".split() for num in tests: print("{} => {}".format(num, num2ordinal(num))) TENS = [None, None, "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"] SMALL = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"] HUGE = [None, None] + [h + "illion" for h in ("m", "b", "tr", "quadr", "quint", "sext", "sept", "oct", "non", "dec")] def nonzero(c, n, connect=''): return "" if n == 0 else connect + c + spell_integer(n) def last_and(num): if ',' in num: pre, last = num.rsplit(',', 1) if ' and ' not in last: last = ' and' + last num = ''.join([pre, ',', last]) return num def big(e, n): if e == 0: return spell_integer(n) elif e == 1: return spell_integer(n) + " thousand" else: return spell_integer(n) + " " + HUGE[e] def base1000_rev(n): while n != 0: n, r = divmod(n, 1000) yield r def spell_integer(n): if n < 0: return "minus " + spell_integer(-n) elif n < 20: return SMALL[n] elif n < 100: a, b = divmod(n, 10) return TENS[a] + nonzero("-", b) elif n < 1000: a, b = divmod(n, 100) return SMALL[a] + " hundred" + nonzero(" ", b, ' and') else: num = ", ".join([big(e, x) for e, x in enumerate(base1000_rev(n)) if x][::-1]) return last_and(num)
Generate an equivalent Python version of this C code.
#include <stdio.h> inline int self_desc(unsigned long long xx) { register unsigned int d, x; unsigned char cnt[10] = {0}, dig[10] = {0}; for (d = 0; xx > ~0U; xx /= 10) cnt[ dig[d++] = xx % 10 ]++; for (x = xx; x; x /= 10) cnt[ dig[d++] = x % 10 ]++; while(d-- && dig[x++] == cnt[d]); return d == -1; } int main() { int i; for (i = 1; i < 100000000; i++) if (self_desc(i)) printf("%d\n", i); return 0; }
>>> def isSelfDescribing(n): s = str(n) return all(s.count(str(i)) == int(ch) for i, ch in enumerate(s)) >>> [x for x in range(4000000) if isSelfDescribing(x)] [1210, 2020, 21200, 3211000] >>> [(x, isSelfDescribing(x)) for x in (1210, 2020, 21200, 3211000, 42101000, 521001000, 6210001000)] [(1210, True), (2020, True), (21200, True), (3211000, True), (42101000, True), (521001000, True), (6210001000, True)]
Rewrite the snippet below in Python so it works the same as the original C code.
#include <stdio.h> #include <stdlib.h> #include <string.h> #define TRUE 1 #define FALSE 0 typedef int bool; typedef struct { int x, y; } pair; int* example = NULL; int exampleLen = 0; void reverse(int s[], int len) { int i, j, t; for (i = 0, j = len - 1; i < j; ++i, --j) { t = s[i]; s[i] = s[j]; s[j] = t; } } pair tryPerm(int i, int pos, int seq[], int n, int len, int minLen); pair checkSeq(int pos, int seq[], int n, int len, int minLen) { pair p; if (pos > minLen || seq[0] > n) { p.x = minLen; p.y = 0; return p; } else if (seq[0] == n) { example = malloc(len * sizeof(int)); memcpy(example, seq, len * sizeof(int)); exampleLen = len; p.x = pos; p.y = 1; return p; } else if (pos < minLen) { return tryPerm(0, pos, seq, n, len, minLen); } else { p.x = minLen; p.y = 0; return p; } } pair tryPerm(int i, int pos, int seq[], int n, int len, int minLen) { int *seq2; pair p, res1, res2; size_t size = sizeof(int); if (i > pos) { p.x = minLen; p.y = 0; return p; } seq2 = malloc((len + 1) * size); memcpy(seq2 + 1, seq, len * size); seq2[0] = seq[0] + seq[i]; res1 = checkSeq(pos + 1, seq2, n, len + 1, minLen); res2 = tryPerm(i + 1, pos, seq, n, len, res1.x); free(seq2); if (res2.x < res1.x) return res2; else if (res2.x == res1.x) { p.x = res2.x; p.y = res1.y + res2.y; return p; } else { printf("Error in tryPerm\n"); p.x = 0; p.y = 0; return p; } } pair initTryPerm(int x, int minLen) { int seq[1] = {1}; return tryPerm(0, 0, seq, x, 1, minLen); } void printArray(int a[], int len) { int i; printf("["); for (i = 0; i < len; ++i) printf("%d ", a[i]); printf("\b]\n"); } bool isBrauer(int a[], int len) { int i, j; bool ok; for (i = 2; i < len; ++i) { ok = FALSE; for (j = i - 1; j >= 0; j--) { if (a[i-1] + a[j] == a[i]) { ok = TRUE; break; } } if (!ok) return FALSE; } return TRUE; } bool isAdditionChain(int a[], int len) { int i, j, k; bool ok, exit; for (i = 2; i < len; ++i) { if (a[i] > a[i - 1] * 2) return FALSE; ok = FALSE; exit = FALSE; for (j = i - 1; j >= 0; --j) { for (k = j; k >= 0; --k) { if (a[j] + a[k] == a[i]) { ok = TRUE; exit = TRUE; break; } } if (exit) break; } if (!ok) return FALSE; } if (example == NULL && !isBrauer(a, len)) { example = malloc(len * sizeof(int)); memcpy(example, a, len * sizeof(int)); exampleLen = len; } return TRUE; } void nextChains(int index, int len, int seq[], int *pcount) { for (;;) { int i; if (index < len - 1) { nextChains(index + 1, len, seq, pcount); } if (seq[index] + len - 1 - index >= seq[len - 1]) return; seq[index]++; for (i = index + 1; i < len - 1; ++i) { seq[i] = seq[i-1] + 1; } if (isAdditionChain(seq, len)) (*pcount)++; } } int findNonBrauer(int num, int len, int brauer) { int i, count = 0; int *seq = malloc(len * sizeof(int)); seq[0] = 1; seq[len - 1] = num; for (i = 1; i < len - 1; ++i) { seq[i] = seq[i - 1] + 1; } if (isAdditionChain(seq, len)) count = 1; nextChains(2, len, seq, &count); free(seq); return count - brauer; } void findBrauer(int num, int minLen, int nbLimit) { pair p = initTryPerm(num, minLen); int actualMin = p.x, brauer = p.y, nonBrauer; printf("\nN = %d\n", num); printf("Minimum length of chains : L(%d) = %d\n", num, actualMin); printf("Number of minimum length Brauer chains : %d\n", brauer); if (brauer > 0) { printf("Brauer example : "); reverse(example, exampleLen); printArray(example, exampleLen); } if (example != NULL) { free(example); example = NULL; exampleLen = 0; } if (num <= nbLimit) { nonBrauer = findNonBrauer(num, actualMin + 1, brauer); printf("Number of minimum length non-Brauer chains : %d\n", nonBrauer); if (nonBrauer > 0) { printf("Non-Brauer example : "); printArray(example, exampleLen); } if (example != NULL) { free(example); example = NULL; exampleLen = 0; } } else { printf("Non-Brauer analysis suppressed\n"); } } int main() { int i; int nums[12] = {7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379}; printf("Searching for Brauer chains up to a minimum length of 12:\n"); for (i = 0; i < 12; ++i) findBrauer(nums[i], 12, 79); return 0; }
def prepend(n, seq): return [n] + seq def check_seq(pos, seq, n, min_len): if pos > min_len or seq[0] > n: return min_len, 0 if seq[0] == n: return pos, 1 if pos < min_len: return try_perm(0, pos, seq, n, min_len) return min_len, 0 def try_perm(i, pos, seq, n, min_len): if i > pos: return min_len, 0 res1 = check_seq(pos + 1, prepend(seq[0] + seq[i], seq), n, min_len) res2 = try_perm(i + 1, pos, seq, n, res1[0]) if res2[0] < res1[0]: return res2 if res2[0] == res1[0]: return res2[0], res1[1] + res2[1] raise Exception("try_perm exception") def init_try_perm(x): return try_perm(0, 0, [1], x, 12) def find_brauer(num): res = init_try_perm(num) print print "N = ", num print "Minimum length of chains: L(n) = ", res[0] print "Number of minimum length Brauer chains: ", res[1] nums = [7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379] for i in nums: find_brauer(i)
Produce a language-to-language conversion: from C to Python, same semantics.
#include <stdio.h> void repeat(void (*f)(void), unsigned int n) { while (n-->0) (*f)(); } void example() { printf("Example\n"); } int main(int argc, char *argv[]) { repeat(example, 4); return 0; }
def repeat(f,n): for i in range(n): f(); def procedure(): print("Example"); repeat(procedure,3);
Change the programming language of this snippet from C to Python without modifying what it does.
#include <stdio.h> void repeat(void (*f)(void), unsigned int n) { while (n-->0) (*f)(); } void example() { printf("Example\n"); } int main(int argc, char *argv[]) { repeat(example, 4); return 0; }
def repeat(f,n): for i in range(n): f(); def procedure(): print("Example"); repeat(procedure,3);
Change the following C code into Python without altering its purpose.
#include<string.h> #include<stdlib.h> #include<locale.h> #include<stdio.h> #include<wchar.h> #include<math.h> int main(int argC,char* argV[]) { double* arr,min,max; char* str; int i,len; if(argC == 1) printf("Usage : %s <data points separated by spaces or commas>",argV[0]); else{ arr = (double*)malloc((argC-1)*sizeof(double)); for(i=1;i<argC;i++){ len = strlen(argV[i]); if(argV[i][len-1]==','){ str = (char*)malloc(len*sizeof(char)); strncpy(str,argV[i],len-1); arr[i-1] = atof(str); free(str); } else arr[i-1] = atof(argV[i]); if(i==1){ min = arr[i-1]; max = arr[i-1]; } else{ min=(min<arr[i-1]?min:arr[i-1]); max=(max>arr[i-1]?max:arr[i-1]); } } printf("\n%Max : %lf,Min : %lf,Range : %lf\n",max,min,max-min); setlocale(LC_ALL, ""); for(i=1;i<argC;i++){ printf("%lc", (wint_t)(9601 + (int)ceil((arr[i-1]-min)/(max-min)*7))); } } return 0; }
bar = '▁▂▃▄▅▆▇█' barcount = len(bar) def sparkline(numbers): mn, mx = min(numbers), max(numbers) extent = mx - mn sparkline = ''.join(bar[min([barcount - 1, int((n - mn) / extent * barcount)])] for n in numbers) return mn, mx, sparkline if __name__ == '__main__': import re for line in ("0 0 1 1; 0 1 19 20; 0 999 4000 4999 7000 7999;" "1 2 3 4 5 6 7 8 7 6 5 4 3 2 1;" "1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5 ").split(';'): print("\nNumbers:", line) numbers = [float(n) for n in re.split(r'[\s,]+', line.strip())] mn, mx, sp = sparkline(numbers) print(' min: %5f; max: %5f' % (mn, mx)) print(" " + sp)
Rewrite this program in Python while keeping its functionality equivalent to the C version.
count = 1; n = 1; limit = 100; while (n < limit) { k=3; p=1; n=n+2; while ((k*k<=n) && (p)) { p=n/k*k!=n; k=k+2; } if (p) { print(n, " is prime\n"); count = count + 1; } } print("Total primes found: ", count, "\n");
def load_ast() line = readline() line_list = tokenize the line, respecting double quotes text = line_list[0] if text == ";" return NULL node_type = text if len(line_list) > 1 return make_leaf(node_type, line_list[1]) left = load_ast() right = load_ast() return make_node(node_type, left, right)
Produce a language-to-language conversion: from C to Python, same semantics.
count = 1; n = 1; limit = 100; while (n < limit) { k=3; p=1; n=n+2; while ((k*k<=n) && (p)) { p=n/k*k!=n; k=k+2; } if (p) { print(n, " is prime\n"); count = count + 1; } } print("Total primes found: ", count, "\n");
def load_ast() line = readline() line_list = tokenize the line, respecting double quotes text = line_list[0] if text == ";" return NULL node_type = text if len(line_list) > 1 return make_leaf(node_type, line_list[1]) left = load_ast() right = load_ast() return make_node(node_type, left, right)
Keep all operations the same but rewrite the snippet in Python.
count = 1; n = 1; limit = 100; while (n < limit) { k=3; p=1; n=n+2; while ((k*k<=n) && (p)) { p=n/k*k!=n; k=k+2; } if (p) { print(n, " is prime\n"); count = count + 1; } } print("Total primes found: ", count, "\n");
def load_ast() line = readline() line_list = tokenize the line, respecting double quotes text = line_list[0] if text == ";" return NULL node_type = text if len(line_list) > 1 return make_leaf(node_type, line_list[1]) left = load_ast() right = load_ast() return make_node(node_type, left, right)
Convert this C block to Python, preserving its control flow and logic.
#include <stdio.h> int mul_inv(int a, int b) { int b0 = b, t, q; int x0 = 0, x1 = 1; if (b == 1) return 1; while (a > 1) { q = a / b; t = b, b = a % b, a = t; t = x0, x0 = x1 - q * x0, x1 = t; } if (x1 < 0) x1 += b0; return x1; } int main(void) { printf("%d\n", mul_inv(42, 2017)); return 0; }
>>> def extended_gcd(aa, bb): lastremainder, remainder = abs(aa), abs(bb) x, lastx, y, lasty = 0, 1, 1, 0 while remainder: lastremainder, (quotient, remainder) = remainder, divmod(lastremainder, remainder) x, lastx = lastx - quotient*x, x y, lasty = lasty - quotient*y, y return lastremainder, lastx * (-1 if aa < 0 else 1), lasty * (-1 if bb < 0 else 1) >>> def modinv(a, m): g, x, y = extended_gcd(a, m) if g != 1: raise ValueError return x % m >>> modinv(42, 2017) 1969 >>>
Generate an equivalent Python version of this C code.
#define WINVER 0x500 #include<windows.h> int main() { int maxX = GetSystemMetrics(SM_CXSCREEN), maxY = GetSystemMetrics(SM_CYSCREEN); int x = maxX/2, y = maxY/2; double factorX = 65536.0 / maxX,factorY = 65536.0 / maxY; INPUT ip; ZeroMemory(&ip,sizeof(ip)); ip.type = INPUT_MOUSE; while(x > 5 || y < maxY-5){ ip.mi.mouseData = 0; ip.mi.dx = x * factorX; ip.mi.dy = y * factorY; ip.mi.dwFlags = MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE; SendInput(1,&ip,sizeof(ip)); Sleep(1); if(x>3) x-=1; if(y<maxY-3) y+=1; } ip.mi.dwFlags = MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP; SendInput(1,&ip,sizeof(ip)); return 0; }
import ctypes def click(): ctypes.windll.user32.mouse_event(0x2, 0,0,0,0) ctypes.windll.user32.mouse_event(0x4, 0,0,0,0) click()
Write a version of this C function in Python with identical behavior.
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <arpa/inet.h> #include <err.h> char response[] = "HTTP/1.1 200 OK\r\n" "Content-Type: text/html; charset=UTF-8\r\n\r\n" "<!DOCTYPE html><html><head><title>Bye-bye baby bye-bye</title>" "<style>body { background-color: #111 }" "h1 { font-size:4cm; text-align: center; color: black;" " text-shadow: 0 0 2mm red}</style></head>" "<body><h1>Goodbye, world!</h1></body></html>\r\n"; int main() { int one = 1, client_fd; struct sockaddr_in svr_addr, cli_addr; socklen_t sin_len = sizeof(cli_addr); int sock = socket(AF_INET, SOCK_STREAM, 0); if (sock < 0) err(1, "can't open socket"); setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(int)); int port = 8080; svr_addr.sin_family = AF_INET; svr_addr.sin_addr.s_addr = INADDR_ANY; svr_addr.sin_port = htons(port); if (bind(sock, (struct sockaddr *) &svr_addr, sizeof(svr_addr)) == -1) { close(sock); err(1, "Can't bind"); } listen(sock, 5); while (1) { client_fd = accept(sock, (struct sockaddr *) &cli_addr, &sin_len); printf("got connection\n"); if (client_fd == -1) { perror("Can't accept"); continue; } write(client_fd, response, sizeof(response) - 1); close(client_fd); } }
from wsgiref.simple_server import make_server def app(environ, start_response): start_response('200 OK', [('Content-Type','text/html')]) yield b"<h1>Goodbye, World!</h1>" server = make_server('127.0.0.1', 8080, app) server.serve_forever()
Convert the following code from C to Python, ensuring the logic remains intact.
#include<graphics.h> #include<math.h> #define pi M_PI void sunflower(int winWidth, int winHeight, double diskRatio, int iter){ double factor = .5 + sqrt(1.25),r,theta; double x = winWidth/2.0, y = winHeight/2.0; double maxRad = pow(iter,factor)/iter; int i; setbkcolor(LIGHTBLUE); for(i=0;i<=iter;i++){ r = pow(i,factor)/iter; r/maxRad < diskRatio?setcolor(BLACK):setcolor(YELLOW); theta = 2*pi*factor*i; circle(x + r*sin(theta), y + r*cos(theta), 10 * i/(1.0*iter)); } } int main() { initwindow(1000,1000,"Sunflower..."); sunflower(1000,1000,0.5,3000); getch(); closegraph(); return 0; }
from turtle import * from math import * iter = 3000 diskRatio = .5 factor = .5 + sqrt(1.25) screen = getscreen() (winWidth, winHeight) = screen.screensize() x = 0.0 y = 0.0 maxRad = pow(iter,factor)/iter; bgcolor("light blue") hideturtle() tracer(0, 0) for i in range(iter+1): r = pow(i,factor)/iter; if r/maxRad < diskRatio: pencolor("black") else: pencolor("yellow") theta = 2*pi*factor*i; up() setposition(x + r*sin(theta), y + r*cos(theta)) down() circle(10.0 * i/(1.0*iter)) update() done()
Produce a language-to-language conversion: from C to Python, same semantics.
#include <stdio.h> #include <limits.h> #define TRUE 1 #define FALSE 0 #define N_ROWS 4 #define N_COLS 5 typedef int bool; int supply[N_ROWS] = { 50, 60, 50, 50 }; int demand[N_COLS] = { 30, 20, 70, 30, 60 }; int costs[N_ROWS][N_COLS] = { { 16, 16, 13, 22, 17 }, { 14, 14, 13, 19, 15 }, { 19, 19, 20, 23, 50 }, { 50, 12, 50, 15, 11 } }; bool row_done[N_ROWS] = { FALSE }; bool col_done[N_COLS] = { FALSE }; void diff(int j, int len, bool is_row, int res[3]) { int i, c, min1 = INT_MAX, min2 = min1, min_p = -1; for (i = 0; i < len; ++i) { if((is_row) ? col_done[i] : row_done[i]) continue; c = (is_row) ? costs[j][i] : costs[i][j]; if (c < min1) { min2 = min1; min1 = c; min_p = i; } else if (c < min2) min2 = c; } res[0] = min2 - min1; res[1] = min1; res[2] = min_p; } void max_penalty(int len1, int len2, bool is_row, int res[4]) { int i, pc = -1, pm = -1, mc = -1, md = INT_MIN; int res2[3]; for (i = 0; i < len1; ++i) { if((is_row) ? row_done[i] : col_done[i]) continue; diff(i, len2, is_row, res2); if (res2[0] > md) { md = res2[0]; pm = i; mc = res2[1]; pc = res2[2]; } } if (is_row) { res[0] = pm; res[1] = pc; } else { res[0] = pc; res[1] = pm; } res[2] = mc; res[3] = md; } void next_cell(int res[4]) { int i, res1[4], res2[4]; max_penalty(N_ROWS, N_COLS, TRUE, res1); max_penalty(N_COLS, N_ROWS, FALSE, res2); if (res1[3] == res2[3]) { if (res1[2] < res2[2]) for (i = 0; i < 4; ++i) res[i] = res1[i]; else for (i = 0; i < 4; ++i) res[i] = res2[i]; return; } if (res1[3] > res2[3]) for (i = 0; i < 4; ++i) res[i] = res2[i]; else for (i = 0; i < 4; ++i) res[i] = res1[i]; } int main() { int i, j, r, c, q, supply_left = 0, total_cost = 0, cell[4]; int results[N_ROWS][N_COLS] = { 0 }; for (i = 0; i < N_ROWS; ++i) supply_left += supply[i]; while (supply_left > 0) { next_cell(cell); r = cell[0]; c = cell[1]; q = (demand[c] <= supply[r]) ? demand[c] : supply[r]; demand[c] -= q; if (!demand[c]) col_done[c] = TRUE; supply[r] -= q; if (!supply[r]) row_done[r] = TRUE; results[r][c] = q; supply_left -= q; total_cost += q * costs[r][c]; } printf(" A B C D E\n"); for (i = 0; i < N_ROWS; ++i) { printf("%c", 'W' + i); for (j = 0; j < N_COLS; ++j) printf(" %2d", results[i][j]); printf("\n"); } printf("\nTotal cost = %d\n", total_cost); return 0; }
from collections import defaultdict costs = {'W': {'A': 16, 'B': 16, 'C': 13, 'D': 22, 'E': 17}, 'X': {'A': 14, 'B': 14, 'C': 13, 'D': 19, 'E': 15}, 'Y': {'A': 19, 'B': 19, 'C': 20, 'D': 23, 'E': 50}, 'Z': {'A': 50, 'B': 12, 'C': 50, 'D': 15, 'E': 11}} demand = {'A': 30, 'B': 20, 'C': 70, 'D': 30, 'E': 60} cols = sorted(demand.iterkeys()) supply = {'W': 50, 'X': 60, 'Y': 50, 'Z': 50} res = dict((k, defaultdict(int)) for k in costs) g = {} for x in supply: g[x] = sorted(costs[x].iterkeys(), key=lambda g: costs[x][g]) for x in demand: g[x] = sorted(costs.iterkeys(), key=lambda g: costs[g][x]) while g: d = {} for x in demand: d[x] = (costs[g[x][1]][x] - costs[g[x][0]][x]) if len(g[x]) > 1 else costs[g[x][0]][x] s = {} for x in supply: s[x] = (costs[x][g[x][1]] - costs[x][g[x][0]]) if len(g[x]) > 1 else costs[x][g[x][0]] f = max(d, key=lambda n: d[n]) t = max(s, key=lambda n: s[n]) t, f = (f, g[f][0]) if d[f] > s[t] else (g[t][0], t) v = min(supply[f], demand[t]) res[f][t] += v demand[t] -= v if demand[t] == 0: for k, n in supply.iteritems(): if n != 0: g[k].remove(t) del g[t] del demand[t] supply[f] -= v if supply[f] == 0: for k, n in demand.iteritems(): if n != 0: g[k].remove(f) del g[f] del supply[f] for n in cols: print "\t", n, print cost = 0 for g in sorted(costs): print g, "\t", for n in cols: y = res[g][n] if y != 0: print y, cost += y * costs[g][n] print "\t", print print "\n\nTotal Cost = ", cost
Keep all operations the same but rewrite the snippet in Python.
#include <stdio.h> #include <limits.h> #define TRUE 1 #define FALSE 0 #define N_ROWS 4 #define N_COLS 5 typedef int bool; int supply[N_ROWS] = { 50, 60, 50, 50 }; int demand[N_COLS] = { 30, 20, 70, 30, 60 }; int costs[N_ROWS][N_COLS] = { { 16, 16, 13, 22, 17 }, { 14, 14, 13, 19, 15 }, { 19, 19, 20, 23, 50 }, { 50, 12, 50, 15, 11 } }; bool row_done[N_ROWS] = { FALSE }; bool col_done[N_COLS] = { FALSE }; void diff(int j, int len, bool is_row, int res[3]) { int i, c, min1 = INT_MAX, min2 = min1, min_p = -1; for (i = 0; i < len; ++i) { if((is_row) ? col_done[i] : row_done[i]) continue; c = (is_row) ? costs[j][i] : costs[i][j]; if (c < min1) { min2 = min1; min1 = c; min_p = i; } else if (c < min2) min2 = c; } res[0] = min2 - min1; res[1] = min1; res[2] = min_p; } void max_penalty(int len1, int len2, bool is_row, int res[4]) { int i, pc = -1, pm = -1, mc = -1, md = INT_MIN; int res2[3]; for (i = 0; i < len1; ++i) { if((is_row) ? row_done[i] : col_done[i]) continue; diff(i, len2, is_row, res2); if (res2[0] > md) { md = res2[0]; pm = i; mc = res2[1]; pc = res2[2]; } } if (is_row) { res[0] = pm; res[1] = pc; } else { res[0] = pc; res[1] = pm; } res[2] = mc; res[3] = md; } void next_cell(int res[4]) { int i, res1[4], res2[4]; max_penalty(N_ROWS, N_COLS, TRUE, res1); max_penalty(N_COLS, N_ROWS, FALSE, res2); if (res1[3] == res2[3]) { if (res1[2] < res2[2]) for (i = 0; i < 4; ++i) res[i] = res1[i]; else for (i = 0; i < 4; ++i) res[i] = res2[i]; return; } if (res1[3] > res2[3]) for (i = 0; i < 4; ++i) res[i] = res2[i]; else for (i = 0; i < 4; ++i) res[i] = res1[i]; } int main() { int i, j, r, c, q, supply_left = 0, total_cost = 0, cell[4]; int results[N_ROWS][N_COLS] = { 0 }; for (i = 0; i < N_ROWS; ++i) supply_left += supply[i]; while (supply_left > 0) { next_cell(cell); r = cell[0]; c = cell[1]; q = (demand[c] <= supply[r]) ? demand[c] : supply[r]; demand[c] -= q; if (!demand[c]) col_done[c] = TRUE; supply[r] -= q; if (!supply[r]) row_done[r] = TRUE; results[r][c] = q; supply_left -= q; total_cost += q * costs[r][c]; } printf(" A B C D E\n"); for (i = 0; i < N_ROWS; ++i) { printf("%c", 'W' + i); for (j = 0; j < N_COLS; ++j) printf(" %2d", results[i][j]); printf("\n"); } printf("\nTotal cost = %d\n", total_cost); return 0; }
from collections import defaultdict costs = {'W': {'A': 16, 'B': 16, 'C': 13, 'D': 22, 'E': 17}, 'X': {'A': 14, 'B': 14, 'C': 13, 'D': 19, 'E': 15}, 'Y': {'A': 19, 'B': 19, 'C': 20, 'D': 23, 'E': 50}, 'Z': {'A': 50, 'B': 12, 'C': 50, 'D': 15, 'E': 11}} demand = {'A': 30, 'B': 20, 'C': 70, 'D': 30, 'E': 60} cols = sorted(demand.iterkeys()) supply = {'W': 50, 'X': 60, 'Y': 50, 'Z': 50} res = dict((k, defaultdict(int)) for k in costs) g = {} for x in supply: g[x] = sorted(costs[x].iterkeys(), key=lambda g: costs[x][g]) for x in demand: g[x] = sorted(costs.iterkeys(), key=lambda g: costs[g][x]) while g: d = {} for x in demand: d[x] = (costs[g[x][1]][x] - costs[g[x][0]][x]) if len(g[x]) > 1 else costs[g[x][0]][x] s = {} for x in supply: s[x] = (costs[x][g[x][1]] - costs[x][g[x][0]]) if len(g[x]) > 1 else costs[x][g[x][0]] f = max(d, key=lambda n: d[n]) t = max(s, key=lambda n: s[n]) t, f = (f, g[f][0]) if d[f] > s[t] else (g[t][0], t) v = min(supply[f], demand[t]) res[f][t] += v demand[t] -= v if demand[t] == 0: for k, n in supply.iteritems(): if n != 0: g[k].remove(t) del g[t] del demand[t] supply[f] -= v if supply[f] == 0: for k, n in demand.iteritems(): if n != 0: g[k].remove(f) del g[f] del supply[f] for n in cols: print "\t", n, print cost = 0 for g in sorted(costs): print g, "\t", for n in cols: y = res[g][n] if y != 0: print y, cost += y * costs[g][n] print "\t", print print "\n\nTotal Cost = ", cost
Maintain the same structure and functionality when rewriting this code in Python.
#include <math.h> #include <stdio.h> #define DEG 0.017453292519943295769236907684886127134 #define RE 6371000.0 #define DD 0.001 #define FIN 10000000.0 static double rho(double a) { return exp(-a / 8500.0); } static double height(double a, double z, double d) { double aa = RE + a; double hh = sqrt(aa * aa + d * d - 2.0 * d * aa * cos((180 - z) * DEG)); return hh - RE; } static double column_density(double a, double z) { double sum = 0.0, d = 0.0; while (d < FIN) { double delta = DD * d; if (delta < DD) delta = DD; sum += rho(height(a, z, d + 0.5 * delta)) * delta; d += delta; } return sum; } static double airmass(double a, double z) { return column_density(a, z) / column_density(a, 0.0); } int main() { puts("Angle 0 m 13700 m"); puts("------------------------------------"); for (double z = 0; z <= 90; z+= 5) { printf("%2.0f %11.8f %11.8f\n", z, airmass(0.0, z), airmass(13700.0, z)); } }
from math import sqrt, cos, exp DEG = 0.017453292519943295769236907684886127134 RE = 6371000 dd = 0.001 FIN = 10000000 def rho(a): return exp(-a / 8500.0) def height(a, z, d): return sqrt((RE + a)**2 + d**2 - 2 * d * (RE + a) * cos((180 - z) * DEG)) - RE def column_density(a, z): dsum, d = 0.0, 0.0 while d < FIN: delta = max(dd, (dd)*d) dsum += rho(height(a, z, d + 0.5 * delta)) * delta d += delta return dsum def airmass(a, z): return column_density(a, z) / column_density(a, 0) print('Angle 0 m 13700 m\n', '-' * 36) for z in range(0, 91, 5): print(f"{z: 3d} {airmass(0, z): 12.7f} {airmass(13700, z): 12.7f}")
Produce a functionally identical Python code for the snippet given in C.
#define _XOPEN_SOURCE #include <stdio.h> #include <time.h> int main() { struct tm t[2]; strptime("2021-12-25", "%F", &t[0]); strptime("2022-01-01", "%F", &t[1]); for (int i=0; i<2; i++) { char buf[32]; strftime(buf, 32, "%F is a %A", &t[i]); puts(buf); } return 0; }
import datetime weekDays = ("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday") thisXMas = datetime.date(2021,12,25) thisXMasDay = thisXMas.weekday() thisXMasDayAsString = weekDays[thisXMasDay] print("This year's Christmas is on a {}".format(thisXMasDayAsString)) nextNewYear = datetime.date(2022,1,1) nextNewYearDay = nextNewYear.weekday() nextNewYearDayAsString = weekDays[nextNewYearDay] print("Next new year is on a {}".format(nextNewYearDayAsString))
Convert this C block to Python, preserving its control flow and logic.
#include <stdio.h> #include <stdlib.h> #include <math.h> enum fps_type { FPS_CONST = 0, FPS_ADD, FPS_SUB, FPS_MUL, FPS_DIV, FPS_DERIV, FPS_INT, }; typedef struct fps_t *fps; typedef struct fps_t { int type; fps s1, s2; double a0; } fps_t; fps fps_new() { fps x = malloc(sizeof(fps_t)); x->a0 = 0; x->s1 = x->s2 = 0; x->type = 0; return x; } void fps_redefine(fps x, int op, fps y, fps z) { x->type = op; x->s1 = y; x->s2 = z; } fps _binary(fps x, fps y, int op) { fps s = fps_new(); s->s1 = x; s->s2 = y; s->type = op; return s; } fps _unary(fps x, int op) { fps s = fps_new(); s->s1 = x; s->type = op; return s; } double term(fps x, int n) { double ret = 0; int i; switch (x->type) { case FPS_CONST: return n > 0 ? 0 : x->a0; case FPS_ADD: ret = term(x->s1, n) + term(x->s2, n); break; case FPS_SUB: ret = term(x->s1, n) - term(x->s2, n); break; case FPS_MUL: for (i = 0; i <= n; i++) ret += term(x->s1, i) * term(x->s2, n - i); break; case FPS_DIV: if (! term(x->s2, 0)) return NAN; ret = term(x->s1, n); for (i = 1; i <= n; i++) ret -= term(x->s2, i) * term(x, n - i) / term(x->s2, 0); break; case FPS_DERIV: ret = n * term(x->s1, n + 1); break; case FPS_INT: if (!n) return x->a0; ret = term(x->s1, n - 1) / n; break; default: fprintf(stderr, "Unknown operator %d\n", x->type); exit(1); } return ret; } #define _add(x, y) _binary(x, y, FPS_ADD) #define _sub(x, y) _binary(x, y, FPS_SUB) #define _mul(x, y) _binary(x, y, FPS_MUL) #define _div(x, y) _binary(x, y, FPS_DIV) #define _integ(x) _unary(x, FPS_INT) #define _deriv(x) _unary(x, FPS_DERIV) fps fps_const(double a0) { fps x = fps_new(); x->type = FPS_CONST; x->a0 = a0; return x; } int main() { int i; fps one = fps_const(1); fps fcos = fps_new(); fps fsin = _integ(fcos); fps ftan = _div(fsin, fcos); fps_redefine(fcos, FPS_SUB, one, _integ(fsin)); fps fexp = fps_const(1); fps_redefine(fexp, FPS_INT, fexp, 0); printf("Sin:"); for (i = 0; i < 10; i++) printf(" %g", term(fsin, i)); printf("\nCos:"); for (i = 0; i < 10; i++) printf(" %g", term(fcos, i)); printf("\nTan:"); for (i = 0; i < 10; i++) printf(" %g", term(ftan, i)); printf("\nExp:"); for (i = 0; i < 10; i++) printf(" %g", term(fexp, i)); return 0; }
from itertools import islice from fractions import Fraction from functools import reduce try: from itertools import izip as zip except: pass def head(n): return lambda seq: islice(seq, n) def pipe(gen, *cmds): return reduce(lambda gen, cmd: cmd(gen), cmds, gen) def sinepower(): n = 0 fac = 1 sign = +1 zero = 0 yield zero while True: n +=1 fac *= n yield Fraction(1, fac*sign) sign = -sign n +=1 fac *= n yield zero def cosinepower(): n = 0 fac = 1 sign = +1 yield Fraction(1,fac) zero = 0 while True: n +=1 fac *= n yield zero sign = -sign n +=1 fac *= n yield Fraction(1, fac*sign) def pluspower(*powergenerators): for elements in zip(*powergenerators): yield sum(elements) def minuspower(*powergenerators): for elements in zip(*powergenerators): yield elements[0] - sum(elements[1:]) def mulpower(fgen,ggen): 'From: http://en.wikipedia.org/wiki/Power_series a,b = [],[] for f,g in zip(fgen, ggen): a.append(f) b.append(g) yield sum(f*g for f,g in zip(a, reversed(b))) def constpower(n): yield n while True: yield 0 def diffpower(gen): 'differentiatiate power series' next(gen) for n, an in enumerate(gen, start=1): yield an*n def intgpower(k=0): 'integrate power series with constant k' def _intgpower(gen): yield k for n, an in enumerate(gen, start=1): yield an * Fraction(1,n) return _intgpower print("cosine") c = list(pipe(cosinepower(), head(10))) print(c) print("sine") s = list(pipe(sinepower(), head(10))) print(s) integc = list(pipe(cosinepower(),intgpower(0), head(10))) integs1 = list(minuspower(pipe(constpower(1), head(10)), pipe(sinepower(),intgpower(0), head(10)))) assert s == integc, "The integral of cos should be sin" assert c == integs1, "1 minus the integral of sin should be cos"
Please provide an equivalent version of this C code in Python.
#include <stdio.h> #include <math.h> #define MAX_DIGITS 9 int digits[MAX_DIGITS]; void getDigits(int i) { int ix = 0; while (i > 0) { digits[ix++] = i % 10; i /= 10; } } int main() { int n, d, i, max, lastDigit, sum, dp; int powers[10] = {0, 1, 4, 9, 16, 25, 36, 49, 64, 81}; printf("Own digits power sums for N = 3 to 9 inclusive:\n"); for (n = 3; n < 10; ++n) { for (d = 2; d < 10; ++d) powers[d] *= d; i = (int)pow(10, n-1); max = i * 10; lastDigit = 0; while (i < max) { if (!lastDigit) { getDigits(i); sum = 0; for (d = 0; d < n; ++d) { dp = digits[d]; sum += powers[dp]; } } else if (lastDigit == 1) { sum++; } else { sum += powers[lastDigit] - powers[lastDigit-1]; } if (sum == i) { printf("%d\n", i); if (lastDigit == 0) printf("%d\n", i + 1); i += 10 - lastDigit; lastDigit = 0; } else if (sum > i) { i += 10 - lastDigit; lastDigit = 0; } else if (lastDigit < 9) { i++; lastDigit++; } else { i++; lastDigit = 0; } } } return 0; }
def isowndigitspowersum(integer): digits = [int(c) for c in str(integer)] exponent = len(digits) return sum(x ** exponent for x in digits) == integer print("Own digits power sums for N = 3 to 9 inclusive:") for i in range(100, 1000000000): if isowndigitspowersum(i): print(i)
Write a version of this C function in Python with identical behavior.
#include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <string.h> #include <stdint.h> #include <ctype.h> #define NELEMS(arr) (sizeof(arr) / sizeof(arr[0])) #define da_dim(name, type) type *name = NULL; \ int _qy_ ## name ## _p = 0; \ int _qy_ ## name ## _max = 0 #define da_redim(name) do {if (_qy_ ## name ## _p >= _qy_ ## name ## _max) \ name = realloc(name, (_qy_ ## name ## _max += 32) * sizeof(name[0]));} while (0) #define da_rewind(name) _qy_ ## name ## _p = 0 #define da_append(name, x) do {da_redim(name); name[_qy_ ## name ## _p++] = x;} while (0) typedef unsigned char uchar; typedef uchar code; typedef enum { FETCH, STORE, PUSH, ADD, SUB, MUL, DIV, MOD, LT, GT, LE, GE, EQ, NE, AND, OR, NEG, NOT, JMP, JZ, PRTC, PRTS, PRTI, HALT } Code_t; typedef struct Code_map { char *text; Code_t op; } Code_map; Code_map code_map[] = { {"fetch", FETCH}, {"store", STORE}, {"push", PUSH }, {"add", ADD }, {"sub", SUB }, {"mul", MUL }, {"div", DIV }, {"mod", MOD }, {"lt", LT }, {"gt", GT }, {"le", LE }, {"ge", GE }, {"eq", EQ }, {"ne", NE }, {"and", AND }, {"or", OR }, {"neg", NEG }, {"not", NOT }, {"jmp", JMP }, {"jz", JZ }, {"prtc", PRTC }, {"prts", PRTS }, {"prti", PRTI }, {"halt", HALT }, }; FILE *source_fp; da_dim(object, code); void error(const char *fmt, ... ) { va_list ap; char buf[1000]; va_start(ap, fmt); vsprintf(buf, fmt, ap); va_end(ap); printf("error: %s\n", buf); exit(1); } void run_vm(const code obj[], int32_t data[], int g_size, char **string_pool) { int32_t *sp = &data[g_size + 1]; const code *pc = obj; again: switch (*pc++) { case FETCH: *sp++ = data[*(int32_t *)pc]; pc += sizeof(int32_t); goto again; case STORE: data[*(int32_t *)pc] = *--sp; pc += sizeof(int32_t); goto again; case PUSH: *sp++ = *(int32_t *)pc; pc += sizeof(int32_t); goto again; case ADD: sp[-2] += sp[-1]; --sp; goto again; case SUB: sp[-2] -= sp[-1]; --sp; goto again; case MUL: sp[-2] *= sp[-1]; --sp; goto again; case DIV: sp[-2] /= sp[-1]; --sp; goto again; case MOD: sp[-2] %= sp[-1]; --sp; goto again; case LT: sp[-2] = sp[-2] < sp[-1]; --sp; goto again; case GT: sp[-2] = sp[-2] > sp[-1]; --sp; goto again; case LE: sp[-2] = sp[-2] <= sp[-1]; --sp; goto again; case GE: sp[-2] = sp[-2] >= sp[-1]; --sp; goto again; case EQ: sp[-2] = sp[-2] == sp[-1]; --sp; goto again; case NE: sp[-2] = sp[-2] != sp[-1]; --sp; goto again; case AND: sp[-2] = sp[-2] && sp[-1]; --sp; goto again; case OR: sp[-2] = sp[-2] || sp[-1]; --sp; goto again; case NEG: sp[-1] = -sp[-1]; goto again; case NOT: sp[-1] = !sp[-1]; goto again; case JMP: pc += *(int32_t *)pc; goto again; case JZ: pc += (*--sp == 0) ? *(int32_t *)pc : (int32_t)sizeof(int32_t); goto again; case PRTC: printf("%c", sp[-1]); --sp; goto again; case PRTS: printf("%s", string_pool[sp[-1]]); --sp; goto again; case PRTI: printf("%d", sp[-1]); --sp; goto again; case HALT: break; default: error("Unknown opcode %d\n", *(pc - 1)); } } char *read_line(int *len) { static char *text = NULL; static int textmax = 0; for (*len = 0; ; (*len)++) { int ch = fgetc(source_fp); if (ch == EOF || ch == '\n') { if (*len == 0) return NULL; break; } if (*len + 1 >= textmax) { textmax = (textmax == 0 ? 128 : textmax * 2); text = realloc(text, textmax); } text[*len] = ch; } text[*len] = '\0'; return text; } char *rtrim(char *text, int *len) { for (; *len > 0 && isspace(text[*len - 1]); --(*len)) ; text[*len] = '\0'; return text; } char *translate(char *st) { char *p, *q; if (st[0] == '"') ++st; p = q = st; while ((*p++ = *q++) != '\0') { if (q[-1] == '\\') { if (q[0] == 'n') { p[-1] = '\n'; ++q; } else if (q[0] == '\\') { ++q; } } if (q[0] == '"' && q[1] == '\0') ++q; } return st; } int findit(const char text[], int offset) { for (size_t i = 0; i < sizeof(code_map) / sizeof(code_map[0]); i++) { if (strcmp(code_map[i].text, text) == 0) return code_map[i].op; } error("Unknown instruction %s at %d\n", text, offset); return -1; } void emit_byte(int c) { da_append(object, (uchar)c); } void emit_int(int32_t n) { union { int32_t n; unsigned char c[sizeof(int32_t)]; } x; x.n = n; for (size_t i = 0; i < sizeof(x.n); ++i) { emit_byte(x.c[i]); } } char **load_code(int *ds) { int line_len, n_strings; char **string_pool; char *text = read_line(&line_len); text = rtrim(text, &line_len); strtok(text, " "); *ds = atoi(strtok(NULL, " ")); strtok(NULL, " "); n_strings = atoi(strtok(NULL, " ")); string_pool = malloc(n_strings * sizeof(char *)); for (int i = 0; i < n_strings; ++i) { text = read_line(&line_len); text = rtrim(text, &line_len); text = translate(text); string_pool[i] = strdup(text); } for (;;) { int len; text = read_line(&line_len); if (text == NULL) break; text = rtrim(text, &line_len); int offset = atoi(strtok(text, " ")); char *instr = strtok(NULL, " "); int opcode = findit(instr, offset); emit_byte(opcode); char *operand = strtok(NULL, " "); switch (opcode) { case JMP: case JZ: operand++; len = strlen(operand); operand[len - 1] = '\0'; emit_int(atoi(operand)); break; case PUSH: emit_int(atoi(operand)); break; case FETCH: case STORE: operand++; len = strlen(operand); operand[len - 1] = '\0'; emit_int(atoi(operand)); break; } } return string_pool; } void init_io(FILE **fp, FILE *std, const char mode[], const char fn[]) { if (fn[0] == '\0') *fp = std; else if ((*fp = fopen(fn, mode)) == NULL) error(0, 0, "Can't open %s\n", fn); } int main(int argc, char *argv[]) { init_io(&source_fp, stdin, "r", argc > 1 ? argv[1] : ""); int data_size; char **string_pool = load_code(&data_size); int data[1000 + data_size]; run_vm(object, data, data_size, string_pool); }
def run_vm(data_size) int stack[data_size + 1000] set stack[0..data_size - 1] to 0 int pc = 0 while True: op = code[pc] pc += 1 if op == FETCH: stack.append(stack[bytes_to_int(code[pc:pc+word_size])[0]]); pc += word_size elif op == STORE: stack[bytes_to_int(code[pc:pc+word_size])[0]] = stack.pop(); pc += word_size elif op == PUSH: stack.append(bytes_to_int(code[pc:pc+word_size])[0]); pc += word_size elif op == ADD: stack[-2] += stack[-1]; stack.pop() elif op == SUB: stack[-2] -= stack[-1]; stack.pop() elif op == MUL: stack[-2] *= stack[-1]; stack.pop() elif op == DIV: stack[-2] /= stack[-1]; stack.pop() elif op == MOD: stack[-2] %= stack[-1]; stack.pop() elif op == LT: stack[-2] = stack[-2] < stack[-1]; stack.pop() elif op == GT: stack[-2] = stack[-2] > stack[-1]; stack.pop() elif op == LE: stack[-2] = stack[-2] <= stack[-1]; stack.pop() elif op == GE: stack[-2] = stack[-2] >= stack[-1]; stack.pop() elif op == EQ: stack[-2] = stack[-2] == stack[-1]; stack.pop() elif op == NE: stack[-2] = stack[-2] != stack[-1]; stack.pop() elif op == AND: stack[-2] = stack[-2] and stack[-1]; stack.pop() elif op == OR: stack[-2] = stack[-2] or stack[-1]; stack.pop() elif op == NEG: stack[-1] = -stack[-1] elif op == NOT: stack[-1] = not stack[-1] elif op == JMP: pc += bytes_to_int(code[pc:pc+word_size])[0] elif op == JZ: if stack.pop() then pc += word_size else pc += bytes_to_int(code[pc:pc+word_size])[0] elif op == PRTC: print stack[-1] as a character; stack.pop() elif op == PRTS: print the constant string referred to by stack[-1]; stack.pop() elif op == PRTI: print stack[-1] as an integer; stack.pop() elif op == HALT: break
Rewrite this program in Python while keeping its functionality equivalent to the C version.
#include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <string.h> #include <stdint.h> #include <ctype.h> #define NELEMS(arr) (sizeof(arr) / sizeof(arr[0])) #define da_dim(name, type) type *name = NULL; \ int _qy_ ## name ## _p = 0; \ int _qy_ ## name ## _max = 0 #define da_redim(name) do {if (_qy_ ## name ## _p >= _qy_ ## name ## _max) \ name = realloc(name, (_qy_ ## name ## _max += 32) * sizeof(name[0]));} while (0) #define da_rewind(name) _qy_ ## name ## _p = 0 #define da_append(name, x) do {da_redim(name); name[_qy_ ## name ## _p++] = x;} while (0) typedef unsigned char uchar; typedef uchar code; typedef enum { FETCH, STORE, PUSH, ADD, SUB, MUL, DIV, MOD, LT, GT, LE, GE, EQ, NE, AND, OR, NEG, NOT, JMP, JZ, PRTC, PRTS, PRTI, HALT } Code_t; typedef struct Code_map { char *text; Code_t op; } Code_map; Code_map code_map[] = { {"fetch", FETCH}, {"store", STORE}, {"push", PUSH }, {"add", ADD }, {"sub", SUB }, {"mul", MUL }, {"div", DIV }, {"mod", MOD }, {"lt", LT }, {"gt", GT }, {"le", LE }, {"ge", GE }, {"eq", EQ }, {"ne", NE }, {"and", AND }, {"or", OR }, {"neg", NEG }, {"not", NOT }, {"jmp", JMP }, {"jz", JZ }, {"prtc", PRTC }, {"prts", PRTS }, {"prti", PRTI }, {"halt", HALT }, }; FILE *source_fp; da_dim(object, code); void error(const char *fmt, ... ) { va_list ap; char buf[1000]; va_start(ap, fmt); vsprintf(buf, fmt, ap); va_end(ap); printf("error: %s\n", buf); exit(1); } void run_vm(const code obj[], int32_t data[], int g_size, char **string_pool) { int32_t *sp = &data[g_size + 1]; const code *pc = obj; again: switch (*pc++) { case FETCH: *sp++ = data[*(int32_t *)pc]; pc += sizeof(int32_t); goto again; case STORE: data[*(int32_t *)pc] = *--sp; pc += sizeof(int32_t); goto again; case PUSH: *sp++ = *(int32_t *)pc; pc += sizeof(int32_t); goto again; case ADD: sp[-2] += sp[-1]; --sp; goto again; case SUB: sp[-2] -= sp[-1]; --sp; goto again; case MUL: sp[-2] *= sp[-1]; --sp; goto again; case DIV: sp[-2] /= sp[-1]; --sp; goto again; case MOD: sp[-2] %= sp[-1]; --sp; goto again; case LT: sp[-2] = sp[-2] < sp[-1]; --sp; goto again; case GT: sp[-2] = sp[-2] > sp[-1]; --sp; goto again; case LE: sp[-2] = sp[-2] <= sp[-1]; --sp; goto again; case GE: sp[-2] = sp[-2] >= sp[-1]; --sp; goto again; case EQ: sp[-2] = sp[-2] == sp[-1]; --sp; goto again; case NE: sp[-2] = sp[-2] != sp[-1]; --sp; goto again; case AND: sp[-2] = sp[-2] && sp[-1]; --sp; goto again; case OR: sp[-2] = sp[-2] || sp[-1]; --sp; goto again; case NEG: sp[-1] = -sp[-1]; goto again; case NOT: sp[-1] = !sp[-1]; goto again; case JMP: pc += *(int32_t *)pc; goto again; case JZ: pc += (*--sp == 0) ? *(int32_t *)pc : (int32_t)sizeof(int32_t); goto again; case PRTC: printf("%c", sp[-1]); --sp; goto again; case PRTS: printf("%s", string_pool[sp[-1]]); --sp; goto again; case PRTI: printf("%d", sp[-1]); --sp; goto again; case HALT: break; default: error("Unknown opcode %d\n", *(pc - 1)); } } char *read_line(int *len) { static char *text = NULL; static int textmax = 0; for (*len = 0; ; (*len)++) { int ch = fgetc(source_fp); if (ch == EOF || ch == '\n') { if (*len == 0) return NULL; break; } if (*len + 1 >= textmax) { textmax = (textmax == 0 ? 128 : textmax * 2); text = realloc(text, textmax); } text[*len] = ch; } text[*len] = '\0'; return text; } char *rtrim(char *text, int *len) { for (; *len > 0 && isspace(text[*len - 1]); --(*len)) ; text[*len] = '\0'; return text; } char *translate(char *st) { char *p, *q; if (st[0] == '"') ++st; p = q = st; while ((*p++ = *q++) != '\0') { if (q[-1] == '\\') { if (q[0] == 'n') { p[-1] = '\n'; ++q; } else if (q[0] == '\\') { ++q; } } if (q[0] == '"' && q[1] == '\0') ++q; } return st; } int findit(const char text[], int offset) { for (size_t i = 0; i < sizeof(code_map) / sizeof(code_map[0]); i++) { if (strcmp(code_map[i].text, text) == 0) return code_map[i].op; } error("Unknown instruction %s at %d\n", text, offset); return -1; } void emit_byte(int c) { da_append(object, (uchar)c); } void emit_int(int32_t n) { union { int32_t n; unsigned char c[sizeof(int32_t)]; } x; x.n = n; for (size_t i = 0; i < sizeof(x.n); ++i) { emit_byte(x.c[i]); } } char **load_code(int *ds) { int line_len, n_strings; char **string_pool; char *text = read_line(&line_len); text = rtrim(text, &line_len); strtok(text, " "); *ds = atoi(strtok(NULL, " ")); strtok(NULL, " "); n_strings = atoi(strtok(NULL, " ")); string_pool = malloc(n_strings * sizeof(char *)); for (int i = 0; i < n_strings; ++i) { text = read_line(&line_len); text = rtrim(text, &line_len); text = translate(text); string_pool[i] = strdup(text); } for (;;) { int len; text = read_line(&line_len); if (text == NULL) break; text = rtrim(text, &line_len); int offset = atoi(strtok(text, " ")); char *instr = strtok(NULL, " "); int opcode = findit(instr, offset); emit_byte(opcode); char *operand = strtok(NULL, " "); switch (opcode) { case JMP: case JZ: operand++; len = strlen(operand); operand[len - 1] = '\0'; emit_int(atoi(operand)); break; case PUSH: emit_int(atoi(operand)); break; case FETCH: case STORE: operand++; len = strlen(operand); operand[len - 1] = '\0'; emit_int(atoi(operand)); break; } } return string_pool; } void init_io(FILE **fp, FILE *std, const char mode[], const char fn[]) { if (fn[0] == '\0') *fp = std; else if ((*fp = fopen(fn, mode)) == NULL) error(0, 0, "Can't open %s\n", fn); } int main(int argc, char *argv[]) { init_io(&source_fp, stdin, "r", argc > 1 ? argv[1] : ""); int data_size; char **string_pool = load_code(&data_size); int data[1000 + data_size]; run_vm(object, data, data_size, string_pool); }
def run_vm(data_size) int stack[data_size + 1000] set stack[0..data_size - 1] to 0 int pc = 0 while True: op = code[pc] pc += 1 if op == FETCH: stack.append(stack[bytes_to_int(code[pc:pc+word_size])[0]]); pc += word_size elif op == STORE: stack[bytes_to_int(code[pc:pc+word_size])[0]] = stack.pop(); pc += word_size elif op == PUSH: stack.append(bytes_to_int(code[pc:pc+word_size])[0]); pc += word_size elif op == ADD: stack[-2] += stack[-1]; stack.pop() elif op == SUB: stack[-2] -= stack[-1]; stack.pop() elif op == MUL: stack[-2] *= stack[-1]; stack.pop() elif op == DIV: stack[-2] /= stack[-1]; stack.pop() elif op == MOD: stack[-2] %= stack[-1]; stack.pop() elif op == LT: stack[-2] = stack[-2] < stack[-1]; stack.pop() elif op == GT: stack[-2] = stack[-2] > stack[-1]; stack.pop() elif op == LE: stack[-2] = stack[-2] <= stack[-1]; stack.pop() elif op == GE: stack[-2] = stack[-2] >= stack[-1]; stack.pop() elif op == EQ: stack[-2] = stack[-2] == stack[-1]; stack.pop() elif op == NE: stack[-2] = stack[-2] != stack[-1]; stack.pop() elif op == AND: stack[-2] = stack[-2] and stack[-1]; stack.pop() elif op == OR: stack[-2] = stack[-2] or stack[-1]; stack.pop() elif op == NEG: stack[-1] = -stack[-1] elif op == NOT: stack[-1] = not stack[-1] elif op == JMP: pc += bytes_to_int(code[pc:pc+word_size])[0] elif op == JZ: if stack.pop() then pc += word_size else pc += bytes_to_int(code[pc:pc+word_size])[0] elif op == PRTC: print stack[-1] as a character; stack.pop() elif op == PRTS: print the constant string referred to by stack[-1]; stack.pop() elif op == PRTI: print stack[-1] as an integer; stack.pop() elif op == HALT: break
Write the same code in Python as shown below in C.
#include <stdio.h> #define ELEMENTS 10000000U void make_klarner_rado(unsigned int *dst, unsigned int n) { unsigned int i, i2 = 0, i3 = 0; unsigned int m, m2 = 1, m3 = 1; for (i = 0; i < n; ++i) { dst[i] = m = m2 < m3 ? m2 : m3; if (m2 == m) m2 = dst[i2++] << 1 | 1; if (m3 == m) m3 = dst[i3++] * 3 + 1; } } int main(void) { static unsigned int klarner_rado[ELEMENTS]; unsigned int i; make_klarner_rado(klarner_rado, ELEMENTS); for (i = 0; i < 99; ++i) printf("%u ", klarner_rado[i]); for (i = 100; i <= ELEMENTS; i *= 10) printf("%u\n", klarner_rado[i - 1]); return 0; }
def KlarnerRado(N): K = [1] for i in range(N): j = K[i] firstadd, secondadd = 2 * j + 1, 3 * j + 1 if firstadd < K[-1]: for pos in range(len(K)-1, 1, -1): if K[pos] < firstadd < K[pos + 1]: K.insert(pos + 1, firstadd) break elif firstadd > K[-1]: K.append(firstadd) if secondadd < K[-1]: for pos in range(len(K)-1, 1, -1): if K[pos] < secondadd < K[pos + 1]: K.insert(pos + 1, secondadd) break elif secondadd > K[-1]: K.append(secondadd) return K kr1m = KlarnerRado(100_000) print('First 100 Klarner-Rado sequence numbers:') for idx, v in enumerate(kr1m[:100]): print(f'{v: 4}', end='\n' if (idx + 1) % 20 == 0 else '') for n in [1000, 10_000, 100_000]: print(f'The {n :,}th Klarner-Rado number is {kr1m[n-1] :,}')
Keep all operations the same but rewrite the snippet in Python.
#include <stdio.h> #define ELEMENTS 10000000U void make_klarner_rado(unsigned int *dst, unsigned int n) { unsigned int i, i2 = 0, i3 = 0; unsigned int m, m2 = 1, m3 = 1; for (i = 0; i < n; ++i) { dst[i] = m = m2 < m3 ? m2 : m3; if (m2 == m) m2 = dst[i2++] << 1 | 1; if (m3 == m) m3 = dst[i3++] * 3 + 1; } } int main(void) { static unsigned int klarner_rado[ELEMENTS]; unsigned int i; make_klarner_rado(klarner_rado, ELEMENTS); for (i = 0; i < 99; ++i) printf("%u ", klarner_rado[i]); for (i = 100; i <= ELEMENTS; i *= 10) printf("%u\n", klarner_rado[i - 1]); return 0; }
def KlarnerRado(N): K = [1] for i in range(N): j = K[i] firstadd, secondadd = 2 * j + 1, 3 * j + 1 if firstadd < K[-1]: for pos in range(len(K)-1, 1, -1): if K[pos] < firstadd < K[pos + 1]: K.insert(pos + 1, firstadd) break elif firstadd > K[-1]: K.append(firstadd) if secondadd < K[-1]: for pos in range(len(K)-1, 1, -1): if K[pos] < secondadd < K[pos + 1]: K.insert(pos + 1, secondadd) break elif secondadd > K[-1]: K.append(secondadd) return K kr1m = KlarnerRado(100_000) print('First 100 Klarner-Rado sequence numbers:') for idx, v in enumerate(kr1m[:100]): print(f'{v: 4}', end='\n' if (idx + 1) % 20 == 0 else '') for n in [1000, 10_000, 100_000]: print(f'The {n :,}th Klarner-Rado number is {kr1m[n-1] :,}')
Change the following C code into Python without altering its purpose.
void cubic_bezier( image img, unsigned int x1, unsigned int y1, unsigned int x2, unsigned int y2, unsigned int x3, unsigned int y3, unsigned int x4, unsigned int y4, color_component r, color_component g, color_component b );
def cubicbezier(self, x0, y0, x1, y1, x2, y2, x3, y3, n=20): pts = [] for i in range(n+1): t = i / n a = (1. - t)**3 b = 3. * t * (1. - t)**2 c = 3.0 * t**2 * (1.0 - t) d = t**3 x = int(a * x0 + b * x1 + c * x2 + d * x3) y = int(a * y0 + b * y1 + c * y2 + d * y3) pts.append( (x, y) ) for i in range(n): self.line(pts[i][0], pts[i][1], pts[i+1][0], pts[i+1][1]) Bitmap.cubicbezier = cubicbezier bitmap = Bitmap(17,17) bitmap.cubicbezier(16,1, 1,4, 3,16, 15,11) bitmap.chardisplay()
Convert this C snippet to Python and keep its semantics consistent.
int pancake_sort(int *list, unsigned int length) { if(length<2) return 0; int i,a,max_num_pos,moves; moves=0; for(i=length;i>1;i--) { max_num_pos=0; for(a=0;a<i;a++) { if(list[a]>list[max_num_pos]) max_num_pos=a; } if(max_num_pos==i-1) continue; if(max_num_pos) { moves++; do_flip(list, length, max_num_pos+1); } moves++; do_flip(list, length, i); } return moves; }
tutor = False def pancakesort(data): if len(data) <= 1: return data if tutor: print() for size in range(len(data), 1, -1): maxindex = max(range(size), key=data.__getitem__) if maxindex+1 != size: if maxindex != 0: if tutor: print('With: %r doflip %i' % ( ' '.join(str(x) for x in data), maxindex+1 )) data[:maxindex+1] = reversed(data[:maxindex+1]) if tutor: print('With: %r doflip %i' % ( ' '.join(str(x) for x in data), size )) data[:size] = reversed(data[:size]) if tutor: print()
Rewrite this program in Python while keeping its functionality equivalent to the C version.
#include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <time.h> #define DIGITS 1000 #define NUMSIZE 5 uint8_t randomDigit() { uint8_t d; do {d = rand() & 0xF;} while (d >= 10); return d; } int numberAt(uint8_t *d, int size) { int acc = 0; while (size--) acc = 10*acc + *d++; return acc; } int main() { uint8_t digits[DIGITS]; int i, largest = 0; srand(time(NULL)); for (i=0; i<DIGITS; i++) digits[i] = randomDigit(); for (i=0; i<DIGITS-NUMSIZE; i++) { int here = numberAt(&digits[i], NUMSIZE); if (here > largest) largest = here; } printf("%d\n", largest); return 0; }
from random import seed,randint from datetime import datetime seed(str(datetime.now())) largeNum = [randint(1,9)] for i in range(1,1000): largeNum.append(randint(0,9)) maxNum,minNum = 0,99999 for i in range(0,994): num = int("".join(map(str,largeNum[i:i+5]))) if num > maxNum: maxNum = num elif num < minNum: minNum = num print("Largest 5-adjacent number found ", maxNum) print("Smallest 5-adjacent number found ", minNum)
Translate the given C code snippet into Python without altering its behavior.
#include <stdio.h> #include <stdbool.h> int digit_sum(int n) { int sum; for (sum = 0; n; n /= 10) sum += n % 10; return sum; } bool prime(int n) { if (n<4) return n>=2; for (int d=2; d*d <= n; d++) if (n%d == 0) return false; return true; } int main() { for (int i=1; i<100; i++) if (prime(digit_sum(i*i)) & prime(digit_sum(i*i*i))) printf("%d ", i); printf("\n"); return 0; }
def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True def digSum(n, b): s = 0 while n: s += (n % b) n = n // b return s if __name__ == '__main__': for n in range(11, 99): if isPrime(digSum(n**3, 10)) and isPrime(digSum(n**2, 10)): print(n, end = " ")
Write a version of this C function in Python with identical behavior.
#include <stdio.h> #include <stdlib.h> #include <math.h> int main(void) { int nprimes = 1000000; int nmax = ceil(nprimes*(log(nprimes)+log(log(nprimes))-0.9385)); int i, j, m, k; int *a; k = (nmax-2)/2; a = (int *)calloc(k + 1, sizeof(int)); for(i = 0; i <= k; i++)a[i] = 2*i+1; for (i = 1; (i+1)*i*2 <= k; i++) for (j = i; j <= (k-i)/(2*i+1); j++) { m = i + j + 2*i*j; if(a[m]) a[m] = 0; } for (i = 1, j = 0; i <= k; i++) if (a[i]) { if(j%10 == 0 && j <= 100)printf("\n"); j++; if(j <= 100)printf("%3d ", a[i]); else if(j == nprimes){ printf("\n%d th prime is %d\n",j,a[i]); break; } } }
from numpy import log def sieve_of_Sundaram(nth, print_all=True): assert nth > 0, "nth must be a positive integer" k = int((2.4 * nth * log(nth)) // 2) integers_list = [True] * k for i in range(1, k): j = i while i + j + 2 * i * j < k: integers_list[i + j + 2 * i * j] = False j += 1 pcount = 0 for i in range(1, k + 1): if integers_list[i]: pcount += 1 if print_all: print(f"{2 * i + 1:4}", end=' ') if pcount % 10 == 0: print() if pcount == nth: print(f"\nSundaram primes start with 3. The {nth}th Sundaram prime is {2 * i + 1}.\n") break sieve_of_Sundaram(100, True) sieve_of_Sundaram(1000000, False)
Preserve the algorithm and functionality while converting the code from C to Python.
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef char *string; typedef struct node_t { string symbol; double weight; struct node_t *next; } node; node *make_node(string symbol, double weight) { node *nptr = malloc(sizeof(node)); if (nptr) { nptr->symbol = symbol; nptr->weight = weight; nptr->next = NULL; return nptr; } return NULL; } void free_node(node *ptr) { if (ptr) { free_node(ptr->next); ptr->next = NULL; free(ptr); } } node *insert(string symbol, double weight, node *head) { node *nptr = make_node(symbol, weight); nptr->next = head; return nptr; } node *dic; void init() { dic = make_node("H", 1.008); dic = insert("He", 4.002602, dic); dic = insert("Li", 6.94, dic); dic = insert("Be", 9.0121831, dic); dic = insert("B", 10.81, dic); dic = insert("C", 12.011, dic); dic = insert("N", 14.007, dic); dic = insert("O", 15.999, dic); dic = insert("F", 18.998403163, dic); dic = insert("Ne", 20.1797, dic); dic = insert("Na", 22.98976928, dic); dic = insert("Mg", 24.305, dic); dic = insert("Al", 26.9815385, dic); dic = insert("Si", 28.085, dic); dic = insert("P", 30.973761998, dic); dic = insert("S", 32.06, dic); dic = insert("Cl", 35.45, dic); dic = insert("Ar", 39.948, dic); dic = insert("K", 39.0983, dic); dic = insert("Ca", 40.078, dic); dic = insert("Sc", 44.955908, dic); dic = insert("Ti", 47.867, dic); dic = insert("V", 50.9415, dic); dic = insert("Cr", 51.9961, dic); dic = insert("Mn", 54.938044, dic); dic = insert("Fe", 55.845, dic); dic = insert("Co", 58.933194, dic); dic = insert("Ni", 58.6934, dic); dic = insert("Cu", 63.546, dic); dic = insert("Zn", 65.38, dic); dic = insert("Ga", 69.723, dic); dic = insert("Ge", 72.630, dic); dic = insert("As", 74.921595, dic); dic = insert("Se", 78.971, dic); dic = insert("Br", 79.904, dic); dic = insert("Kr", 83.798, dic); dic = insert("Rb", 85.4678, dic); dic = insert("Sr", 87.62, dic); dic = insert("Y", 88.90584, dic); dic = insert("Zr", 91.224, dic); dic = insert("Nb", 92.90637, dic); dic = insert("Mo", 95.95, dic); dic = insert("Ru", 101.07, dic); dic = insert("Rh", 102.90550, dic); dic = insert("Pd", 106.42, dic); dic = insert("Ag", 107.8682, dic); dic = insert("Cd", 112.414, dic); dic = insert("In", 114.818, dic); dic = insert("Sn", 118.710, dic); dic = insert("Sb", 121.760, dic); dic = insert("Te", 127.60, dic); dic = insert("I", 126.90447, dic); dic = insert("Xe", 131.293, dic); dic = insert("Cs", 132.90545196, dic); dic = insert("Ba", 137.327, dic); dic = insert("La", 138.90547, dic); dic = insert("Ce", 140.116, dic); dic = insert("Pr", 140.90766, dic); dic = insert("Nd", 144.242, dic); dic = insert("Pm", 145, dic); dic = insert("Sm", 150.36, dic); dic = insert("Eu", 151.964, dic); dic = insert("Gd", 157.25, dic); dic = insert("Tb", 158.92535, dic); dic = insert("Dy", 162.500, dic); dic = insert("Ho", 164.93033, dic); dic = insert("Er", 167.259, dic); dic = insert("Tm", 168.93422, dic); dic = insert("Yb", 173.054, dic); dic = insert("Lu", 174.9668, dic); dic = insert("Hf", 178.49, dic); dic = insert("Ta", 180.94788, dic); dic = insert("W", 183.84, dic); dic = insert("Re", 186.207, dic); dic = insert("Os", 190.23, dic); dic = insert("Ir", 192.217, dic); dic = insert("Pt", 195.084, dic); dic = insert("Au", 196.966569, dic); dic = insert("Hg", 200.592, dic); dic = insert("Tl", 204.38, dic); dic = insert("Pb", 207.2, dic); dic = insert("Bi", 208.98040, dic); dic = insert("Po", 209, dic); dic = insert("At", 210, dic); dic = insert("Rn", 222, dic); dic = insert("Fr", 223, dic); dic = insert("Ra", 226, dic); dic = insert("Ac", 227, dic); dic = insert("Th", 232.0377, dic); dic = insert("Pa", 231.03588, dic); dic = insert("U", 238.02891, dic); dic = insert("Np", 237, dic); dic = insert("Pu", 244, dic); dic = insert("Am", 243, dic); dic = insert("Cm", 247, dic); dic = insert("Bk", 247, dic); dic = insert("Cf", 251, dic); dic = insert("Es", 252, dic); dic = insert("Fm", 257, dic); dic = insert("Uue", 315, dic); dic = insert("Ubn", 299, dic); } double lookup(string symbol) { for (node *ptr = dic; ptr; ptr = ptr->next) { if (strcmp(symbol, ptr->symbol) == 0) { return ptr->weight; } } printf("symbol not found: %s\n", symbol); return 0.0; } double total(double mass, int count) { if (count > 0) { return mass * count; } return mass; } double total_s(string sym, int count) { double mass = lookup(sym); return total(mass, count); } double evaluate_c(string expr, size_t *pos, double mass) { int count = 0; if (expr[*pos] < '0' || '9' < expr[*pos]) { printf("expected to find a count, saw the character: %c\n", expr[*pos]); } for (; expr[*pos]; (*pos)++) { char c = expr[*pos]; if ('0' <= c && c <= '9') { count = count * 10 + c - '0'; } else { break; } } return total(mass, count); } double evaluate_p(string expr, size_t limit, size_t *pos) { char sym[4]; int sym_pos = 0; int count = 0; double sum = 0.0; for (; *pos < limit && expr[*pos]; (*pos)++) { char c = expr[*pos]; if ('A' <= c && c <= 'Z') { if (sym_pos > 0) { sum += total_s(sym, count); sym_pos = 0; count = 0; } sym[sym_pos++] = c; sym[sym_pos] = 0; } else if ('a' <= c && c <= 'z') { sym[sym_pos++] = c; sym[sym_pos] = 0; } else if ('0' <= c && c <= '9') { count = count * 10 + c - '0'; } else if (c == '(') { if (sym_pos > 0) { sum += total_s(sym, count); sym_pos = 0; count = 0; } (*pos)++; double mass = evaluate_p(expr, limit, pos); sum += evaluate_c(expr, pos, mass); (*pos)--; } else if (c == ')') { if (sym_pos > 0) { sum += total_s(sym, count); sym_pos = 0; count = 0; } (*pos)++; return sum; } else { printf("Unexpected character encountered: %c\n", c); } } if (sym_pos > 0) { sum += total_s(sym, count); } return sum; } double evaluate(string expr) { size_t limit = strlen(expr); size_t pos = 0; return evaluate_p(expr, limit, &pos); } void test(string expr) { double mass = evaluate(expr); printf("%17s -> %7.3f\n", expr, mass); } int main() { init(); test("H"); test("H2"); test("H2O"); test("H2O2"); test("(HO)2"); test("Na2SO4"); test("C6H12"); test("COOH(C(CH3)2)3CH3"); test("C6H4O2(OH)4"); test("C27H46O"); test("Uue"); free_node(dic); dic = NULL; return 0; }
assert 1.008 == molar_mass('H') assert 2.016 == molar_mass('H2') assert 18.015 == molar_mass('H2O') assert 34.014 == molar_mass('H2O2') assert 34.014 == molar_mass('(HO)2') assert 142.036 == molar_mass('Na2SO4') assert 84.162 == molar_mass('C6H12') assert 186.295 == molar_mass('COOH(C(CH3)2)3CH3') assert 176.124 == molar_mass('C6H4O2(OH)4') assert 386.664 == molar_mass('C27H46O') assert 315 == molar_mass('Uue')
Rewrite the snippet below in Python so it works the same as the original C code.
#include <ldap.h> ... char *name, *password; ... LDAP *ld = ldap_init("ldap.somewhere.com", 389); ldap_simple_bind_s(ld, name, password); ... after done with it... ldap_unbind(ld);
import ldap l = ldap.initialize("ldap://ldap.example.com") try: l.protocol_version = ldap.VERSION3 l.set_option(ldap.OPT_REFERRALS, 0) bind = l.simple_bind_s("me@example.com", "password") finally: l.unbind()