Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Preserve the algorithm and functionality while converting the code from C# to Go. | using System;
using System.Reflection;
public class Rosetta
{
public static void Main()
{
BindingFlags flags = BindingFlags.Instance | BindingFlags.Static
| BindingFlags.Public | BindingFlags.NonPublic
| BindingFlags.DeclaredOnly;
foreach (var method in typeof(TestForMethodReflection).GetMethods(flags))
Console.WriteLine(method);
}
class TestForMethodReflection
{
public void MyPublicMethod() {}
private void MyPrivateMethod() {}
public static void MyPublicStaticMethod() {}
private static void MyPrivateStaticMethod() {}
}
}
| package main
import (
"fmt"
"image"
"reflect"
)
type t int
func (r t) Twice() t { return r * 2 }
func (r t) Half() t { return r / 2 }
func (r t) Less(r2 t) bool { return r < r2 }
func (r t) privateMethod() {}
func main() {
report(t(0))
report(image.Point{})
}
func report(x interface{}) {
v := reflect.ValueOf(x)
t := reflect.TypeOf(x)
n := t.NumMethod()
fmt.Printf("Type %v has %d exported methods:\n", t, n)
const format = "%-6s %-46s %s\n"
fmt.Printf(format, "Name", "Method expression", "Method value")
for i := 0; i < n; i++ {
fmt.Printf(format,
t.Method(i).Name,
t.Method(i).Func.Type(),
v.Method(i).Type(),
)
}
fmt.Println()
}
|
Change the following C# code into Go without altering its purpose. | using System;
class Example
{
public int foo(int x)
{
return 42 + x;
}
}
class Program
{
static void Main(string[] args)
{
var example = new Example();
var method = "foo";
var result = (int)example.GetType().GetMethod(method).Invoke(example, new object[]{ 5 });
Console.WriteLine("{0}(5) = {1}", method, result);
}
}
| package main
import (
"fmt"
"reflect"
)
type example struct{}
func (example) Foo() int {
return 42
}
func main() {
var e example
m := reflect.ValueOf(e).MethodByName("Foo")
r := m.Call(nil)
fmt.Println(r[0].Int())
}
|
Generate an equivalent Go version of this C# code. | using System;
using System.Collections.Generic;
using System.Linq;
public static class TwelveStatements
{
public static void Main() {
Func<Statements, bool>[] checks = {
st => st[1],
st => st[2] == (7.To(12).Count(i => st[i]) == 3),
st => st[3] == (2.To(12, by: 2).Count(i => st[i]) == 2),
st => st[4] == st[5].Implies(st[6] && st[7]),
st => st[5] == (!st[2] && !st[3] && !st[4]),
st => st[6] == (1.To(12, by: 2).Count(i => st[i]) == 4),
st => st[7] == (st[2] != st[3]),
st => st[8] == st[7].Implies(st[5] && st[6]),
st => st[9] == (1.To(6).Count(i => st[i]) == 3),
st => st[10] == (st[11] && st[12]),
st => st[11] == (7.To(9).Count(i => st[i]) == 1),
st => st[12] == (1.To(11).Count(i => st[i]) == 4)
};
for (Statements statements = new Statements(0); statements.Value < 4096; statements++) {
int count = 0;
int falseIndex = 0;
for (int i = 0; i < checks.Length; i++) {
if (checks[i](statements)) count++;
else falseIndex = i;
}
if (count == 0) Console.WriteLine($"{"All wrong:", -13}{statements}");
else if (count == 11) Console.WriteLine($"{$"Wrong at {falseIndex + 1}:", -13}{statements}");
else if (count == 12) Console.WriteLine($"{"All correct:", -13}{statements}");
}
}
struct Statements
{
public Statements(int value) : this() { Value = value; }
public int Value { get; }
public bool this[int index] => (Value & (1 << index - 1)) != 0;
public static Statements operator ++(Statements statements) => new Statements(statements.Value + 1);
public override string ToString() {
Statements copy = this;
return string.Join(" ", from i in 1.To(12) select copy[i] ? "T" : "F");
}
}
static bool Implies(this bool x, bool y) => !x || y;
static IEnumerable<int> To(this int start, int end, int by = 1) {
while (start <= end) {
yield return start;
start += by;
}
}
}
| package main
import "fmt"
var solution = make(chan int)
var nearMiss = make(chan int)
var done = make(chan bool)
func main() {
for i := 0; i < 4096; i++ {
go checkPerm(i)
}
var ms []int
for i := 0; i < 4096; {
select {
case <-done:
i++
case s := <-solution:
print12("solution", s)
case m := <-nearMiss:
ms = append(ms, m)
}
}
for _, m := range ms {
print12("near miss", m)
}
}
func print12(label string, bits int) {
fmt.Print(label, ":")
for i := 1; i <= 12; i++ {
if bits&1 == 1 {
fmt.Print(" ", i)
}
bits >>= 1
}
fmt.Println()
}
func checkPerm(tz int) {
ts := func(n uint) bool {
return tz>>(n-1)&1 == 1
}
ntrue := func(xs ...uint) int {
nt := 0
for _, x := range xs {
if ts(x) {
nt++
}
}
return nt
}
var con bool
test := func(statement uint, b bool) {
switch {
case ts(statement) == b:
case con:
panic("bail")
default:
con = true
}
}
defer func() {
if x := recover(); x != nil {
if msg, ok := x.(string); !ok && msg != "bail" {
panic(x)
}
}
done <- true
}()
test(1, true)
test(2, ntrue(7, 8, 9, 10, 11, 12) == 3)
test(3, ntrue(2, 4, 6, 8, 10, 12) == 2)
test(4, !ts(5) || ts(6) && ts(7))
test(5, !ts(4) && !ts(3) && !ts(2))
test(6, ntrue(1, 3, 5, 7, 9, 11) == 4)
test(7, ts(2) != ts(3))
test(8, !ts(7) || ts(5) && ts(6))
test(9, ntrue(1, 2, 3, 4, 5, 6) == 3)
test(10, ts(11) && ts(12))
test(11, ntrue(7, 8, 9) == 1)
test(12, ntrue(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11) == 4)
if con {
nearMiss <- tz
} else {
solution <- tz
}
}
|
Translate this program into Go but keep the logic exactly as in C#. | using System;
using System.Collections.Generic;
using System.Linq;
public static class TwelveStatements
{
public static void Main() {
Func<Statements, bool>[] checks = {
st => st[1],
st => st[2] == (7.To(12).Count(i => st[i]) == 3),
st => st[3] == (2.To(12, by: 2).Count(i => st[i]) == 2),
st => st[4] == st[5].Implies(st[6] && st[7]),
st => st[5] == (!st[2] && !st[3] && !st[4]),
st => st[6] == (1.To(12, by: 2).Count(i => st[i]) == 4),
st => st[7] == (st[2] != st[3]),
st => st[8] == st[7].Implies(st[5] && st[6]),
st => st[9] == (1.To(6).Count(i => st[i]) == 3),
st => st[10] == (st[11] && st[12]),
st => st[11] == (7.To(9).Count(i => st[i]) == 1),
st => st[12] == (1.To(11).Count(i => st[i]) == 4)
};
for (Statements statements = new Statements(0); statements.Value < 4096; statements++) {
int count = 0;
int falseIndex = 0;
for (int i = 0; i < checks.Length; i++) {
if (checks[i](statements)) count++;
else falseIndex = i;
}
if (count == 0) Console.WriteLine($"{"All wrong:", -13}{statements}");
else if (count == 11) Console.WriteLine($"{$"Wrong at {falseIndex + 1}:", -13}{statements}");
else if (count == 12) Console.WriteLine($"{"All correct:", -13}{statements}");
}
}
struct Statements
{
public Statements(int value) : this() { Value = value; }
public int Value { get; }
public bool this[int index] => (Value & (1 << index - 1)) != 0;
public static Statements operator ++(Statements statements) => new Statements(statements.Value + 1);
public override string ToString() {
Statements copy = this;
return string.Join(" ", from i in 1.To(12) select copy[i] ? "T" : "F");
}
}
static bool Implies(this bool x, bool y) => !x || y;
static IEnumerable<int> To(this int start, int end, int by = 1) {
while (start <= end) {
yield return start;
start += by;
}
}
}
| package main
import "fmt"
var solution = make(chan int)
var nearMiss = make(chan int)
var done = make(chan bool)
func main() {
for i := 0; i < 4096; i++ {
go checkPerm(i)
}
var ms []int
for i := 0; i < 4096; {
select {
case <-done:
i++
case s := <-solution:
print12("solution", s)
case m := <-nearMiss:
ms = append(ms, m)
}
}
for _, m := range ms {
print12("near miss", m)
}
}
func print12(label string, bits int) {
fmt.Print(label, ":")
for i := 1; i <= 12; i++ {
if bits&1 == 1 {
fmt.Print(" ", i)
}
bits >>= 1
}
fmt.Println()
}
func checkPerm(tz int) {
ts := func(n uint) bool {
return tz>>(n-1)&1 == 1
}
ntrue := func(xs ...uint) int {
nt := 0
for _, x := range xs {
if ts(x) {
nt++
}
}
return nt
}
var con bool
test := func(statement uint, b bool) {
switch {
case ts(statement) == b:
case con:
panic("bail")
default:
con = true
}
}
defer func() {
if x := recover(); x != nil {
if msg, ok := x.(string); !ok && msg != "bail" {
panic(x)
}
}
done <- true
}()
test(1, true)
test(2, ntrue(7, 8, 9, 10, 11, 12) == 3)
test(3, ntrue(2, 4, 6, 8, 10, 12) == 2)
test(4, !ts(5) || ts(6) && ts(7))
test(5, !ts(4) && !ts(3) && !ts(2))
test(6, ntrue(1, 3, 5, 7, 9, 11) == 4)
test(7, ts(2) != ts(3))
test(8, !ts(7) || ts(5) && ts(6))
test(9, ntrue(1, 2, 3, 4, 5, 6) == 3)
test(10, ts(11) && ts(12))
test(11, ntrue(7, 8, 9) == 1)
test(12, ntrue(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11) == 4)
if con {
nearMiss <- tz
} else {
solution <- tz
}
}
|
Translate this program into Go but keep the logic exactly as in C#. |
using System;
using System.Dynamic;
namespace DynamicClassVariable
{
internal static class Program
{
#region Static Members
private static void Main()
{
dynamic sampleObj = new ExpandoObject();
sampleObj.bar = 1;
Console.WriteLine( "sampleObj.bar = {0}", sampleObj.bar );
Console.WriteLine( "< Press any key >" );
Console.ReadKey();
}
#endregion
}
}
| package main
import (
"bufio"
"fmt"
"log"
"os"
)
type SomeStruct struct {
runtimeFields map[string]string
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
ss := SomeStruct{make(map[string]string)}
scanner := bufio.NewScanner(os.Stdin)
fmt.Println("Create two fields at runtime: ")
for i := 1; i <= 2; i++ {
fmt.Printf(" Field #%d:\n", i)
fmt.Print(" Enter name : ")
scanner.Scan()
name := scanner.Text()
fmt.Print(" Enter value : ")
scanner.Scan()
value := scanner.Text()
check(scanner.Err())
ss.runtimeFields[name] = value
fmt.Println()
}
for {
fmt.Print("Which field do you want to inspect ? ")
scanner.Scan()
name := scanner.Text()
check(scanner.Err())
value, ok := ss.runtimeFields[name]
if !ok {
fmt.Println("There is no field of that name, try again")
} else {
fmt.Printf("Its value is '%s'\n", value)
return
}
}
}
|
Translate this program into Go but keep the logic exactly as in C#. | using System;
using System.Security.Cryptography;
namespace RosettaTOTP
{
public class TOTP_SHA1
{
private byte[] K;
public TOTP_SHA1()
{
GenerateKey();
}
public void GenerateKey()
{
using (RandomNumberGenerator rng = new RNGCryptoServiceProvider())
{
K = new byte[HMACSHA1.Create().HashSize / 8];
rng.GetBytes(K);
}
}
public int HOTP(UInt64 C, int digits = 6)
{
var hmac = HMACSHA1.Create();
hmac.Key = K;
hmac.ComputeHash(BitConverter.GetBytes(C));
return Truncate(hmac.Hash, digits);
}
public UInt64 CounterNow(int T1 = 30)
{
var secondsSinceEpoch = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds;
return (UInt64)Math.Floor(secondsSinceEpoch / T1);
}
private int DT(byte[] hmac_result)
{
int offset = hmac_result[19] & 0xf;
int bin_code = (hmac_result[offset] & 0x7f) << 24
| (hmac_result[offset + 1] & 0xff) << 16
| (hmac_result[offset + 2] & 0xff) << 8
| (hmac_result[offset + 3] & 0xff);
return bin_code;
}
private int Truncate(byte[] hmac_result, int digits)
{
var Snum = DT(hmac_result);
return Snum % (int)Math.Pow(10, digits);
}
}
class Program
{
static void Main(string[] args)
{
var totp = new TOTP_SHA1();
Console.WriteLine(totp.HOTP(totp.CounterNow()));
}
}
}
|
package onetime
import (
"crypto/hmac"
"crypto/sha1"
"encoding/binary"
"errors"
"hash"
"math"
"time"
)
type OneTimePassword struct {
Digit int
TimeStep time.Duration
BaseTime time.Time
Hash func() hash.Hash
}
func (otp *OneTimePassword) HOTP(secret []byte, count uint64) uint {
hs := otp.hmacSum(secret, count)
return otp.truncate(hs)
}
func (otp *OneTimePassword) hmacSum(secret []byte, count uint64) []byte {
mac := hmac.New(otp.Hash, secret)
binary.Write(mac, binary.BigEndian, count)
return mac.Sum(nil)
}
func (otp *OneTimePassword) truncate(hs []byte) uint {
sbits := dt(hs)
snum := uint(sbits[3]) | uint(sbits[2])<<8
snum |= uint(sbits[1])<<16 | uint(sbits[0])<<24
return snum % uint(math.Pow(10, float64(otp.Digit)))
}
func Simple(digit int) (otp OneTimePassword, err error) {
if digit < 6 {
err = errors.New("minimum of 6 digits is required for a valid HTOP code")
return
} else if digit > 9 {
err = errors.New("HTOP code cannot be longer than 9 digits")
return
}
const step = 30 * time.Second
otp = OneTimePassword{digit, step, time.Unix(0, 0), sha1.New}
return
}
func (otp *OneTimePassword) TOTP(secret []byte) uint {
return otp.HOTP(secret, otp.steps(time.Now()))
}
func (otp *OneTimePassword) steps(now time.Time) uint64 {
elapsed := now.Unix() - otp.BaseTime.Unix()
return uint64(float64(elapsed) / otp.TimeStep.Seconds())
}
func dt(hs []byte) []byte {
offset := int(hs[len(hs)-1] & 0xf)
p := hs[offset : offset+4]
p[0] &= 0x7f
return p
}
|
Generate a Python translation of this C snippet without changing its computational steps. | #include <stdio.h>
#include <stdlib.h>
typedef struct func_t *func;
typedef struct func_t {
func (*fn) (func, func);
func _;
int num;
} func_t;
func new(func(*f)(func, func), func _) {
func x = malloc(sizeof(func_t));
x->fn = f;
x->_ = _;
x->num = 0;
return x;
}
func call(func f, func n) {
return f->fn(f, n);
}
func Y(func(*f)(func, func)) {
func g = new(f, 0);
g->_ = g;
return g;
}
func num(int n) {
func x = new(0, 0);
x->num = n;
return x;
}
func fac(func self, func n) {
int nn = n->num;
return nn > 1 ? num(nn * call(self->_, num(nn - 1))->num)
: num(1);
}
func fib(func self, func n) {
int nn = n->num;
return nn > 1
? num( call(self->_, num(nn - 1))->num +
call(self->_, num(nn - 2))->num )
: num(1);
}
void show(func n) { printf(" %d", n->num); }
int main() {
int i;
func f = Y(fac);
printf("fac: ");
for (i = 1; i < 10; i++)
show( call(f, num(i)) );
printf("\n");
f = Y(fib);
printf("fib: ");
for (i = 1; i < 10; i++)
show( call(f, num(i)) );
printf("\n");
return 0;
}
| >>> Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args)))
>>> fac = lambda f: lambda n: (1 if n<2 else n*f(n-1))
>>> [ Y(fac)(i) for i in range(10) ]
[1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
>>> fib = lambda f: lambda n: 0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2))
>>> [ Y(fib)(i) for i in range(10) ]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
|
Write a version of this C function in Python with identical behavior. | #include<stdio.h>
typedef struct{
int integer;
float decimal;
char letter;
char string[100];
double bigDecimal;
}Composite;
Composite example()
{
Composite C = {1, 2.3, 'a', "Hello World", 45.678};
return C;
}
int main()
{
Composite C = example();
printf("Values from a function returning a structure : { %d, %f, %c, %s, %f}\n", C.integer, C.decimal, C.letter, C.string, C.bigDecimal);
return 0;
}
| def addsub(x, y):
return x + y, x - y
|
Convert this C snippet to Python and keep its semantics consistent. | #include <stdlib.h>
#include <stdio.h>
int main(int argc, const char *argv[]) {
const int max = 1000;
int *a = malloc(max * sizeof(int));
for (int n = 0; n < max - 1; n ++) {
for (int m = n - 1; m >= 0; m --) {
if (a[m] == a[n]) {
a[n+1] = n - m;
break;
}
}
}
printf("The first ten terms of the Van Eck sequence are:\n");
for (int i = 0; i < 10; i ++) printf("%d ", a[i]);
printf("\n\nTerms 991 to 1000 of the sequence are:\n");
for (int i = 990; i < 1000; i ++) printf("%d ", a[i]);
putchar('\n');
return 0;
}
| def van_eck():
n, seen, val = 0, {}, 0
while True:
yield val
last = {val: n}
val = n - seen.get(val, n)
seen.update(last)
n += 1
if __name__ == '__main__':
print("Van Eck: first 10 terms: ", list(islice(van_eck(), 10)))
print("Van Eck: terms 991 - 1000:", list(islice(van_eck(), 1000))[-10:])
|
Ensure the translated Python code behaves exactly like the original C snippet. | #include <stdlib.h>
#include <stdio.h>
int main(int argc, const char *argv[]) {
const int max = 1000;
int *a = malloc(max * sizeof(int));
for (int n = 0; n < max - 1; n ++) {
for (int m = n - 1; m >= 0; m --) {
if (a[m] == a[n]) {
a[n+1] = n - m;
break;
}
}
}
printf("The first ten terms of the Van Eck sequence are:\n");
for (int i = 0; i < 10; i ++) printf("%d ", a[i]);
printf("\n\nTerms 991 to 1000 of the sequence are:\n");
for (int i = 990; i < 1000; i ++) printf("%d ", a[i]);
putchar('\n');
return 0;
}
| def van_eck():
n, seen, val = 0, {}, 0
while True:
yield val
last = {val: n}
val = n - seen.get(val, n)
seen.update(last)
n += 1
if __name__ == '__main__':
print("Van Eck: first 10 terms: ", list(islice(van_eck(), 10)))
print("Van Eck: terms 991 - 1000:", list(islice(van_eck(), 1000))[-10:])
|
Convert this C snippet to Python and keep its semantics consistent. | #include <ftplib.h>
int main(void)
{
netbuf *nbuf;
FtpInit();
FtpConnect("kernel.org", &nbuf);
FtpLogin("anonymous", "", nbuf);
FtpOptions(FTPLIB_CONNMODE, FTPLIB_PASSIVE, nbuf);
FtpChdir("pub/linux/kernel", nbuf);
FtpDir((void*)0, ".", nbuf);
FtpGet("ftp.README", "README", FTPLIB_ASCII, nbuf);
FtpQuit(nbuf);
return 0;
}
| from ftplib import FTP
ftp = FTP('kernel.org')
ftp.login()
ftp.cwd('/pub/linux/kernel')
ftp.set_pasv(True)
print ftp.retrlines('LIST')
print ftp.retrbinary('RETR README', open('README', 'wb').write)
ftp.quit()
|
Maintain the same structure and functionality when rewriting this code in Python. | #include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <setjmp.h>
#include <time.h>
jmp_buf ctx;
const char *msg;
enum { OP_NONE = 0, OP_NUM, OP_ADD, OP_SUB, OP_MUL, OP_DIV };
typedef struct expr_t *expr, expr_t;
struct expr_t {
int op, val, used;
expr left, right;
};
#define N_DIGITS 4
expr_t digits[N_DIGITS];
void gen_digits()
{
int i;
for (i = 0; i < N_DIGITS; i++)
digits[i].val = 1 + rand() % 9;
}
#define MAX_INPUT 64
char str[MAX_INPUT];
int pos;
#define POOL_SIZE 8
expr_t pool[POOL_SIZE];
int pool_ptr;
void reset()
{
int i;
msg = 0;
pool_ptr = pos = 0;
for (i = 0; i < POOL_SIZE; i++) {
pool[i].op = OP_NONE;
pool[i].left = pool[i].right = 0;
}
for (i = 0; i < N_DIGITS; i++)
digits[i].used = 0;
}
void bail(const char *s)
{
msg = s;
longjmp(ctx, 1);
}
expr new_expr()
{
if (pool_ptr < POOL_SIZE)
return pool + pool_ptr++;
return 0;
}
int next_tok()
{
while (isspace(str[pos])) pos++;
return str[pos];
}
int take()
{
if (str[pos] != '\0') return ++pos;
return 0;
}
expr get_fact();
expr get_term();
expr get_expr();
expr get_expr()
{
int c;
expr l, r, ret;
if (!(ret = get_term())) bail("Expected term");
while ((c = next_tok()) == '+' || c == '-') {
if (!take()) bail("Unexpected end of input");
if (!(r = get_term())) bail("Expected term");
l = ret;
ret = new_expr();
ret->op = (c == '+') ? OP_ADD : OP_SUB;
ret->left = l;
ret->right = r;
}
return ret;
}
expr get_term()
{
int c;
expr l, r, ret;
ret = get_fact();
while((c = next_tok()) == '*' || c == '/') {
if (!take()) bail("Unexpected end of input");
r = get_fact();
l = ret;
ret = new_expr();
ret->op = (c == '*') ? OP_MUL : OP_DIV;
ret->left = l;
ret->right = r;
}
return ret;
}
expr get_digit()
{
int i, c = next_tok();
expr ret;
if (c >= '0' && c <= '9') {
take();
ret = new_expr();
ret->op = OP_NUM;
ret->val = c - '0';
for (i = 0; i < N_DIGITS; i++)
if (digits[i].val == ret->val && !digits[i].used) {
digits[i].used = 1;
return ret;
}
bail("Invalid digit");
}
return 0;
}
expr get_fact()
{
int c;
expr l = get_digit();
if (l) return l;
if ((c = next_tok()) == '(') {
take();
l = get_expr();
if (next_tok() != ')') bail("Unbalanced parens");
take();
return l;
}
return 0;
}
expr parse()
{
int i;
expr ret = get_expr();
if (next_tok() != '\0')
bail("Trailing garbage");
for (i = 0; i < N_DIGITS; i++)
if (!digits[i].used)
bail("Not all digits are used");
return ret;
}
typedef struct frac_t frac_t, *frac;
struct frac_t { int denom, num; };
int gcd(int m, int n)
{
int t;
while (m) {
t = m; m = n % m; n = t;
}
return n;
}
void eval_tree(expr e, frac res)
{
frac_t l, r;
int t;
if (e->op == OP_NUM) {
res->num = e->val;
res->denom = 1;
return;
}
eval_tree(e->left, &l);
eval_tree(e->right, &r);
switch(e->op) {
case OP_ADD:
res->num = l.num * r.denom + l.denom * r.num;
res->denom = l.denom * r.denom;
break;
case OP_SUB:
res->num = l.num * r.denom - l.denom * r.num;
res->denom = l.denom * r.denom;
break;
case OP_MUL:
res->num = l.num * r.num;
res->denom = l.denom * r.denom;
break;
case OP_DIV:
res->num = l.num * r.denom;
res->denom = l.denom * r.num;
break;
}
if ((t = gcd(res->denom, res->num))) {
res->denom /= t;
res->num /= t;
}
}
void get_input()
{
int i;
reinput:
reset();
printf("\nAvailable digits are:");
for (i = 0; i < N_DIGITS; i++)
printf(" %d", digits[i].val);
printf(". Type an expression and I'll check it for you, or make new numbers.\n"
"Your choice? [Expr/n/q] ");
while (1) {
for (i = 0; i < MAX_INPUT; i++) str[i] = '\n';
fgets(str, MAX_INPUT, stdin);
if (*str == '\0') goto reinput;
if (str[MAX_INPUT - 1] != '\n')
bail("string too long");
for (i = 0; i < MAX_INPUT; i++)
if (str[i] == '\n') str[i] = '\0';
if (str[0] == 'q') {
printf("Bye\n");
exit(0);
}
if (str[0] == 'n') {
gen_digits();
goto reinput;
}
return;
}
}
int main()
{
frac_t f;
srand(time(0));
gen_digits();
while(1) {
get_input();
setjmp(ctx);
if (msg) {
printf("%s at '%.*s'\n", msg, pos, str);
continue;
}
eval_tree(parse(), &f);
if (f.denom == 0) bail("Divide by zero");
if (f.denom == 1 && f.num == 24)
printf("You got 24. Very good.\n");
else {
if (f.denom == 1)
printf("Eval to: %d, ", f.num);
else
printf("Eval to: %d/%d, ", f.num, f.denom);
printf("no good. Try again.\n");
}
}
return 0;
}
|
from __future__ import division, print_function
import random, ast, re
import sys
if sys.version_info[0] < 3: input = raw_input
def choose4():
'four random digits >0 as characters'
return [str(random.randint(1,9)) for i in range(4)]
def welcome(digits):
print (__doc__)
print ("Your four digits: " + ' '.join(digits))
def check(answer, digits):
allowed = set('() +-*/\t'+''.join(digits))
ok = all(ch in allowed for ch in answer) and \
all(digits.count(dig) == answer.count(dig) for dig in set(digits)) \
and not re.search('\d\d', answer)
if ok:
try:
ast.parse(answer)
except:
ok = False
return ok
def main():
digits = choose4()
welcome(digits)
trial = 0
answer = ''
chk = ans = False
while not (chk and ans == 24):
trial +=1
answer = input("Expression %i: " % trial)
chk = check(answer, digits)
if answer.lower() == 'q':
break
if answer == '!':
digits = choose4()
print ("New digits:", ' '.join(digits))
continue
if not chk:
print ("The input '%s' was wonky!" % answer)
else:
ans = eval(answer)
print (" = ", ans)
if ans == 24:
print ("Thats right!")
print ("Thank you and goodbye")
if __name__ == '__main__': main()
|
Transform the following C implementation into Python, maintaining the same output and logic. | #include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <setjmp.h>
#include <time.h>
jmp_buf ctx;
const char *msg;
enum { OP_NONE = 0, OP_NUM, OP_ADD, OP_SUB, OP_MUL, OP_DIV };
typedef struct expr_t *expr, expr_t;
struct expr_t {
int op, val, used;
expr left, right;
};
#define N_DIGITS 4
expr_t digits[N_DIGITS];
void gen_digits()
{
int i;
for (i = 0; i < N_DIGITS; i++)
digits[i].val = 1 + rand() % 9;
}
#define MAX_INPUT 64
char str[MAX_INPUT];
int pos;
#define POOL_SIZE 8
expr_t pool[POOL_SIZE];
int pool_ptr;
void reset()
{
int i;
msg = 0;
pool_ptr = pos = 0;
for (i = 0; i < POOL_SIZE; i++) {
pool[i].op = OP_NONE;
pool[i].left = pool[i].right = 0;
}
for (i = 0; i < N_DIGITS; i++)
digits[i].used = 0;
}
void bail(const char *s)
{
msg = s;
longjmp(ctx, 1);
}
expr new_expr()
{
if (pool_ptr < POOL_SIZE)
return pool + pool_ptr++;
return 0;
}
int next_tok()
{
while (isspace(str[pos])) pos++;
return str[pos];
}
int take()
{
if (str[pos] != '\0') return ++pos;
return 0;
}
expr get_fact();
expr get_term();
expr get_expr();
expr get_expr()
{
int c;
expr l, r, ret;
if (!(ret = get_term())) bail("Expected term");
while ((c = next_tok()) == '+' || c == '-') {
if (!take()) bail("Unexpected end of input");
if (!(r = get_term())) bail("Expected term");
l = ret;
ret = new_expr();
ret->op = (c == '+') ? OP_ADD : OP_SUB;
ret->left = l;
ret->right = r;
}
return ret;
}
expr get_term()
{
int c;
expr l, r, ret;
ret = get_fact();
while((c = next_tok()) == '*' || c == '/') {
if (!take()) bail("Unexpected end of input");
r = get_fact();
l = ret;
ret = new_expr();
ret->op = (c == '*') ? OP_MUL : OP_DIV;
ret->left = l;
ret->right = r;
}
return ret;
}
expr get_digit()
{
int i, c = next_tok();
expr ret;
if (c >= '0' && c <= '9') {
take();
ret = new_expr();
ret->op = OP_NUM;
ret->val = c - '0';
for (i = 0; i < N_DIGITS; i++)
if (digits[i].val == ret->val && !digits[i].used) {
digits[i].used = 1;
return ret;
}
bail("Invalid digit");
}
return 0;
}
expr get_fact()
{
int c;
expr l = get_digit();
if (l) return l;
if ((c = next_tok()) == '(') {
take();
l = get_expr();
if (next_tok() != ')') bail("Unbalanced parens");
take();
return l;
}
return 0;
}
expr parse()
{
int i;
expr ret = get_expr();
if (next_tok() != '\0')
bail("Trailing garbage");
for (i = 0; i < N_DIGITS; i++)
if (!digits[i].used)
bail("Not all digits are used");
return ret;
}
typedef struct frac_t frac_t, *frac;
struct frac_t { int denom, num; };
int gcd(int m, int n)
{
int t;
while (m) {
t = m; m = n % m; n = t;
}
return n;
}
void eval_tree(expr e, frac res)
{
frac_t l, r;
int t;
if (e->op == OP_NUM) {
res->num = e->val;
res->denom = 1;
return;
}
eval_tree(e->left, &l);
eval_tree(e->right, &r);
switch(e->op) {
case OP_ADD:
res->num = l.num * r.denom + l.denom * r.num;
res->denom = l.denom * r.denom;
break;
case OP_SUB:
res->num = l.num * r.denom - l.denom * r.num;
res->denom = l.denom * r.denom;
break;
case OP_MUL:
res->num = l.num * r.num;
res->denom = l.denom * r.denom;
break;
case OP_DIV:
res->num = l.num * r.denom;
res->denom = l.denom * r.num;
break;
}
if ((t = gcd(res->denom, res->num))) {
res->denom /= t;
res->num /= t;
}
}
void get_input()
{
int i;
reinput:
reset();
printf("\nAvailable digits are:");
for (i = 0; i < N_DIGITS; i++)
printf(" %d", digits[i].val);
printf(". Type an expression and I'll check it for you, or make new numbers.\n"
"Your choice? [Expr/n/q] ");
while (1) {
for (i = 0; i < MAX_INPUT; i++) str[i] = '\n';
fgets(str, MAX_INPUT, stdin);
if (*str == '\0') goto reinput;
if (str[MAX_INPUT - 1] != '\n')
bail("string too long");
for (i = 0; i < MAX_INPUT; i++)
if (str[i] == '\n') str[i] = '\0';
if (str[0] == 'q') {
printf("Bye\n");
exit(0);
}
if (str[0] == 'n') {
gen_digits();
goto reinput;
}
return;
}
}
int main()
{
frac_t f;
srand(time(0));
gen_digits();
while(1) {
get_input();
setjmp(ctx);
if (msg) {
printf("%s at '%.*s'\n", msg, pos, str);
continue;
}
eval_tree(parse(), &f);
if (f.denom == 0) bail("Divide by zero");
if (f.denom == 1 && f.num == 24)
printf("You got 24. Very good.\n");
else {
if (f.denom == 1)
printf("Eval to: %d, ", f.num);
else
printf("Eval to: %d/%d, ", f.num, f.denom);
printf("no good. Try again.\n");
}
}
return 0;
}
|
from __future__ import division, print_function
import random, ast, re
import sys
if sys.version_info[0] < 3: input = raw_input
def choose4():
'four random digits >0 as characters'
return [str(random.randint(1,9)) for i in range(4)]
def welcome(digits):
print (__doc__)
print ("Your four digits: " + ' '.join(digits))
def check(answer, digits):
allowed = set('() +-*/\t'+''.join(digits))
ok = all(ch in allowed for ch in answer) and \
all(digits.count(dig) == answer.count(dig) for dig in set(digits)) \
and not re.search('\d\d', answer)
if ok:
try:
ast.parse(answer)
except:
ok = False
return ok
def main():
digits = choose4()
welcome(digits)
trial = 0
answer = ''
chk = ans = False
while not (chk and ans == 24):
trial +=1
answer = input("Expression %i: " % trial)
chk = check(answer, digits)
if answer.lower() == 'q':
break
if answer == '!':
digits = choose4()
print ("New digits:", ' '.join(digits))
continue
if not chk:
print ("The input '%s' was wonky!" % answer)
else:
ans = eval(answer)
print (" = ", ans)
if ans == 24:
print ("Thats right!")
print ("Thank you and goodbye")
if __name__ == '__main__': main()
|
Translate the given C code snippet into Python without altering its behavior. | for(int i = 1;i <= 10; i++){
printf("%d", i);
if(i % 5 == 0){
printf("\n");
continue;
}
printf(", ");
}
| for i in range(1, 11):
if i % 5 == 0:
print(i)
continue
print(i, end=', ')
|
Translate this program into Python but keep the logic exactly as in C. | #include<conio.h>
#define COLOURS 8
int main()
{
int colour=0,i,j,MAXROW,MAXCOL;
struct text_info tInfo;
gettextinfo(&tInfo);
MAXROW = tInfo.screenheight;
MAXCOL = tInfo.screenwidth;
textbackground(BLACK);
clrscr();
for(colour=0;colour<COLOURS;colour++)
{
getch();
gotoxy(1+colour*MAXCOL/COLOURS,1);
textbackground(colour);
for(j=0;j<MAXROW;j++){
for(i=0;i<MAXCOL/COLOURS;i++){
cprintf(" ");
}
gotoxy(1+colour*MAXCOL/COLOURS,1+j);
}
}
getch();
textbackground(BLACK);
return 0;
}
|
from livewires import *
horiz=640; vert=480
begin_graphics(width=horiz,height=vert,title="v_stripes",background=Colour.black)
NameColors=["black","red","green","dark_blue","purple","blue","yellow","white"]
stepik=horiz/len(NameColors)
for index,each in enumerate(NameColors):
ExcStrng="set_colour(Colour."+each+")"
exec ExcStrng
box(index*stepik,0,(index+1)*stepik,vert,filled=1)
while keys_pressed() != ['x']:
pass
end_graphics()
|
Transform the following C implementation into Python, maintaining the same output and logic. | #include<conio.h>
#define COLOURS 8
int main()
{
int colour=0,i,j,MAXROW,MAXCOL;
struct text_info tInfo;
gettextinfo(&tInfo);
MAXROW = tInfo.screenheight;
MAXCOL = tInfo.screenwidth;
textbackground(BLACK);
clrscr();
for(colour=0;colour<COLOURS;colour++)
{
getch();
gotoxy(1+colour*MAXCOL/COLOURS,1);
textbackground(colour);
for(j=0;j<MAXROW;j++){
for(i=0;i<MAXCOL/COLOURS;i++){
cprintf(" ");
}
gotoxy(1+colour*MAXCOL/COLOURS,1+j);
}
}
getch();
textbackground(BLACK);
return 0;
}
|
from livewires import *
horiz=640; vert=480
begin_graphics(width=horiz,height=vert,title="v_stripes",background=Colour.black)
NameColors=["black","red","green","dark_blue","purple","blue","yellow","white"]
stepik=horiz/len(NameColors)
for index,each in enumerate(NameColors):
ExcStrng="set_colour(Colour."+each+")"
exec ExcStrng
box(index*stepik,0,(index+1)*stepik,vert,filled=1)
while keys_pressed() != ['x']:
pass
end_graphics()
|
Write the same algorithm in Python as shown in this C implementation. | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define foreach(a, b, c) for (int a = b; a < c; a++)
#define for_i foreach(i, 0, n)
#define for_j foreach(j, 0, n)
#define for_k foreach(k, 0, n)
#define for_ij for_i for_j
#define for_ijk for_ij for_k
#define _dim int n
#define _swap(x, y) { typeof(x) tmp = x; x = y; y = tmp; }
#define _sum_k(a, b, c, s) { s = 0; foreach(k, a, b) s+= c; }
typedef double **mat;
#define _zero(a) mat_zero(a, n)
void mat_zero(mat x, int n) { for_ij x[i][j] = 0; }
#define _new(a) a = mat_new(n)
mat mat_new(_dim)
{
mat x = malloc(sizeof(double*) * n);
x[0] = malloc(sizeof(double) * n * n);
for_i x[i] = x[0] + n * i;
_zero(x);
return x;
}
#define _copy(a) mat_copy(a, n)
mat mat_copy(void *s, _dim)
{
mat x = mat_new(n);
for_ij x[i][j] = ((double (*)[n])s)[i][j];
return x;
}
#define _del(x) mat_del(x)
void mat_del(mat x) { free(x[0]); free(x); }
#define _QUOT(x) #x
#define QUOTE(x) _QUOT(x)
#define _show(a) printf(QUOTE(a)" =");mat_show(a, 0, n)
void mat_show(mat x, char *fmt, _dim)
{
if (!fmt) fmt = "%8.4g";
for_i {
printf(i ? " " : " [ ");
for_j {
printf(fmt, x[i][j]);
printf(j < n - 1 ? " " : i == n - 1 ? " ]\n" : "\n");
}
}
}
#define _mul(a, b) mat_mul(a, b, n)
mat mat_mul(mat a, mat b, _dim)
{
mat c = _new(c);
for_ijk c[i][j] += a[i][k] * b[k][j];
return c;
}
#define _pivot(a, b) mat_pivot(a, b, n)
void mat_pivot(mat a, mat p, _dim)
{
for_ij { p[i][j] = (i == j); }
for_i {
int max_j = i;
foreach(j, i, n)
if (fabs(a[j][i]) > fabs(a[max_j][i])) max_j = j;
if (max_j != i)
for_k { _swap(p[i][k], p[max_j][k]); }
}
}
#define _LU(a, l, u, p) mat_LU(a, l, u, p, n)
void mat_LU(mat A, mat L, mat U, mat P, _dim)
{
_zero(L); _zero(U);
_pivot(A, P);
mat Aprime = _mul(P, A);
for_i { L[i][i] = 1; }
for_ij {
double s;
if (j <= i) {
_sum_k(0, j, L[j][k] * U[k][i], s)
U[j][i] = Aprime[j][i] - s;
}
if (j >= i) {
_sum_k(0, i, L[j][k] * U[k][i], s);
L[j][i] = (Aprime[j][i] - s) / U[i][i];
}
}
_del(Aprime);
}
double A3[][3] = {{ 1, 3, 5 }, { 2, 4, 7 }, { 1, 1, 0 }};
double A4[][4] = {{11, 9, 24, 2}, {1, 5, 2, 6}, {3, 17, 18, 1}, {2, 5, 7, 1}};
int main()
{
int n = 3;
mat A, L, P, U;
_new(L); _new(P); _new(U);
A = _copy(A3);
_LU(A, L, U, P);
_show(A); _show(L); _show(U); _show(P);
_del(A); _del(L); _del(U); _del(P);
printf("\n");
n = 4;
_new(L); _new(P); _new(U);
A = _copy(A4);
_LU(A, L, U, P);
_show(A); _show(L); _show(U); _show(P);
_del(A); _del(L); _del(U); _del(P);
return 0;
}
| from pprint import pprint
def matrixMul(A, B):
TB = zip(*B)
return [[sum(ea*eb for ea,eb in zip(a,b)) for b in TB] for a in A]
def pivotize(m):
n = len(m)
ID = [[float(i == j) for i in xrange(n)] for j in xrange(n)]
for j in xrange(n):
row = max(xrange(j, n), key=lambda i: abs(m[i][j]))
if j != row:
ID[j], ID[row] = ID[row], ID[j]
return ID
def lu(A):
n = len(A)
L = [[0.0] * n for i in xrange(n)]
U = [[0.0] * n for i in xrange(n)]
P = pivotize(A)
A2 = matrixMul(P, A)
for j in xrange(n):
L[j][j] = 1.0
for i in xrange(j+1):
s1 = sum(U[k][j] * L[i][k] for k in xrange(i))
U[i][j] = A2[i][j] - s1
for i in xrange(j, n):
s2 = sum(U[k][j] * L[i][k] for k in xrange(j))
L[i][j] = (A2[i][j] - s2) / U[j][j]
return (L, U, P)
a = [[1, 3, 5], [2, 4, 7], [1, 1, 0]]
for part in lu(a):
pprint(part, width=19)
print
print
b = [[11,9,24,2],[1,5,2,6],[3,17,18,1],[2,5,7,1]]
for part in lu(b):
pprint(part)
print
|
Port the provided C code into Python while preserving the original functionality. | #include <stdio.h>
#include <stdlib.h>
struct replace_info {
int n;
char *text;
};
int compare(const void *a, const void *b)
{
struct replace_info *x = (struct replace_info *) a;
struct replace_info *y = (struct replace_info *) b;
return x->n - y->n;
}
void generic_fizz_buzz(int max, struct replace_info *info, int info_length)
{
int i, it;
int found_word;
for (i = 1; i < max; ++i) {
found_word = 0;
for (it = 0; it < info_length; ++it) {
if (0 == i % info[it].n) {
printf("%s", info[it].text);
found_word = 1;
}
}
if (0 == found_word)
printf("%d", i);
printf("\n");
}
}
int main(void)
{
struct replace_info info[3] = {
{5, "Buzz"},
{7, "Baxx"},
{3, "Fizz"}
};
qsort(info, 3, sizeof(struct replace_info), compare);
generic_fizz_buzz(20, info, 3);
return 0;
}
| def genfizzbuzz(factorwords, numbers):
factorwords.sort(key=lambda factor_and_word: factor_and_word[0])
lines = []
for num in numbers:
words = ''.join(word for factor, word in factorwords if (num % factor) == 0)
lines.append(words if words else str(num))
return '\n'.join(lines)
if __name__ == '__main__':
print(genfizzbuzz([(5, 'Buzz'), (3, 'Fizz'), (7, 'Baxx')], range(1, 21)))
|
Generate a Python translation of this C snippet without changing its computational steps. | #include <unistd.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <err.h>
int read_file_line(const char *path, int line_no)
{
struct stat s;
char *buf;
off_t start = -1, end = -1;
size_t i;
int ln, fd, ret = 1;
if (line_no == 1) start = 0;
else if (line_no < 1){
warn("line_no too small");
return 0;
}
line_no--;
fd = open(path, O_RDONLY);
fstat(fd, &s);
buf = mmap(0, s.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
madvise(buf, s.st_size, MADV_SEQUENTIAL);
for (i = ln = 0; i < s.st_size && ln <= line_no; i++) {
if (buf[i] != '\n') continue;
if (++ln == line_no) start = i + 1;
else if (ln == line_no + 1) end = i + 1;
}
if (start >= s.st_size || start < 0) {
warn("file does not have line %d", line_no + 1);
ret = 0;
} else {
}
munmap(buf, s.st_size);
close(fd);
return ret;
}
| with open('xxx.txt') as f:
for i, line in enumerate(f):
if i == 6:
break
else:
print('Not 7 lines in file')
line = None
|
Convert this C block to Python, preserving its control flow and logic. | #include <unistd.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <err.h>
int read_file_line(const char *path, int line_no)
{
struct stat s;
char *buf;
off_t start = -1, end = -1;
size_t i;
int ln, fd, ret = 1;
if (line_no == 1) start = 0;
else if (line_no < 1){
warn("line_no too small");
return 0;
}
line_no--;
fd = open(path, O_RDONLY);
fstat(fd, &s);
buf = mmap(0, s.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
madvise(buf, s.st_size, MADV_SEQUENTIAL);
for (i = ln = 0; i < s.st_size && ln <= line_no; i++) {
if (buf[i] != '\n') continue;
if (++ln == line_no) start = i + 1;
else if (ln == line_no + 1) end = i + 1;
}
if (start >= s.st_size || start < 0) {
warn("file does not have line %d", line_no + 1);
ret = 0;
} else {
}
munmap(buf, s.st_size);
close(fd);
return ret;
}
| with open('xxx.txt') as f:
for i, line in enumerate(f):
if i == 6:
break
else:
print('Not 7 lines in file')
line = None
|
Transform the following C implementation into Python, maintaining the same output and logic. |
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <locale.h>
#include <string.h>
#ifdef _Bool
#include <stdbool.h>
#else
#define bool int
#define true 1
#define false 0
#endif
int checkFileExtension(char* fileName, char* fileExtensions)
{
char* fileExtension = fileExtensions;
if ( *fileName )
{
while ( *fileExtension )
{
int fileNameLength = strlen(fileName);
int extensionLength = strlen(fileExtension);
if ( fileNameLength >= extensionLength )
{
char* a = fileName + fileNameLength - extensionLength;
char* b = fileExtension;
while ( *a && toupper(*a++) == toupper(*b++) )
;
if ( !*a )
return true;
}
fileExtension += extensionLength + 1;
}
}
return false;
}
void printExtensions(char* extensions)
{
while( *extensions )
{
printf("%s\n", extensions);
extensions += strlen(extensions) + 1;
}
}
bool test(char* fileName, char* extension, bool expectedResult)
{
bool result = checkFileExtension(fileName,extension);
bool returnValue = result == expectedResult;
printf("%20s result: %-5s expected: %-5s test %s\n",
fileName,
result ? "true" : "false",
expectedResult ? "true" : "false",
returnValue ? "passed" : "failed" );
return returnValue;
}
int main(void)
{
static char extensions[] = ".zip\0.rar\0.7z\0.gz\0.archive\0.A##\0.tar.bz2\0";
setlocale(LC_ALL,"");
printExtensions(extensions);
printf("\n");
if ( test("MyData.a##", extensions,true )
&& test("MyData.tar.Gz", extensions,true )
&& test("MyData.gzip", extensions,false)
&& test("MyData.7z.backup", extensions,false)
&& test("MyData...", extensions,false)
&& test("MyData", extensions,false)
&& test("MyData_v1.0.tar.bz2",extensions,true )
&& test("MyData_v1.0.bz2", extensions,false)
&& test("filename", extensions,false)
)
printf("\n%s\n", "All tests passed.");
else
printf("\n%s\n", "Last test failed.");
printf("\n%s\n", "press enter");
getchar();
return 0;
}
| def isExt(fileName, extensions):
return True in map(fileName.lower().endswith, ("." + e.lower() for e in extensions))
|
Change the following C code into Python without altering its purpose. |
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <locale.h>
#include <string.h>
#ifdef _Bool
#include <stdbool.h>
#else
#define bool int
#define true 1
#define false 0
#endif
int checkFileExtension(char* fileName, char* fileExtensions)
{
char* fileExtension = fileExtensions;
if ( *fileName )
{
while ( *fileExtension )
{
int fileNameLength = strlen(fileName);
int extensionLength = strlen(fileExtension);
if ( fileNameLength >= extensionLength )
{
char* a = fileName + fileNameLength - extensionLength;
char* b = fileExtension;
while ( *a && toupper(*a++) == toupper(*b++) )
;
if ( !*a )
return true;
}
fileExtension += extensionLength + 1;
}
}
return false;
}
void printExtensions(char* extensions)
{
while( *extensions )
{
printf("%s\n", extensions);
extensions += strlen(extensions) + 1;
}
}
bool test(char* fileName, char* extension, bool expectedResult)
{
bool result = checkFileExtension(fileName,extension);
bool returnValue = result == expectedResult;
printf("%20s result: %-5s expected: %-5s test %s\n",
fileName,
result ? "true" : "false",
expectedResult ? "true" : "false",
returnValue ? "passed" : "failed" );
return returnValue;
}
int main(void)
{
static char extensions[] = ".zip\0.rar\0.7z\0.gz\0.archive\0.A##\0.tar.bz2\0";
setlocale(LC_ALL,"");
printExtensions(extensions);
printf("\n");
if ( test("MyData.a##", extensions,true )
&& test("MyData.tar.Gz", extensions,true )
&& test("MyData.gzip", extensions,false)
&& test("MyData.7z.backup", extensions,false)
&& test("MyData...", extensions,false)
&& test("MyData", extensions,false)
&& test("MyData_v1.0.tar.bz2",extensions,true )
&& test("MyData_v1.0.bz2", extensions,false)
&& test("filename", extensions,false)
)
printf("\n%s\n", "All tests passed.");
else
printf("\n%s\n", "Last test failed.");
printf("\n%s\n", "press enter");
getchar();
return 0;
}
| def isExt(fileName, extensions):
return True in map(fileName.lower().endswith, ("." + e.lower() for e in extensions))
|
Write the same algorithm in Python as shown in this C implementation. | #include <stdio.h>
typedef struct {int val, op, left, right;} Node;
Node nodes[10000];
int iNodes;
int b;
float eval(Node x){
if (x.op != -1){
float l = eval(nodes[x.left]), r = eval(nodes[x.right]);
switch(x.op){
case 0: return l+r;
case 1: return l-r;
case 2: return r-l;
case 3: return l*r;
case 4: return r?l/r:(b=1,0);
case 5: return l?r/l:(b=1,0);
}
}
else return x.val*1.;
}
void show(Node x){
if (x.op != -1){
printf("(");
switch(x.op){
case 0: show(nodes[x.left]); printf(" + "); show(nodes[x.right]); break;
case 1: show(nodes[x.left]); printf(" - "); show(nodes[x.right]); break;
case 2: show(nodes[x.right]); printf(" - "); show(nodes[x.left]); break;
case 3: show(nodes[x.left]); printf(" * "); show(nodes[x.right]); break;
case 4: show(nodes[x.left]); printf(" / "); show(nodes[x.right]); break;
case 5: show(nodes[x.right]); printf(" / "); show(nodes[x.left]); break;
}
printf(")");
}
else printf("%d", x.val);
}
int float_fix(float x){ return x < 0.00001 && x > -0.00001; }
void solutions(int a[], int n, float t, int s){
if (s == n){
b = 0;
float e = eval(nodes[0]);
if (!b && float_fix(e-t)){
show(nodes[0]);
printf("\n");
}
}
else{
nodes[iNodes++] = (typeof(Node)){a[s],-1,-1,-1};
for (int op = 0; op < 6; op++){
int k = iNodes-1;
for (int i = 0; i < k; i++){
nodes[iNodes++] = nodes[i];
nodes[i] = (typeof(Node)){-1,op,iNodes-1,iNodes-2};
solutions(a, n, t, s+1);
nodes[i] = nodes[--iNodes];
}
}
iNodes--;
}
};
int main(){
int a[4] = {8, 3, 8, 3};
float t = 24;
nodes[0] = (typeof(Node)){a[0],-1,-1,-1};
iNodes = 1;
solutions(a, sizeof(a)/sizeof(int), t, 1);
return 0;
}
|
from __future__ import division, print_function
from itertools import permutations, combinations, product, \
chain
from pprint import pprint as pp
from fractions import Fraction as F
import random, ast, re
import sys
if sys.version_info[0] < 3:
input = raw_input
from itertools import izip_longest as zip_longest
else:
from itertools import zip_longest
def choose4():
'four random digits >0 as characters'
return [str(random.randint(1,9)) for i in range(4)]
def ask4():
'get four random digits >0 from the player'
digits = ''
while len(digits) != 4 or not all(d in '123456789' for d in digits):
digits = input('Enter the digits to solve for: ')
digits = ''.join(digits.strip().split())
return list(digits)
def welcome(digits):
print (__doc__)
print ("Your four digits: " + ' '.join(digits))
def check(answer, digits):
allowed = set('() +-*/\t'+''.join(digits))
ok = all(ch in allowed for ch in answer) and \
all(digits.count(dig) == answer.count(dig) for dig in set(digits)) \
and not re.search('\d\d', answer)
if ok:
try:
ast.parse(answer)
except:
ok = False
return ok
def solve(digits):
digilen = len(digits)
exprlen = 2 * digilen - 1
digiperm = sorted(set(permutations(digits)))
opcomb = list(product('+-*/', repeat=digilen-1))
brackets = ( [()] + [(x,y)
for x in range(0, exprlen, 2)
for y in range(x+4, exprlen+2, 2)
if (x,y) != (0,exprlen+1)]
+ [(0, 3+1, 4+2, 7+3)] )
for d in digiperm:
for ops in opcomb:
if '/' in ops:
d2 = [('F(%s)' % i) for i in d]
else:
d2 = d
ex = list(chain.from_iterable(zip_longest(d2, ops, fillvalue='')))
for b in brackets:
exp = ex[::]
for insertpoint, bracket in zip(b, '()'*(len(b)//2)):
exp.insert(insertpoint, bracket)
txt = ''.join(exp)
try:
num = eval(txt)
except ZeroDivisionError:
continue
if num == 24:
if '/' in ops:
exp = [ (term if not term.startswith('F(') else term[2])
for term in exp ]
ans = ' '.join(exp).rstrip()
print ("Solution found:",ans)
return ans
print ("No solution found for:", ' '.join(digits))
return '!'
def main():
digits = choose4()
welcome(digits)
trial = 0
answer = ''
chk = ans = False
while not (chk and ans == 24):
trial +=1
answer = input("Expression %i: " % trial)
chk = check(answer, digits)
if answer == '?':
solve(digits)
answer = '!'
if answer.lower() == 'q':
break
if answer == '!':
digits = choose4()
trial = 0
print ("\nNew digits:", ' '.join(digits))
continue
if answer == '!!':
digits = ask4()
trial = 0
print ("\nNew digits:", ' '.join(digits))
continue
if not chk:
print ("The input '%s' was wonky!" % answer)
else:
if '/' in answer:
answer = ''.join( (('F(%s)' % char) if char in '123456789' else char)
for char in answer )
ans = eval(answer)
print (" = ", ans)
if ans == 24:
print ("Thats right!")
print ("Thank you and goodbye")
main()
|
Can you help me rewrite this code in Python instead of C, keeping it the same logically? | #include <stdio.h>
typedef struct {int val, op, left, right;} Node;
Node nodes[10000];
int iNodes;
int b;
float eval(Node x){
if (x.op != -1){
float l = eval(nodes[x.left]), r = eval(nodes[x.right]);
switch(x.op){
case 0: return l+r;
case 1: return l-r;
case 2: return r-l;
case 3: return l*r;
case 4: return r?l/r:(b=1,0);
case 5: return l?r/l:(b=1,0);
}
}
else return x.val*1.;
}
void show(Node x){
if (x.op != -1){
printf("(");
switch(x.op){
case 0: show(nodes[x.left]); printf(" + "); show(nodes[x.right]); break;
case 1: show(nodes[x.left]); printf(" - "); show(nodes[x.right]); break;
case 2: show(nodes[x.right]); printf(" - "); show(nodes[x.left]); break;
case 3: show(nodes[x.left]); printf(" * "); show(nodes[x.right]); break;
case 4: show(nodes[x.left]); printf(" / "); show(nodes[x.right]); break;
case 5: show(nodes[x.right]); printf(" / "); show(nodes[x.left]); break;
}
printf(")");
}
else printf("%d", x.val);
}
int float_fix(float x){ return x < 0.00001 && x > -0.00001; }
void solutions(int a[], int n, float t, int s){
if (s == n){
b = 0;
float e = eval(nodes[0]);
if (!b && float_fix(e-t)){
show(nodes[0]);
printf("\n");
}
}
else{
nodes[iNodes++] = (typeof(Node)){a[s],-1,-1,-1};
for (int op = 0; op < 6; op++){
int k = iNodes-1;
for (int i = 0; i < k; i++){
nodes[iNodes++] = nodes[i];
nodes[i] = (typeof(Node)){-1,op,iNodes-1,iNodes-2};
solutions(a, n, t, s+1);
nodes[i] = nodes[--iNodes];
}
}
iNodes--;
}
};
int main(){
int a[4] = {8, 3, 8, 3};
float t = 24;
nodes[0] = (typeof(Node)){a[0],-1,-1,-1};
iNodes = 1;
solutions(a, sizeof(a)/sizeof(int), t, 1);
return 0;
}
|
from __future__ import division, print_function
from itertools import permutations, combinations, product, \
chain
from pprint import pprint as pp
from fractions import Fraction as F
import random, ast, re
import sys
if sys.version_info[0] < 3:
input = raw_input
from itertools import izip_longest as zip_longest
else:
from itertools import zip_longest
def choose4():
'four random digits >0 as characters'
return [str(random.randint(1,9)) for i in range(4)]
def ask4():
'get four random digits >0 from the player'
digits = ''
while len(digits) != 4 or not all(d in '123456789' for d in digits):
digits = input('Enter the digits to solve for: ')
digits = ''.join(digits.strip().split())
return list(digits)
def welcome(digits):
print (__doc__)
print ("Your four digits: " + ' '.join(digits))
def check(answer, digits):
allowed = set('() +-*/\t'+''.join(digits))
ok = all(ch in allowed for ch in answer) and \
all(digits.count(dig) == answer.count(dig) for dig in set(digits)) \
and not re.search('\d\d', answer)
if ok:
try:
ast.parse(answer)
except:
ok = False
return ok
def solve(digits):
digilen = len(digits)
exprlen = 2 * digilen - 1
digiperm = sorted(set(permutations(digits)))
opcomb = list(product('+-*/', repeat=digilen-1))
brackets = ( [()] + [(x,y)
for x in range(0, exprlen, 2)
for y in range(x+4, exprlen+2, 2)
if (x,y) != (0,exprlen+1)]
+ [(0, 3+1, 4+2, 7+3)] )
for d in digiperm:
for ops in opcomb:
if '/' in ops:
d2 = [('F(%s)' % i) for i in d]
else:
d2 = d
ex = list(chain.from_iterable(zip_longest(d2, ops, fillvalue='')))
for b in brackets:
exp = ex[::]
for insertpoint, bracket in zip(b, '()'*(len(b)//2)):
exp.insert(insertpoint, bracket)
txt = ''.join(exp)
try:
num = eval(txt)
except ZeroDivisionError:
continue
if num == 24:
if '/' in ops:
exp = [ (term if not term.startswith('F(') else term[2])
for term in exp ]
ans = ' '.join(exp).rstrip()
print ("Solution found:",ans)
return ans
print ("No solution found for:", ' '.join(digits))
return '!'
def main():
digits = choose4()
welcome(digits)
trial = 0
answer = ''
chk = ans = False
while not (chk and ans == 24):
trial +=1
answer = input("Expression %i: " % trial)
chk = check(answer, digits)
if answer == '?':
solve(digits)
answer = '!'
if answer.lower() == 'q':
break
if answer == '!':
digits = choose4()
trial = 0
print ("\nNew digits:", ' '.join(digits))
continue
if answer == '!!':
digits = ask4()
trial = 0
print ("\nNew digits:", ' '.join(digits))
continue
if not chk:
print ("The input '%s' was wonky!" % answer)
else:
if '/' in answer:
answer = ''.join( (('F(%s)' % char) if char in '123456789' else char)
for char in answer )
ans = eval(answer)
print (" = ", ans)
if ans == 24:
print ("Thats right!")
print ("Thank you and goodbye")
main()
|
Generate a Python translation of this C snippet without changing its computational steps. | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <omp.h>
int main()
{
int jobs = 41, tid;
omp_set_num_threads(5);
#pragma omp parallel shared(jobs) private(tid)
{
tid = omp_get_thread_num();
while (jobs > 0) {
#pragma omp barrier
if (!jobs) break;
printf("%d: taking job %d\n", tid, jobs--);
usleep(100000 + rand() / (double) RAND_MAX * 3000000);
printf("%d: done job\n", tid);
}
printf("[%d] leaving\n", tid);
#pragma omp barrier
}
return 0;
}
|
import threading
import time
import random
def worker(workernum, barrier):
sleeptime = random.random()
print('Starting worker '+str(workernum)+" task 1, sleeptime="+str(sleeptime))
time.sleep(sleeptime)
print('Exiting worker'+str(workernum))
barrier.wait()
sleeptime = random.random()
print('Starting worker '+str(workernum)+" task 2, sleeptime="+str(sleeptime))
time.sleep(sleeptime)
print('Exiting worker'+str(workernum))
barrier = threading.Barrier(3)
w1 = threading.Thread(target=worker, args=((1,barrier)))
w2 = threading.Thread(target=worker, args=((2,barrier)))
w3 = threading.Thread(target=worker, args=((3,barrier)))
w1.start()
w2.start()
w3.start()
|
Please provide an equivalent version of this C code in Python. | #include <stdio.h>
#include <stdint.h>
void to_seq(uint64_t x, uint8_t *out)
{
int i, j;
for (i = 9; i > 0; i--) {
if (x & 127ULL << i * 7) break;
}
for (j = 0; j <= i; j++)
out[j] = ((x >> ((i - j) * 7)) & 127) | 128;
out[i] ^= 128;
}
uint64_t from_seq(uint8_t *in)
{
uint64_t r = 0;
do {
r = (r << 7) | (uint64_t)(*in & 127);
} while (*in++ & 128);
return r;
}
int main()
{
uint8_t s[10];
uint64_t x[] = { 0x7f, 0x4000, 0, 0x3ffffe, 0x1fffff, 0x200000, 0x3311a1234df31413ULL};
int i, j;
for (j = 0; j < sizeof(x)/8; j++) {
to_seq(x[j], s);
printf("seq from %llx: [ ", x[j]);
i = 0;
do { printf("%02x ", s[i]); } while ((s[i++] & 128));
printf("] back: %llx\n", from_seq(s));
}
return 0;
}
| def tobits(n, _group=8, _sep='_', _pad=False):
'Express n as binary bits with separator'
bits = '{0:b}'.format(n)[::-1]
if _pad:
bits = '{0:0{1}b}'.format(n,
((_group+len(bits)-1)//_group)*_group)[::-1]
answer = _sep.join(bits[i:i+_group]
for i in range(0, len(bits), _group))[::-1]
answer = '0'*(len(_sep)-1) + answer
else:
answer = _sep.join(bits[i:i+_group]
for i in range(0, len(bits), _group))[::-1]
return answer
def tovlq(n):
return tobits(n, _group=7, _sep='1_', _pad=True)
def toint(vlq):
return int(''.join(vlq.split('_1')), 2)
def vlqsend(vlq):
for i, byte in enumerate(vlq.split('_')[::-1]):
print('Sent byte {0:3}: {1:
|
Write the same algorithm in Python as shown in this C implementation. | #include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
void * record(size_t bytes)
{
int fd;
if (-1 == (fd = open("/dev/dsp", O_RDONLY))) return 0;
void *a = malloc(bytes);
read(fd, a, bytes);
close(fd);
return a;
}
int play(void *buf, size_t len)
{
int fd;
if (-1 == (fd = open("/dev/dsp", O_WRONLY))) return 0;
write(fd, buf, len);
close(fd);
return 1;
}
int main()
{
void *p = record(65536);
play(p, 65536);
return 0;
}
| import pyaudio
chunk = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
p = pyaudio.PyAudio()
stream = p.open(format = FORMAT,
channels = CHANNELS,
rate = RATE,
input = True,
frames_per_buffer = chunk)
data = stream.read(chunk)
print [ord(i) for i in data]
|
Please provide an equivalent version of this C code in Python. | #include <glib.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
guchar* sha256_merkle_tree(FILE* in, size_t block_size) {
gchar* buffer = g_malloc(block_size);
GPtrArray* hashes = g_ptr_array_new_with_free_func(g_free);
gssize digest_length = g_checksum_type_get_length(G_CHECKSUM_SHA256);
GChecksum* checksum = g_checksum_new(G_CHECKSUM_SHA256);
size_t bytes;
while ((bytes = fread(buffer, 1, block_size, in)) > 0) {
g_checksum_reset(checksum);
g_checksum_update(checksum, (guchar*)buffer, bytes);
gsize len = digest_length;
guchar* digest = g_malloc(len);
g_checksum_get_digest(checksum, digest, &len);
g_ptr_array_add(hashes, digest);
}
g_free(buffer);
guint hashes_length = hashes->len;
if (hashes_length == 0) {
g_ptr_array_free(hashes, TRUE);
g_checksum_free(checksum);
return NULL;
}
while (hashes_length > 1) {
guint j = 0;
for (guint i = 0; i < hashes_length; i += 2, ++j) {
guchar* digest1 = g_ptr_array_index(hashes, i);
guchar* digest_out = g_ptr_array_index(hashes, j);
if (i + 1 < hashes_length) {
guchar* digest2 = g_ptr_array_index(hashes, i + 1);
g_checksum_reset(checksum);
g_checksum_update(checksum, digest1, digest_length);
g_checksum_update(checksum, digest2, digest_length);
gsize len = digest_length;
g_checksum_get_digest(checksum, digest_out, &len);
} else {
memcpy(digest_out, digest1, digest_length);
}
}
hashes_length = j;
}
guchar* result = g_ptr_array_steal_index(hashes, 0);
g_ptr_array_free(hashes, TRUE);
g_checksum_free(checksum);
return result;
}
int main(int argc, char** argv) {
if (argc != 2) {
fprintf(stderr, "usage: %s filename\n", argv[0]);
return EXIT_FAILURE;
}
FILE* in = fopen(argv[1], "rb");
if (in) {
guchar* digest = sha256_merkle_tree(in, 1024);
fclose(in);
if (digest) {
gssize length = g_checksum_type_get_length(G_CHECKSUM_SHA256);
for (gssize i = 0; i < length; ++i)
printf("%02x", digest[i]);
printf("\n");
g_free(digest);
}
} else {
perror(argv[1]);
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
|
import argh
import hashlib
import sys
@argh.arg('filename', nargs='?', default=None)
def main(filename, block_size=1024*1024):
if filename:
fin = open(filename, 'rb')
else:
fin = sys.stdin
stack = []
block = fin.read(block_size)
while block:
node = (0, hashlib.sha256(block).digest())
stack.append(node)
while len(stack) >= 2 and stack[-2][0] == stack[-1][0]:
a = stack[-2]
b = stack[-1]
l = a[0]
stack[-2:] = [(l+1, hashlib.sha256(a[1] + b[1]).digest())]
block = fin.read(block_size)
while len(stack) > 1:
a = stack[-2]
b = stack[-1]
al = a[0]
bl = b[0]
stack[-2:] = [(max(al, bl)+1, hashlib.sha256(a[1] + b[1]).digest())]
print(stack[0][1].hex())
argh.dispatch_command(main)
|
Port the following code from C to Python with equivalent syntax and logic. |
#include <ctype.h>
#include <stdio.h>
void str_toupper(char *s)
{
while(*s)
{
*s=toupper(*s);
s++;
}
}
void str_tolower(char *s)
{
while(*s)
{
*s=tolower(*s);
s++;
}
}
int main(int argc, char *argv[])
{
char t[255]="alphaBETA";
str_toupper(t);
printf("uppercase: %s\n", t);
str_tolower(t);
printf("lowercase: %s\n", t);
return 0;
}
| s = "alphaBETA"
print s.upper()
print s.lower()
print s.swapcase()
print "fOo bAR".capitalize()
print "fOo bAR".title()
import string
print string.capwords("fOo bAR")
|
Produce a language-to-language conversion: from C to Python, same semantics. | #include <gtk/gtk.h>
void ok_hit(GtkButton *o, GtkWidget **w)
{
GtkMessageDialog *msg;
gdouble v = gtk_spin_button_get_value((GtkSpinButton *)w[1]);
const gchar *c = gtk_entry_get_text((GtkEntry *)w[0]);
msg = (GtkMessageDialog *)
gtk_message_dialog_new(NULL,
GTK_DIALOG_MODAL,
(v==75000) ? GTK_MESSAGE_INFO : GTK_MESSAGE_ERROR,
GTK_BUTTONS_OK,
"You wrote '%s' and selected the number %d%s",
c, (gint)v,
(v==75000) ? "" : " which is wrong (75000 expected)!");
gtk_widget_show_all(GTK_WIDGET(msg));
(void)gtk_dialog_run(GTK_DIALOG(msg));
gtk_widget_destroy(GTK_WIDGET(msg));
if ( v==75000 ) gtk_main_quit();
}
int main(int argc, char **argv)
{
GtkWindow *win;
GtkEntry *entry;
GtkSpinButton *spin;
GtkButton *okbutton;
GtkLabel *entry_l, *spin_l;
GtkHBox *hbox[2];
GtkVBox *vbox;
GtkWidget *widgs[2];
gtk_init(&argc, &argv);
win = (GtkWindow *)gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_title(win, "Insert values");
entry_l = (GtkLabel *)gtk_label_new("Insert a string");
spin_l = (GtkLabel *)gtk_label_new("Insert 75000");
entry = (GtkEntry *)gtk_entry_new();
spin = (GtkSpinButton *)gtk_spin_button_new_with_range(0, 80000, 1);
widgs[0] = GTK_WIDGET(entry);
widgs[1] = GTK_WIDGET(spin);
okbutton = (GtkButton *)gtk_button_new_with_label("Ok");
hbox[0] = (GtkHBox *)gtk_hbox_new(FALSE, 1);
hbox[1] = (GtkHBox *)gtk_hbox_new(FALSE, 1);
vbox = (GtkVBox *)gtk_vbox_new(TRUE, 1);
gtk_container_add(GTK_CONTAINER(hbox[0]), GTK_WIDGET(entry_l));
gtk_container_add(GTK_CONTAINER(hbox[0]), GTK_WIDGET(entry));
gtk_container_add(GTK_CONTAINER(hbox[1]), GTK_WIDGET(spin_l));
gtk_container_add(GTK_CONTAINER(hbox[1]), GTK_WIDGET(spin));
gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(hbox[0]));
gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(hbox[1]));
gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(okbutton));
gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(vbox));
g_signal_connect(G_OBJECT(win), "delete-event", (GCallback)gtk_main_quit, NULL);
g_signal_connect(G_OBJECT(okbutton), "clicked", (GCallback)ok_hit, widgs);
gtk_widget_show_all(GTK_WIDGET(win));
gtk_main();
return 0;
}
| from javax.swing import JOptionPane
def to_int(n, default=0):
try:
return int(n)
except ValueError:
return default
number = to_int(JOptionPane.showInputDialog ("Enter an Integer"))
println(number)
a_string = JOptionPane.showInputDialog ("Enter a String")
println(a_string)
|
Please provide an equivalent version of this C code in Python. |
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct cursor_tag {
double x;
double y;
int angle;
} cursor_t;
void turn(cursor_t* cursor, int angle) {
cursor->angle = (cursor->angle + angle) % 360;
}
void draw_line(FILE* out, cursor_t* cursor, double length) {
double theta = (M_PI * cursor->angle)/180.0;
cursor->x += length * cos(theta);
cursor->y += length * sin(theta);
fprintf(out, "L%g,%g\n", cursor->x, cursor->y);
}
void curve(FILE* out, int order, double length, cursor_t* cursor, int angle) {
if (order == 0) {
draw_line(out, cursor, length);
} else {
curve(out, order - 1, length/2, cursor, -angle);
turn(cursor, angle);
curve(out, order - 1, length/2, cursor, angle);
turn(cursor, angle);
curve(out, order - 1, length/2, cursor, -angle);
}
}
void write_sierpinski_arrowhead(FILE* out, int size, int order) {
const double margin = 20.0;
const double side = size - 2.0 * margin;
cursor_t cursor;
cursor.angle = 0;
cursor.x = margin;
cursor.y = 0.5 * size + 0.25 * sqrt(3) * side;
if ((order & 1) != 0)
turn(&cursor, -60);
fprintf(out, "<svg xmlns='http:
size, size);
fprintf(out, "<rect width='100%%' height='100%%' fill='white'/>\n");
fprintf(out, "<path stroke-width='1' stroke='black' fill='none' d='");
fprintf(out, "M%g,%g\n", cursor.x, cursor.y);
curve(out, order, side, &cursor, 60);
fprintf(out, "'/>\n</svg>\n");
}
int main(int argc, char** argv) {
const char* filename = "sierpinski_arrowhead.svg";
if (argc == 2)
filename = argv[1];
FILE* out = fopen(filename, "w");
if (!out) {
perror(filename);
return EXIT_FAILURE;
}
write_sierpinski_arrowhead(out, 600, 8);
fclose(out);
return EXIT_SUCCESS;
}
| t = { 'x': 20, 'y': 30, 'a': 60 }
def setup():
size(450, 400)
background(0, 0, 200)
stroke(-1)
sc(7, 400, -60)
def sc(o, l, a, s = t, X = 'x', Y = 'y', A = 'a', HALF = .5):
if o:
o -= 1
l *= HALF
sc(o, l, -a)[A] += a
sc(o, l, a)[A] += a
sc(o, l, -a)
else:
x, y = s[X], s[Y]
s[X] += cos(radians(s[A])) * l
s[Y] += sin(radians(s[A])) * l
line(x, y, s[X], s[Y])
return s
|
Write the same algorithm in Python as shown in this C implementation. | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
static int badHrs, maxBadHrs;
static double hrsTot = 0.0;
static int rdgsTot = 0;
char bhEndDate[40];
int mungeLine( char *line, int lno, FILE *fout )
{
char date[40], *tkn;
int dHrs, flag, hrs2, hrs;
double hrsSum;
int hrsCnt = 0;
double avg;
tkn = strtok(line, ".");
if (tkn) {
int n = sscanf(tkn, "%s %d", &date, &hrs2);
if (n<2) {
printf("badly formated line - %d %s\n", lno, tkn);
return 0;
}
hrsSum = 0.0;
while( tkn= strtok(NULL, ".")) {
n = sscanf(tkn,"%d %d %d", &dHrs, &flag, &hrs);
if (n>=2) {
if (flag > 0) {
hrsSum += 1.0*hrs2 + .001*dHrs;
hrsCnt += 1;
if (maxBadHrs < badHrs) {
maxBadHrs = badHrs;
strcpy(bhEndDate, date);
}
badHrs = 0;
}
else {
badHrs += 1;
}
hrs2 = hrs;
}
else {
printf("bad file syntax line %d: %s\n",lno, tkn);
}
}
avg = (hrsCnt > 0)? hrsSum/hrsCnt : 0.0;
fprintf(fout, "%s Reject: %2d Accept: %2d Average: %7.3f\n",
date, 24-hrsCnt, hrsCnt, hrsSum/hrsCnt);
hrsTot += hrsSum;
rdgsTot += hrsCnt;
}
return 1;
}
int main()
{
FILE *infile, *outfile;
int lineNo = 0;
char line[512];
const char *ifilename = "readings.txt";
outfile = fopen("V0.txt", "w");
infile = fopen(ifilename, "rb");
if (!infile) {
printf("Can't open %s\n", ifilename);
exit(1);
}
while (NULL != fgets(line, 512, infile)) {
lineNo += 1;
if (0 == mungeLine(line, lineNo, outfile))
printf("Bad line at %d",lineNo);
}
fclose(infile);
fprintf(outfile, "File: %s\n", ifilename);
fprintf(outfile, "Total: %.3f\n", hrsTot);
fprintf(outfile, "Readings: %d\n", rdgsTot);
fprintf(outfile, "Average: %.3f\n", hrsTot/rdgsTot);
fprintf(outfile, "\nMaximum number of consecutive bad readings is %d\n", maxBadHrs);
fprintf(outfile, "Ends on date %s\n", bhEndDate);
fclose(outfile);
return 0;
}
| import fileinput
import sys
nodata = 0;
nodata_max=-1;
nodata_maxline=[];
tot_file = 0
num_file = 0
infiles = sys.argv[1:]
for line in fileinput.input():
tot_line=0;
num_line=0;
field = line.split()
date = field[0]
data = [float(f) for f in field[1::2]]
flags = [int(f) for f in field[2::2]]
for datum, flag in zip(data, flags):
if flag<1:
nodata += 1
else:
if nodata_max==nodata and nodata>0:
nodata_maxline.append(date)
if nodata_max<nodata and nodata>0:
nodata_max=nodata
nodata_maxline=[date]
nodata=0;
tot_line += datum
num_line += 1
tot_file += tot_line
num_file += num_line
print "Line: %11s Reject: %2i Accept: %2i Line_tot: %10.3f Line_avg: %10.3f" % (
date,
len(data) -num_line,
num_line, tot_line,
tot_line/num_line if (num_line>0) else 0)
print ""
print "File(s) = %s" % (", ".join(infiles),)
print "Total = %10.3f" % (tot_file,)
print "Readings = %6i" % (num_file,)
print "Average = %10.3f" % (tot_file / num_file,)
print "\nMaximum run(s) of %i consecutive false readings ends at line starting with date(s): %s" % (
nodata_max, ", ".join(nodata_maxline))
|
Write the same algorithm in Python as shown in this C implementation. | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/md5.h>
const char *string = "The quick brown fox jumped over the lazy dog's back";
int main()
{
int i;
unsigned char result[MD5_DIGEST_LENGTH];
MD5(string, strlen(string), result);
for(i = 0; i < MD5_DIGEST_LENGTH; i++)
printf("%02x", result[i]);
printf("\n");
return EXIT_SUCCESS;
}
| >>> import hashlib
>>>
>>> tests = (
(b"", 'd41d8cd98f00b204e9800998ecf8427e'),
(b"a", '0cc175b9c0f1b6a831c399e269772661'),
(b"abc", '900150983cd24fb0d6963f7d28e17f72'),
(b"message digest", 'f96b697d7cb7938d525a2f31aaf161d0'),
(b"abcdefghijklmnopqrstuvwxyz", 'c3fcd3d76192e4007dfb496cca67e13b'),
(b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", 'd174ab98d277d9f5a5611c2c9f419d9f'),
(b"12345678901234567890123456789012345678901234567890123456789012345678901234567890", '57edf4a22be3c955ac49da2e2107b67a') )
>>> for text, golden in tests: assert hashlib.md5(text).hexdigest() == golden
>>>
|
Keep all operations the same but rewrite the snippet in Python. | #include<stdlib.h>
#include<string.h>
#include<stdio.h>
unsigned long long bruteForceProperDivisorSum(unsigned long long n){
unsigned long long i,sum = 0;
for(i=1;i<(n+1)/2;i++)
if(n%i==0 && n!=i)
sum += i;
return sum;
}
void printSeries(unsigned long long* arr,int size,char* type){
int i;
printf("\nInteger : %llu, Type : %s, Series : ",arr[0],type);
for(i=0;i<size-1;i++)
printf("%llu, ",arr[i]);
printf("%llu",arr[i]);
}
void aliquotClassifier(unsigned long long n){
unsigned long long arr[16];
int i,j;
arr[0] = n;
for(i=1;i<16;i++){
arr[i] = bruteForceProperDivisorSum(arr[i-1]);
if(arr[i]==0||arr[i]==n||(arr[i]==arr[i-1] && arr[i]!=n)){
printSeries(arr,i+1,(arr[i]==0)?"Terminating":(arr[i]==n && i==1)?"Perfect":(arr[i]==n && i==2)?"Amicable":(arr[i]==arr[i-1] && arr[i]!=n)?"Aspiring":"Sociable");
return;
}
for(j=1;j<i;j++){
if(arr[j]==arr[i]){
printSeries(arr,i+1,"Cyclic");
return;
}
}
}
printSeries(arr,i+1,"Non-Terminating");
}
void processFile(char* fileName){
FILE* fp = fopen(fileName,"r");
char str[21];
while(fgets(str,21,fp)!=NULL)
aliquotClassifier(strtoull(str,(char**)NULL,10));
fclose(fp);
}
int main(int argC,char* argV[])
{
if(argC!=2)
printf("Usage : %s <positive integer>",argV[0]);
else{
if(strchr(argV[1],'.')!=NULL)
processFile(argV[1]);
else
aliquotClassifier(strtoull(argV[1],(char**)NULL,10));
}
return 0;
}
| from proper_divisors import proper_divs
from functools import lru_cache
@lru_cache()
def pdsum(n):
return sum(proper_divs(n))
def aliquot(n, maxlen=16, maxterm=2**47):
if n == 0:
return 'terminating', [0]
s, slen, new = [n], 1, n
while slen <= maxlen and new < maxterm:
new = pdsum(s[-1])
if new in s:
if s[0] == new:
if slen == 1:
return 'perfect', s
elif slen == 2:
return 'amicable', s
else:
return 'sociable of length %i' % slen, s
elif s[-1] == new:
return 'aspiring', s
else:
return 'cyclic back to %i' % new, s
elif new == 0:
return 'terminating', s + [0]
else:
s.append(new)
slen += 1
else:
return 'non-terminating', s
if __name__ == '__main__':
for n in range(1, 11):
print('%s: %r' % aliquot(n))
print()
for n in [11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, 15355717786080]:
print('%s: %r' % aliquot(n))
|
Write the same algorithm in Python as shown in this C implementation. | #include<stdlib.h>
#include<string.h>
#include<stdio.h>
unsigned long long bruteForceProperDivisorSum(unsigned long long n){
unsigned long long i,sum = 0;
for(i=1;i<(n+1)/2;i++)
if(n%i==0 && n!=i)
sum += i;
return sum;
}
void printSeries(unsigned long long* arr,int size,char* type){
int i;
printf("\nInteger : %llu, Type : %s, Series : ",arr[0],type);
for(i=0;i<size-1;i++)
printf("%llu, ",arr[i]);
printf("%llu",arr[i]);
}
void aliquotClassifier(unsigned long long n){
unsigned long long arr[16];
int i,j;
arr[0] = n;
for(i=1;i<16;i++){
arr[i] = bruteForceProperDivisorSum(arr[i-1]);
if(arr[i]==0||arr[i]==n||(arr[i]==arr[i-1] && arr[i]!=n)){
printSeries(arr,i+1,(arr[i]==0)?"Terminating":(arr[i]==n && i==1)?"Perfect":(arr[i]==n && i==2)?"Amicable":(arr[i]==arr[i-1] && arr[i]!=n)?"Aspiring":"Sociable");
return;
}
for(j=1;j<i;j++){
if(arr[j]==arr[i]){
printSeries(arr,i+1,"Cyclic");
return;
}
}
}
printSeries(arr,i+1,"Non-Terminating");
}
void processFile(char* fileName){
FILE* fp = fopen(fileName,"r");
char str[21];
while(fgets(str,21,fp)!=NULL)
aliquotClassifier(strtoull(str,(char**)NULL,10));
fclose(fp);
}
int main(int argC,char* argV[])
{
if(argC!=2)
printf("Usage : %s <positive integer>",argV[0]);
else{
if(strchr(argV[1],'.')!=NULL)
processFile(argV[1]);
else
aliquotClassifier(strtoull(argV[1],(char**)NULL,10));
}
return 0;
}
| from proper_divisors import proper_divs
from functools import lru_cache
@lru_cache()
def pdsum(n):
return sum(proper_divs(n))
def aliquot(n, maxlen=16, maxterm=2**47):
if n == 0:
return 'terminating', [0]
s, slen, new = [n], 1, n
while slen <= maxlen and new < maxterm:
new = pdsum(s[-1])
if new in s:
if s[0] == new:
if slen == 1:
return 'perfect', s
elif slen == 2:
return 'amicable', s
else:
return 'sociable of length %i' % slen, s
elif s[-1] == new:
return 'aspiring', s
else:
return 'cyclic back to %i' % new, s
elif new == 0:
return 'terminating', s + [0]
else:
s.append(new)
slen += 1
else:
return 'non-terminating', s
if __name__ == '__main__':
for n in range(1, 11):
print('%s: %r' % aliquot(n))
print()
for n in [11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, 15355717786080]:
print('%s: %r' % aliquot(n))
|
Convert the following code from C to Python, ensuring the logic remains intact. | #include<stdlib.h>
#include<string.h>
#include<stdio.h>
unsigned long long bruteForceProperDivisorSum(unsigned long long n){
unsigned long long i,sum = 0;
for(i=1;i<(n+1)/2;i++)
if(n%i==0 && n!=i)
sum += i;
return sum;
}
void printSeries(unsigned long long* arr,int size,char* type){
int i;
printf("\nInteger : %llu, Type : %s, Series : ",arr[0],type);
for(i=0;i<size-1;i++)
printf("%llu, ",arr[i]);
printf("%llu",arr[i]);
}
void aliquotClassifier(unsigned long long n){
unsigned long long arr[16];
int i,j;
arr[0] = n;
for(i=1;i<16;i++){
arr[i] = bruteForceProperDivisorSum(arr[i-1]);
if(arr[i]==0||arr[i]==n||(arr[i]==arr[i-1] && arr[i]!=n)){
printSeries(arr,i+1,(arr[i]==0)?"Terminating":(arr[i]==n && i==1)?"Perfect":(arr[i]==n && i==2)?"Amicable":(arr[i]==arr[i-1] && arr[i]!=n)?"Aspiring":"Sociable");
return;
}
for(j=1;j<i;j++){
if(arr[j]==arr[i]){
printSeries(arr,i+1,"Cyclic");
return;
}
}
}
printSeries(arr,i+1,"Non-Terminating");
}
void processFile(char* fileName){
FILE* fp = fopen(fileName,"r");
char str[21];
while(fgets(str,21,fp)!=NULL)
aliquotClassifier(strtoull(str,(char**)NULL,10));
fclose(fp);
}
int main(int argC,char* argV[])
{
if(argC!=2)
printf("Usage : %s <positive integer>",argV[0]);
else{
if(strchr(argV[1],'.')!=NULL)
processFile(argV[1]);
else
aliquotClassifier(strtoull(argV[1],(char**)NULL,10));
}
return 0;
}
| from proper_divisors import proper_divs
from functools import lru_cache
@lru_cache()
def pdsum(n):
return sum(proper_divs(n))
def aliquot(n, maxlen=16, maxterm=2**47):
if n == 0:
return 'terminating', [0]
s, slen, new = [n], 1, n
while slen <= maxlen and new < maxterm:
new = pdsum(s[-1])
if new in s:
if s[0] == new:
if slen == 1:
return 'perfect', s
elif slen == 2:
return 'amicable', s
else:
return 'sociable of length %i' % slen, s
elif s[-1] == new:
return 'aspiring', s
else:
return 'cyclic back to %i' % new, s
elif new == 0:
return 'terminating', s + [0]
else:
s.append(new)
slen += 1
else:
return 'non-terminating', s
if __name__ == '__main__':
for n in range(1, 11):
print('%s: %r' % aliquot(n))
print()
for n in [11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, 15355717786080]:
print('%s: %r' % aliquot(n))
|
Convert this C snippet to Python and keep its semantics consistent. | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
struct tm ts;
time_t t;
const char *d = "March 7 2009 7:30pm EST";
strptime(d, "%B %d %Y %I:%M%p %Z", &ts);
t = mktime(&ts);
t += 12*60*60;
printf("%s", ctime(&t));
return EXIT_SUCCESS;
}
| import datetime
def mt():
datime1="March 7 2009 7:30pm EST"
formatting = "%B %d %Y %I:%M%p "
datime2 = datime1[:-3]
tdelta = datetime.timedelta(hours=12)
s3 = datetime.datetime.strptime(datime2, formatting)
datime2 = s3+tdelta
print datime2.strftime("%B %d %Y %I:%M%p %Z") + datime1[-3:]
mt()
|
Generate a Python translation of this C snippet without changing its computational steps. | >>>>>,----------[++++++++
++[->+>+<<]>+>[-<<+>>]+++
+++++[-<------>]>>+>,----
------<<+[->>>>>+<<<<<]>>
]>>>[<<<<[<<<[->>+<<[->+>
[-]<<]]>[-<+>]>[-<<<.>>>>
->>>>>[>>>>>]<-<<<<[<<<<<
]+<]<<<<]>>>>>[>>>>>]<]
| from time import sleep
from threading import Timer
def sleepsort(values):
sleepsort.result = []
def add1(x):
sleepsort.result.append(x)
mx = values[0]
for v in values:
if mx < v: mx = v
Timer(v, add1, [v]).start()
sleep(mx+1)
return sleepsort.result
if __name__ == '__main__':
x = [3,2,4,7,3,6,9,1]
if sleepsort(x) == sorted(x):
print('sleep sort worked for:',x)
else:
print('sleep sort FAILED for:',x)
|
Translate the given C code snippet into Python without altering its behavior. | #include <stdlib.h>
#include <time.h>
#include <stdio.h>
int main() {
int a[10][10], i, j;
srand(time(NULL));
for (i = 0; i < 10; i++)
for (j = 0; j < 10; j++)
a[i][j] = rand() % 20 + 1;
for (i = 0; i < 10; i++) {
for (j = 0; j < 10; j++) {
printf(" %d", a[i][j]);
if (a[i][j] == 20)
goto Done;
}
printf("\n");
}
Done:
printf("\n");
return 0;
}
| from random import randint
def do_scan(mat):
for row in mat:
for item in row:
print item,
if item == 20:
print
return
print
print
mat = [[randint(1, 20) for x in xrange(10)] for y in xrange(10)]
do_scan(mat)
|
Write a version of this C function in Python with identical behavior. | #include <stdio.h>
#include <stdlib.h>
typedef unsigned long long xint;
typedef unsigned long ulong;
inline ulong gcd(ulong m, ulong n)
{
ulong t;
while (n) { t = n; n = m % n; m = t; }
return m;
}
int main()
{
ulong a, b, c, pytha = 0, prim = 0, max_p = 100;
xint aa, bb, cc;
for (a = 1; a <= max_p / 3; a++) {
aa = (xint)a * a;
printf("a = %lu\r", a);
fflush(stdout);
for (b = a + 1; b < max_p/2; b++) {
bb = (xint)b * b;
for (c = b + 1; c < max_p/2; c++) {
cc = (xint)c * c;
if (aa + bb < cc) break;
if (a + b + c > max_p) break;
if (aa + bb == cc) {
pytha++;
if (gcd(a, b) == 1) prim++;
}
}
}
}
printf("Up to %lu, there are %lu triples, of which %lu are primitive\n",
max_p, pytha, prim);
return 0;
}
| from fractions import gcd
def pt1(maxperimeter=100):
trips = []
for a in range(1, maxperimeter):
aa = a*a
for b in range(a, maxperimeter-a+1):
bb = b*b
for c in range(b, maxperimeter-b-a+1):
cc = c*c
if a+b+c > maxperimeter or cc > aa + bb: break
if aa + bb == cc:
trips.append((a,b,c, gcd(a, b) == 1))
return trips
def pytrip(trip=(3,4,5),perim=100, prim=1):
a0, b0, c0 = a, b, c = sorted(trip)
t, firstprim = set(), prim>0
while a + b + c <= perim:
t.add((a, b, c, firstprim>0))
a, b, c, firstprim = a+a0, b+b0, c+c0, False
t2 = set()
for a, b, c, firstprim in t:
a2, a5, b2, b5, c2, c3, c7 = a*2, a*5, b*2, b*5, c*2, c*3, c*7
if a5 - b5 + c7 <= perim:
t2 |= pytrip(( a - b2 + c2, a2 - b + c2, a2 - b2 + c3), perim, firstprim)
if a5 + b5 + c7 <= perim:
t2 |= pytrip(( a + b2 + c2, a2 + b + c2, a2 + b2 + c3), perim, firstprim)
if -a5 + b5 + c7 <= perim:
t2 |= pytrip((-a + b2 + c2, -a2 + b + c2, -a2 + b2 + c3), perim, firstprim)
return t | t2
def pt2(maxperimeter=100):
trips = pytrip((3,4,5), maxperimeter, 1)
return trips
def printit(maxperimeter=100, pt=pt1):
trips = pt(maxperimeter)
print(" Up to a perimeter of %i there are %i triples, of which %i are primitive"
% (maxperimeter,
len(trips),
len([prim for a,b,c,prim in trips if prim])))
for algo, mn, mx in ((pt1, 250, 2500), (pt2, 500, 20000)):
print(algo.__doc__)
for maxperimeter in range(mn, mx+1, mn):
printit(maxperimeter, algo)
|
Generate a Python translation of this C snippet without changing its computational steps. | #include <stdio.h>
#include <stdlib.h>
typedef unsigned long long xint;
typedef unsigned long ulong;
inline ulong gcd(ulong m, ulong n)
{
ulong t;
while (n) { t = n; n = m % n; m = t; }
return m;
}
int main()
{
ulong a, b, c, pytha = 0, prim = 0, max_p = 100;
xint aa, bb, cc;
for (a = 1; a <= max_p / 3; a++) {
aa = (xint)a * a;
printf("a = %lu\r", a);
fflush(stdout);
for (b = a + 1; b < max_p/2; b++) {
bb = (xint)b * b;
for (c = b + 1; c < max_p/2; c++) {
cc = (xint)c * c;
if (aa + bb < cc) break;
if (a + b + c > max_p) break;
if (aa + bb == cc) {
pytha++;
if (gcd(a, b) == 1) prim++;
}
}
}
}
printf("Up to %lu, there are %lu triples, of which %lu are primitive\n",
max_p, pytha, prim);
return 0;
}
| from fractions import gcd
def pt1(maxperimeter=100):
trips = []
for a in range(1, maxperimeter):
aa = a*a
for b in range(a, maxperimeter-a+1):
bb = b*b
for c in range(b, maxperimeter-b-a+1):
cc = c*c
if a+b+c > maxperimeter or cc > aa + bb: break
if aa + bb == cc:
trips.append((a,b,c, gcd(a, b) == 1))
return trips
def pytrip(trip=(3,4,5),perim=100, prim=1):
a0, b0, c0 = a, b, c = sorted(trip)
t, firstprim = set(), prim>0
while a + b + c <= perim:
t.add((a, b, c, firstprim>0))
a, b, c, firstprim = a+a0, b+b0, c+c0, False
t2 = set()
for a, b, c, firstprim in t:
a2, a5, b2, b5, c2, c3, c7 = a*2, a*5, b*2, b*5, c*2, c*3, c*7
if a5 - b5 + c7 <= perim:
t2 |= pytrip(( a - b2 + c2, a2 - b + c2, a2 - b2 + c3), perim, firstprim)
if a5 + b5 + c7 <= perim:
t2 |= pytrip(( a + b2 + c2, a2 + b + c2, a2 + b2 + c3), perim, firstprim)
if -a5 + b5 + c7 <= perim:
t2 |= pytrip((-a + b2 + c2, -a2 + b + c2, -a2 + b2 + c3), perim, firstprim)
return t | t2
def pt2(maxperimeter=100):
trips = pytrip((3,4,5), maxperimeter, 1)
return trips
def printit(maxperimeter=100, pt=pt1):
trips = pt(maxperimeter)
print(" Up to a perimeter of %i there are %i triples, of which %i are primitive"
% (maxperimeter,
len(trips),
len([prim for a,b,c,prim in trips if prim])))
for algo, mn, mx in ((pt1, 250, 2500), (pt2, 500, 20000)):
print(algo.__doc__)
for maxperimeter in range(mn, mx+1, mn):
printit(maxperimeter, algo)
|
Maintain the same structure and functionality when rewriting this code in Python. | #include <stdio.h>
#include <stdlib.h>
struct list_node {int x; struct list_node *next;};
typedef struct list_node node;
node * uniq(int *a, unsigned alen)
{if (alen == 0) return NULL;
node *start = malloc(sizeof(node));
if (start == NULL) exit(EXIT_FAILURE);
start->x = a[0];
start->next = NULL;
for (int i = 1 ; i < alen ; ++i)
{node *n = start;
for (;; n = n->next)
{if (a[i] == n->x) break;
if (n->next == NULL)
{n->next = malloc(sizeof(node));
n = n->next;
if (n == NULL) exit(EXIT_FAILURE);
n->x = a[i];
n->next = NULL;
break;}}}
return start;}
int main(void)
{int a[] = {1, 2, 1, 4, 5, 2, 15, 1, 3, 4};
for (node *n = uniq(a, 10) ; n != NULL ; n = n->next)
printf("%d ", n->x);
puts("");
return 0;}
| items = [1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd']
unique = list(set(items))
|
Rewrite the snippet below in Python so it works the same as the original C code. | #include <stdio.h>
#include <stdlib.h>
int main()
{
char *a = malloc(2), *b = 0, *x, c;
int cnt, len = 1;
for (sprintf(a, "1"); (b = realloc(b, len * 2 + 1)); a = b, b = x) {
puts(x = a);
for (len = 0, cnt = 1; (c = *a); ) {
if (c == *++a)
cnt++;
else if (c) {
len += sprintf(b + len, "%d%c", cnt, c);
cnt = 1;
}
}
}
return 0;
}
| def lookandsay(number):
result = ""
repeat = number[0]
number = number[1:]+" "
times = 1
for actual in number:
if actual != repeat:
result += str(times)+repeat
times = 1
repeat = actual
else:
times += 1
return result
num = "1"
for i in range(10):
print num
num = lookandsay(num)
|
Transform the following C implementation into Python, maintaining the same output and logic. | #include <stdio.h>
#include <stdlib.h>
#define DECL_STACK_TYPE(type, name) \
typedef struct stk_##name##_t{type *buf; size_t alloc,len;}*stk_##name; \
stk_##name stk_##name##_create(size_t init_size) { \
stk_##name s; if (!init_size) init_size = 4; \
s = malloc(sizeof(struct stk_##name##_t)); \
if (!s) return 0; \
s->buf = malloc(sizeof(type) * init_size); \
if (!s->buf) { free(s); return 0; } \
s->len = 0, s->alloc = init_size; \
return s; } \
int stk_##name##_push(stk_##name s, type item) { \
type *tmp; \
if (s->len >= s->alloc) { \
tmp = realloc(s->buf, s->alloc*2*sizeof(type)); \
if (!tmp) return -1; s->buf = tmp; \
s->alloc *= 2; } \
s->buf[s->len++] = item; \
return s->len; } \
type stk_##name##_pop(stk_##name s) { \
type tmp; \
if (!s->len) abort(); \
tmp = s->buf[--s->len]; \
if (s->len * 2 <= s->alloc && s->alloc >= 8) { \
s->alloc /= 2; \
s->buf = realloc(s->buf, s->alloc * sizeof(type));} \
return tmp; } \
void stk_##name##_delete(stk_##name s) { \
free(s->buf); free(s); }
#define stk_empty(s) (!(s)->len)
#define stk_size(s) ((s)->len)
DECL_STACK_TYPE(int, int)
int main(void)
{
int i;
stk_int stk = stk_int_create(0);
printf("pushing: ");
for (i = 'a'; i <= 'z'; i++) {
printf(" %c", i);
stk_int_push(stk, i);
}
printf("\nsize now: %d", stk_size(stk));
printf("\nstack is%s empty\n", stk_empty(stk) ? "" : " not");
printf("\npoppoing:");
while (stk_size(stk))
printf(" %c", stk_int_pop(stk));
printf("\nsize now: %d", stk_size(stk));
printf("\nstack is%s empty\n", stk_empty(stk) ? "" : " not");
stk_int_delete(stk);
return 0;
}
| from collections import deque
stack = deque()
stack.append(value)
value = stack.pop()
not stack
|
Change the following C code into Python without altering its purpose. |
#include<stdio.h>
int totient(int n){
int tot = n,i;
for(i=2;i*i<=n;i+=2){
if(n%i==0){
while(n%i==0)
n/=i;
tot-=tot/i;
}
if(i==2)
i=1;
}
if(n>1)
tot-=tot/n;
return tot;
}
int main()
{
int count = 0,n,tot;
printf(" n %c prime",237);
printf("\n---------------\n");
for(n=1;n<=25;n++){
tot = totient(n);
if(n-1 == tot)
count++;
printf("%2d %2d %s\n", n, tot, n-1 == tot?"True":"False");
}
printf("\nNumber of primes up to %6d =%4d\n", 25,count);
for(n = 26; n <= 100000; n++){
tot = totient(n);
if(tot == n-1)
count++;
if(n == 100 || n == 1000 || n%10000 == 0){
printf("\nNumber of primes up to %6d = %4d\n", n, count);
}
}
return 0;
}
| from math import gcd
def φ(n):
return sum(1 for k in range(1, n + 1) if gcd(n, k) == 1)
if __name__ == '__main__':
def is_prime(n):
return φ(n) == n - 1
for n in range(1, 26):
print(f" φ({n}) == {φ(n)}{', is prime' if is_prime(n) else ''}")
count = 0
for n in range(1, 10_000 + 1):
count += is_prime(n)
if n in {100, 1000, 10_000}:
print(f"Primes up to {n}: {count}")
|
Write a version of this C function in Python with identical behavior. | int a = 3;
if (a == 2) {
puts ("a is 2");
} else if (a == 3) {
puts ("a is 3");
} else {
puts("a is 4");
}
unless (a == 2) {
puts ("a is 2");
} else if (a == 3) {
puts ("a is 3");
} else {
puts("a is 4");
}
switch (a) {
case 2:
puts ("a is 2");
break;
case 3:
puts ("a is 3");
break;
case 4:
puts ("a is 4");
break;
default:
puts("is neither");
}
| if x == 0:
foo()
elif x == 1:
bar()
elif x == 2:
baz()
else:
qux()
match x:
0 => foo()
1 => bar()
2 => baz()
_ => qux()
(a) ? b : c
|
Change the programming language of this snippet from C to Python without modifying what it does. | #include <stdio.h>
#include <stdlib.h>
#include <gmp.h>
typedef struct frac_s *frac;
struct frac_s {
int n, d;
frac next;
};
frac parse(char *s)
{
int offset = 0;
struct frac_s h = {0}, *p = &h;
while (2 == sscanf(s, "%d/%d%n", &h.n, &h.d, &offset)) {
s += offset;
p = p->next = malloc(sizeof *p);
*p = h;
p->next = 0;
}
return h.next;
}
int run(int v, char *s)
{
frac n, p = parse(s);
mpz_t val;
mpz_init_set_ui(val, v);
loop: n = p;
if (mpz_popcount(val) == 1)
gmp_printf("\n[2^%d = %Zd]", mpz_scan1(val, 0), val);
else
gmp_printf(" %Zd", val);
for (n = p; n; n = n->next) {
if (!mpz_divisible_ui_p(val, n->d)) continue;
mpz_divexact_ui(val, val, n->d);
mpz_mul_ui(val, val, n->n);
goto loop;
}
gmp_printf("\nhalt: %Zd has no divisors\n", val);
mpz_clear(val);
while (p) {
n = p->next;
free(p);
p = n;
}
return 0;
}
int main(void)
{
run(2, "17/91 78/85 19/51 23/38 29/33 77/29 95/23 "
"77/19 1/17 11/13 13/11 15/14 15/2 55/1");
return 0;
}
| from fractions import Fraction
def fractran(n, fstring='17 / 91, 78 / 85, 19 / 51, 23 / 38, 29 / 33,'
'77 / 29, 95 / 23, 77 / 19, 1 / 17, 11 / 13,'
'13 / 11, 15 / 14, 15 / 2, 55 / 1'):
flist = [Fraction(f) for f in fstring.replace(' ', '').split(',')]
n = Fraction(n)
while True:
yield n.numerator
for f in flist:
if (n * f).denominator == 1:
break
else:
break
n *= f
if __name__ == '__main__':
n, m = 2, 15
print('First %i members of fractran(%i):\n ' % (m, n) +
', '.join(str(f) for f,i in zip(fractran(n), range(m))))
|
Convert the following code from C to Python, ensuring the logic remains intact. | #include <stdio.h>
#include <stdlib.h>
#include <gmp.h>
typedef struct frac_s *frac;
struct frac_s {
int n, d;
frac next;
};
frac parse(char *s)
{
int offset = 0;
struct frac_s h = {0}, *p = &h;
while (2 == sscanf(s, "%d/%d%n", &h.n, &h.d, &offset)) {
s += offset;
p = p->next = malloc(sizeof *p);
*p = h;
p->next = 0;
}
return h.next;
}
int run(int v, char *s)
{
frac n, p = parse(s);
mpz_t val;
mpz_init_set_ui(val, v);
loop: n = p;
if (mpz_popcount(val) == 1)
gmp_printf("\n[2^%d = %Zd]", mpz_scan1(val, 0), val);
else
gmp_printf(" %Zd", val);
for (n = p; n; n = n->next) {
if (!mpz_divisible_ui_p(val, n->d)) continue;
mpz_divexact_ui(val, val, n->d);
mpz_mul_ui(val, val, n->n);
goto loop;
}
gmp_printf("\nhalt: %Zd has no divisors\n", val);
mpz_clear(val);
while (p) {
n = p->next;
free(p);
p = n;
}
return 0;
}
int main(void)
{
run(2, "17/91 78/85 19/51 23/38 29/33 77/29 95/23 "
"77/19 1/17 11/13 13/11 15/14 15/2 55/1");
return 0;
}
| from fractions import Fraction
def fractran(n, fstring='17 / 91, 78 / 85, 19 / 51, 23 / 38, 29 / 33,'
'77 / 29, 95 / 23, 77 / 19, 1 / 17, 11 / 13,'
'13 / 11, 15 / 14, 15 / 2, 55 / 1'):
flist = [Fraction(f) for f in fstring.replace(' ', '').split(',')]
n = Fraction(n)
while True:
yield n.numerator
for f in flist:
if (n * f).denominator == 1:
break
else:
break
n *= f
if __name__ == '__main__':
n, m = 2, 15
print('First %i members of fractran(%i):\n ' % (m, n) +
', '.join(str(f) for f,i in zip(fractran(n), range(m))))
|
Convert this C snippet to Python and keep its semantics consistent. | #include <stdio.h>
#define SWAP(r,s) do{ t=r; r=s; s=t; } while(0)
void StoogeSort(int a[], int i, int j)
{
int t;
if (a[j] < a[i]) SWAP(a[i], a[j]);
if (j - i > 1)
{
t = (j - i + 1) / 3;
StoogeSort(a, i, j - t);
StoogeSort(a, i + t, j);
StoogeSort(a, i, j - t);
}
}
int main(int argc, char *argv[])
{
int nums[] = {1, 4, 5, 3, -6, 3, 7, 10, -2, -5, 7, 5, 9, -3, 7};
int i, n;
n = sizeof(nums)/sizeof(int);
StoogeSort(nums, 0, n-1);
for(i = 0; i <= n-1; i++)
printf("%5d", nums[i]);
return 0;
}
| >>> data = [1, 4, 5, 3, -6, 3, 7, 10, -2, -5, 7, 5, 9, -3, 7]
>>> def stoogesort(L, i=0, j=None):
if j is None:
j = len(L) - 1
if L[j] < L[i]:
L[i], L[j] = L[j], L[i]
if j - i > 1:
t = (j - i + 1) // 3
stoogesort(L, i , j-t)
stoogesort(L, i+t, j )
stoogesort(L, i , j-t)
return L
>>> stoogesort(data)
[-6, -5, -3, -2, 1, 3, 3, 4, 5, 5, 7, 7, 7, 9, 10]
|
Write a version of this C function in Python with identical behavior. | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BALLS 1024
int n, w, h = 45, *x, *y, cnt = 0;
char *b;
#define B(y, x) b[(y)*w + x]
#define C(y, x) ' ' == b[(y)*w + x]
#define V(i) B(y[i], x[i])
inline int rnd(int a) { return (rand()/(RAND_MAX/a))%a; }
void show_board()
{
int i, j;
for (puts("\033[H"), i = 0; i < h; i++, putchar('\n'))
for (j = 0; j < w; j++, putchar(' '))
printf(B(i, j) == '*' ?
C(i - 1, j) ? "\033[32m%c\033[m" :
"\033[31m%c\033[m" : "%c", B(i, j));
}
void init()
{
int i, j;
puts("\033[H\033[J");
b = malloc(w * h);
memset(b, ' ', w * h);
x = malloc(sizeof(int) * BALLS * 2);
y = x + BALLS;
for (i = 0; i < n; i++)
for (j = -i; j <= i; j += 2)
B(2 * i+2, j + w/2) = '*';
srand(time(0));
}
void move(int idx)
{
int xx = x[idx], yy = y[idx], c, kill = 0, sl = 3, o = 0;
if (yy < 0) return;
if (yy == h - 1) { y[idx] = -1; return; }
switch(c = B(yy + 1, xx)) {
case ' ': yy++; break;
case '*': sl = 1;
default: if (xx < w - 1 && C(yy, xx + 1) && C(yy + 1, xx + 1))
if (!rnd(sl++)) o = 1;
if (xx && C(yy, xx - 1) && C(yy + 1, xx - 1))
if (!rnd(sl++)) o = -1;
if (!o) kill = 1;
xx += o;
}
c = V(idx); V(idx) = ' ';
idx[y] = yy, idx[x] = xx;
B(yy, xx) = c;
if (kill) idx[y] = -1;
}
int run(void)
{
static int step = 0;
int i;
for (i = 0; i < cnt; i++) move(i);
if (2 == ++step && cnt < BALLS) {
step = 0;
x[cnt] = w/2;
y[cnt] = 0;
if (V(cnt) != ' ') return 0;
V(cnt) = rnd(80) + 43;
cnt++;
}
return 1;
}
int main(int c, char **v)
{
if (c < 2 || (n = atoi(v[1])) <= 3) n = 5;
if (n >= 20) n = 20;
w = n * 2 + 1;
init();
do { show_board(), usleep(60000); } while (run());
return 0;
}
|
import sys, os
import random
import time
def print_there(x, y, text):
sys.stdout.write("\x1b7\x1b[%d;%df%s\x1b8" % (x, y, text))
sys.stdout.flush()
class Ball():
def __init__(self):
self.x = 0
self.y = 0
def update(self):
self.x += random.randint(0,1)
self.y += 1
def fall(self):
self.y +=1
class Board():
def __init__(self, width, well_depth, N):
self.balls = []
self.fallen = [0] * (width + 1)
self.width = width
self.well_depth = well_depth
self.N = N
self.shift = 4
def update(self):
for ball in self.balls:
if ball.y < self.width:
ball.update()
elif ball.y < self.width + self.well_depth - self.fallen[ball.x]:
ball.fall()
elif ball.y == self.width + self.well_depth - self.fallen[ball.x]:
self.fallen[ball.x] += 1
else:
pass
def balls_on_board(self):
return len(self.balls) - sum(self.fallen)
def add_ball(self):
if(len(self.balls) <= self.N):
self.balls.append(Ball())
def print_board(self):
for y in range(self.width + 1):
for x in range(y):
print_there( y + 1 ,self.width - y + 2*x + self.shift + 1, "
def print_ball(self, ball):
if ball.y <= self.width:
x = self.width - ball.y + 2*ball.x + self.shift
else:
x = 2*ball.x + self.shift
y = ball.y + 1
print_there(y, x, "*")
def print_all(self):
print(chr(27) + "[2J")
self.print_board();
for ball in self.balls:
self.print_ball(ball)
def main():
board = Board(width = 15, well_depth = 5, N = 10)
board.add_ball()
while(board.balls_on_board() > 0):
board.print_all()
time.sleep(0.25)
board.update()
board.print_all()
time.sleep(0.25)
board.update()
board.add_ball()
if __name__=="__main__":
main()
|
Ensure the translated Python code behaves exactly like the original C snippet. | #include <stdio.h>
int circle_sort_inner(int *start, int *end)
{
int *p, *q, t, swapped;
if (start == end) return 0;
for (swapped = 0, p = start, q = end; p<q || (p==q && ++q); p++, q--)
if (*p > *q)
t = *p, *p = *q, *q = t, swapped = 1;
return swapped | circle_sort_inner(start, q) | circle_sort_inner(p, end);
}
void circle_sort(int *x, int n)
{
do {
int i;
for (i = 0; i < n; i++) printf("%d ", x[i]);
putchar('\n');
} while (circle_sort_inner(x, x + (n - 1)));
}
int main(void)
{
int x[] = {5, -1, 101, -4, 0, 1, 8, 6, 2, 3};
circle_sort(x, sizeof(x) / sizeof(*x));
return 0;
}
|
def circle_sort_backend(A:list, L:int, R:int)->'sort A in place, returning the number of swaps':
n = R-L
if n < 2:
return 0
swaps = 0
m = n//2
for i in range(m):
if A[R-(i+1)] < A[L+i]:
(A[R-(i+1)], A[L+i],) = (A[L+i], A[R-(i+1)],)
swaps += 1
if (n & 1) and (A[L+m] < A[L+m-1]):
(A[L+m-1], A[L+m],) = (A[L+m], A[L+m-1],)
swaps += 1
return swaps + circle_sort_backend(A, L, L+m) + circle_sort_backend(A, L+m, R)
def circle_sort(L:list)->'sort A in place, returning the number of swaps':
swaps = 0
s = 1
while s:
s = circle_sort_backend(L, 0, len(L))
swaps += s
return swaps
if __name__ == '__main__':
from random import shuffle
for i in range(309):
L = list(range(i))
M = L[:]
shuffle(L)
N = L[:]
circle_sort(L)
if L != M:
print(len(L))
print(N)
print(L)
|
Port the following code from C to Python with equivalent syntax and logic. | #include<graphics.h>
#include<stdlib.h>
#include<stdio.h>
typedef struct{
int row, col;
}cell;
int ROW,COL,SUM=0;
unsigned long raiseTo(int base,int power){
if(power==0)
return 1;
else
return base*raiseTo(base,power-1);
}
cell* kroneckerProduct(char* inputFile,int power){
FILE* fp = fopen(inputFile,"r");
int i,j,k,l;
unsigned long prod;
int** matrix;
cell *coreList,*tempList,*resultList;
fscanf(fp,"%d%d",&ROW,&COL);
matrix = (int**)malloc(ROW*sizeof(int*));
for(i=0;i<ROW;i++){
matrix[i] = (int*)malloc(COL*sizeof(int));
for(j=0;j<COL;j++){
fscanf(fp,"%d",&matrix[i][j]);
if(matrix[i][j]==1)
SUM++;
}
}
coreList = (cell*)malloc(SUM*sizeof(cell));
resultList = (cell*)malloc(SUM*sizeof(cell));
k = 0;
for(i=0;i<ROW;i++){
for(j=0;j<COL;j++){
if(matrix[i][j]==1){
coreList[k].row = i+1;
coreList[k].col = j+1;
resultList[k].row = i+1;
resultList[k].col = j+1;
k++;
}
}
}
prod = k;
for(i=2;i<=power;i++){
tempList = (cell*)malloc(prod*k*sizeof(cell));
l = 0;
for(j=0;j<prod;j++){
for(k=0;k<SUM;k++){
tempList[l].row = (resultList[j].row-1)*ROW + coreList[k].row;
tempList[l].col = (resultList[j].col-1)*COL + coreList[k].col;
l++;
}
}
free(resultList);
prod *= k;
resultList = (cell*)malloc(prod*sizeof(cell));
for(j=0;j<prod;j++){
resultList[j].row = tempList[j].row;
resultList[j].col = tempList[j].col;
}
free(tempList);
}
return resultList;
}
int main(){
char fileName[100];
int power,i,length;
cell* resultList;
printf("Enter input file name : ");
scanf("%s",fileName);
printf("Enter power : ");
scanf("%d",&power);
resultList = kroneckerProduct(fileName,power);
initwindow(raiseTo(ROW,power),raiseTo(COL,power),"Kronecker Product Fractal");
length = raiseTo(SUM,power);
for(i=0;i<length;i++){
putpixel(resultList[i].row,resultList[i].col,15);
}
getch();
closegraph();
return 0;
}
| import os
from PIL import Image
def imgsave(path, arr):
w, h = len(arr), len(arr[0])
img = Image.new('1', (w, h))
for x in range(w):
for y in range(h):
img.putpixel((x, y), arr[x][y])
img.save(path)
def get_shape(mat):
return len(mat), len(mat[0])
def kron(matrix1, matrix2):
final_list = []
count = len(matrix2)
for elem1 in matrix1:
for i in range(count):
sub_list = []
for num1 in elem1:
for num2 in matrix2[i]:
sub_list.append(num1 * num2)
final_list.append(sub_list)
return final_list
def kronpow(mat):
matrix = mat
while True:
yield matrix
matrix = kron(mat, matrix)
def fractal(name, mat, order=6):
path = os.path.join('fractals', name)
os.makedirs(path, exist_ok=True)
fgen = kronpow(mat)
print(name)
for i in range(order):
p = os.path.join(path, f'{i}.jpg')
print('Calculating n =', i, end='\t', flush=True)
mat = next(fgen)
imgsave(p, mat)
x, y = get_shape(mat)
print('Saved as', x, 'x', y, 'image', p)
test1 = [
[0, 1, 0],
[1, 1, 1],
[0, 1, 0]
]
test2 = [
[1, 1, 1],
[1, 0, 1],
[1, 1, 1]
]
test3 = [
[1, 0, 1],
[0, 1, 0],
[1, 0, 1]
]
fractal('test1', test1)
fractal('test2', test2)
fractal('test3', test3)
|
Keep all operations the same but rewrite the snippet in Python. | #include<graphics.h>
#include<stdlib.h>
#include<stdio.h>
typedef struct{
int row, col;
}cell;
int ROW,COL,SUM=0;
unsigned long raiseTo(int base,int power){
if(power==0)
return 1;
else
return base*raiseTo(base,power-1);
}
cell* kroneckerProduct(char* inputFile,int power){
FILE* fp = fopen(inputFile,"r");
int i,j,k,l;
unsigned long prod;
int** matrix;
cell *coreList,*tempList,*resultList;
fscanf(fp,"%d%d",&ROW,&COL);
matrix = (int**)malloc(ROW*sizeof(int*));
for(i=0;i<ROW;i++){
matrix[i] = (int*)malloc(COL*sizeof(int));
for(j=0;j<COL;j++){
fscanf(fp,"%d",&matrix[i][j]);
if(matrix[i][j]==1)
SUM++;
}
}
coreList = (cell*)malloc(SUM*sizeof(cell));
resultList = (cell*)malloc(SUM*sizeof(cell));
k = 0;
for(i=0;i<ROW;i++){
for(j=0;j<COL;j++){
if(matrix[i][j]==1){
coreList[k].row = i+1;
coreList[k].col = j+1;
resultList[k].row = i+1;
resultList[k].col = j+1;
k++;
}
}
}
prod = k;
for(i=2;i<=power;i++){
tempList = (cell*)malloc(prod*k*sizeof(cell));
l = 0;
for(j=0;j<prod;j++){
for(k=0;k<SUM;k++){
tempList[l].row = (resultList[j].row-1)*ROW + coreList[k].row;
tempList[l].col = (resultList[j].col-1)*COL + coreList[k].col;
l++;
}
}
free(resultList);
prod *= k;
resultList = (cell*)malloc(prod*sizeof(cell));
for(j=0;j<prod;j++){
resultList[j].row = tempList[j].row;
resultList[j].col = tempList[j].col;
}
free(tempList);
}
return resultList;
}
int main(){
char fileName[100];
int power,i,length;
cell* resultList;
printf("Enter input file name : ");
scanf("%s",fileName);
printf("Enter power : ");
scanf("%d",&power);
resultList = kroneckerProduct(fileName,power);
initwindow(raiseTo(ROW,power),raiseTo(COL,power),"Kronecker Product Fractal");
length = raiseTo(SUM,power);
for(i=0;i<length;i++){
putpixel(resultList[i].row,resultList[i].col,15);
}
getch();
closegraph();
return 0;
}
| import os
from PIL import Image
def imgsave(path, arr):
w, h = len(arr), len(arr[0])
img = Image.new('1', (w, h))
for x in range(w):
for y in range(h):
img.putpixel((x, y), arr[x][y])
img.save(path)
def get_shape(mat):
return len(mat), len(mat[0])
def kron(matrix1, matrix2):
final_list = []
count = len(matrix2)
for elem1 in matrix1:
for i in range(count):
sub_list = []
for num1 in elem1:
for num2 in matrix2[i]:
sub_list.append(num1 * num2)
final_list.append(sub_list)
return final_list
def kronpow(mat):
matrix = mat
while True:
yield matrix
matrix = kron(mat, matrix)
def fractal(name, mat, order=6):
path = os.path.join('fractals', name)
os.makedirs(path, exist_ok=True)
fgen = kronpow(mat)
print(name)
for i in range(order):
p = os.path.join(path, f'{i}.jpg')
print('Calculating n =', i, end='\t', flush=True)
mat = next(fgen)
imgsave(p, mat)
x, y = get_shape(mat)
print('Saved as', x, 'x', y, 'image', p)
test1 = [
[0, 1, 0],
[1, 1, 1],
[0, 1, 0]
]
test2 = [
[1, 1, 1],
[1, 0, 1],
[1, 1, 1]
]
test3 = [
[1, 0, 1],
[0, 1, 0],
[1, 0, 1]
]
fractal('test1', test1)
fractal('test2', test2)
fractal('test3', test3)
|
Translate the given C code snippet into Python without altering its behavior. | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <confini.h>
#define rosetta_uint8_t unsigned char
#define FALSE 0
#define TRUE 1
#define CONFIGS_TO_READ 5
#define INI_ARRAY_DELIMITER ','
struct configs {
char *fullname;
char *favouritefruit;
rosetta_uint8_t needspeeling;
rosetta_uint8_t seedsremoved;
char **otherfamily;
size_t otherfamily_len;
size_t _configs_left_;
};
static char ** make_array (size_t * arrlen, const char * src, const size_t buffsize, IniFormat ini_format) {
*arrlen = ini_array_get_length(src, INI_ARRAY_DELIMITER, ini_format);
char ** const dest = *arrlen ? (char **) malloc(*arrlen * sizeof(char *) + buffsize) : NULL;
if (!dest) { return NULL; }
memcpy(dest + *arrlen, src, buffsize);
char * iter = (char *) (dest + *arrlen);
for (size_t idx = 0; idx < *arrlen; idx++) {
dest[idx] = ini_array_release(&iter, INI_ARRAY_DELIMITER, ini_format);
ini_string_parse(dest[idx], ini_format);
}
return dest;
}
static int configs_member_handler (IniDispatch *this, void *v_confs) {
struct configs *confs = (struct configs *) v_confs;
if (this->type != INI_KEY) {
return 0;
}
if (ini_string_match_si("FULLNAME", this->data, this->format)) {
if (confs->fullname) { return 0; }
this->v_len = ini_string_parse(this->value, this->format);
confs->fullname = strndup(this->value, this->v_len);
confs->_configs_left_--;
} else if (ini_string_match_si("FAVOURITEFRUIT", this->data, this->format)) {
if (confs->favouritefruit) { return 0; }
this->v_len = ini_string_parse(this->value, this->format);
confs->favouritefruit = strndup(this->value, this->v_len);
confs->_configs_left_--;
} else if (ini_string_match_si("NEEDSPEELING", this->data, this->format)) {
if (~confs->needspeeling & 0x80) { return 0; }
confs->needspeeling = ini_get_bool(this->value, TRUE);
confs->_configs_left_--;
} else if (ini_string_match_si("SEEDSREMOVED", this->data, this->format)) {
if (~confs->seedsremoved & 0x80) { return 0; }
confs->seedsremoved = ini_get_bool(this->value, TRUE);
confs->_configs_left_--;
} else if (!confs->otherfamily && ini_string_match_si("OTHERFAMILY", this->data, this->format)) {
if (confs->otherfamily) { return 0; }
this->v_len = ini_array_collapse(this->value, INI_ARRAY_DELIMITER, this->format);
confs->otherfamily = make_array(&confs->otherfamily_len, this->value, this->v_len + 1, this->format);
confs->_configs_left_--;
}
return !confs->_configs_left_;
}
static int populate_configs (struct configs * confs) {
IniFormat config_format = {
.delimiter_symbol = INI_ANY_SPACE,
.case_sensitive = FALSE,
.semicolon_marker = INI_IGNORE,
.hash_marker = INI_IGNORE,
.multiline_nodes = INI_NO_MULTILINE,
.section_paths = INI_NO_SECTIONS,
.no_single_quotes = FALSE,
.no_double_quotes = FALSE,
.no_spaces_in_names = TRUE,
.implicit_is_not_empty = TRUE,
.do_not_collapse_values = FALSE,
.preserve_empty_quotes = FALSE,
.disabled_after_space = TRUE,
.disabled_can_be_implicit = FALSE
};
*confs = (struct configs) { NULL, NULL, 0x80, 0x80, NULL, 0, CONFIGS_TO_READ };
if (load_ini_path("rosetta.conf", config_format, NULL, configs_member_handler, confs) & CONFINI_ERROR) {
fprintf(stderr, "Sorry, something went wrong :-(\n");
return 1;
}
confs->needspeeling &= 0x7F;
confs->seedsremoved &= 0x7F;
return 0;
}
int main () {
struct configs confs;
ini_global_set_implicit_value("YES", 0);
if (populate_configs(&confs)) {
return 1;
}
printf(
"Full name: %s\n"
"Favorite fruit: %s\n"
"Need spelling: %s\n"
"Seeds removed: %s\n",
confs.fullname,
confs.favouritefruit,
confs.needspeeling ? "True" : "False",
confs.seedsremoved ? "True" : "False"
);
for (size_t idx = 0; idx < confs.otherfamily_len; idx++) {
printf("Other family[%d]: %s\n", idx, confs.otherfamily[idx]);
}
#define FREE_NON_NULL(PTR) if (PTR) { free(PTR); }
FREE_NON_NULL(confs.fullname);
FREE_NON_NULL(confs.favouritefruit);
FREE_NON_NULL(confs.otherfamily);
return 0;
}
| def readconf(fn):
ret = {}
with file(fn) as fp:
for line in fp:
line = line.strip()
if not line or line.startswith('
boolval = True
if line.startswith(';'):
line = line.lstrip(';')
if len(line.split()) != 1: continue
boolval = False
bits = line.split(None, 1)
if len(bits) == 1:
k = bits[0]
v = boolval
else:
k, v = bits
ret[k.lower()] = v
return ret
if __name__ == '__main__':
import sys
conf = readconf(sys.argv[1])
for k, v in sorted(conf.items()):
print k, '=', v
|
Please provide an equivalent version of this C code in Python. | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <confini.h>
#define rosetta_uint8_t unsigned char
#define FALSE 0
#define TRUE 1
#define CONFIGS_TO_READ 5
#define INI_ARRAY_DELIMITER ','
struct configs {
char *fullname;
char *favouritefruit;
rosetta_uint8_t needspeeling;
rosetta_uint8_t seedsremoved;
char **otherfamily;
size_t otherfamily_len;
size_t _configs_left_;
};
static char ** make_array (size_t * arrlen, const char * src, const size_t buffsize, IniFormat ini_format) {
*arrlen = ini_array_get_length(src, INI_ARRAY_DELIMITER, ini_format);
char ** const dest = *arrlen ? (char **) malloc(*arrlen * sizeof(char *) + buffsize) : NULL;
if (!dest) { return NULL; }
memcpy(dest + *arrlen, src, buffsize);
char * iter = (char *) (dest + *arrlen);
for (size_t idx = 0; idx < *arrlen; idx++) {
dest[idx] = ini_array_release(&iter, INI_ARRAY_DELIMITER, ini_format);
ini_string_parse(dest[idx], ini_format);
}
return dest;
}
static int configs_member_handler (IniDispatch *this, void *v_confs) {
struct configs *confs = (struct configs *) v_confs;
if (this->type != INI_KEY) {
return 0;
}
if (ini_string_match_si("FULLNAME", this->data, this->format)) {
if (confs->fullname) { return 0; }
this->v_len = ini_string_parse(this->value, this->format);
confs->fullname = strndup(this->value, this->v_len);
confs->_configs_left_--;
} else if (ini_string_match_si("FAVOURITEFRUIT", this->data, this->format)) {
if (confs->favouritefruit) { return 0; }
this->v_len = ini_string_parse(this->value, this->format);
confs->favouritefruit = strndup(this->value, this->v_len);
confs->_configs_left_--;
} else if (ini_string_match_si("NEEDSPEELING", this->data, this->format)) {
if (~confs->needspeeling & 0x80) { return 0; }
confs->needspeeling = ini_get_bool(this->value, TRUE);
confs->_configs_left_--;
} else if (ini_string_match_si("SEEDSREMOVED", this->data, this->format)) {
if (~confs->seedsremoved & 0x80) { return 0; }
confs->seedsremoved = ini_get_bool(this->value, TRUE);
confs->_configs_left_--;
} else if (!confs->otherfamily && ini_string_match_si("OTHERFAMILY", this->data, this->format)) {
if (confs->otherfamily) { return 0; }
this->v_len = ini_array_collapse(this->value, INI_ARRAY_DELIMITER, this->format);
confs->otherfamily = make_array(&confs->otherfamily_len, this->value, this->v_len + 1, this->format);
confs->_configs_left_--;
}
return !confs->_configs_left_;
}
static int populate_configs (struct configs * confs) {
IniFormat config_format = {
.delimiter_symbol = INI_ANY_SPACE,
.case_sensitive = FALSE,
.semicolon_marker = INI_IGNORE,
.hash_marker = INI_IGNORE,
.multiline_nodes = INI_NO_MULTILINE,
.section_paths = INI_NO_SECTIONS,
.no_single_quotes = FALSE,
.no_double_quotes = FALSE,
.no_spaces_in_names = TRUE,
.implicit_is_not_empty = TRUE,
.do_not_collapse_values = FALSE,
.preserve_empty_quotes = FALSE,
.disabled_after_space = TRUE,
.disabled_can_be_implicit = FALSE
};
*confs = (struct configs) { NULL, NULL, 0x80, 0x80, NULL, 0, CONFIGS_TO_READ };
if (load_ini_path("rosetta.conf", config_format, NULL, configs_member_handler, confs) & CONFINI_ERROR) {
fprintf(stderr, "Sorry, something went wrong :-(\n");
return 1;
}
confs->needspeeling &= 0x7F;
confs->seedsremoved &= 0x7F;
return 0;
}
int main () {
struct configs confs;
ini_global_set_implicit_value("YES", 0);
if (populate_configs(&confs)) {
return 1;
}
printf(
"Full name: %s\n"
"Favorite fruit: %s\n"
"Need spelling: %s\n"
"Seeds removed: %s\n",
confs.fullname,
confs.favouritefruit,
confs.needspeeling ? "True" : "False",
confs.seedsremoved ? "True" : "False"
);
for (size_t idx = 0; idx < confs.otherfamily_len; idx++) {
printf("Other family[%d]: %s\n", idx, confs.otherfamily[idx]);
}
#define FREE_NON_NULL(PTR) if (PTR) { free(PTR); }
FREE_NON_NULL(confs.fullname);
FREE_NON_NULL(confs.favouritefruit);
FREE_NON_NULL(confs.otherfamily);
return 0;
}
| def readconf(fn):
ret = {}
with file(fn) as fp:
for line in fp:
line = line.strip()
if not line or line.startswith('
boolval = True
if line.startswith(';'):
line = line.lstrip(';')
if len(line.split()) != 1: continue
boolval = False
bits = line.split(None, 1)
if len(bits) == 1:
k = bits[0]
v = boolval
else:
k, v = bits
ret[k.lower()] = v
return ret
if __name__ == '__main__':
import sys
conf = readconf(sys.argv[1])
for k, v in sorted(conf.items()):
print k, '=', v
|
Generate a Python translation of this C snippet without changing its computational steps. | #include <stdlib.h>
#include <string.h>
#include <strings.h>
int mycmp(const void *s1, const void *s2)
{
const char *l = *(const char **)s1, *r = *(const char **)s2;
size_t ll = strlen(l), lr = strlen(r);
if (ll > lr) return -1;
if (ll < lr) return 1;
return strcasecmp(l, r);
}
int main()
{
const char *strings[] = {
"Here", "are", "some", "sample", "strings", "to", "be", "sorted" };
qsort(strings, sizeof(strings)/sizeof(*strings), sizeof(*strings), mycmp);
return 0;
}
| strings = "here are Some sample strings to be sorted".split()
def mykey(x):
return -len(x), x.upper()
print sorted(strings, key=mykey)
|
Keep all operations the same but rewrite the snippet in Python. | #include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <gmp.h>
bool is_prime(uint32_t n) {
if (n == 2)
return true;
if (n < 2 || n % 2 == 0)
return false;
for (uint32_t p = 3; p * p <= n; p += 2) {
if (n % p == 0)
return false;
}
return true;
}
uint32_t cycle(uint32_t n) {
uint32_t m = n, p = 1;
while (m >= 10) {
p *= 10;
m /= 10;
}
return m + 10 * (n % p);
}
bool is_circular_prime(uint32_t p) {
if (!is_prime(p))
return false;
uint32_t p2 = cycle(p);
while (p2 != p) {
if (p2 < p || !is_prime(p2))
return false;
p2 = cycle(p2);
}
return true;
}
void test_repunit(uint32_t digits) {
char* str = malloc(digits + 1);
if (str == 0) {
fprintf(stderr, "Out of memory\n");
exit(1);
}
memset(str, '1', digits);
str[digits] = 0;
mpz_t bignum;
mpz_init_set_str(bignum, str, 10);
free(str);
if (mpz_probab_prime_p(bignum, 10))
printf("R(%u) is probably prime.\n", digits);
else
printf("R(%u) is not prime.\n", digits);
mpz_clear(bignum);
}
int main() {
uint32_t p = 2;
printf("First 19 circular primes:\n");
for (int count = 0; count < 19; ++p) {
if (is_circular_prime(p)) {
if (count > 0)
printf(", ");
printf("%u", p);
++count;
}
}
printf("\n");
printf("Next 4 circular primes:\n");
uint32_t repunit = 1, digits = 1;
for (; repunit < p; ++digits)
repunit = 10 * repunit + 1;
mpz_t bignum;
mpz_init_set_ui(bignum, repunit);
for (int count = 0; count < 4; ) {
if (mpz_probab_prime_p(bignum, 15)) {
if (count > 0)
printf(", ");
printf("R(%u)", digits);
++count;
}
++digits;
mpz_mul_ui(bignum, bignum, 10);
mpz_add_ui(bignum, bignum, 1);
}
mpz_clear(bignum);
printf("\n");
test_repunit(5003);
test_repunit(9887);
test_repunit(15073);
test_repunit(25031);
test_repunit(35317);
test_repunit(49081);
return 0;
}
| import random
def is_Prime(n):
if n!=int(n):
return False
n=int(n)
if n==0 or n==1 or n==4 or n==6 or n==8 or n==9:
return False
if n==2 or n==3 or n==5 or n==7:
return True
s = 0
d = n-1
while d%2==0:
d>>=1
s+=1
assert(2**s * d == n-1)
def trial_composite(a):
if pow(a, d, n) == 1:
return False
for i in range(s):
if pow(a, 2**i * d, n) == n-1:
return False
return True
for i in range(8):
a = random.randrange(2, n)
if trial_composite(a):
return False
return True
def isPrime(n: int) -> bool:
if (n <= 1) :
return False
if (n <= 3) :
return True
if (n % 2 == 0 or n % 3 == 0) :
return False
i = 5
while(i * i <= n) :
if (n % i == 0 or n % (i + 2) == 0) :
return False
i = i + 6
return True
def rotations(n: int)-> set((int,)):
a = str(n)
return set(int(a[i:] + a[:i]) for i in range(len(a)))
def isCircular(n: int) -> bool:
return all(isPrime(int(o)) for o in rotations(n))
from itertools import product
def main():
result = [2, 3, 5, 7]
first = '137'
latter = '1379'
for i in range(1, 6):
s = set(int(''.join(a)) for a in product(first, *((latter,) * i)))
while s:
a = s.pop()
b = rotations(a)
if isCircular(a):
result.append(min(b))
s -= b
result.sort()
return result
assert [2, 3, 5, 7, 11, 13, 17, 37, 79, 113, 197, 199, 337, 1193, 3779, 11939, 19937, 193939, 199933] == main()
repunit = lambda n: int('1' * n)
def repmain(n: int) -> list:
result = []
i = 2
while len(result) < n:
if is_Prime(repunit(i)):
result.append(i)
i += 1
return result
assert [2, 19, 23, 317, 1031] == repmain(5)
|
Change the programming language of this snippet from C to Python without modifying what it does. | #include <stdlib.h>
#include <string.h>
#include <gtk/gtk.h>
const gchar *hello = "Hello World! ";
gint direction = -1;
gint cx=0;
gint slen=0;
GtkLabel *label;
void change_dir(GtkLayout *o, gpointer d)
{
direction = -direction;
}
gchar *rotateby(const gchar *t, gint q, gint l)
{
gint i, cl = l, j;
gchar *r = malloc(l+1);
for(i=q, j=0; cl > 0; cl--, i = (i + 1)%l, j++)
r[j] = t[i];
r[l] = 0;
return r;
}
gboolean scroll_it(gpointer data)
{
if ( direction > 0 )
cx = (cx + 1) % slen;
else
cx = (cx + slen - 1 ) % slen;
gchar *scrolled = rotateby(hello, cx, slen);
gtk_label_set_text(label, scrolled);
free(scrolled);
return TRUE;
}
int main(int argc, char **argv)
{
GtkWidget *win;
GtkButton *button;
PangoFontDescription *pd;
gtk_init(&argc, &argv);
win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_title(GTK_WINDOW(win), "Basic Animation");
g_signal_connect(G_OBJECT(win), "delete-event", gtk_main_quit, NULL);
label = (GtkLabel *)gtk_label_new(hello);
pd = pango_font_description_new();
pango_font_description_set_family(pd, "monospace");
gtk_widget_modify_font(GTK_WIDGET(label), pd);
button = (GtkButton *)gtk_button_new();
gtk_container_add(GTK_CONTAINER(button), GTK_WIDGET(label));
gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(button));
g_signal_connect(G_OBJECT(button), "clicked", G_CALLBACK(change_dir), NULL);
slen = strlen(hello);
g_timeout_add(125, scroll_it, NULL);
gtk_widget_show_all(GTK_WIDGET(win));
gtk_main();
return 0;
}
| txt = "Hello, world! "
left = True
def draw():
global txt
background(128)
text(txt, 10, height / 2)
if frameCount % 10 == 0:
if (left):
txt = rotate(txt, 1)
else:
txt = rotate(txt, -1)
println(txt)
def mouseReleased():
global left
left = not left
def rotate(text, startIdx):
rotated = text[startIdx:] + text[:startIdx]
return rotated
|
Convert the following code from C to Python, ensuring the logic remains intact. | #include <stdlib.h>
#include <string.h>
#include <gtk/gtk.h>
const gchar *hello = "Hello World! ";
gint direction = -1;
gint cx=0;
gint slen=0;
GtkLabel *label;
void change_dir(GtkLayout *o, gpointer d)
{
direction = -direction;
}
gchar *rotateby(const gchar *t, gint q, gint l)
{
gint i, cl = l, j;
gchar *r = malloc(l+1);
for(i=q, j=0; cl > 0; cl--, i = (i + 1)%l, j++)
r[j] = t[i];
r[l] = 0;
return r;
}
gboolean scroll_it(gpointer data)
{
if ( direction > 0 )
cx = (cx + 1) % slen;
else
cx = (cx + slen - 1 ) % slen;
gchar *scrolled = rotateby(hello, cx, slen);
gtk_label_set_text(label, scrolled);
free(scrolled);
return TRUE;
}
int main(int argc, char **argv)
{
GtkWidget *win;
GtkButton *button;
PangoFontDescription *pd;
gtk_init(&argc, &argv);
win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_title(GTK_WINDOW(win), "Basic Animation");
g_signal_connect(G_OBJECT(win), "delete-event", gtk_main_quit, NULL);
label = (GtkLabel *)gtk_label_new(hello);
pd = pango_font_description_new();
pango_font_description_set_family(pd, "monospace");
gtk_widget_modify_font(GTK_WIDGET(label), pd);
button = (GtkButton *)gtk_button_new();
gtk_container_add(GTK_CONTAINER(button), GTK_WIDGET(label));
gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(button));
g_signal_connect(G_OBJECT(button), "clicked", G_CALLBACK(change_dir), NULL);
slen = strlen(hello);
g_timeout_add(125, scroll_it, NULL);
gtk_widget_show_all(GTK_WIDGET(win));
gtk_main();
return 0;
}
| txt = "Hello, world! "
left = True
def draw():
global txt
background(128)
text(txt, 10, height / 2)
if frameCount % 10 == 0:
if (left):
txt = rotate(txt, 1)
else:
txt = rotate(txt, -1)
println(txt)
def mouseReleased():
global left
left = not left
def rotate(text, startIdx):
rotated = text[startIdx:] + text[:startIdx]
return rotated
|
Transform the following C implementation into Python, maintaining the same output and logic. | #include <stdio.h>
#include <limits.h>
#include <stdlib.h>
#include <time.h>
#define ARR_LEN(ARR) (sizeof ARR / sizeof *ARR)
#define RAND_RNG(M,N) (M + rand() / (RAND_MAX / (N - M + 1) + 1));
static void swap(unsigned *a, unsigned *b) {
unsigned tmp = *a;
*a = *b;
*b = tmp;
}
static void rad_sort_u(unsigned *from, unsigned *to, unsigned bit)
{
if (!bit || to < from + 1) return;
unsigned *ll = from, *rr = to - 1;
for (;;) {
while (ll < rr && !(*ll & bit)) ll++;
while (ll < rr && (*rr & bit)) rr--;
if (ll >= rr) break;
swap(ll, rr);
}
if (!(bit & *ll) && ll < to) ll++;
bit >>= 1;
rad_sort_u(from, ll, bit);
rad_sort_u(ll, to, bit);
}
static void radix_sort(int *a, const size_t len)
{
size_t i;
unsigned *x = (unsigned*) a;
for (i = 0; i < len; i++)
x[i] ^= INT_MIN;
rad_sort_u(x, x + len, INT_MIN);
for (i = 0; i < len; i++)
x[i] ^= INT_MIN;
}
int main(void)
{
srand(time(NULL));
int x[16];
for (size_t i = 0; i < ARR_LEN(x); i++)
x[i] = RAND_RNG(-128,127)
radix_sort(x, ARR_LEN(x));
for (size_t i = 0; i < ARR_LEN(x); i++)
printf("%d%c", x[i], i + 1 < ARR_LEN(x) ? ' ' : '\n');
}
|
from math import log
def getDigit(num, base, digit_num):
return (num // base ** digit_num) % base
def makeBlanks(size):
return [ [] for i in range(size) ]
def split(a_list, base, digit_num):
buckets = makeBlanks(base)
for num in a_list:
buckets[getDigit(num, base, digit_num)].append(num)
return buckets
def merge(a_list):
new_list = []
for sublist in a_list:
new_list.extend(sublist)
return new_list
def maxAbs(a_list):
return max(abs(num) for num in a_list)
def split_by_sign(a_list):
buckets = [[], []]
for num in a_list:
if num < 0:
buckets[0].append(num)
else:
buckets[1].append(num)
return buckets
def radixSort(a_list, base):
passes = int(round(log(maxAbs(a_list), base)) + 1)
new_list = list(a_list)
for digit_num in range(passes):
new_list = merge(split(new_list, base, digit_num))
return merge(split_by_sign(new_list))
|
Change the following C code into Python without altering its purpose. | for (int i = f + 1; i <= t; i ++) { e = e->nx = listNew(sizeof i, &i); }
| [(x,y,z) for x in xrange(1,n+1) for y in xrange(x,n+1) for z in xrange(y,n+1) if x**2 + y**2 == z**2]
|
Produce a language-to-language conversion: from C to Python, same semantics. | for (int i = f + 1; i <= t; i ++) { e = e->nx = listNew(sizeof i, &i); }
| [(x,y,z) for x in xrange(1,n+1) for y in xrange(x,n+1) for z in xrange(y,n+1) if x**2 + y**2 == z**2]
|
Produce a functionally identical Python code for the snippet given in C. | #include <stdio.h>
void selection_sort (int *a, int n) {
int i, j, m, t;
for (i = 0; i < n; i++) {
for (j = i, m = i; j < n; j++) {
if (a[j] < a[m]) {
m = j;
}
}
t = a[i];
a[i] = a[m];
a[m] = t;
}
}
int main () {
int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};
int n = sizeof a / sizeof a[0];
int i;
for (i = 0; i < n; i++)
printf("%d%s", a[i], i == n - 1 ? "\n" : " ");
selection_sort(a, n);
for (i = 0; i < n; i++)
printf("%d%s", a[i], i == n - 1 ? "\n" : " ");
return 0;
}
| def selection_sort(lst):
for i, e in enumerate(lst):
mn = min(range(i,len(lst)), key=lst.__getitem__)
lst[i], lst[mn] = lst[mn], e
return lst
|
Keep all operations the same but rewrite the snippet in Python. | #include <stdlib.h>
#include <stdio.h>
#define SWAP(a, b) (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b)))
int jacobi(unsigned long a, unsigned long n) {
if (a >= n) a %= n;
int result = 1;
while (a) {
while ((a & 1) == 0) {
a >>= 1;
if ((n & 7) == 3 || (n & 7) == 5) result = -result;
}
SWAP(a, n);
if ((a & 3) == 3 && (n & 3) == 3) result = -result;
a %= n;
}
if (n == 1) return result;
return 0;
}
void print_table(unsigned kmax, unsigned nmax) {
printf("n\\k|");
for (int k = 0; k <= kmax; ++k) printf("%'3u", k);
printf("\n----");
for (int k = 0; k <= kmax; ++k) printf("---");
putchar('\n');
for (int n = 1; n <= nmax; n += 2) {
printf("%-2u |", n);
for (int k = 0; k <= kmax; ++k)
printf("%'3d", jacobi(k, n));
putchar('\n');
}
}
int main() {
print_table(20, 21);
return 0;
}
| def jacobi(a, n):
if n <= 0:
raise ValueError("'n' must be a positive integer.")
if n % 2 == 0:
raise ValueError("'n' must be odd.")
a %= n
result = 1
while a != 0:
while a % 2 == 0:
a /= 2
n_mod_8 = n % 8
if n_mod_8 in (3, 5):
result = -result
a, n = n, a
if a % 4 == 3 and n % 4 == 3:
result = -result
a %= n
if n == 1:
return result
else:
return 0
|
Produce a functionally identical Python code for the snippet given in C. | #include <stdlib.h>
#include <stdio.h>
#define SWAP(a, b) (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b)))
int jacobi(unsigned long a, unsigned long n) {
if (a >= n) a %= n;
int result = 1;
while (a) {
while ((a & 1) == 0) {
a >>= 1;
if ((n & 7) == 3 || (n & 7) == 5) result = -result;
}
SWAP(a, n);
if ((a & 3) == 3 && (n & 3) == 3) result = -result;
a %= n;
}
if (n == 1) return result;
return 0;
}
void print_table(unsigned kmax, unsigned nmax) {
printf("n\\k|");
for (int k = 0; k <= kmax; ++k) printf("%'3u", k);
printf("\n----");
for (int k = 0; k <= kmax; ++k) printf("---");
putchar('\n');
for (int n = 1; n <= nmax; n += 2) {
printf("%-2u |", n);
for (int k = 0; k <= kmax; ++k)
printf("%'3d", jacobi(k, n));
putchar('\n');
}
}
int main() {
print_table(20, 21);
return 0;
}
| def jacobi(a, n):
if n <= 0:
raise ValueError("'n' must be a positive integer.")
if n % 2 == 0:
raise ValueError("'n' must be odd.")
a %= n
result = 1
while a != 0:
while a % 2 == 0:
a /= 2
n_mod_8 = n % 8
if n_mod_8 in (3, 5):
result = -result
a, n = n, a
if a % 4 == 3 and n % 4 == 3:
result = -result
a %= n
if n == 1:
return result
else:
return 0
|
Transform the following C implementation into Python, maintaining the same output and logic. | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <time.h>
#define MAX_DIM 3
struct kd_node_t{
double x[MAX_DIM];
struct kd_node_t *left, *right;
};
inline double
dist(struct kd_node_t *a, struct kd_node_t *b, int dim)
{
double t, d = 0;
while (dim--) {
t = a->x[dim] - b->x[dim];
d += t * t;
}
return d;
}
inline void swap(struct kd_node_t *x, struct kd_node_t *y) {
double tmp[MAX_DIM];
memcpy(tmp, x->x, sizeof(tmp));
memcpy(x->x, y->x, sizeof(tmp));
memcpy(y->x, tmp, sizeof(tmp));
}
struct kd_node_t*
find_median(struct kd_node_t *start, struct kd_node_t *end, int idx)
{
if (end <= start) return NULL;
if (end == start + 1)
return start;
struct kd_node_t *p, *store, *md = start + (end - start) / 2;
double pivot;
while (1) {
pivot = md->x[idx];
swap(md, end - 1);
for (store = p = start; p < end; p++) {
if (p->x[idx] < pivot) {
if (p != store)
swap(p, store);
store++;
}
}
swap(store, end - 1);
if (store->x[idx] == md->x[idx])
return md;
if (store > md) end = store;
else start = store;
}
}
struct kd_node_t*
make_tree(struct kd_node_t *t, int len, int i, int dim)
{
struct kd_node_t *n;
if (!len) return 0;
if ((n = find_median(t, t + len, i))) {
i = (i + 1) % dim;
n->left = make_tree(t, n - t, i, dim);
n->right = make_tree(n + 1, t + len - (n + 1), i, dim);
}
return n;
}
int visited;
void nearest(struct kd_node_t *root, struct kd_node_t *nd, int i, int dim,
struct kd_node_t **best, double *best_dist)
{
double d, dx, dx2;
if (!root) return;
d = dist(root, nd, dim);
dx = root->x[i] - nd->x[i];
dx2 = dx * dx;
visited ++;
if (!*best || d < *best_dist) {
*best_dist = d;
*best = root;
}
if (!*best_dist) return;
if (++i >= dim) i = 0;
nearest(dx > 0 ? root->left : root->right, nd, i, dim, best, best_dist);
if (dx2 >= *best_dist) return;
nearest(dx > 0 ? root->right : root->left, nd, i, dim, best, best_dist);
}
#define N 1000000
#define rand1() (rand() / (double)RAND_MAX)
#define rand_pt(v) { v.x[0] = rand1(); v.x[1] = rand1(); v.x[2] = rand1(); }
int main(void)
{
int i;
struct kd_node_t wp[] = {
{{2, 3}}, {{5, 4}}, {{9, 6}}, {{4, 7}}, {{8, 1}}, {{7, 2}}
};
struct kd_node_t testNode = {{9, 2}};
struct kd_node_t *root, *found, *million;
double best_dist;
root = make_tree(wp, sizeof(wp) / sizeof(wp[1]), 0, 2);
visited = 0;
found = 0;
nearest(root, &testNode, 0, 2, &found, &best_dist);
printf(">> WP tree\nsearching for (%g, %g)\n"
"found (%g, %g) dist %g\nseen %d nodes\n\n",
testNode.x[0], testNode.x[1],
found->x[0], found->x[1], sqrt(best_dist), visited);
million =(struct kd_node_t*) calloc(N, sizeof(struct kd_node_t));
srand(time(0));
for (i = 0; i < N; i++) rand_pt(million[i]);
root = make_tree(million, N, 0, 3);
rand_pt(testNode);
visited = 0;
found = 0;
nearest(root, &testNode, 0, 3, &found, &best_dist);
printf(">> Million tree\nsearching for (%g, %g, %g)\n"
"found (%g, %g, %g) dist %g\nseen %d nodes\n",
testNode.x[0], testNode.x[1], testNode.x[2],
found->x[0], found->x[1], found->x[2],
sqrt(best_dist), visited);
int sum = 0, test_runs = 100000;
for (i = 0; i < test_runs; i++) {
found = 0;
visited = 0;
rand_pt(testNode);
nearest(root, &testNode, 0, 3, &found, &best_dist);
sum += visited;
}
printf("\n>> Million tree\n"
"visited %d nodes for %d random findings (%f per lookup)\n",
sum, test_runs, sum/(double)test_runs);
return 0;
}
| from random import seed, random
from time import time
from operator import itemgetter
from collections import namedtuple
from math import sqrt
from copy import deepcopy
def sqd(p1, p2):
return sum((c1 - c2) ** 2 for c1, c2 in zip(p1, p2))
class KdNode(object):
__slots__ = ("dom_elt", "split", "left", "right")
def __init__(self, dom_elt, split, left, right):
self.dom_elt = dom_elt
self.split = split
self.left = left
self.right = right
class Orthotope(object):
__slots__ = ("min", "max")
def __init__(self, mi, ma):
self.min, self.max = mi, ma
class KdTree(object):
__slots__ = ("n", "bounds")
def __init__(self, pts, bounds):
def nk2(split, exset):
if not exset:
return None
exset.sort(key=itemgetter(split))
m = len(exset) // 2
d = exset[m]
while m + 1 < len(exset) and exset[m + 1][split] == d[split]:
m += 1
d = exset[m]
s2 = (split + 1) % len(d)
return KdNode(d, split, nk2(s2, exset[:m]),
nk2(s2, exset[m + 1:]))
self.n = nk2(0, pts)
self.bounds = bounds
T3 = namedtuple("T3", "nearest dist_sqd nodes_visited")
def find_nearest(k, t, p):
def nn(kd, target, hr, max_dist_sqd):
if kd is None:
return T3([0.0] * k, float("inf"), 0)
nodes_visited = 1
s = kd.split
pivot = kd.dom_elt
left_hr = deepcopy(hr)
right_hr = deepcopy(hr)
left_hr.max[s] = pivot[s]
right_hr.min[s] = pivot[s]
if target[s] <= pivot[s]:
nearer_kd, nearer_hr = kd.left, left_hr
further_kd, further_hr = kd.right, right_hr
else:
nearer_kd, nearer_hr = kd.right, right_hr
further_kd, further_hr = kd.left, left_hr
n1 = nn(nearer_kd, target, nearer_hr, max_dist_sqd)
nearest = n1.nearest
dist_sqd = n1.dist_sqd
nodes_visited += n1.nodes_visited
if dist_sqd < max_dist_sqd:
max_dist_sqd = dist_sqd
d = (pivot[s] - target[s]) ** 2
if d > max_dist_sqd:
return T3(nearest, dist_sqd, nodes_visited)
d = sqd(pivot, target)
if d < dist_sqd:
nearest = pivot
dist_sqd = d
max_dist_sqd = dist_sqd
n2 = nn(further_kd, target, further_hr, max_dist_sqd)
nodes_visited += n2.nodes_visited
if n2.dist_sqd < dist_sqd:
nearest = n2.nearest
dist_sqd = n2.dist_sqd
return T3(nearest, dist_sqd, nodes_visited)
return nn(t.n, p, t.bounds, float("inf"))
def show_nearest(k, heading, kd, p):
print(heading + ":")
print("Point: ", p)
n = find_nearest(k, kd, p)
print("Nearest neighbor:", n.nearest)
print("Distance: ", sqrt(n.dist_sqd))
print("Nodes visited: ", n.nodes_visited, "\n")
def random_point(k):
return [random() for _ in range(k)]
def random_points(k, n):
return [random_point(k) for _ in range(n)]
if __name__ == "__main__":
seed(1)
P = lambda *coords: list(coords)
kd1 = KdTree([P(2, 3), P(5, 4), P(9, 6), P(4, 7), P(8, 1), P(7, 2)],
Orthotope(P(0, 0), P(10, 10)))
show_nearest(2, "Wikipedia example data", kd1, P(9, 2))
N = 400000
t0 = time()
kd2 = KdTree(random_points(3, N), Orthotope(P(0, 0, 0), P(1, 1, 1)))
t1 = time()
text = lambda *parts: "".join(map(str, parts))
show_nearest(2, text("k-d tree with ", N,
" random 3D points (generation time: ",
t1-t0, "s)"),
kd2, random_point(3))
|
Generate an equivalent Python version of this C code. | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <time.h>
#define MAX_DIM 3
struct kd_node_t{
double x[MAX_DIM];
struct kd_node_t *left, *right;
};
inline double
dist(struct kd_node_t *a, struct kd_node_t *b, int dim)
{
double t, d = 0;
while (dim--) {
t = a->x[dim] - b->x[dim];
d += t * t;
}
return d;
}
inline void swap(struct kd_node_t *x, struct kd_node_t *y) {
double tmp[MAX_DIM];
memcpy(tmp, x->x, sizeof(tmp));
memcpy(x->x, y->x, sizeof(tmp));
memcpy(y->x, tmp, sizeof(tmp));
}
struct kd_node_t*
find_median(struct kd_node_t *start, struct kd_node_t *end, int idx)
{
if (end <= start) return NULL;
if (end == start + 1)
return start;
struct kd_node_t *p, *store, *md = start + (end - start) / 2;
double pivot;
while (1) {
pivot = md->x[idx];
swap(md, end - 1);
for (store = p = start; p < end; p++) {
if (p->x[idx] < pivot) {
if (p != store)
swap(p, store);
store++;
}
}
swap(store, end - 1);
if (store->x[idx] == md->x[idx])
return md;
if (store > md) end = store;
else start = store;
}
}
struct kd_node_t*
make_tree(struct kd_node_t *t, int len, int i, int dim)
{
struct kd_node_t *n;
if (!len) return 0;
if ((n = find_median(t, t + len, i))) {
i = (i + 1) % dim;
n->left = make_tree(t, n - t, i, dim);
n->right = make_tree(n + 1, t + len - (n + 1), i, dim);
}
return n;
}
int visited;
void nearest(struct kd_node_t *root, struct kd_node_t *nd, int i, int dim,
struct kd_node_t **best, double *best_dist)
{
double d, dx, dx2;
if (!root) return;
d = dist(root, nd, dim);
dx = root->x[i] - nd->x[i];
dx2 = dx * dx;
visited ++;
if (!*best || d < *best_dist) {
*best_dist = d;
*best = root;
}
if (!*best_dist) return;
if (++i >= dim) i = 0;
nearest(dx > 0 ? root->left : root->right, nd, i, dim, best, best_dist);
if (dx2 >= *best_dist) return;
nearest(dx > 0 ? root->right : root->left, nd, i, dim, best, best_dist);
}
#define N 1000000
#define rand1() (rand() / (double)RAND_MAX)
#define rand_pt(v) { v.x[0] = rand1(); v.x[1] = rand1(); v.x[2] = rand1(); }
int main(void)
{
int i;
struct kd_node_t wp[] = {
{{2, 3}}, {{5, 4}}, {{9, 6}}, {{4, 7}}, {{8, 1}}, {{7, 2}}
};
struct kd_node_t testNode = {{9, 2}};
struct kd_node_t *root, *found, *million;
double best_dist;
root = make_tree(wp, sizeof(wp) / sizeof(wp[1]), 0, 2);
visited = 0;
found = 0;
nearest(root, &testNode, 0, 2, &found, &best_dist);
printf(">> WP tree\nsearching for (%g, %g)\n"
"found (%g, %g) dist %g\nseen %d nodes\n\n",
testNode.x[0], testNode.x[1],
found->x[0], found->x[1], sqrt(best_dist), visited);
million =(struct kd_node_t*) calloc(N, sizeof(struct kd_node_t));
srand(time(0));
for (i = 0; i < N; i++) rand_pt(million[i]);
root = make_tree(million, N, 0, 3);
rand_pt(testNode);
visited = 0;
found = 0;
nearest(root, &testNode, 0, 3, &found, &best_dist);
printf(">> Million tree\nsearching for (%g, %g, %g)\n"
"found (%g, %g, %g) dist %g\nseen %d nodes\n",
testNode.x[0], testNode.x[1], testNode.x[2],
found->x[0], found->x[1], found->x[2],
sqrt(best_dist), visited);
int sum = 0, test_runs = 100000;
for (i = 0; i < test_runs; i++) {
found = 0;
visited = 0;
rand_pt(testNode);
nearest(root, &testNode, 0, 3, &found, &best_dist);
sum += visited;
}
printf("\n>> Million tree\n"
"visited %d nodes for %d random findings (%f per lookup)\n",
sum, test_runs, sum/(double)test_runs);
return 0;
}
| from random import seed, random
from time import time
from operator import itemgetter
from collections import namedtuple
from math import sqrt
from copy import deepcopy
def sqd(p1, p2):
return sum((c1 - c2) ** 2 for c1, c2 in zip(p1, p2))
class KdNode(object):
__slots__ = ("dom_elt", "split", "left", "right")
def __init__(self, dom_elt, split, left, right):
self.dom_elt = dom_elt
self.split = split
self.left = left
self.right = right
class Orthotope(object):
__slots__ = ("min", "max")
def __init__(self, mi, ma):
self.min, self.max = mi, ma
class KdTree(object):
__slots__ = ("n", "bounds")
def __init__(self, pts, bounds):
def nk2(split, exset):
if not exset:
return None
exset.sort(key=itemgetter(split))
m = len(exset) // 2
d = exset[m]
while m + 1 < len(exset) and exset[m + 1][split] == d[split]:
m += 1
d = exset[m]
s2 = (split + 1) % len(d)
return KdNode(d, split, nk2(s2, exset[:m]),
nk2(s2, exset[m + 1:]))
self.n = nk2(0, pts)
self.bounds = bounds
T3 = namedtuple("T3", "nearest dist_sqd nodes_visited")
def find_nearest(k, t, p):
def nn(kd, target, hr, max_dist_sqd):
if kd is None:
return T3([0.0] * k, float("inf"), 0)
nodes_visited = 1
s = kd.split
pivot = kd.dom_elt
left_hr = deepcopy(hr)
right_hr = deepcopy(hr)
left_hr.max[s] = pivot[s]
right_hr.min[s] = pivot[s]
if target[s] <= pivot[s]:
nearer_kd, nearer_hr = kd.left, left_hr
further_kd, further_hr = kd.right, right_hr
else:
nearer_kd, nearer_hr = kd.right, right_hr
further_kd, further_hr = kd.left, left_hr
n1 = nn(nearer_kd, target, nearer_hr, max_dist_sqd)
nearest = n1.nearest
dist_sqd = n1.dist_sqd
nodes_visited += n1.nodes_visited
if dist_sqd < max_dist_sqd:
max_dist_sqd = dist_sqd
d = (pivot[s] - target[s]) ** 2
if d > max_dist_sqd:
return T3(nearest, dist_sqd, nodes_visited)
d = sqd(pivot, target)
if d < dist_sqd:
nearest = pivot
dist_sqd = d
max_dist_sqd = dist_sqd
n2 = nn(further_kd, target, further_hr, max_dist_sqd)
nodes_visited += n2.nodes_visited
if n2.dist_sqd < dist_sqd:
nearest = n2.nearest
dist_sqd = n2.dist_sqd
return T3(nearest, dist_sqd, nodes_visited)
return nn(t.n, p, t.bounds, float("inf"))
def show_nearest(k, heading, kd, p):
print(heading + ":")
print("Point: ", p)
n = find_nearest(k, kd, p)
print("Nearest neighbor:", n.nearest)
print("Distance: ", sqrt(n.dist_sqd))
print("Nodes visited: ", n.nodes_visited, "\n")
def random_point(k):
return [random() for _ in range(k)]
def random_points(k, n):
return [random_point(k) for _ in range(n)]
if __name__ == "__main__":
seed(1)
P = lambda *coords: list(coords)
kd1 = KdTree([P(2, 3), P(5, 4), P(9, 6), P(4, 7), P(8, 1), P(7, 2)],
Orthotope(P(0, 0), P(10, 10)))
show_nearest(2, "Wikipedia example data", kd1, P(9, 2))
N = 400000
t0 = time()
kd2 = KdTree(random_points(3, N), Orthotope(P(0, 0, 0), P(1, 1, 1)))
t1 = time()
text = lambda *parts: "".join(map(str, parts))
show_nearest(2, text("k-d tree with ", N,
" random 3D points (generation time: ",
t1-t0, "s)"),
kd2, random_point(3))
|
Rewrite this program in Python while keeping its functionality equivalent to the C version. | #ifndef CALLBACK_H
#define CALLBACK_H
void map(int* array, int len, void(*callback)(int,int));
#endif
| def square(n):
return n * n
numbers = [1, 3, 5, 7]
squares1 = [square(n) for n in numbers]
squares2a = map(square, numbers)
squares2b = map(lambda x: x*x, numbers)
squares3 = [n * n for n in numbers]
isquares1 = (n * n for n in numbers)
import itertools
isquares2 = itertools.imap(square, numbers)
|
Generate a Python translation of this C snippet without changing its computational steps. | #ifndef SILLY_H
#define SILLY_H
extern void JumpOverTheDog( int numberOfTimes);
extern int PlayFetchWithDog( float weightOfStick);
#endif
| >>> class Borg(object):
__state = {}
def __init__(self):
self.__dict__ = self.__state
>>> b1 = Borg()
>>> b2 = Borg()
>>> b1 is b2
False
>>> b1.datum = range(5)
>>> b1.datum
[0, 1, 2, 3, 4]
>>> b2.datum
[0, 1, 2, 3, 4]
>>> b1.datum is b2.datum
True
>>>
|
Rewrite the snippet below in Python so it works the same as the original C code. | #include <fenv.h>
#include <stdio.h>
void
safe_add(volatile double interval[2], volatile double a, volatile double b)
{
#pragma STDC FENV_ACCESS ON
unsigned int orig;
orig = fegetround();
fesetround(FE_DOWNWARD);
interval[0] = a + b;
fesetround(FE_UPWARD);
interval[1] = a + b;
fesetround(orig);
}
int
main()
{
const double nums[][2] = {
{1, 2},
{0.1, 0.2},
{1e100, 1e-100},
{1e308, 1e308},
};
double ival[2];
int i;
for (i = 0; i < sizeof(nums) / sizeof(nums[0]); i++) {
safe_add(ival, nums[i][0], nums[i][1]);
printf("%.17g + %.17g =\n", nums[i][0], nums[i][1]);
printf(" [%.17g, %.17g]\n", ival[0], ival[1]);
printf(" size %.17g\n\n", ival[1] - ival[0]);
}
return 0;
}
| >>> sum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1])
0.9999999999999999
>>> from math import fsum
>>> fsum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1])
1.0
|
Preserve the algorithm and functionality while converting the code from C to Python. | #include <stdio.h>
static const char *dog = "Benjamin";
static const char *Dog = "Samba";
static const char *DOG = "Bernie";
int main()
{
printf("The three dogs are named %s, %s and %s.\n", dog, Dog, DOG);
return 0;
}
| >>> dog = 'Benjamin'; Dog = 'Samba'; DOG = 'Bernie'
>>> print ('The three dogs are named ',dog,', ',Dog,', and ',DOG)
The three dogs are named Benjamin , Samba , and Bernie
>>>
|
Maintain the same structure and functionality when rewriting this code in Python. | int i;
for(i = 10; i >= 0; --i)
printf("%d\n",i);
| for i in xrange(10, -1, -1):
print i
|
Can you help me rewrite this code in Python instead of C, keeping it the same logically? |
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main(void)
{
return 0 >= fputs("ANY STRING TO WRITE TO A FILE AT ONCE.",
freopen("sample.txt","wb",stdout));
}
| with open(filename, 'w') as f:
f.write(data)
|
Keep all operations the same but rewrite the snippet in Python. | int i, j;
for (i = 1; i <= 5; i++) {
for (j = 1; j <= i; j++)
putchar('*');
puts("");
}
| for i in 1..5:
for j in 1..i:
stdout.write("*")
echo("")
|
Convert this C block to Python, preserving its control flow and logic. | #include <stdbool.h>
#include <stdio.h>
#include <stdint.h>
typedef uint64_t integer;
integer reverse(integer n) {
integer rev = 0;
while (n > 0) {
rev = rev * 10 + (n % 10);
n /= 10;
}
return rev;
}
typedef struct palgen_tag {
integer power;
integer next;
int digit;
bool even;
} palgen_t;
void init_palgen(palgen_t* palgen, int digit) {
palgen->power = 10;
palgen->next = digit * palgen->power - 1;
palgen->digit = digit;
palgen->even = false;
}
integer next_palindrome(palgen_t* p) {
++p->next;
if (p->next == p->power * (p->digit + 1)) {
if (p->even)
p->power *= 10;
p->next = p->digit * p->power;
p->even = !p->even;
}
return p->next * (p->even ? 10 * p->power : p->power)
+ reverse(p->even ? p->next : p->next/10);
}
bool gapful(integer n) {
integer m = n;
while (m >= 10)
m /= 10;
return n % (n % 10 + 10 * m) == 0;
}
void print(int len, integer array[][len]) {
for (int digit = 1; digit < 10; ++digit) {
printf("%d: ", digit);
for (int i = 0; i < len; ++i)
printf(" %llu", array[digit - 1][i]);
printf("\n");
}
}
int main() {
const int n1 = 20, n2 = 15, n3 = 10;
const int m1 = 100, m2 = 1000;
integer pg1[9][n1];
integer pg2[9][n2];
integer pg3[9][n3];
for (int digit = 1; digit < 10; ++digit) {
palgen_t pgen;
init_palgen(&pgen, digit);
for (int i = 0; i < m2; ) {
integer n = next_palindrome(&pgen);
if (!gapful(n))
continue;
if (i < n1)
pg1[digit - 1][i] = n;
else if (i < m1 && i >= m1 - n2)
pg2[digit - 1][i - (m1 - n2)] = n;
else if (i >= m2 - n3)
pg3[digit - 1][i - (m2 - n3)] = n;
++i;
}
}
printf("First %d palindromic gapful numbers ending in:\n", n1);
print(n1, pg1);
printf("\nLast %d of first %d palindromic gapful numbers ending in:\n", n2, m1);
print(n2, pg2);
printf("\nLast %d of first %d palindromic gapful numbers ending in:\n", n3, m2);
print(n3, pg3);
return 0;
}
| from itertools import count
from pprint import pformat
import re
import heapq
def pal_part_gen(odd=True):
for i in count(1):
fwd = str(i)
rev = fwd[::-1][1:] if odd else fwd[::-1]
yield int(fwd + rev)
def pal_ordered_gen():
yield from heapq.merge(pal_part_gen(odd=True), pal_part_gen(odd=False))
def is_gapful(x):
return (x % (int(str(x)[0]) * 10 + (x % 10)) == 0)
if __name__ == '__main__':
start = 100
for mx, last in [(20, 20), (100, 15), (1_000, 10)]:
print(f"\nLast {last} of the first {mx} binned-by-last digit "
f"gapful numbers >= {start}")
bin = {i: [] for i in range(1, 10)}
gen = (i for i in pal_ordered_gen() if i >= start and is_gapful(i))
while any(len(val) < mx for val in bin.values()):
g = next(gen)
val = bin[g % 10]
if len(val) < mx:
val.append(g)
b = {k:v[-last:] for k, v in bin.items()}
txt = pformat(b, width=220)
print('', re.sub(r"[{},\[\]]", '', txt))
|
Translate the given C code snippet into Python without altering its behavior. | #include <stdbool.h>
#include <stdio.h>
#include <stdint.h>
typedef uint64_t integer;
integer reverse(integer n) {
integer rev = 0;
while (n > 0) {
rev = rev * 10 + (n % 10);
n /= 10;
}
return rev;
}
typedef struct palgen_tag {
integer power;
integer next;
int digit;
bool even;
} palgen_t;
void init_palgen(palgen_t* palgen, int digit) {
palgen->power = 10;
palgen->next = digit * palgen->power - 1;
palgen->digit = digit;
palgen->even = false;
}
integer next_palindrome(palgen_t* p) {
++p->next;
if (p->next == p->power * (p->digit + 1)) {
if (p->even)
p->power *= 10;
p->next = p->digit * p->power;
p->even = !p->even;
}
return p->next * (p->even ? 10 * p->power : p->power)
+ reverse(p->even ? p->next : p->next/10);
}
bool gapful(integer n) {
integer m = n;
while (m >= 10)
m /= 10;
return n % (n % 10 + 10 * m) == 0;
}
void print(int len, integer array[][len]) {
for (int digit = 1; digit < 10; ++digit) {
printf("%d: ", digit);
for (int i = 0; i < len; ++i)
printf(" %llu", array[digit - 1][i]);
printf("\n");
}
}
int main() {
const int n1 = 20, n2 = 15, n3 = 10;
const int m1 = 100, m2 = 1000;
integer pg1[9][n1];
integer pg2[9][n2];
integer pg3[9][n3];
for (int digit = 1; digit < 10; ++digit) {
palgen_t pgen;
init_palgen(&pgen, digit);
for (int i = 0; i < m2; ) {
integer n = next_palindrome(&pgen);
if (!gapful(n))
continue;
if (i < n1)
pg1[digit - 1][i] = n;
else if (i < m1 && i >= m1 - n2)
pg2[digit - 1][i - (m1 - n2)] = n;
else if (i >= m2 - n3)
pg3[digit - 1][i - (m2 - n3)] = n;
++i;
}
}
printf("First %d palindromic gapful numbers ending in:\n", n1);
print(n1, pg1);
printf("\nLast %d of first %d palindromic gapful numbers ending in:\n", n2, m1);
print(n2, pg2);
printf("\nLast %d of first %d palindromic gapful numbers ending in:\n", n3, m2);
print(n3, pg3);
return 0;
}
| from itertools import count
from pprint import pformat
import re
import heapq
def pal_part_gen(odd=True):
for i in count(1):
fwd = str(i)
rev = fwd[::-1][1:] if odd else fwd[::-1]
yield int(fwd + rev)
def pal_ordered_gen():
yield from heapq.merge(pal_part_gen(odd=True), pal_part_gen(odd=False))
def is_gapful(x):
return (x % (int(str(x)[0]) * 10 + (x % 10)) == 0)
if __name__ == '__main__':
start = 100
for mx, last in [(20, 20), (100, 15), (1_000, 10)]:
print(f"\nLast {last} of the first {mx} binned-by-last digit "
f"gapful numbers >= {start}")
bin = {i: [] for i in range(1, 10)}
gen = (i for i in pal_ordered_gen() if i >= start and is_gapful(i))
while any(len(val) < mx for val in bin.values()):
g = next(gen)
val = bin[g % 10]
if len(val) < mx:
val.append(g)
b = {k:v[-last:] for k, v in bin.items()}
txt = pformat(b, width=220)
print('', re.sub(r"[{},\[\]]", '', txt))
|
Write a version of this C function in Python with identical behavior. | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
long long x, y, dx, dy, scale, clen, cscale;
typedef struct { double r, g, b; } rgb;
rgb ** pix;
void sc_up()
{
scale *= 2; x *= 2; y *= 2;
cscale *= 3;
}
void h_rgb(long long x, long long y)
{
rgb *p = &pix[y][x];
# define SAT 1
double h = 6.0 * clen / cscale;
double VAL = 1;
double c = SAT * VAL;
double X = c * (1 - fabs(fmod(h, 2) - 1));
switch((int)h) {
case 0: p->r += c; p->g += X; return;
case 1: p->r += X; p->g += c; return;
case 2: p->g += c; p->b += X; return;
case 3: p->g += X; p->b += c; return;
case 4: p->r += X; p->b += c; return;
default:
p->r += c; p->b += X;
}
}
void iter_string(const char * str, int d)
{
long long len;
while (*str != '\0') {
switch(*(str++)) {
case 'X':
if (d) iter_string("XHXVX", d - 1);
else{
clen ++;
h_rgb(x/scale, y/scale);
x += dx;
y -= dy;
}
continue;
case 'V':
len = 1LLU << d;
while (len--) {
clen ++;
h_rgb(x/scale, y/scale);
y += dy;
}
continue;
case 'H':
len = 1LLU << d;
while(len --) {
clen ++;
h_rgb(x/scale, y/scale);
x -= dx;
}
continue;
}
}
}
void sierp(long leng, int depth)
{
long i;
long h = leng + 20, w = leng + 20;
rgb *buf = malloc(sizeof(rgb) * w * h);
pix = malloc(sizeof(rgb *) * h);
for (i = 0; i < h; i++)
pix[i] = buf + w * i;
memset(buf, 0, sizeof(rgb) * w * h);
x = y = 10; dx = leng; dy = leng; scale = 1; clen = 0; cscale = 3;
for (i = 0; i < depth; i++) sc_up();
iter_string("VXH", depth);
unsigned char *fpix = malloc(w * h * 3);
double maxv = 0, *dbuf = (double*)buf;
for (i = 3 * w * h - 1; i >= 0; i--)
if (dbuf[i] > maxv) maxv = dbuf[i];
for (i = 3 * h * w - 1; i >= 0; i--)
fpix[i] = 255 * dbuf[i] / maxv;
printf("P6\n%ld %ld\n255\n", w, h);
fflush(stdout);
fwrite(fpix, h * w * 3, 1, stdout);
}
int main(int c, char ** v)
{
int size, depth;
depth = (c > 1) ? atoi(v[1]) : 10;
size = 1 << depth;
fprintf(stderr, "size: %d depth: %d\n", size, depth);
sierp(size, depth + 2);
return 0;
}
|
import turtle as t
def sier(n,length):
if n == 0:
return
for i in range(3):
sier(n - 1, length / 2)
t.fd(length)
t.rt(120)
|
Convert this C block to Python, preserving its control flow and logic. | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
long long x, y, dx, dy, scale, clen, cscale;
typedef struct { double r, g, b; } rgb;
rgb ** pix;
void sc_up()
{
scale *= 2; x *= 2; y *= 2;
cscale *= 3;
}
void h_rgb(long long x, long long y)
{
rgb *p = &pix[y][x];
# define SAT 1
double h = 6.0 * clen / cscale;
double VAL = 1;
double c = SAT * VAL;
double X = c * (1 - fabs(fmod(h, 2) - 1));
switch((int)h) {
case 0: p->r += c; p->g += X; return;
case 1: p->r += X; p->g += c; return;
case 2: p->g += c; p->b += X; return;
case 3: p->g += X; p->b += c; return;
case 4: p->r += X; p->b += c; return;
default:
p->r += c; p->b += X;
}
}
void iter_string(const char * str, int d)
{
long long len;
while (*str != '\0') {
switch(*(str++)) {
case 'X':
if (d) iter_string("XHXVX", d - 1);
else{
clen ++;
h_rgb(x/scale, y/scale);
x += dx;
y -= dy;
}
continue;
case 'V':
len = 1LLU << d;
while (len--) {
clen ++;
h_rgb(x/scale, y/scale);
y += dy;
}
continue;
case 'H':
len = 1LLU << d;
while(len --) {
clen ++;
h_rgb(x/scale, y/scale);
x -= dx;
}
continue;
}
}
}
void sierp(long leng, int depth)
{
long i;
long h = leng + 20, w = leng + 20;
rgb *buf = malloc(sizeof(rgb) * w * h);
pix = malloc(sizeof(rgb *) * h);
for (i = 0; i < h; i++)
pix[i] = buf + w * i;
memset(buf, 0, sizeof(rgb) * w * h);
x = y = 10; dx = leng; dy = leng; scale = 1; clen = 0; cscale = 3;
for (i = 0; i < depth; i++) sc_up();
iter_string("VXH", depth);
unsigned char *fpix = malloc(w * h * 3);
double maxv = 0, *dbuf = (double*)buf;
for (i = 3 * w * h - 1; i >= 0; i--)
if (dbuf[i] > maxv) maxv = dbuf[i];
for (i = 3 * h * w - 1; i >= 0; i--)
fpix[i] = 255 * dbuf[i] / maxv;
printf("P6\n%ld %ld\n255\n", w, h);
fflush(stdout);
fwrite(fpix, h * w * 3, 1, stdout);
}
int main(int c, char ** v)
{
int size, depth;
depth = (c > 1) ? atoi(v[1]) : 10;
size = 1 << depth;
fprintf(stderr, "size: %d depth: %d\n", size, depth);
sierp(size, depth + 2);
return 0;
}
|
import turtle as t
def sier(n,length):
if n == 0:
return
for i in range(3):
sier(n - 1, length / 2)
t.fd(length)
t.rt(120)
|
Transform the following C implementation into Python, maintaining the same output and logic. | #include <stdbool.h>
#include <stdio.h>
bool is_prime(int n) {
int i = 5;
if (n < 2) {
return false;
}
if (n % 2 == 0) {
return n == 2;
}
if (n % 3 == 0) {
return n == 3;
}
while (i * i <= n) {
if (n % i == 0) {
return false;
}
i += 2;
if (n % i == 0) {
return false;
}
i += 4;
}
return true;
}
int main() {
const int start = 1;
const int stop = 1000;
int sum = 0;
int count = 0;
int sc = 0;
int p;
for (p = start; p < stop; p++) {
if (is_prime(p)) {
count++;
sum += p;
if (is_prime(sum)) {
printf("The sum of %3d primes in [2, %3d] is %5d which is also prime\n", count, p, sum);
sc++;
}
}
}
printf("There are %d summerized primes in [%d, %d)\n", sc, start, stop);
return 0;
}
|
from itertools import accumulate, chain, takewhile
def primeSums():
return (
x for x in enumerate(
accumulate(
chain([(0, 0)], primes()),
lambda a, p: (p, p + a[1])
)
) if isPrime(x[1][1])
)
def main():
for x in takewhile(
lambda t: 1000 > t[1][0],
primeSums()
):
print(f'{x[0]} -> {x[1][1]}')
def isPrime(n):
if n in (2, 3):
return True
if 2 > n or 0 == n % 2:
return False
if 9 > n:
return True
if 0 == n % 3:
return False
def p(x):
return 0 == n % x or 0 == n % (2 + x)
return not any(map(p, range(5, 1 + int(n ** 0.5), 6)))
def primes():
n = 2
dct = {}
while True:
if n in dct:
for p in dct[n]:
dct.setdefault(n + p, []).append(p)
del dct[n]
else:
yield n
dct[n * n] = [n]
n = 1 + n
if __name__ == '__main__':
main()
|
Change the following C code into Python without altering its purpose. | #include <stdbool.h>
#include <stdio.h>
bool is_prime(int n) {
int i = 5;
if (n < 2) {
return false;
}
if (n % 2 == 0) {
return n == 2;
}
if (n % 3 == 0) {
return n == 3;
}
while (i * i <= n) {
if (n % i == 0) {
return false;
}
i += 2;
if (n % i == 0) {
return false;
}
i += 4;
}
return true;
}
int main() {
const int start = 1;
const int stop = 1000;
int sum = 0;
int count = 0;
int sc = 0;
int p;
for (p = start; p < stop; p++) {
if (is_prime(p)) {
count++;
sum += p;
if (is_prime(sum)) {
printf("The sum of %3d primes in [2, %3d] is %5d which is also prime\n", count, p, sum);
sc++;
}
}
}
printf("There are %d summerized primes in [%d, %d)\n", sc, start, stop);
return 0;
}
|
from itertools import accumulate, chain, takewhile
def primeSums():
return (
x for x in enumerate(
accumulate(
chain([(0, 0)], primes()),
lambda a, p: (p, p + a[1])
)
) if isPrime(x[1][1])
)
def main():
for x in takewhile(
lambda t: 1000 > t[1][0],
primeSums()
):
print(f'{x[0]} -> {x[1][1]}')
def isPrime(n):
if n in (2, 3):
return True
if 2 > n or 0 == n % 2:
return False
if 9 > n:
return True
if 0 == n % 3:
return False
def p(x):
return 0 == n % x or 0 == n % (2 + x)
return not any(map(p, range(5, 1 + int(n ** 0.5), 6)))
def primes():
n = 2
dct = {}
while True:
if n in dct:
for p in dct[n]:
dct.setdefault(n + p, []).append(p)
del dct[n]
else:
yield n
dct[n * n] = [n]
n = 1 + n
if __name__ == '__main__':
main()
|
Maintain the same structure and functionality when rewriting this code in Python. | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define COUNTOF(a) (sizeof(a)/sizeof(a[0]))
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;
}
int icompare(const void* p1, const void* p2) {
const int* ip1 = p1;
const int* ip2 = p2;
return (*ip1 < *ip2) ? -1 : ((*ip1 > *ip2) ? 1 : 0);
}
size_t unique(int* array, size_t len) {
size_t out_index = 0;
int prev;
for (size_t i = 0; i < len; ++i) {
if (i == 0 || prev != array[i])
array[out_index++] = array[i];
prev = array[i];
}
return out_index;
}
int* common_sorted_list(const int** arrays, const size_t* lengths, size_t count, size_t* size) {
size_t len = 0;
for (size_t i = 0; i < count; ++i)
len += lengths[i];
int* array = xmalloc(len * sizeof(int));
for (size_t i = 0, offset = 0; i < count; ++i) {
memcpy(array + offset, arrays[i], lengths[i] * sizeof(int));
offset += lengths[i];
}
qsort(array, len, sizeof(int), icompare);
*size = unique(array, len);
return array;
}
void print(const int* array, size_t len) {
printf("[");
for (size_t i = 0; i < len; ++i) {
if (i > 0)
printf(", ");
printf("%d", array[i]);
}
printf("]\n");
}
int main() {
const int a[] = {5, 1, 3, 8, 9, 4, 8, 7};
const int b[] = {3, 5, 9, 8, 4};
const int c[] = {1, 3, 7, 9};
size_t len = 0;
const int* arrays[] = {a, b, c};
size_t lengths[] = {COUNTOF(a), COUNTOF(b), COUNTOF(c)};
int* sorted = common_sorted_list(arrays, lengths, COUNTOF(arrays), &len);
print(sorted, len);
free(sorted);
return 0;
}
|
from itertools import chain
def main():
print(
sorted(nub(concat([
[5, 1, 3, 8, 9, 4, 8, 7],
[3, 5, 9, 8, 4],
[1, 3, 7, 9]
])))
)
def concat(xs):
return list(chain(*xs))
def nub(xs):
return list(dict.fromkeys(xs))
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 COUNTOF(a) (sizeof(a)/sizeof(a[0]))
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;
}
int icompare(const void* p1, const void* p2) {
const int* ip1 = p1;
const int* ip2 = p2;
return (*ip1 < *ip2) ? -1 : ((*ip1 > *ip2) ? 1 : 0);
}
size_t unique(int* array, size_t len) {
size_t out_index = 0;
int prev;
for (size_t i = 0; i < len; ++i) {
if (i == 0 || prev != array[i])
array[out_index++] = array[i];
prev = array[i];
}
return out_index;
}
int* common_sorted_list(const int** arrays, const size_t* lengths, size_t count, size_t* size) {
size_t len = 0;
for (size_t i = 0; i < count; ++i)
len += lengths[i];
int* array = xmalloc(len * sizeof(int));
for (size_t i = 0, offset = 0; i < count; ++i) {
memcpy(array + offset, arrays[i], lengths[i] * sizeof(int));
offset += lengths[i];
}
qsort(array, len, sizeof(int), icompare);
*size = unique(array, len);
return array;
}
void print(const int* array, size_t len) {
printf("[");
for (size_t i = 0; i < len; ++i) {
if (i > 0)
printf(", ");
printf("%d", array[i]);
}
printf("]\n");
}
int main() {
const int a[] = {5, 1, 3, 8, 9, 4, 8, 7};
const int b[] = {3, 5, 9, 8, 4};
const int c[] = {1, 3, 7, 9};
size_t len = 0;
const int* arrays[] = {a, b, c};
size_t lengths[] = {COUNTOF(a), COUNTOF(b), COUNTOF(c)};
int* sorted = common_sorted_list(arrays, lengths, COUNTOF(arrays), &len);
print(sorted, len);
free(sorted);
return 0;
}
|
from itertools import chain
def main():
print(
sorted(nub(concat([
[5, 1, 3, 8, 9, 4, 8, 7],
[3, 5, 9, 8, 4],
[1, 3, 7, 9]
])))
)
def concat(xs):
return list(chain(*xs))
def nub(xs):
return list(dict.fromkeys(xs))
if __name__ == '__main__':
main()
|
Produce a functionally identical Python code for the snippet given in C. | #include <assert.h>
#include <stdio.h>
int main(int c, char **v)
{
unsigned int n = 1 << (c - 1), i = n, j, k;
assert(n);
while (i--) {
if (!(i & (i + (i & -(int)i))))
continue;
for (j = n, k = 1; j >>= 1; k++)
if (i & j) printf("%s ", v[k]);
putchar('\n');
}
return 0;
}
| def ncsub(seq, s=0):
if seq:
x = seq[:1]
xs = seq[1:]
p2 = s % 2
p1 = not p2
return [x + ys for ys in ncsub(xs, s + p1)] + ncsub(xs, s + p2)
else:
return [[]] if s >= 3 else []
|
Generate a Python translation of this C snippet without changing its computational steps. | #include <stdio.h>
int main(void)
{
puts( "%!PS-Adobe-3.0 EPSF\n"
"%%BoundingBox: -10 -10 400 565\n"
"/a{0 0 moveto 0 .4 translate 0 0 lineto stroke -1 1 scale}def\n"
"/b{a 90 rotate}def");
char i;
for (i = 'c'; i <= 'z'; i++)
printf("/%c{%c %c}def\n", i, i-1, i-2);
puts("0 setlinewidth z showpage\n%%EOF");
return 0;
}
| from functools import wraps
from turtle import *
def memoize(obj):
cache = obj.cache = {}
@wraps(obj)
def memoizer(*args, **kwargs):
key = str(args) + str(kwargs)
if key not in cache:
cache[key] = obj(*args, **kwargs)
return cache[key]
return memoizer
@memoize
def fibonacci_word(n):
assert n > 0
if n == 1:
return "1"
if n == 2:
return "0"
return fibonacci_word(n - 1) + fibonacci_word(n - 2)
def draw_fractal(word, step):
for i, c in enumerate(word, 1):
forward(step)
if c == "0":
if i % 2 == 0:
left(90)
else:
right(90)
def main():
n = 25
step = 1
width = 1050
height = 1050
w = fibonacci_word(n)
setup(width=width, height=height)
speed(0)
setheading(90)
left(90)
penup()
forward(500)
right(90)
backward(500)
pendown()
tracer(10000)
hideturtle()
draw_fractal(w, step)
getscreen().getcanvas().postscript(file="fibonacci_word_fractal.eps")
exitonclick()
if __name__ == '__main__':
main()
|
Translate this program into Python but keep the logic exactly as in C. | #include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
bool isPrime(int64_t n) {
int64_t i;
if (n < 2) return false;
if (n % 2 == 0) return n == 2;
if (n % 3 == 0) return n == 3;
if (n % 5 == 0) return n == 5;
if (n % 7 == 0) return n == 7;
if (n % 11 == 0) return n == 11;
if (n % 13 == 0) return n == 13;
if (n % 17 == 0) return n == 17;
if (n % 19 == 0) return n == 19;
for (i = 23; i * i <= n; i += 2) {
if (n % i == 0) return false;
}
return true;
}
int countTwinPrimes(int limit) {
int count = 0;
int64_t p3 = true, p2 = true, p1 = false;
int64_t i;
for (i = 5; i <= limit; i++) {
p3 = p2;
p2 = p1;
p1 = isPrime(i);
if (p3 && p1) {
count++;
}
}
return count;
}
void test(int limit) {
int count = countTwinPrimes(limit);
printf("Number of twin prime pairs less than %d is %d\n", limit, count);
}
int main() {
test(10);
test(100);
test(1000);
test(10000);
test(100000);
test(1000000);
test(10000000);
test(100000000);
return 0;
}
| primes = [2, 3, 5, 7, 11, 13, 17, 19]
def count_twin_primes(limit: int) -> int:
global primes
if limit > primes[-1]:
ram_limit = primes[-1] + 90000000 - len(primes)
reasonable_limit = min(limit, primes[-1] ** 2, ram_limit) - 1
while reasonable_limit < limit:
ram_limit = primes[-1] + 90000000 - len(primes)
if ram_limit > primes[-1]:
reasonable_limit = min(limit, primes[-1] ** 2, ram_limit)
else:
reasonable_limit = min(limit, primes[-1] ** 2)
sieve = list({x for prime in primes for x in
range(primes[-1] + prime - (primes[-1] % prime), reasonable_limit, prime)})
primes += [x - 1 for i, x in enumerate(sieve) if i and x - 1 != sieve[i - 1] and x - 1 < limit]
count = len([(x, y) for (x, y) in zip(primes, primes[1:]) if x + 2 == y])
return count
def test(limit: int):
count = count_twin_primes(limit)
print(f"Number of twin prime pairs less than {limit} is {count}\n")
test(10)
test(100)
test(1000)
test(10000)
test(100000)
test(1000000)
test(10000000)
test(100000000)
|
Translate this program into Python but keep the logic exactly as in C. | #include <stdio.h>
#include <math.h>
int main()
{
double a, c, s, PI2 = atan2(1, 1) * 8;
int n, i;
for (n = 1; n < 10; n++) for (i = 0; i < n; i++) {
c = s = 0;
if (!i ) c = 1;
else if(n == 4 * i) s = 1;
else if(n == 2 * i) c = -1;
else if(3 * n == 4 * i) s = -1;
else
a = i * PI2 / n, c = cos(a), s = sin(a);
if (c) printf("%.2g", c);
printf(s == 1 ? "i" : s == -1 ? "-i" : s ? "%+.2gi" : "", s);
printf(i == n - 1 ?"\n":", ");
}
return 0;
}
| import cmath
class Complex(complex):
def __repr__(self):
rp = '%7.5f' % self.real if not self.pureImag() else ''
ip = '%7.5fj' % self.imag if not self.pureReal() else ''
conj = '' if (
self.pureImag() or self.pureReal() or self.imag < 0.0
) else '+'
return '0.0' if (
self.pureImag() and self.pureReal()
) else rp + conj + ip
def pureImag(self):
return abs(self.real) < 0.000005
def pureReal(self):
return abs(self.imag) < 0.000005
def croots(n):
if n <= 0:
return None
return (Complex(cmath.rect(1, 2 * k * cmath.pi / n)) for k in range(n))
for nr in range(2, 11):
print(nr, list(croots(nr)))
|
Translate this program into Python but keep the logic exactly as in C. | #include <stdio.h>
#include <string.h>
void longmulti(const char *a, const char *b, char *c)
{
int i = 0, j = 0, k = 0, n, carry;
int la, lb;
if (!strcmp(a, "0") || !strcmp(b, "0")) {
c[0] = '0', c[1] = '\0';
return;
}
if (a[0] == '-') { i = 1; k = !k; }
if (b[0] == '-') { j = 1; k = !k; }
if (i || j) {
if (k) c[0] = '-';
longmulti(a + i, b + j, c + k);
return;
}
la = strlen(a);
lb = strlen(b);
memset(c, '0', la + lb);
c[la + lb] = '\0';
# define I(a) (a - '0')
for (i = la - 1; i >= 0; i--) {
for (j = lb - 1, k = i + j + 1, carry = 0; j >= 0; j--, k--) {
n = I(a[i]) * I(b[j]) + I(c[k]) + carry;
carry = n / 10;
c[k] = (n % 10) + '0';
}
c[k] += carry;
}
# undef I
if (c[0] == '0') memmove(c, c + 1, la + lb);
return;
}
int main()
{
char c[1024];
longmulti("-18446744073709551616", "-18446744073709551616", c);
printf("%s\n", c);
return 0;
}
|
print 2**64*2**64
|
Write a version of this C function in Python with identical behavior. | #include <math.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
struct Pair {
uint64_t v1, v2;
};
struct Pair makePair(uint64_t a, uint64_t b) {
struct Pair r;
r.v1 = a;
r.v2 = b;
return r;
}
struct Pair solvePell(int n) {
int x = (int) sqrt(n);
if (x * x == n) {
return makePair(1, 0);
} else {
int y = x;
int z = 1;
int r = 2 * x;
struct Pair e = makePair(1, 0);
struct Pair f = makePair(0, 1);
uint64_t a = 0;
uint64_t b = 0;
while (true) {
y = r * z - y;
z = (n - y * y) / z;
r = (x + y) / z;
e = makePair(e.v2, r * e.v2 + e.v1);
f = makePair(f.v2, r * f.v2 + f.v1);
a = e.v2 + x * f.v2;
b = f.v2;
if (a * a - n * b * b == 1) {
break;
}
}
return makePair(a, b);
}
}
void test(int n) {
struct Pair r = solvePell(n);
printf("x^2 - %3d * y^2 = 1 for x = %21llu and y = %21llu\n", n, r.v1, r.v2);
}
int main() {
test(61);
test(109);
test(181);
test(277);
return 0;
}
| import math
def solvePell(n):
x = int(math.sqrt(n))
y, z, r = x, 1, x << 1
e1, e2 = 1, 0
f1, f2 = 0, 1
while True:
y = r * z - y
z = (n - y * y) // z
r = (x + y) // z
e1, e2 = e2, e1 + e2 * r
f1, f2 = f2, f1 + f2 * r
a, b = f2 * x + e2, f2
if a * a - n * b * b == 1:
return a, b
for n in [61, 109, 181, 277]:
x, y = solvePell(n)
print("x^2 - %3d * y^2 = 1 for x = %27d and y = %25d" % (n, x, y))
|
Produce a functionally identical Python code for the snippet given in C. | #include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <stdbool.h>
#include <curses.h>
#include <string.h>
#define MAX_NUM_TRIES 72
#define LINE_BEGIN 7
#define LAST_LINE 18
int yp=LINE_BEGIN, xp=0;
char number[5];
char guess[5];
#define MAX_STR 256
void mvaddstrf(int y, int x, const char *fmt, ...)
{
va_list args;
char buf[MAX_STR];
va_start(args, fmt);
vsprintf(buf, fmt, args);
move(y, x);
clrtoeol();
addstr(buf);
va_end(args);
}
void ask_for_a_number()
{
int i=0;
char symbols[] = "123456789";
move(5,0); clrtoeol();
addstr("Enter four digits: ");
while(i<4) {
int c = getch();
if ( (c >= '1') && (c <= '9') && (symbols[c-'1']!=0) ) {
addch(c);
symbols[c-'1'] = 0;
guess[i++] = c;
}
}
}
void choose_the_number()
{
int i=0, j;
char symbols[] = "123456789";
while(i<4) {
j = rand() % 9;
if ( symbols[j] != 0 ) {
number[i++] = symbols[j];
symbols[j] = 0;
}
}
}
|
import random
digits = '123456789'
size = 4
chosen = ''.join(random.sample(digits,size))
print % (size, size)
guesses = 0
while True:
guesses += 1
while True:
guess = raw_input('\nNext guess [%i]: ' % guesses).strip()
if len(guess) == size and \
all(char in digits for char in guess) \
and len(set(guess)) == size:
break
print "Problem, try again. You need to enter %i unique digits from 1 to 9" % size
if guess == chosen:
print '\nCongratulations you guessed correctly in',guesses,'attempts'
break
bulls = cows = 0
for i in range(size):
if guess[i] == chosen[i]:
bulls += 1
elif guess[i] in chosen:
cows += 1
print ' %i Bulls\n %i Cows' % (bulls, cows)
|
Change the following C code into Python without altering its purpose. | #include <stdio.h>
void bubble_sort (int *a, int n) {
int i, t, j = n, s = 1;
while (s) {
s = 0;
for (i = 1; i < j; i++) {
if (a[i] < a[i - 1]) {
t = a[i];
a[i] = a[i - 1];
a[i - 1] = t;
s = 1;
}
}
j--;
}
}
int main () {
int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};
int n = sizeof a / sizeof a[0];
int i;
for (i = 0; i < n; i++)
printf("%d%s", a[i], i == n - 1 ? "\n" : " ");
bubble_sort(a, n);
for (i = 0; i < n; i++)
printf("%d%s", a[i], i == n - 1 ? "\n" : " ");
return 0;
}
| def bubble_sort(seq):
changed = True
while changed:
changed = False
for i in range(len(seq) - 1):
if seq[i] > seq[i+1]:
seq[i], seq[i+1] = seq[i+1], seq[i]
changed = True
return seq
if __name__ == "__main__":
from random import shuffle
testset = [_ for _ in range(100)]
testcase = testset.copy()
shuffle(testcase)
assert testcase != testset
bubble_sort(testcase)
assert testcase == testset
|
Change the following C code into Python without altering its purpose. | #include <math.h>
#include <stdio.h>
unsigned int divisor_count(unsigned int n) {
unsigned int total = 1;
unsigned int p;
for (; (n & 1) == 0; n >>= 1) {
++total;
}
for (p = 3; p * p <= n; p += 2) {
unsigned int count = 1;
for (; n % p == 0; n /= p) {
++count;
}
total *= count;
}
if (n > 1) {
total *= 2;
}
return total;
}
unsigned int divisor_product(unsigned int n) {
return pow(n, divisor_count(n) / 2.0);
}
int main() {
const unsigned int limit = 50;
unsigned int n;
printf("Product of divisors for the first %d positive integers:\n", limit);
for (n = 1; n <= limit; ++n) {
printf("%11d", divisor_product(n));
if (n % 5 == 0) {
printf("\n");
}
}
return 0;
}
| def product_of_divisors(n):
assert(isinstance(n, int) and 0 < n)
ans = i = j = 1
while i*i <= n:
if 0 == n%i:
ans *= i
j = n//i
if j != i:
ans *= j
i += 1
return ans
if __name__ == "__main__":
print([product_of_divisors(n) for n in range(1,51)])
|
Translate the given C code snippet into Python without altering its behavior. | #include <math.h>
#include <stdio.h>
unsigned int divisor_count(unsigned int n) {
unsigned int total = 1;
unsigned int p;
for (; (n & 1) == 0; n >>= 1) {
++total;
}
for (p = 3; p * p <= n; p += 2) {
unsigned int count = 1;
for (; n % p == 0; n /= p) {
++count;
}
total *= count;
}
if (n > 1) {
total *= 2;
}
return total;
}
unsigned int divisor_product(unsigned int n) {
return pow(n, divisor_count(n) / 2.0);
}
int main() {
const unsigned int limit = 50;
unsigned int n;
printf("Product of divisors for the first %d positive integers:\n", limit);
for (n = 1; n <= limit; ++n) {
printf("%11d", divisor_product(n));
if (n % 5 == 0) {
printf("\n");
}
}
return 0;
}
| def product_of_divisors(n):
assert(isinstance(n, int) and 0 < n)
ans = i = j = 1
while i*i <= n:
if 0 == n%i:
ans *= i
j = n//i
if j != i:
ans *= j
i += 1
return ans
if __name__ == "__main__":
print([product_of_divisors(n) for n in range(1,51)])
|
Maintain the same structure and functionality when rewriting this code in Python. | #include <stdio.h>
int main(int argc, char **argv) {
FILE *in, *out;
int c;
in = fopen("input.txt", "r");
if (!in) {
fprintf(stderr, "Error opening input.txt for reading.\n");
return 1;
}
out = fopen("output.txt", "w");
if (!out) {
fprintf(stderr, "Error opening output.txt for writing.\n");
fclose(in);
return 1;
}
while ((c = fgetc(in)) != EOF) {
fputc(c, out);
}
fclose(out);
fclose(in);
return 0;
}
| import shutil
shutil.copyfile('input.txt', 'output.txt')
|
Translate the given C code snippet into Python without altering its behavior. | #include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int a, b;
if (argc < 3) exit(1);
b = atoi(argv[--argc]);
if (b == 0) exit(2);
a = atoi(argv[--argc]);
printf("a+b = %d\n", a+b);
printf("a-b = %d\n", a-b);
printf("a*b = %d\n", a*b);
printf("a/b = %d\n", a/b);
printf("a%%b = %d\n", a%b);
return 0;
}
| x = int(raw_input("Number 1: "))
y = int(raw_input("Number 2: "))
print "Sum: %d" % (x + y)
print "Difference: %d" % (x - y)
print "Product: %d" % (x * y)
print "Quotient: %d" % (x / y)
print "Remainder: %d" % (x % y)
print "Quotient: %d with Remainder: %d" % divmod(x, y)
print "Power: %d" % x**y
raw_input( )
|
Keep all operations the same but rewrite the snippet in Python. | #include <stdio.h>
void transpose(void *dest, void *src, int src_h, int src_w)
{
int i, j;
double (*d)[src_h] = dest, (*s)[src_w] = src;
for (i = 0; i < src_h; i++)
for (j = 0; j < src_w; j++)
d[j][i] = s[i][j];
}
int main()
{
int i, j;
double a[3][5] = {{ 0, 1, 2, 3, 4 },
{ 5, 6, 7, 8, 9 },
{ 1, 0, 0, 0, 42}};
double b[5][3];
transpose(b, a, 3, 5);
for (i = 0; i < 5; i++)
for (j = 0; j < 3; j++)
printf("%g%c", b[i][j], j == 2 ? '\n' : ' ');
return 0;
}
| m=((1, 1, 1, 1),
(2, 4, 8, 16),
(3, 9, 27, 81),
(4, 16, 64, 256),
(5, 25,125, 625))
print(zip(*m))
|
Maintain the same structure and functionality when rewriting this code in Python. |
#include <stdio.h>
#include <stdlib.h>
typedef struct arg
{
int (*fn)(struct arg*);
int *k;
struct arg *x1, *x2, *x3, *x4, *x5;
} ARG;
int f_1 (ARG* _) { return -1; }
int f0 (ARG* _) { return 0; }
int f1 (ARG* _) { return 1; }
int eval(ARG* a) { return a->fn(a); }
#define MAKE_ARG(...) (&(ARG){__VA_ARGS__})
#define FUN(...) MAKE_ARG(B, &k, __VA_ARGS__)
int A(ARG*);
int B(ARG* a)
{
int k = *a->k -= 1;
return A(FUN(a, a->x1, a->x2, a->x3, a->x4));
}
int A(ARG* a)
{
return *a->k <= 0 ? eval(a->x4) + eval(a->x5) : B(a);
}
int main(int argc, char **argv)
{
int k = argc == 2 ? strtol(argv[1], 0, 0) : 10;
printf("%d\n", A(FUN(MAKE_ARG(f1), MAKE_ARG(f_1), MAKE_ARG(f_1),
MAKE_ARG(f1), MAKE_ARG(f0))));
return 0;
}
|
import sys
sys.setrecursionlimit(1025)
def a(in_k, x1, x2, x3, x4, x5):
k = [in_k]
def b():
k[0] -= 1
return a(k[0], b, x1, x2, x3, x4)
return x4() + x5() if k[0] <= 0 else b()
x = lambda i: lambda: i
print(a(10, x(1), x(-1), x(-1), x(1), x(0)))
|
Generate an equivalent Python version of this C code. | #include <stdio.h>
#include <stdbool.h>
bool a(bool in)
{
printf("I am a\n");
return in;
}
bool b(bool in)
{
printf("I am b\n");
return in;
}
#define TEST(X,Y,O) \
do { \
x = a(X) O b(Y); \
printf(#X " " #O " " #Y " = %s\n\n", x ? "true" : "false"); \
} while(false);
int main()
{
bool x;
TEST(false, true, &&);
TEST(true, false, ||);
TEST(true, false, &&);
TEST(false, false, ||);
return 0;
}
| >>> def a(answer):
print("
return answer
>>> def b(answer):
print("
return answer
>>> for i in (False, True):
for j in (False, True):
print ("\nCalculating: x = a(i) and b(j)")
x = a(i) and b(j)
print ("Calculating: y = a(i) or b(j)")
y = a(i) or b(j)
Calculating: x = a(i) and b(j)
Calculating: y = a(i) or b(j)
Calculating: x = a(i) and b(j)
Calculating: y = a(i) or b(j)
Calculating: x = a(i) and b(j)
Calculating: y = a(i) or b(j)
Calculating: x = a(i) and b(j)
Calculating: y = a(i) or b(j)
|
Produce a functionally identical Python code for the snippet given in C. | #include <stdio.h>
#include <stdbool.h>
bool a(bool in)
{
printf("I am a\n");
return in;
}
bool b(bool in)
{
printf("I am b\n");
return in;
}
#define TEST(X,Y,O) \
do { \
x = a(X) O b(Y); \
printf(#X " " #O " " #Y " = %s\n\n", x ? "true" : "false"); \
} while(false);
int main()
{
bool x;
TEST(false, true, &&);
TEST(true, false, ||);
TEST(true, false, &&);
TEST(false, false, ||);
return 0;
}
| >>> def a(answer):
print("
return answer
>>> def b(answer):
print("
return answer
>>> for i in (False, True):
for j in (False, True):
print ("\nCalculating: x = a(i) and b(j)")
x = a(i) and b(j)
print ("Calculating: y = a(i) or b(j)")
y = a(i) or b(j)
Calculating: x = a(i) and b(j)
Calculating: y = a(i) or b(j)
Calculating: x = a(i) and b(j)
Calculating: y = a(i) or b(j)
Calculating: x = a(i) and b(j)
Calculating: y = a(i) or b(j)
Calculating: x = a(i) and b(j)
Calculating: y = a(i) or b(j)
|
Please provide an equivalent version of this C code in Python. | #include <stdio.h>
void recurse(unsigned int i)
{
printf("%d\n", i);
recurse(i+1);
}
int main()
{
recurse(0);
return 0;
}
| import sys
print(sys.getrecursionlimit())
|
Port the following code from C to Python with equivalent syntax and logic. | #include <stdio.h>
void recurse(unsigned int i)
{
printf("%d\n", i);
recurse(i+1);
}
int main()
{
recurse(0);
return 0;
}
| import sys
print(sys.getrecursionlimit())
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.