Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Translate the given C# code snippet into Go without altering its behavior.
using System; class Program { const long Lm = (long)1e18; const string Fm = "D18"; struct LI { public long lo, ml, mh, hi, tp; } static void inc(ref LI d, LI s) { if ((d.lo += s.lo) >= Lm) { d.ml++; d.lo -= Lm; } if ((d.ml += s.ml) >= Lm) { d.mh++; d.ml -= Lm; } if ((d.mh += s.mh) >= Lm) { d.hi++; d.mh -= Lm; } if ((d.hi += s.hi) >= Lm) { d.tp++; d.hi -= Lm; } d.tp += s.tp; } static void dec(ref LI d, LI s) { if ((d.lo -= s.lo) < 0) { d.ml--; d.lo += Lm; } if ((d.ml -= s.ml) < 0) { d.mh--; d.ml += Lm; } if ((d.mh -= s.mh) < 0) { d.hi--; d.mh += Lm; } if ((d.hi -= s.hi) < 0) { d.tp--; d.hi += Lm; } d.tp -= s.tp; } static LI set(long s) { LI d; d.lo = s; d.ml = d.mh = d.hi = d.tp = 0; return d; } static string fmt(LI x) { if (x.tp > 0) return x.tp.ToString() + x.hi.ToString(Fm) + x.mh.ToString(Fm) + x.ml.ToString(Fm) + x.lo.ToString(Fm); if (x.hi > 0) return x.hi.ToString() + x.mh.ToString(Fm) + x.ml.ToString(Fm) + x.lo.ToString(Fm); if (x.mh > 0) return x.mh.ToString() + x.ml.ToString(Fm) + x.lo.ToString(Fm); if (x.ml > 0) return x.ml.ToString() + x.lo.ToString(Fm); return x.lo.ToString(); } static LI partcount(int n) { var P = new LI[n + 1]; P[0] = set(1); for (int i = 1; i <= n; i++) { int k = 0, d = -2, j = i; LI x = set(0); while (true) { if ((j -= (d += 3) -k) >= 0) inc(ref x, P[j]); else break; if ((j -= ++k) >= 0) inc(ref x, P[j]); else break; if ((j -= (d += 3) -k) >= 0) dec(ref x, P[j]); else break; if ((j -= ++k) >= 0) dec(ref x, P[j]); else break; } P[i] = x; } return P[n]; } static void Main(string[] args) { var sw = System.Diagnostics.Stopwatch.StartNew (); var res = partcount(6666); sw.Stop(); Console.Write("{0} {1} ms", fmt(res), sw.Elapsed.TotalMilliseconds); } }
package main import ( "fmt" "math/big" "time" ) var p []*big.Int var pd []int func partDiffDiff(n int) int { if n&1 == 1 { return (n + 1) / 2 } return n + 1 } func partDiff(n int) int { if n < 2 { return 1 } pd[n] = pd[n-1] + partDiffDiff(n-1) return pd[n] } func partitionsP(n int) { if n < 2 { return } psum := new(big.Int) for i := 1; i <= n; i++ { pdi := partDiff(i) if pdi > n { break } sign := int64(-1) if (i-1)%4 < 2 { sign = 1 } t := new(big.Int).Mul(p[n-pdi], big.NewInt(sign)) psum.Add(psum, t) } p[n] = psum } func main() { start := time.Now() const N = 6666 p = make([]*big.Int, N+1) pd = make([]int, N+1) p[0], pd[0] = big.NewInt(1), 1 p[1], pd[1] = big.NewInt(1), 1 for n := 2; n <= N; n++ { partitionsP(n) } fmt.Printf("p[%d)] = %d\n", N, p[N]) fmt.Printf("Took %s\n", time.Since(start)) }
Can you help me rewrite this code in Go instead of C#, keeping it the same logically?
using System; using static System.Console; using LI = System.Collections.Generic.SortedSet<int>; class Program { static LI unl(LI res, LI set, int lft, int mul = 1, int vlu = 0) { if (lft == 0) res.Add(vlu); else if (lft > 0) foreach (int itm in set) res = unl(res, set, lft - itm, mul * 10, vlu + itm * mul); return res; } static void Main(string[] args) { WriteLine(string.Join(" ", unl(new LI {}, new LI { 2, 3, 5, 7 }, 13))); } }
package main import ( "fmt" "sort" "strconv" ) func combrep(n int, lst []byte) [][]byte { if n == 0 { return [][]byte{nil} } if len(lst) == 0 { return nil } r := combrep(n, lst[1:]) for _, x := range combrep(n-1, lst) { r = append(r, append(x, lst[0])) } return r } func shouldSwap(s []byte, start, curr int) bool { for i := start; i < curr; i++ { if s[i] == s[curr] { return false } } return true } func findPerms(s []byte, index, n int, res *[]string) { if index >= n { *res = append(*res, string(s)) return } for i := index; i < n; i++ { check := shouldSwap(s, index, i) if check { s[index], s[i] = s[i], s[index] findPerms(s, index+1, n, res) s[index], s[i] = s[i], s[index] } } } func main() { primes := []byte{2, 3, 5, 7} var res []string for n := 3; n <= 6; n++ { reps := combrep(n, primes) for _, rep := range reps { sum := byte(0) for _, r := range rep { sum += r } if sum == 13 { var perms []string for i := 0; i < len(rep); i++ { rep[i] += 48 } findPerms(rep, 0, len(rep), &perms) res = append(res, perms...) } } } res2 := make([]int, len(res)) for i, r := range res { res2[i], _ = strconv.Atoi(r) } sort.Ints(res2) fmt.Println("Those numbers whose digits are all prime and sum to 13 are:") fmt.Println(res2) }
Can you help me rewrite this code in Go instead of C#, keeping it the same logically?
using System; using static System.Console; using LI = System.Collections.Generic.SortedSet<int>; class Program { static LI unl(LI res, LI set, int lft, int mul = 1, int vlu = 0) { if (lft == 0) res.Add(vlu); else if (lft > 0) foreach (int itm in set) res = unl(res, set, lft - itm, mul * 10, vlu + itm * mul); return res; } static void Main(string[] args) { WriteLine(string.Join(" ", unl(new LI {}, new LI { 2, 3, 5, 7 }, 13))); } }
package main import ( "fmt" "sort" "strconv" ) func combrep(n int, lst []byte) [][]byte { if n == 0 { return [][]byte{nil} } if len(lst) == 0 { return nil } r := combrep(n, lst[1:]) for _, x := range combrep(n-1, lst) { r = append(r, append(x, lst[0])) } return r } func shouldSwap(s []byte, start, curr int) bool { for i := start; i < curr; i++ { if s[i] == s[curr] { return false } } return true } func findPerms(s []byte, index, n int, res *[]string) { if index >= n { *res = append(*res, string(s)) return } for i := index; i < n; i++ { check := shouldSwap(s, index, i) if check { s[index], s[i] = s[i], s[index] findPerms(s, index+1, n, res) s[index], s[i] = s[i], s[index] } } } func main() { primes := []byte{2, 3, 5, 7} var res []string for n := 3; n <= 6; n++ { reps := combrep(n, primes) for _, rep := range reps { sum := byte(0) for _, r := range rep { sum += r } if sum == 13 { var perms []string for i := 0; i < len(rep); i++ { rep[i] += 48 } findPerms(rep, 0, len(rep), &perms) res = append(res, perms...) } } } res2 := make([]int, len(res)) for i, r := range res { res2[i], _ = strconv.Atoi(r) } sort.Ints(res2) fmt.Println("Those numbers whose digits are all prime and sum to 13 are:") fmt.Println(res2) }
Convert this C# snippet to Go and keep its semantics consistent.
using System; using System.IO; using System.Text; namespace RosettaCode { internal class Program { private const string FileName = "NOTES.TXT"; private static void Main(string[] args) { if (args.Length==0) { string txt = File.ReadAllText(FileName); Console.WriteLine(txt); } else { var sb = new StringBuilder(); sb.Append(DateTime.Now).Append("\n\t"); foreach (string s in args) sb.Append(s).Append(" "); sb.Append("\n"); if (File.Exists(FileName)) File.AppendAllText(FileName, sb.ToString()); else File.WriteAllText(FileName, sb.ToString()); } } } }
package main import ( "fmt" "io" "os" "strings" "time" ) func addNote(fn string, note string) error { f, err := os.OpenFile(fn, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666) if err != nil { return err } _, err = fmt.Fprint(f, time.Now().Format(time.RFC1123), "\n\t", note, "\n") if cErr := f.Close(); err == nil { err = cErr } return err } func showNotes(w io.Writer, fn string) error { f, err := os.Open(fn) if err != nil { if os.IsNotExist(err) { return nil } return err } _, err = io.Copy(w, f) f.Close() return err } func main() { const fn = "NOTES.TXT" var err error if len(os.Args) > 1 { err = addNote(fn, strings.Join(os.Args[1:], " ")) } else { err = showNotes(os.Stdout, fn) } if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } }
Change the following C# code into Go without altering its purpose.
using System; public static class Angles { public static void Main() => Print(-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 6399, 1_000_000); public static void Print(params double[] angles) { string[] names = { "Degrees", "Gradians", "Mils", "Radians" }; Func<double, double> rnd = a => Math.Round(a, 4); Func<double, double>[] normal = { NormalizeDeg, NormalizeGrad, NormalizeMil, NormalizeRad }; Func<double, double>[,] convert = { { a => a, DegToGrad, DegToMil, DegToRad }, { GradToDeg, a => a, GradToMil, GradToRad }, { MilToDeg, MilToGrad, a => a, MilToRad }, { RadToDeg, RadToGrad, RadToMil, a => a } }; Console.WriteLine($@"{"Angle",-12}{"Normalized",-12}{"Unit",-12}{ "Degrees",-12}{"Gradians",-12}{"Mils",-12}{"Radians",-12}"); foreach (double angle in angles) { for (int i = 0; i < 4; i++) { double nAngle = normal[i](angle); Console.WriteLine($@"{ rnd(angle),-12}{ rnd(nAngle),-12}{ names[i],-12}{ rnd(convert[i, 0](nAngle)),-12}{ rnd(convert[i, 1](nAngle)),-12}{ rnd(convert[i, 2](nAngle)),-12}{ rnd(convert[i, 3](nAngle)),-12}"); } } } public static double NormalizeDeg(double angle) => Normalize(angle, 360); public static double NormalizeGrad(double angle) => Normalize(angle, 400); public static double NormalizeMil(double angle) => Normalize(angle, 6400); public static double NormalizeRad(double angle) => Normalize(angle, 2 * Math.PI); private static double Normalize(double angle, double N) { while (angle <= -N) angle += N; while (angle >= N) angle -= N; return angle; } public static double DegToGrad(double angle) => angle * 10 / 9; public static double DegToMil(double angle) => angle * 160 / 9; public static double DegToRad(double angle) => angle * Math.PI / 180; public static double GradToDeg(double angle) => angle * 9 / 10; public static double GradToMil(double angle) => angle * 16; public static double GradToRad(double angle) => angle * Math.PI / 200; public static double MilToDeg(double angle) => angle * 9 / 160; public static double MilToGrad(double angle) => angle / 16; public static double MilToRad(double angle) => angle * Math.PI / 3200; public static double RadToDeg(double angle) => angle * 180 / Math.PI; public static double RadToGrad(double angle) => angle * 200 / Math.PI; public static double RadToMil(double angle) => angle * 3200 / Math.PI; }
package main import ( "fmt" "math" "strconv" "strings" ) func d2d(d float64) float64 { return math.Mod(d, 360) } func g2g(g float64) float64 { return math.Mod(g, 400) } func m2m(m float64) float64 { return math.Mod(m, 6400) } func r2r(r float64) float64 { return math.Mod(r, 2*math.Pi) } func d2g(d float64) float64 { return d2d(d) * 400 / 360 } func d2m(d float64) float64 { return d2d(d) * 6400 / 360 } func d2r(d float64) float64 { return d2d(d) * math.Pi / 180 } func g2d(g float64) float64 { return g2g(g) * 360 / 400 } func g2m(g float64) float64 { return g2g(g) * 6400 / 400 } func g2r(g float64) float64 { return g2g(g) * math.Pi / 200 } func m2d(m float64) float64 { return m2m(m) * 360 / 6400 } func m2g(m float64) float64 { return m2m(m) * 400 / 6400 } func m2r(m float64) float64 { return m2m(m) * math.Pi / 3200 } func r2d(r float64) float64 { return r2r(r) * 180 / math.Pi } func r2g(r float64) float64 { return r2r(r) * 200 / math.Pi } func r2m(r float64) float64 { return r2r(r) * 3200 / math.Pi } func s(f float64) string { wf := strings.Split(strconv.FormatFloat(f, 'g', 15, 64), ".") if len(wf) == 1 { return fmt.Sprintf("%7s ", wf[0]) } le := len(wf[1]) if le > 7 { le = 7 } return fmt.Sprintf("%7s.%-7s", wf[0], wf[1][:le]) } func main() { angles := []float64{-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 399, 6399, 1000000} ft := "%s %s %s %s %s\n" fmt.Printf(ft, " degrees ", "normalized degs", " gradians ", " mils ", " radians") for _, a := range angles { fmt.Printf(ft, s(a), s(d2d(a)), s(d2g(a)), s(d2m(a)), s(d2r(a))) } fmt.Printf(ft, "\n gradians ", "normalized grds", " degrees ", " mils ", " radians") for _, a := range angles { fmt.Printf(ft, s(a), s(g2g(a)), s(g2d(a)), s(g2m(a)), s(g2r(a))) } fmt.Printf(ft, "\n mils ", "normalized mils", " degrees ", " gradians ", " radians") for _, a := range angles { fmt.Printf(ft, s(a), s(m2m(a)), s(m2d(a)), s(m2g(a)), s(m2r(a))) } fmt.Printf(ft, "\n radians ", "normalized rads", " degrees ", " gradians ", " mils ") for _, a := range angles { fmt.Printf(ft, s(a), s(r2r(a)), s(r2d(a)), s(r2g(a)), s(r2m(a))) } }
Translate the given C# code snippet into Go without altering its behavior.
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace RosettaCodeTasks { class Program { static void Main ( string[ ] args ) { FindCommonDirectoryPath.Test ( ); } } class FindCommonDirectoryPath { public static void Test ( ) { Console.WriteLine ( "Find Common Directory Path" ); Console.WriteLine ( ); List<string> PathSet1 = new List<string> ( ); PathSet1.Add ( "/home/user1/tmp/coverage/test" ); PathSet1.Add ( "/home/user1/tmp/covert/operator" ); PathSet1.Add ( "/home/user1/tmp/coven/members" ); Console.WriteLine("Path Set 1 (All Absolute Paths):"); foreach ( string path in PathSet1 ) { Console.WriteLine ( path ); } Console.WriteLine ( "Path Set 1 Common Path: {0}", FindCommonPath ( "/", PathSet1 ) ); } public static string FindCommonPath ( string Separator, List<string> Paths ) { string CommonPath = String.Empty; List<string> SeparatedPath = Paths .First ( str => str.Length == Paths.Max ( st2 => st2.Length ) ) .Split ( new string[ ] { Separator }, StringSplitOptions.RemoveEmptyEntries ) .ToList ( ); foreach ( string PathSegment in SeparatedPath.AsEnumerable ( ) ) { if ( CommonPath.Length == 0 && Paths.All ( str => str.StartsWith ( PathSegment ) ) ) { CommonPath = PathSegment; } else if ( Paths.All ( str => str.StartsWith ( CommonPath + Separator + PathSegment ) ) ) { CommonPath += Separator + PathSegment; } else { break; } } return CommonPath; } } }
package main import ( "fmt" "os" "path" ) func CommonPrefix(sep byte, paths ...string) string { switch len(paths) { case 0: return "" case 1: return path.Clean(paths[0]) } c := []byte(path.Clean(paths[0])) c = append(c, sep) for _, v := range paths[1:] { v = path.Clean(v) + string(sep) if len(v) < len(c) { c = c[:len(v)] } for i := 0; i < len(c); i++ { if v[i] != c[i] { c = c[:i] break } } } for i := len(c) - 1; i >= 0; i-- { if c[i] == sep { c = c[:i] break } } return string(c) } func main() { c := CommonPrefix(os.PathSeparator, "/home/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members", "/home "/home/user1/././tmp/covertly/foo", "/home/bob/../user1/tmp/coved/bar", ) if c == "" { fmt.Println("No common path") } else { fmt.Println("Common path:", c) } }
Transform the following C# implementation into Go, maintaining the same output and logic.
using System; using System.Collections.Generic; namespace RecamanSequence { class Program { static void Main(string[] args) { List<int> a = new List<int>() { 0 }; HashSet<int> used = new HashSet<int>() { 0 }; HashSet<int> used1000 = new HashSet<int>() { 0 }; bool foundDup = false; int n = 1; while (n <= 15 || !foundDup || used1000.Count < 1001) { int next = a[n - 1] - n; if (next < 1 || used.Contains(next)) { next += 2 * n; } bool alreadyUsed = used.Contains(next); a.Add(next); if (!alreadyUsed) { used.Add(next); if (0 <= next && next <= 1000) { used1000.Add(next); } } if (n == 14) { Console.WriteLine("The first 15 terms of the Recaman sequence are: [{0}]", string.Join(", ", a)); } if (!foundDup && alreadyUsed) { Console.WriteLine("The first duplicated term is a[{0}] = {1}", n, next); foundDup = true; } if (used1000.Count == 1001) { Console.WriteLine("Terms up to a[{0}] are needed to generate 0 to 1000", n); } n++; } } } }
package main import "fmt" func main() { a := []int{0} used := make(map[int]bool, 1001) used[0] = true used1000 := make(map[int]bool, 1001) used1000[0] = true for n, foundDup := 1, false; n <= 15 || !foundDup || len(used1000) < 1001; n++ { next := a[n-1] - n if next < 1 || used[next] { next += 2 * n } alreadyUsed := used[next] a = append(a, next) if !alreadyUsed { used[next] = true if next >= 0 && next <= 1000 { used1000[next] = true } } if n == 14 { fmt.Println("The first 15 terms of the Recaman's sequence are:", a) } if !foundDup && alreadyUsed { fmt.Printf("The first duplicated term is a[%d] = %d\n", n, next) foundDup = true } if len(used1000) == 1001 { fmt.Printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n) } } }
Produce a functionally identical Go code for the snippet given in C#.
using System; using System.Collections.Generic; namespace RecamanSequence { class Program { static void Main(string[] args) { List<int> a = new List<int>() { 0 }; HashSet<int> used = new HashSet<int>() { 0 }; HashSet<int> used1000 = new HashSet<int>() { 0 }; bool foundDup = false; int n = 1; while (n <= 15 || !foundDup || used1000.Count < 1001) { int next = a[n - 1] - n; if (next < 1 || used.Contains(next)) { next += 2 * n; } bool alreadyUsed = used.Contains(next); a.Add(next); if (!alreadyUsed) { used.Add(next); if (0 <= next && next <= 1000) { used1000.Add(next); } } if (n == 14) { Console.WriteLine("The first 15 terms of the Recaman sequence are: [{0}]", string.Join(", ", a)); } if (!foundDup && alreadyUsed) { Console.WriteLine("The first duplicated term is a[{0}] = {1}", n, next); foundDup = true; } if (used1000.Count == 1001) { Console.WriteLine("Terms up to a[{0}] are needed to generate 0 to 1000", n); } n++; } } } }
package main import "fmt" func main() { a := []int{0} used := make(map[int]bool, 1001) used[0] = true used1000 := make(map[int]bool, 1001) used1000[0] = true for n, foundDup := 1, false; n <= 15 || !foundDup || len(used1000) < 1001; n++ { next := a[n-1] - n if next < 1 || used[next] { next += 2 * n } alreadyUsed := used[next] a = append(a, next) if !alreadyUsed { used[next] = true if next >= 0 && next <= 1000 { used1000[next] = true } } if n == 14 { fmt.Println("The first 15 terms of the Recaman's sequence are:", a) } if !foundDup && alreadyUsed { fmt.Printf("The first duplicated term is a[%d] = %d\n", n, next) foundDup = true } if len(used1000) == 1001 { fmt.Printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n) } } }
Write the same code in Go as shown below in C#.
using System; using System.Runtime.InteropServices; public unsafe class Program { public static unsafe void HeapMemory() { const int HEAP_ZERO_MEMORY = 0x00000008; const int size = 1000; int ph = GetProcessHeap(); void* pointer = HeapAlloc(ph, HEAP_ZERO_MEMORY, size); if (pointer == null) throw new OutOfMemoryException(); Console.WriteLine(HeapSize(ph, 0, pointer)); HeapFree(ph, 0, pointer); } public static unsafe void StackMemory() { byte* buffer = stackalloc byte[1000]; } public static void Main(string[] args) { HeapMemory(); StackMemory(); } [DllImport("kernel32")] static extern void* HeapAlloc(int hHeap, int flags, int size); [DllImport("kernel32")] static extern bool HeapFree(int hHeap, int flags, void* block); [DllImport("kernel32")] static extern int GetProcessHeap(); [DllImport("kernel32")] static extern int HeapSize(int hHeap, int flags, void* block); }
func inc(n int) { x := n + 1 println(x) }
Convert this C# block to Go, preserving its control flow and logic.
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace RosettaTicTacToe { class Program { static string[][] Players = new string[][] { new string[] { "COMPUTER", "X" }, new string[] { "HUMAN", "O" } }; const int Unplayed = -1; const int Computer = 0; const int Human = 1; static int[] GameBoard = new int[9]; static int[] corners = new int[] { 0, 2, 6, 8 }; static int[][] wins = new int[][] { new int[] { 0, 1, 2 }, new int[] { 3, 4, 5 }, new int[] { 6, 7, 8 }, new int[] { 0, 3, 6 }, new int[] { 1, 4, 7 }, new int[] { 2, 5, 8 }, new int[] { 0, 4, 8 }, new int[] { 2, 4, 6 } }; static void Main(string[] args) { while (true) { Console.Clear(); Console.WriteLine("Welcome to Rosetta Code Tic-Tac-Toe for C#."); initializeGameBoard(); displayGameBoard(); int currentPlayer = rnd.Next(0, 2); Console.WriteLine("The first move goes to {0} who is playing {1}s.\n", playerName(currentPlayer), playerToken(currentPlayer)); while (true) { int thisMove = getMoveFor(currentPlayer); if (thisMove == Unplayed) { Console.WriteLine("{0}, you've quit the game ... am I that good?", playerName(currentPlayer)); break; } playMove(thisMove, currentPlayer); displayGameBoard(); if (isGameWon()) { Console.WriteLine("{0} has won the game!", playerName(currentPlayer)); break; } else if (isGameTied()) { Console.WriteLine("Cat game ... we have a tie."); break; } currentPlayer = getNextPlayer(currentPlayer); } if (!playAgain()) return; } } static int getMoveFor(int player) { if (player == Human) return getManualMove(player); else { int selectedMove = getSemiRandomMove(player); Console.WriteLine("{0} selects position {1}.", playerName(player), selectedMove + 1); return selectedMove; } } static int getManualMove(int player) { while (true) { Console.Write("{0}, enter you move (number): ", playerName(player)); ConsoleKeyInfo keyInfo = Console.ReadKey(); Console.WriteLine(); if (keyInfo.Key == ConsoleKey.Escape) return Unplayed; if (keyInfo.Key >= ConsoleKey.D1 && keyInfo.Key <= ConsoleKey.D9) { int move = keyInfo.KeyChar - '1'; if (GameBoard[move] == Unplayed) return move; else Console.WriteLine("Spot {0} is already taken, please select again.", move + 1); } else Console.WriteLine("Illegal move, please select again.\n"); } } static int getRandomMove(int player) { int movesLeft = GameBoard.Count(position => position == Unplayed); int x = rnd.Next(0, movesLeft); for (int i = 0; i < GameBoard.Length; i++) { if (GameBoard[i] == Unplayed && x < 0) return i; x--; } return Unplayed; } static int getSemiRandomMove(int player) { int posToPlay; if (checkForWinningMove(player, out posToPlay)) return posToPlay; if (checkForBlockingMove(player, out posToPlay)) return posToPlay; return getRandomMove(player); } static int getBestMove(int player) { return -1; } static bool checkForWinningMove(int player, out int posToPlay) { posToPlay = Unplayed; foreach (var line in wins) if (twoOfThreeMatchPlayer(player, line, out posToPlay)) return true; return false; } static bool checkForBlockingMove(int player, out int posToPlay) { posToPlay = Unplayed; foreach (var line in wins) if (twoOfThreeMatchPlayer(getNextPlayer(player), line, out posToPlay)) return true; return false; } static bool twoOfThreeMatchPlayer(int player, int[] line, out int posToPlay) { int cnt = 0; posToPlay = int.MinValue; foreach (int pos in line) { if (GameBoard[pos] == player) cnt++; else if (GameBoard[pos] == Unplayed) posToPlay = pos; } return cnt == 2 && posToPlay >= 0; } static void playMove(int boardPosition, int player) { GameBoard[boardPosition] = player; } static bool isGameWon() { return wins.Any(line => takenBySamePlayer(line[0], line[1], line[2])); } static bool takenBySamePlayer(int a, int b, int c) { return GameBoard[a] != Unplayed && GameBoard[a] == GameBoard[b] && GameBoard[a] == GameBoard[c]; } static bool isGameTied() { return !GameBoard.Any(spot => spot == Unplayed); } static Random rnd = new Random(); static void initializeGameBoard() { for (int i = 0; i < GameBoard.Length; i++) GameBoard[i] = Unplayed; } static string playerName(int player) { return Players[player][0]; } static string playerToken(int player) { return Players[player][1]; } static int getNextPlayer(int player) { return (player + 1) % 2; } static void displayGameBoard() { Console.WriteLine(" {0} | {1} | {2}", pieceAt(0), pieceAt(1), pieceAt(2)); Console.WriteLine("---|---|---"); Console.WriteLine(" {0} | {1} | {2}", pieceAt(3), pieceAt(4), pieceAt(5)); Console.WriteLine("---|---|---"); Console.WriteLine(" {0} | {1} | {2}", pieceAt(6), pieceAt(7), pieceAt(8)); Console.WriteLine(); } static string pieceAt(int boardPosition) { if (GameBoard[boardPosition] == Unplayed) return (boardPosition + 1).ToString(); return playerToken(GameBoard[boardPosition]); } private static bool playAgain() { Console.WriteLine("\nDo you want to play again?"); return Console.ReadKey(false).Key == ConsoleKey.Y; } } }
package main import ( "bufio" "fmt" "math/rand" "os" "strings" ) var b []byte func printBoard() { fmt.Printf("%s\n%s\n%s\n", b[0:3], b[3:6], b[6:9]) } var pScore, cScore int var pMark, cMark byte = 'X', 'O' var in = bufio.NewReader(os.Stdin) func main() { b = make([]byte, 9) fmt.Println("Play by entering a digit.") for { for i := range b { b[i] = '1' + byte(i) } computerStart := cMark == 'X' if computerStart { fmt.Println("I go first, playing X's") } else { fmt.Println("You go first, playing X's") } TakeTurns: for { if !computerStart { if !playerTurn() { return } if gameOver() { break TakeTurns } } computerStart = false computerTurn() if gameOver() { break TakeTurns } } fmt.Println("Score: you", pScore, "me", cScore) fmt.Println("\nLet's play again.") } } func playerTurn() bool { var pm string var err error for i := 0; i < 3; i++ { printBoard() fmt.Printf("%c's move? ", pMark) if pm, err = in.ReadString('\n'); err != nil { fmt.Println(err) return false } pm = strings.TrimSpace(pm) if pm >= "1" && pm <= "9" && b[pm[0]-'1'] == pm[0] { x := pm[0] - '1' b[x] = pMark return true } } fmt.Println("You're not playing right.") return false } var choices = make([]int, 9) func computerTurn() { printBoard() var x int defer func() { fmt.Println("My move:", x+1) b[x] = cMark }() block := -1 for _, l := range lines { var mine, yours int x = -1 for _, sq := range l { switch b[sq] { case cMark: mine++ case pMark: yours++ default: x = sq } } if mine == 2 && x >= 0 { return } if yours == 2 && x >= 0 { block = x } } if block >= 0 { x = block return } choices = choices[:0] for i, sq := range b { if sq == '1'+byte(i) { choices = append(choices, i) } } x = choices[rand.Intn(len(choices))] } func gameOver() bool { for _, l := range lines { if b[l[0]] == b[l[1]] && b[l[1]] == b[l[2]] { printBoard() if b[l[0]] == cMark { fmt.Println("I win!") cScore++ pMark, cMark = 'X', 'O' } else { fmt.Println("You win!") pScore++ pMark, cMark = 'O', 'X' } return true } } for i, sq := range b { if sq == '1'+byte(i) { return false } } fmt.Println("Cat game.") pMark, cMark = cMark, pMark return true } var lines = [][]int{ {0, 1, 2}, {3, 4, 5}, {6, 7, 8}, {0, 3, 6}, {1, 4, 7}, {2, 5, 8}, {0, 4, 8}, {2, 4, 6}, }
Write a version of this C# function in Go with identical behavior.
using System; using System.Numerics; class Program { static void Main() { BigInteger i = 1; while (true) { Console.WriteLine(i++); } } }
package main import "fmt" func main() { for i := 1;; i++ { fmt.Println(i) } }
Convert this C# snippet to Go and keep its semantics consistent.
using System; using System.Numerics; class Program { static void Main() { BigInteger i = 1; while (true) { Console.WriteLine(i++); } } }
package main import "fmt" func main() { for i := 1;; i++ { fmt.Println(i) } }
Translate this program into Go but keep the logic exactly as in C#.
private string LookupDns(string s) { try { System.Net.IPHostEntry ip = System.Net.Dns.GetHostEntry(s); string result = ip.AddressList[0].ToString(); for (int i = 1; i < ip.AddressList.Length; ++i) result += ", " + ip.AddressList[i].ToString(); return result; } catch (System.Net.Sockets.SocketException se) { return se.Message; } }
package main import ( "fmt" "net" ) func main() { if addrs, err := net.LookupHost("www.kame.net"); err == nil { fmt.Println(addrs) } else { fmt.Println(err) } }
Produce a functionally identical Go code for the snippet given in C#.
using System; public class SevenSidedDice { Random random = new Random(); static void Main(string[] args) { SevenSidedDice sevenDice = new SevenSidedDice(); Console.WriteLine("Random number from 1 to 7: "+ sevenDice.seven()); Console.Read(); } int seven() { int v=21; while(v>20) v=five()+five()*5-6; return 1+v%7; } int five() { return 1 + random.Next(5); } }
package main import ( "fmt" "math" "math/rand" "time" ) func dice5() int { return rand.Intn(5) + 1 } func dice7() (i int) { for { i = 5*dice5() + dice5() if i < 27 { break } } return (i / 3) - 1 } func distCheck(f func() int, n int, repeats int, delta float64) (max float64, flatEnough bool) { count := make([]int, n) for i := 0; i < repeats; i++ { count[f()-1]++ } expected := float64(repeats) / float64(n) for _, c := range count { max = math.Max(max, math.Abs(float64(c)-expected)) } return max, max < delta } func main() { rand.Seed(time.Now().UnixNano()) const calls = 1000000 max, flatEnough := distCheck(dice7, 7, calls, 500) fmt.Println("Max delta:", max, "Flat enough:", flatEnough) max, flatEnough = distCheck(dice7, 7, calls, 500) fmt.Println("Max delta:", max, "Flat enough:", flatEnough) }
Write a version of this C# function in Go with identical behavior.
using System; using static System.Console; class Program { static bool[] np; static void ms(long lmt) { np = new bool[lmt]; np[0] = np[1] = true; for (long n = 2, j = 1; n < lmt; n += j, j = 2) if (!np[n]) for (long k = n * n; k < lmt; k += n) np[k] = true; } static bool is_Mag(long n) { long res, rem; for (long p = 10; n >= p; p *= 10) { res = Math.DivRem (n, p, out rem); if (np[res + rem]) return false; } return true; } static void Main(string[] args) { ms(100_009); string mn; WriteLine("First 45{0}", mn = " magnanimous numbers:"); for (long l = 0, c = 0; c < 400; l++) if (is_Mag(l)) { if (c++ < 45 || (c > 240 && c <= 250) || c > 390) Write(c <= 45 ? "{0,4} " : "{0,8:n0} ", l); if (c < 45 && c % 15 == 0) WriteLine(); if (c == 240) WriteLine ("\n\n241st through 250th{0}", mn); if (c == 390) WriteLine ("\n\n391st through 400th{0}", mn); } } }
package main import "fmt" func isPrime(n uint64) bool { switch { case n < 2: return false case n%2 == 0: return n == 2 case n%3 == 0: return n == 3 default: d := uint64(5) for d*d <= n { if n%d == 0 { return false } d += 2 if n%d == 0 { return false } d += 4 } return true } } func ord(n int) string { m := n % 100 if m >= 4 && m <= 20 { return fmt.Sprintf("%dth", n) } m %= 10 suffix := "th" if m < 4 { switch m { case 1: suffix = "st" case 2: suffix = "nd" case 3: suffix = "rd" } } return fmt.Sprintf("%d%s", n, suffix) } func isMagnanimous(n uint64) bool { if n < 10 { return true } for p := uint64(10); ; p *= 10 { q := n / p r := n % p if !isPrime(q + r) { return false } if q < 10 { break } } return true } func listMags(from, thru, digs, perLine int) { if from < 2 { fmt.Println("\nFirst", thru, "magnanimous numbers:") } else { fmt.Printf("\n%s through %s magnanimous numbers:\n", ord(from), ord(thru)) } for i, c := uint64(0), 0; c < thru; i++ { if isMagnanimous(i) { c++ if c >= from { fmt.Printf("%*d ", digs, i) if c%perLine == 0 { fmt.Println() } } } } } func main() { listMags(1, 45, 3, 15) listMags(241, 250, 1, 10) listMags(391, 400, 1, 10) }
Ensure the translated Go code behaves exactly like the original C# snippet.
class Program { static void Main(string[] args) { Console.WriteLine("Enter two integers. Space delimited please: "); string s = Console.ReadLine(); int[,] myArray=new int[(int)s[0],(int)s[2]]; myArray[0, 0] = 2; Console.WriteLine(myArray[0, 0]); Console.ReadLine(); } }
package main import "fmt" func main() { var row, col int fmt.Print("enter rows cols: ") fmt.Scan(&row, &col) a := make([][]int, row) for i := range a { a[i] = make([]int, col) } fmt.Println("a[0][0] =", a[0][0]) a[row-1][col-1] = 7 fmt.Printf("a[%d][%d] = %d\n", row-1, col-1, a[row-1][col-1]) a = nil }
Port the provided C# code into Go while preserving the original functionality.
class Program { static void Main(string[] args) { Console.WriteLine("Enter two integers. Space delimited please: "); string s = Console.ReadLine(); int[,] myArray=new int[(int)s[0],(int)s[2]]; myArray[0, 0] = 2; Console.WriteLine(myArray[0, 0]); Console.ReadLine(); } }
package main import "fmt" func main() { var row, col int fmt.Print("enter rows cols: ") fmt.Scan(&row, &col) a := make([][]int, row) for i := range a { a[i] = make([]int, col) } fmt.Println("a[0][0] =", a[0][0]) a[row-1][col-1] = 7 fmt.Printf("a[%d][%d] = %d\n", row-1, col-1, a[row-1][col-1]) a = nil }
Please provide an equivalent version of this C# code in Go.
using System; using System.Linq; namespace ChineseRemainderTheorem { class Program { static void Main(string[] args) { int[] n = { 3, 5, 7 }; int[] a = { 2, 3, 2 }; int result = ChineseRemainderTheorem.Solve(n, a); int counter = 0; int maxCount = n.Length - 1; while (counter <= maxCount) { Console.WriteLine($"{result} ≡ {a[counter]} (mod {n[counter]})"); counter++; } } } public static class ChineseRemainderTheorem { public static int Solve(int[] n, int[] a) { int prod = n.Aggregate(1, (i, j) => i * j); int p; int sm = 0; for (int i = 0; i < n.Length; i++) { p = prod / n[i]; sm += a[i] * ModularMultiplicativeInverse(p, n[i]) * p; } return sm % prod; } private static int ModularMultiplicativeInverse(int a, int mod) { int b = a % mod; for (int x = 1; x < mod; x++) { if ((b * x) % mod == 1) { return x; } } return 1; } } }
package main import ( "fmt" "math/big" ) var one = big.NewInt(1) func crt(a, n []*big.Int) (*big.Int, error) { p := new(big.Int).Set(n[0]) for _, n1 := range n[1:] { p.Mul(p, n1) } var x, q, s, z big.Int for i, n1 := range n { q.Div(p, n1) z.GCD(nil, &s, n1, &q) if z.Cmp(one) != 0 { return nil, fmt.Errorf("%d not coprime", n1) } x.Add(&x, s.Mul(a[i], s.Mul(&s, &q))) } return x.Mod(&x, p), nil } func main() { n := []*big.Int{ big.NewInt(3), big.NewInt(5), big.NewInt(7), } a := []*big.Int{ big.NewInt(2), big.NewInt(3), big.NewInt(2), } fmt.Println(crt(a, n)) }
Change the programming language of this snippet from C# to Go without modifying what it does.
using System; using System.Linq; namespace ChineseRemainderTheorem { class Program { static void Main(string[] args) { int[] n = { 3, 5, 7 }; int[] a = { 2, 3, 2 }; int result = ChineseRemainderTheorem.Solve(n, a); int counter = 0; int maxCount = n.Length - 1; while (counter <= maxCount) { Console.WriteLine($"{result} ≡ {a[counter]} (mod {n[counter]})"); counter++; } } } public static class ChineseRemainderTheorem { public static int Solve(int[] n, int[] a) { int prod = n.Aggregate(1, (i, j) => i * j); int p; int sm = 0; for (int i = 0; i < n.Length; i++) { p = prod / n[i]; sm += a[i] * ModularMultiplicativeInverse(p, n[i]) * p; } return sm % prod; } private static int ModularMultiplicativeInverse(int a, int mod) { int b = a % mod; for (int x = 1; x < mod; x++) { if ((b * x) % mod == 1) { return x; } } return 1; } } }
package main import ( "fmt" "math/big" ) var one = big.NewInt(1) func crt(a, n []*big.Int) (*big.Int, error) { p := new(big.Int).Set(n[0]) for _, n1 := range n[1:] { p.Mul(p, n1) } var x, q, s, z big.Int for i, n1 := range n { q.Div(p, n1) z.GCD(nil, &s, n1, &q) if z.Cmp(one) != 0 { return nil, fmt.Errorf("%d not coprime", n1) } x.Add(&x, s.Mul(a[i], s.Mul(&s, &q))) } return x.Mod(&x, p), nil } func main() { n := []*big.Int{ big.NewInt(3), big.NewInt(5), big.NewInt(7), } a := []*big.Int{ big.NewInt(2), big.NewInt(3), big.NewInt(2), } fmt.Println(crt(a, n)) }
Produce a functionally identical Go code for the snippet given in C#.
using System; using System.Linq; namespace ChineseRemainderTheorem { class Program { static void Main(string[] args) { int[] n = { 3, 5, 7 }; int[] a = { 2, 3, 2 }; int result = ChineseRemainderTheorem.Solve(n, a); int counter = 0; int maxCount = n.Length - 1; while (counter <= maxCount) { Console.WriteLine($"{result} ≡ {a[counter]} (mod {n[counter]})"); counter++; } } } public static class ChineseRemainderTheorem { public static int Solve(int[] n, int[] a) { int prod = n.Aggregate(1, (i, j) => i * j); int p; int sm = 0; for (int i = 0; i < n.Length; i++) { p = prod / n[i]; sm += a[i] * ModularMultiplicativeInverse(p, n[i]) * p; } return sm % prod; } private static int ModularMultiplicativeInverse(int a, int mod) { int b = a % mod; for (int x = 1; x < mod; x++) { if ((b * x) % mod == 1) { return x; } } return 1; } } }
package main import ( "fmt" "math/big" ) var one = big.NewInt(1) func crt(a, n []*big.Int) (*big.Int, error) { p := new(big.Int).Set(n[0]) for _, n1 := range n[1:] { p.Mul(p, n1) } var x, q, s, z big.Int for i, n1 := range n { q.Div(p, n1) z.GCD(nil, &s, n1, &q) if z.Cmp(one) != 0 { return nil, fmt.Errorf("%d not coprime", n1) } x.Add(&x, s.Mul(a[i], s.Mul(&s, &q))) } return x.Mod(&x, p), nil } func main() { n := []*big.Int{ big.NewInt(3), big.NewInt(5), big.NewInt(7), } a := []*big.Int{ big.NewInt(2), big.NewInt(3), big.NewInt(2), } fmt.Println(crt(a, n)) }
Convert the following code from C# to Go, ensuring the logic remains intact.
using System; using System.Numerics; namespace PiCalc { internal class Program { private readonly BigInteger FOUR = new BigInteger(4); private readonly BigInteger SEVEN = new BigInteger(7); private readonly BigInteger TEN = new BigInteger(10); private readonly BigInteger THREE = new BigInteger(3); private readonly BigInteger TWO = new BigInteger(2); private BigInteger k = BigInteger.One; private BigInteger l = new BigInteger(3); private BigInteger n = new BigInteger(3); private BigInteger q = BigInteger.One; private BigInteger r = BigInteger.Zero; private BigInteger t = BigInteger.One; public void CalcPiDigits() { BigInteger nn, nr; bool first = true; while (true) { if ((FOUR*q + r - t).CompareTo(n*t) == -1) { Console.Write(n); if (first) { Console.Write("."); first = false; } nr = TEN*(r - (n*t)); n = TEN*(THREE*q + r)/t - (TEN*n); q *= TEN; r = nr; } else { nr = (TWO*q + r)*l; nn = (q*(SEVEN*k) + TWO + r*l)/(t*l); q *= k; t *= l; l += TWO; k += BigInteger.One; n = nn; r = nr; } } } private static void Main(string[] args) { new Program().CalcPiDigits(); } } }
package main import ( "fmt" "math/big" ) type lft struct { q,r,s,t big.Int } func (t *lft) extr(x *big.Int) *big.Rat { var n, d big.Int var r big.Rat return r.SetFrac( n.Add(n.Mul(&t.q, x), &t.r), d.Add(d.Mul(&t.s, x), &t.t)) } var three = big.NewInt(3) var four = big.NewInt(4) func (t *lft) next() *big.Int { r := t.extr(three) var f big.Int return f.Div(r.Num(), r.Denom()) } func (t *lft) safe(n *big.Int) bool { r := t.extr(four) var f big.Int if n.Cmp(f.Div(r.Num(), r.Denom())) == 0 { return true } return false } func (t *lft) comp(u *lft) *lft { var r lft var a, b big.Int r.q.Add(a.Mul(&t.q, &u.q), b.Mul(&t.r, &u.s)) r.r.Add(a.Mul(&t.q, &u.r), b.Mul(&t.r, &u.t)) r.s.Add(a.Mul(&t.s, &u.q), b.Mul(&t.t, &u.s)) r.t.Add(a.Mul(&t.s, &u.r), b.Mul(&t.t, &u.t)) return &r } func (t *lft) prod(n *big.Int) *lft { var r lft r.q.SetInt64(10) r.r.Mul(r.r.SetInt64(-10), n) r.t.SetInt64(1) return r.comp(t) } func main() { z := new(lft) z.q.SetInt64(1) z.t.SetInt64(1) var k int64 lfts := func() *lft { k++ r := new(lft) r.q.SetInt64(k) r.r.SetInt64(4*k+2) r.t.SetInt64(2*k+1) return r } for { y := z.next() if z.safe(y) { fmt.Print(y) z = z.prod(y) } else { z = z.comp(lfts()) } } }
Write the same code in Go as shown below in C#.
using System; static class YCombinator<T, TResult> { private delegate Func<T, TResult> RecursiveFunc(RecursiveFunc r); public static Func<Func<Func<T, TResult>, Func<T, TResult>>, Func<T, TResult>> Fix { get; } = f => ((RecursiveFunc)(g => f(x => g(g)(x))))(g => f(x => g(g)(x))); } static class Program { static void Main() { var fac = YCombinator<int, int>.Fix(f => x => x < 2 ? 1 : x * f(x - 1)); var fib = YCombinator<int, int>.Fix(f => x => x < 2 ? x : f(x - 1) + f(x - 2)); Console.WriteLine(fac(10)); Console.WriteLine(fib(10)); } }
package main import "fmt" type Func func(int) int type FuncFunc func(Func) Func type RecursiveFunc func (RecursiveFunc) Func func main() { fac := Y(almost_fac) fib := Y(almost_fib) fmt.Println("fac(10) = ", fac(10)) fmt.Println("fib(10) = ", fib(10)) } func Y(f FuncFunc) Func { g := func(r RecursiveFunc) Func { return f(func(x int) int { return r(r)(x) }) } return g(g) } func almost_fac(f Func) Func { return func(x int) int { if x <= 1 { return 1 } return x * f(x-1) } } func almost_fib(f Func) Func { return func(x int) int { if x <= 2 { return 1 } return f(x-1)+f(x-2) } }
Ensure the translated Go code behaves exactly like the original C# snippet.
using System.Linq; class Program { static void Main() { int a, b, c, d, e, f, g; int[] h = new int[g = 1000]; for (a = 0, b = 1, c = 2; c < g; a = b, b = c++) for (d = a, e = b - d, f = h[b]; e <= b; e++) if (f == h[d--]) { h[c] = e; break; } void sho(int i) { System.Console.WriteLine(string.Join(" ", h.Skip(i).Take(10))); } sho(0); sho(990); } }
package main import "fmt" func main() { const max = 1000 a := make([]int, max) for n := 0; n < max-1; n++ { for m := n - 1; m >= 0; m-- { if a[m] == a[n] { a[n+1] = n - m break } } } fmt.Println("The first ten terms of the Van Eck sequence are:") fmt.Println(a[:10]) fmt.Println("\nTerms 991 to 1000 of the sequence are:") fmt.Println(a[990:]) }
Write a version of this C# function in Go with identical behavior.
using System.Linq; class Program { static void Main() { int a, b, c, d, e, f, g; int[] h = new int[g = 1000]; for (a = 0, b = 1, c = 2; c < g; a = b, b = c++) for (d = a, e = b - d, f = h[b]; e <= b; e++) if (f == h[d--]) { h[c] = e; break; } void sho(int i) { System.Console.WriteLine(string.Join(" ", h.Skip(i).Take(10))); } sho(0); sho(990); } }
package main import "fmt" func main() { const max = 1000 a := make([]int, max) for n := 0; n < max-1; n++ { for m := n - 1; m >= 0; m-- { if a[m] == a[n] { a[n+1] = n - m break } } } fmt.Println("The first ten terms of the Van Eck sequence are:") fmt.Println(a[:10]) fmt.Println("\nTerms 991 to 1000 of the sequence are:") fmt.Println(a[990:]) }
Convert this C block to Python, preserving its control flow and logic.
void bitwise(int a, int b) { printf("a and b: %d\n", a & b); printf("a or b: %d\n", a | b); printf("a xor b: %d\n", a ^ b); printf("not a: %d\n", ~a); printf("a << n: %d\n", a << b); printf("a >> n: %d\n", a >> b); unsigned int c = a; printf("c >> b: %d\n", c >> b); return 0; }
def bitwise_built_ins(width, a, b): mask = (1 << width) - 1 print(f) def rotr(width, a, n): "Rotate a, n times to the right" if n < 0: return rotl(width, a, -n) elif n == 0: return a else: mask = (1 << width) - 1 a, n = a & mask, n % width return ((a >> n) | ((a & ((1 << n) - 1)) << (width - n))) def rotl(width, a, n): "Rotate a, n times to the left" if n < 0: return rotr(width, a, -n) elif n == 0: return a else: mask = (1 << width) - 1 a, n = a & mask, n % width return (((a << n) & mask) | (a >> (width - n))) def asr(width, a, n): "Arithmetic shift a, n times to the right. (sign preserving)." mask, top_bit_mask = ((1 << width) - 1), 1 << (width - 1) if n < 0: return (a << -n) & mask elif n == 0: return a elif n >= width: return mask if a & top_bit_mask else 0 else: a = a & mask if a & top_bit_mask: signs = (1 << n) - 1 return a >> n | (signs << width - n) else: return a >> n def helper_funcs(width, a): mask, top_bit_mask = ((1 << width) - 1), 1 << (width - 1) aa = a | top_bit_mask print(f) if __name__ == '__main__': bitwise_built_ins(8, 27, 125) helper_funcs(8, 27)
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; typedef struct { double r, g, b; } rgb; rgb ** pix; void sc_up() { long long tmp = dx - dy; dy = dx + dy; dx = tmp; scale *= 2; x *= 2; y *= 2; } void h_rgb(long long x, long long y) { rgb *p = &pix[y][x]; # define SAT 1 double h = 6.0 * clen / scale; double VAL = 1 - (cos(3.141592653579 * 64 * clen / scale) - 1) / 4; 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 tmp; # define LEFT tmp = -dy; dy = dx; dx = tmp # define RIGHT tmp = dy; dy = -dx; dx = tmp while (*str != '\0') { switch(*(str++)) { case 'X': if (d) iter_string("X+YF+", d - 1); continue; case 'Y': if (d) iter_string("-FX-Y", d - 1); continue; case '+': RIGHT; continue; case '-': LEFT; continue; case 'F': clen ++; h_rgb(x/scale, y/scale); x += dx; y += dy; continue; } } } void dragon(long leng, int depth) { long i, d = leng / 3 + 1; long h = leng + 3, w = leng + d * 3 / 2 + 2; 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 = d; dx = leng; dy = 0; scale = 1; clen = 0; for (i = 0; i < depth; i++) sc_up(); iter_string("FX", 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); dragon(size, depth * 2); return 0; }
l = 3 ints = 13 def setup(): size(700, 600) background(0, 0, 255) translate(150, 100) stroke(255) turn_left(l, ints) turn_right(l, ints) def turn_right(l, ints): if ints == 0: line(0, 0, 0, -l) translate(0, -l) else: turn_left(l, ints - 1) rotate(radians(90)) turn_right(l, ints - 1) def turn_left(l, ints): if ints == 0: line(0, 0, 0, -l) translate(0, -l) else: turn_left(l, ints - 1) rotate(radians(-90)) turn_right(l, ints - 1)
Write the same code in Python as shown below in C.
#include <conio.h> #include <stdio.h> int main() { int n1, n2, n3; printf( "\n Introduzca el primer n%cmero (entero): ", 163 ); scanf( "%d", &n1 ); printf( "\n Introduzca el segundo n%cmero (entero): ", 163 ); scanf( "%d", &n2 ); printf( "\n Introduzca el tercer n%cmero (entero): ", 163 ); scanf( "%d", &n3 ); if ( n1 >= n2 && n1 >= n3 ) printf( "\n %d es el mayor.", n1 ); else if ( n2 > n3 ) printf( "\n %d es el mayor.", n2 ); else printf( "\n %d es el mayor.", n3 ); getch(); return 0; }
for line in lines open('input.txt'): print line
Convert this C snippet to Python and keep its semantics consistent.
void insert(link* anchor, link* newlink) { newlink->next = anchor->next; newlink->prev = anchor; (newlink->next)->prev = newlink; anchor->next = newlink; }
def insert(anchor, new): new.next = anchor.next new.prev = anchor anchor.next.prev = new anchor.next = new
Convert the following code from C to Python, ensuring the logic remains intact.
#include <locale.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> typedef uint32_t integer; integer next_prime_digit_number(integer n) { if (n == 0) return 2; switch (n % 10) { case 2: return n + 1; case 3: case 5: return n + 2; default: return 2 + next_prime_digit_number(n/10) * 10; } } bool is_prime(integer n) { 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; static const integer wheel[] = { 4,2,4,2,4,6,2,6 }; integer p = 7; for (;;) { for (int i = 0; i < 8; ++i) { if (p * p > n) return true; if (n % p == 0) return false; p += wheel[i]; } } } int main() { setlocale(LC_ALL, ""); const integer limit = 1000000000; integer n = 0, max = 0; printf("First 25 SPDS primes:\n"); for (int i = 0; n < limit; ) { n = next_prime_digit_number(n); if (!is_prime(n)) continue; if (i < 25) { if (i > 0) printf(" "); printf("%'u", n); } else if (i == 25) printf("\n"); ++i; if (i == 100) printf("Hundredth SPDS prime: %'u\n", n); else if (i == 1000) printf("Thousandth SPDS prime: %'u\n", n); else if (i == 10000) printf("Ten thousandth SPDS prime: %'u\n", n); max = n; } printf("Largest SPDS prime less than %'u: %'u\n", limit, max); return 0; }
def divisors(n): divs = [1] for ii in range(2, int(n ** 0.5) + 3): if n % ii == 0: divs.append(ii) divs.append(int(n / ii)) divs.append(n) return list(set(divs)) def is_prime(n): return len(divisors(n)) == 2 def digit_check(n): if len(str(n))<2: return True else: for digit in str(n): if not is_prime(int(digit)): return False return True def sequence(max_n=None): ii = 0 n = 0 while True: ii += 1 if is_prime(ii): if max_n is not None: if n>max_n: break if digit_check(ii): n += 1 yield ii if __name__ == '__main__': generator = sequence(100) for index, item in zip(range(1, 16), generator): print(index, item) for index, item in zip(range(16, 100), generator): pass print(100, generator.__next__())
Convert this C block to Python, preserving its control flow and logic.
#include <stdio.h> #include <string.h> int qselect(int *v, int len, int k) { # define SWAP(a, b) { tmp = v[a]; v[a] = v[b]; v[b] = tmp; } int i, st, tmp; for (st = i = 0; i < len - 1; i++) { if (v[i] > v[len-1]) continue; SWAP(i, st); st++; } SWAP(len-1, st); return k == st ?v[st] :st > k ? qselect(v, st, k) : qselect(v + st, len - st, k - st); } int main(void) { # define N (sizeof(x)/sizeof(x[0])) int x[] = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4}; int y[N]; int i; for (i = 0; i < 10; i++) { memcpy(y, x, sizeof(x)); printf("%d: %d\n", i, qselect(y, 10, i)); } return 0; }
import random def partition(vector, left, right, pivotIndex): pivotValue = vector[pivotIndex] vector[pivotIndex], vector[right] = vector[right], vector[pivotIndex] storeIndex = left for i in range(left, right): if vector[i] < pivotValue: vector[storeIndex], vector[i] = vector[i], vector[storeIndex] storeIndex += 1 vector[right], vector[storeIndex] = vector[storeIndex], vector[right] return storeIndex def _select(vector, left, right, k): "Returns the k-th smallest, (k >= 0), element of vector within vector[left:right+1] inclusive." while True: pivotIndex = random.randint(left, right) pivotNewIndex = partition(vector, left, right, pivotIndex) pivotDist = pivotNewIndex - left if pivotDist == k: return vector[pivotNewIndex] elif k < pivotDist: right = pivotNewIndex - 1 else: k -= pivotDist + 1 left = pivotNewIndex + 1 def select(vector, k, left=None, right=None): if left is None: left = 0 lv1 = len(vector) - 1 if right is None: right = lv1 assert vector and k >= 0, "Either null vector or k < 0 " assert 0 <= left <= lv1, "left is out of range" assert left <= right <= lv1, "right is out of range" return _select(vector, left, right, k) if __name__ == '__main__': v = [9, 8, 7, 6, 5, 0, 1, 2, 3, 4] print([select(v, i) for i in range(10)])
Produce a functionally identical Python code for the snippet given in C.
#include <stdlib.h> #include <string.h> #include <stdio.h> #include <stdint.h> char *to_base(int64_t num, int base) { char *tbl = "0123456789abcdefghijklmnopqrstuvwxyz"; char buf[66] = {'\0'}; char *out; uint64_t n; int i, len = 0, neg = 0; if (base > 36) { fprintf(stderr, "base %d too large\n", base); return 0; } n = ((neg = num < 0)) ? (~num) + 1 : num; do { buf[len++] = tbl[n % base]; } while(n /= base); out = malloc(len + neg + 1); for (i = neg; len > 0; i++) out[i] = buf[--len]; if (neg) out[0] = '-'; return out; } long from_base(const char *num_str, int base) { char *endptr; int result = strtol(num_str, &endptr, base); return result; } int main() { int64_t x; x = ~(1LL << 63) + 1; printf("%lld in base 2: %s\n", x, to_base(x, 2)); x = 383; printf("%lld in base 16: %s\n", x, to_base(x, 16)); return 0; }
i = int('1a',16)
Can you help me rewrite this code in Python instead of C, keeping it the same logically?
#include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <dirent.h> #include <regex.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <err.h> enum { WALK_OK = 0, WALK_BADPATTERN, WALK_NAMETOOLONG, WALK_BADIO, }; #define WS_NONE 0 #define WS_RECURSIVE (1 << 0) #define WS_DEFAULT WS_RECURSIVE #define WS_FOLLOWLINK (1 << 1) #define WS_DOTFILES (1 << 2) #define WS_MATCHDIRS (1 << 3) int walk_recur(char *dname, regex_t *reg, int spec) { struct dirent *dent; DIR *dir; struct stat st; char fn[FILENAME_MAX]; int res = WALK_OK; int len = strlen(dname); if (len >= FILENAME_MAX - 1) return WALK_NAMETOOLONG; strcpy(fn, dname); fn[len++] = '/'; if (!(dir = opendir(dname))) { warn("can't open %s", dname); return WALK_BADIO; } errno = 0; while ((dent = readdir(dir))) { if (!(spec & WS_DOTFILES) && dent->d_name[0] == '.') continue; if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, "..")) continue; strncpy(fn + len, dent->d_name, FILENAME_MAX - len); if (lstat(fn, &st) == -1) { warn("Can't stat %s", fn); res = WALK_BADIO; continue; } if (S_ISLNK(st.st_mode) && !(spec & WS_FOLLOWLINK)) continue; if (S_ISDIR(st.st_mode)) { if ((spec & WS_RECURSIVE)) walk_recur(fn, reg, spec); if (!(spec & WS_MATCHDIRS)) continue; } if (!regexec(reg, fn, 0, 0, 0)) puts(fn); } if (dir) closedir(dir); return res ? res : errno ? WALK_BADIO : WALK_OK; } int walk_dir(char *dname, char *pattern, int spec) { regex_t r; int res; if (regcomp(&r, pattern, REG_EXTENDED | REG_NOSUB)) return WALK_BADPATTERN; res = walk_recur(dname, &r, spec); regfree(&r); return res; } int main() { int r = walk_dir(".", ".\\.c$", WS_DEFAULT|WS_MATCHDIRS); switch(r) { case WALK_OK: break; case WALK_BADIO: err(1, "IO error"); case WALK_BADPATTERN: err(1, "Bad pattern"); case WALK_NAMETOOLONG: err(1, "Filename too long"); default: err(1, "Unknown error?"); } return 0; }
from pathlib import Path for path in Path('.').rglob('*.*'): print(path)
Please provide an equivalent version of this C code in Python.
static unsigned char const k8[16] = { 14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7 }; static unsigned char const k7[16] = { 15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10 }; static unsigned char const k6[16] = { 10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8 }; static unsigned char const k5[16] = { 7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15 }; static unsigned char const k4[16] = { 2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9 }; static unsigned char const k3[16] = { 12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11 }; static unsigned char const k2[16] = { 4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1 }; static unsigned char const k1[16] = { 13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7 }; static unsigned char k87[256]; static unsigned char k65[256]; static unsigned char k43[256]; static unsigned char k21[256]; void kboxinit(void) { int i; for (i = 0; i < 256; i++) { k87[i] = k8[i >> 4] << 4 | k7[i & 15]; k65[i] = k6[i >> 4] << 4 | k5[i & 15]; k43[i] = k4[i >> 4] << 4 | k3[i & 15]; k21[i] = k2[i >> 4] << 4 | k1[i & 15]; } } static word32 f(word32 x) { x = k87[x>>24 & 255] << 24 | k65[x>>16 & 255] << 16 | k43[x>> 8 & 255] << 8 | k21[x & 255]; return x<<11 | x>>(32-11); }
k8 = [ 14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7 ] k7 = [ 15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10 ] k6 = [ 10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8 ] k5 = [ 7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15 ] k4 = [ 2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9 ] k3 = [ 12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11 ] k2 = [ 4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1 ] k1 = [ 13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7 ] k87 = [0] * 256 k65 = [0] * 256 k43 = [0] * 256 k21 = [0] * 256 def kboxinit(): for i in range(256): k87[i] = k8[i >> 4] << 4 | k7[i & 15] k65[i] = k6[i >> 4] << 4 | k5[i & 15] k43[i] = k4[i >> 4] << 4 | k3[i & 15] k21[i] = k2[i >> 4] << 4 | k1[i & 15] def f(x): x = ( k87[x>>24 & 255] << 24 | k65[x>>16 & 255] << 16 | k43[x>> 8 & 255] << 8 | k21[x & 255] ) return x<<11 | x>>(32-11)
Produce a language-to-language conversion: from C to Python, same semantics.
static unsigned char const k8[16] = { 14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7 }; static unsigned char const k7[16] = { 15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10 }; static unsigned char const k6[16] = { 10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8 }; static unsigned char const k5[16] = { 7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15 }; static unsigned char const k4[16] = { 2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9 }; static unsigned char const k3[16] = { 12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11 }; static unsigned char const k2[16] = { 4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1 }; static unsigned char const k1[16] = { 13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7 }; static unsigned char k87[256]; static unsigned char k65[256]; static unsigned char k43[256]; static unsigned char k21[256]; void kboxinit(void) { int i; for (i = 0; i < 256; i++) { k87[i] = k8[i >> 4] << 4 | k7[i & 15]; k65[i] = k6[i >> 4] << 4 | k5[i & 15]; k43[i] = k4[i >> 4] << 4 | k3[i & 15]; k21[i] = k2[i >> 4] << 4 | k1[i & 15]; } } static word32 f(word32 x) { x = k87[x>>24 & 255] << 24 | k65[x>>16 & 255] << 16 | k43[x>> 8 & 255] << 8 | k21[x & 255]; return x<<11 | x>>(32-11); }
k8 = [ 14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7 ] k7 = [ 15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10 ] k6 = [ 10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8 ] k5 = [ 7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15 ] k4 = [ 2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9 ] k3 = [ 12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11 ] k2 = [ 4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1 ] k1 = [ 13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7 ] k87 = [0] * 256 k65 = [0] * 256 k43 = [0] * 256 k21 = [0] * 256 def kboxinit(): for i in range(256): k87[i] = k8[i >> 4] << 4 | k7[i & 15] k65[i] = k6[i >> 4] << 4 | k5[i & 15] k43[i] = k4[i >> 4] << 4 | k3[i & 15] k21[i] = k2[i >> 4] << 4 | k1[i & 15] def f(x): x = ( k87[x>>24 & 255] << 24 | k65[x>>16 & 255] << 16 | k43[x>> 8 & 255] << 8 | k21[x & 255] ) return x<<11 | x>>(32-11)
Convert this C snippet to Python and keep its semantics consistent.
#include <stdio.h> #include <stdlib.h> #include <string.h> #define USE_FAKES 1 const char *states[] = { #if USE_FAKES "New Kory", "Wen Kory", "York New", "Kory New", "New Kory", #endif "Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", "North Carolina", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming" }; int n_states = sizeof(states)/sizeof(*states); typedef struct { unsigned char c[26]; const char *name[2]; } letters; void count_letters(letters *l, const char *s) { int c; if (!l->name[0]) l->name[0] = s; else l->name[1] = s; while ((c = *s++)) { if (c >= 'a' && c <= 'z') l->c[c - 'a']++; if (c >= 'A' && c <= 'Z') l->c[c - 'A']++; } } int lcmp(const void *aa, const void *bb) { int i; const letters *a = aa, *b = bb; for (i = 0; i < 26; i++) if (a->c[i] > b->c[i]) return 1; else if (a->c[i] < b->c[i]) return -1; return 0; } int scmp(const void *a, const void *b) { return strcmp(*(const char *const *)a, *(const char *const *)b); } void no_dup() { int i, j; qsort(states, n_states, sizeof(const char*), scmp); for (i = j = 0; i < n_states;) { while (++i < n_states && !strcmp(states[i], states[j])); if (i < n_states) states[++j] = states[i]; } n_states = j + 1; } void find_mix() { int i, j, n; letters *l, *p; no_dup(); n = n_states * (n_states - 1) / 2; p = l = calloc(n, sizeof(letters)); for (i = 0; i < n_states; i++) for (j = i + 1; j < n_states; j++, p++) { count_letters(p, states[i]); count_letters(p, states[j]); } qsort(l, n, sizeof(letters), lcmp); for (j = 0; j < n; j++) { for (i = j + 1; i < n && !lcmp(l + j, l + i); i++) { if (l[j].name[0] == l[i].name[0] || l[j].name[1] == l[i].name[0] || l[j].name[1] == l[i].name[1]) continue; printf("%s + %s => %s + %s\n", l[j].name[0], l[j].name[1], l[i].name[0], l[i].name[1]); } } free(l); } int main(void) { find_mix(); return 0; }
from collections import defaultdict states = ["Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", "North Carolina", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming", ] states = sorted(set(states)) smap = defaultdict(list) for i, s1 in enumerate(states[:-1]): for s2 in states[i + 1:]: smap["".join(sorted(s1 + s2))].append(s1 + " + " + s2) for pairs in sorted(smap.itervalues()): if len(pairs) > 1: print " = ".join(pairs)
Change the programming language of this snippet from C to Python without modifying what it does.
#include <stdio.h> #include <string.h> #include <zlib.h> int main() { const char *s = "The quick brown fox jumps over the lazy dog"; printf("%lX\n", crc32(0, (const void*)s, strlen(s))); return 0; }
>>> s = 'The quick brown fox jumps over the lazy dog' >>> import zlib >>> hex(zlib.crc32(s)) '0x414fa339' >>> import binascii >>> hex(binascii.crc32(s)) '0x414fa339'
Convert the following code from C to Python, ensuring the logic remains intact.
#include <stdio.h> const char *input = "Character,Speech\n" "The multitude,The messiah! Show us the messiah!\n" "Brians mother,<angry>Now you listen here! He's not the messiah; " "he's a very naughty boy! Now go away!</angry>\n" "The multitude,Who are you?\n" "Brians mother,I'm his mother; that's who!\n" "The multitude,Behold his mother! Behold his mother!"; int main() { const char *s; printf("<table>\n<tr><td>"); for (s = input; *s; s++) { switch(*s) { case '\n': printf("</td></tr>\n<tr><td>"); break; case ',': printf("</td><td>"); break; case '<': printf("&lt;"); break; case '>': printf("&gt;"); break; case '&': printf("&amp;"); break; default: putchar(*s); } } puts("</td></tr>\n</table>"); return 0; }
csvtxt = from cgi import escape def _row2tr(row, attr=None): cols = escape(row).split(',') return ('<TR>' + ''.join('<TD>%s</TD>' % data for data in cols) + '</TR>') def csv2html(txt): htmltxt = '<TABLE summary="csv2html program output">\n' for rownum, row in enumerate(txt.split('\n')): htmlrow = _row2tr(row) htmlrow = ' <TBODY>%s</TBODY>\n' % htmlrow htmltxt += htmlrow htmltxt += '</TABLE>\n' return htmltxt htmltxt = csv2html(csvtxt) print(htmltxt)
Ensure the translated Python code behaves exactly like the original C snippet.
#include <stdio.h> const char *input = "Character,Speech\n" "The multitude,The messiah! Show us the messiah!\n" "Brians mother,<angry>Now you listen here! He's not the messiah; " "he's a very naughty boy! Now go away!</angry>\n" "The multitude,Who are you?\n" "Brians mother,I'm his mother; that's who!\n" "The multitude,Behold his mother! Behold his mother!"; int main() { const char *s; printf("<table>\n<tr><td>"); for (s = input; *s; s++) { switch(*s) { case '\n': printf("</td></tr>\n<tr><td>"); break; case ',': printf("</td><td>"); break; case '<': printf("&lt;"); break; case '>': printf("&gt;"); break; case '&': printf("&amp;"); break; default: putchar(*s); } } puts("</td></tr>\n</table>"); return 0; }
csvtxt = from cgi import escape def _row2tr(row, attr=None): cols = escape(row).split(',') return ('<TR>' + ''.join('<TD>%s</TD>' % data for data in cols) + '</TR>') def csv2html(txt): htmltxt = '<TABLE summary="csv2html program output">\n' for rownum, row in enumerate(txt.split('\n')): htmlrow = _row2tr(row) htmlrow = ' <TBODY>%s</TBODY>\n' % htmlrow htmltxt += htmlrow htmltxt += '</TABLE>\n' return htmltxt htmltxt = csv2html(csvtxt) print(htmltxt)
Keep all operations the same but rewrite the snippet in Python.
#include <stdlib.h> typedef struct sMyClass { int variable; } *MyClass; MyClass MyClass_new() { MyClass pthis = malloc(sizeof *pthis); pthis->variable = 0; return pthis; } void MyClass_delete(MyClass* pthis) { if (pthis) { free(*pthis); *pthis = NULL; } } void MyClass_someMethod(MyClass pthis) { pthis->variable = 1; } MyClass obj = MyClass_new(); MyClass_someMethod(obj); MyClass_delete(&obj);
class MyClass: name2 = 2 def __init__(self): self.name1 = 0 def someMethod(self): self.name1 = 1 MyClass.name2 = 3 myclass = MyClass() class MyOtherClass: count = 0 def __init__(self, name, gender="Male", age=None): MyOtherClass.count += 1 self.name = name self.gender = gender if age is not None: self.age = age def __del__(self): MyOtherClass.count -= 1 person1 = MyOtherClass("John") print person1.name, person1.gender print person1.age person2 = MyOtherClass("Jane", "Female", 23) print person2.name, person2.gender, person2.age
Change the following C code into Python without altering its purpose.
#include <stdio.h> #include <stdint.h> typedef uint64_t ulong; int kaprekar(ulong n, int base) { ulong nn = n * n, r, tens = 1; if ((nn - n) % (base - 1)) return 0; while (tens < n) tens *= base; if (n == tens) return 1 == n; while ((r = nn % tens) < n) { if (nn / tens + r == n) return tens; tens *= base; } return 0; } void print_num(ulong n, int base) { ulong q, div = base; while (div < n) div *= base; while (n && (div /= base)) { q = n / div; if (q < 10) putchar(q + '0'); else putchar(q + 'a' - 10); n -= q * div; } } int main() { ulong i, tens; int cnt = 0; int base = 10; printf("base 10:\n"); for (i = 1; i < 1000000; i++) if (kaprekar(i, base)) printf("%3d: %llu\n", ++cnt, i); base = 17; printf("\nbase %d:\n 1: 1\n", base); for (i = 2, cnt = 1; i < 1000000; i++) if ((tens = kaprekar(i, base))) { printf("%3d: %llu", ++cnt, i); printf(" \t"); print_num(i, base); printf("\t"); print_num(i * i, base); printf("\t"); print_num(i * i / tens, base); printf(" + "); print_num(i * i % tens, base); printf("\n"); } return 0; }
>>> def k(n): n2 = str(n**2) for i in range(len(n2)): a, b = int(n2[:i] or 0), int(n2[i:]) if b and a + b == n: return n >>> [x for x in range(1,10000) if k(x)] [1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999] >>> len([x for x in range(1,1000000) if k(x)]) 54 >>>
Change the programming language of this snippet from C to Python without modifying what it does.
#include <stdio.h> #include <stdint.h> typedef uint64_t ulong; int kaprekar(ulong n, int base) { ulong nn = n * n, r, tens = 1; if ((nn - n) % (base - 1)) return 0; while (tens < n) tens *= base; if (n == tens) return 1 == n; while ((r = nn % tens) < n) { if (nn / tens + r == n) return tens; tens *= base; } return 0; } void print_num(ulong n, int base) { ulong q, div = base; while (div < n) div *= base; while (n && (div /= base)) { q = n / div; if (q < 10) putchar(q + '0'); else putchar(q + 'a' - 10); n -= q * div; } } int main() { ulong i, tens; int cnt = 0; int base = 10; printf("base 10:\n"); for (i = 1; i < 1000000; i++) if (kaprekar(i, base)) printf("%3d: %llu\n", ++cnt, i); base = 17; printf("\nbase %d:\n 1: 1\n", base); for (i = 2, cnt = 1; i < 1000000; i++) if ((tens = kaprekar(i, base))) { printf("%3d: %llu", ++cnt, i); printf(" \t"); print_num(i, base); printf("\t"); print_num(i * i, base); printf("\t"); print_num(i * i / tens, base); printf(" + "); print_num(i * i % tens, base); printf("\n"); } return 0; }
>>> def k(n): n2 = str(n**2) for i in range(len(n2)): a, b = int(n2[:i] or 0), int(n2[i:]) if b and a + b == n: return n >>> [x for x in range(1,10000) if k(x)] [1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999] >>> len([x for x in range(1,1000000) if k(x)]) 54 >>>
Write the same code in Python as shown below in C.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include <unistd.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> void* mem_alloc(size_t item_size, size_t n_item) { size_t *x = calloc(1, sizeof(size_t)*2 + n_item * item_size); x[0] = item_size; x[1] = n_item; return x + 2; } void* mem_extend(void *m, size_t new_n) { size_t *x = (size_t*)m - 2; x = realloc(x, sizeof(size_t) * 2 + *x * new_n); if (new_n > x[1]) memset((char*)(x + 2) + x[0] * x[1], 0, x[0] * (new_n - x[1])); x[1] = new_n; return x + 2; } inline void _clear(void *m) { size_t *x = (size_t*)m - 2; memset(m, 0, x[0] * x[1]); } #define _new(type, n) mem_alloc(sizeof(type), n) #define _del(m) { free((size_t*)(m) - 2); m = 0; } #define _len(m) *((size_t*)m - 1) #define _setsize(m, n) m = mem_extend(m, n) #define _extend(m) m = mem_extend(m, _len(m) * 2) typedef uint8_t byte; typedef uint16_t ushort; #define M_CLR 256 #define M_EOD 257 #define M_NEW 258 typedef struct { ushort next[256]; } lzw_enc_t; typedef struct { ushort prev, back; byte c; } lzw_dec_t; byte* lzw_encode(byte *in, int max_bits) { int len = _len(in), bits = 9, next_shift = 512; ushort code, c, nc, next_code = M_NEW; lzw_enc_t *d = _new(lzw_enc_t, 512); if (max_bits > 15) max_bits = 15; if (max_bits < 9 ) max_bits = 12; byte *out = _new(ushort, 4); int out_len = 0, o_bits = 0; uint32_t tmp = 0; inline void write_bits(ushort x) { tmp = (tmp << bits) | x; o_bits += bits; if (_len(out) <= out_len) _extend(out); while (o_bits >= 8) { o_bits -= 8; out[out_len++] = tmp >> o_bits; tmp &= (1 << o_bits) - 1; } } for (code = *(in++); --len; ) { c = *(in++); if ((nc = d[code].next[c])) code = nc; else { write_bits(code); nc = d[code].next[c] = next_code++; code = c; } if (next_code == next_shift) { if (++bits > max_bits) { write_bits(M_CLR); bits = 9; next_shift = 512; next_code = M_NEW; _clear(d); } else _setsize(d, next_shift *= 2); } } write_bits(code); write_bits(M_EOD); if (tmp) write_bits(tmp); _del(d); _setsize(out, out_len); return out; } byte* lzw_decode(byte *in) { byte *out = _new(byte, 4); int out_len = 0; inline void write_out(byte c) { while (out_len >= _len(out)) _extend(out); out[out_len++] = c; } lzw_dec_t *d = _new(lzw_dec_t, 512); int len, j, next_shift = 512, bits = 9, n_bits = 0; ushort code, c, t, next_code = M_NEW; uint32_t tmp = 0; inline void get_code() { while(n_bits < bits) { if (len > 0) { len --; tmp = (tmp << 8) | *(in++); n_bits += 8; } else { tmp = tmp << (bits - n_bits); n_bits = bits; } } n_bits -= bits; code = tmp >> n_bits; tmp &= (1 << n_bits) - 1; } inline void clear_table() { _clear(d); for (j = 0; j < 256; j++) d[j].c = j; next_code = M_NEW; next_shift = 512; bits = 9; }; clear_table(); for (len = _len(in); len;) { get_code(); if (code == M_EOD) break; if (code == M_CLR) { clear_table(); continue; } if (code >= next_code) { fprintf(stderr, "Bad sequence\n"); _del(out); goto bail; } d[next_code].prev = c = code; while (c > 255) { t = d[c].prev; d[t].back = c; c = t; } d[next_code - 1].c = c; while (d[c].back) { write_out(d[c].c); t = d[c].back; d[c].back = 0; c = t; } write_out(d[c].c); if (++next_code >= next_shift) { if (++bits > 16) { fprintf(stderr, "Too many bits\n"); _del(out); goto bail; } _setsize(d, next_shift *= 2); } } if (code != M_EOD) fputs("Bits did not end in EOD\n", stderr); _setsize(out, out_len); bail: _del(d); return out; } int main() { int i, fd = open("unixdict.txt", O_RDONLY); if (fd == -1) { fprintf(stderr, "Can't read file\n"); return 1; }; struct stat st; fstat(fd, &st); byte *in = _new(char, st.st_size); read(fd, in, st.st_size); _setsize(in, st.st_size); close(fd); printf("input size: %d\n", _len(in)); byte *enc = lzw_encode(in, 9); printf("encoded size: %d\n", _len(enc)); byte *dec = lzw_decode(enc); printf("decoded size: %d\n", _len(dec)); for (i = 0; i < _len(dec); i++) if (dec[i] != in[i]) { printf("bad decode at %d\n", i); break; } if (i == _len(dec)) printf("Decoded ok\n"); _del(in); _del(enc); _del(dec); return 0; }
def compress(uncompressed): dict_size = 256 dictionary = dict((chr(i), i) for i in range(dict_size)) w = "" result = [] for c in uncompressed: wc = w + c if wc in dictionary: w = wc else: result.append(dictionary[w]) dictionary[wc] = dict_size dict_size += 1 w = c if w: result.append(dictionary[w]) return result def decompress(compressed): from io import StringIO dict_size = 256 dictionary = dict((i, chr(i)) for i in range(dict_size)) result = StringIO() w = chr(compressed.pop(0)) result.write(w) for k in compressed: if k in dictionary: entry = dictionary[k] elif k == dict_size: entry = w + w[0] else: raise ValueError('Bad compressed k: %s' % k) result.write(entry) dictionary[dict_size] = w + entry[0] dict_size += 1 w = entry return result.getvalue() compressed = compress('TOBEORNOTTOBEORTOBEORNOT') print (compressed) decompressed = decompress(compressed) print (decompressed)
Preserve the algorithm and functionality while converting the code from C to Python.
#include <stdio.h> #include <stdlib.h> typedef unsigned long long xint; typedef struct { size_t len, alloc; xint *buf; } xarray; xarray rs, ss; void setsize(xarray *a, size_t size) { size_t n = a->alloc; if (!n) n = 1; while (n < size) n <<= 1; if (a->alloc < n) { a->buf = realloc(a->buf, sizeof(xint) * n); if (!a->buf) abort(); a->alloc = n; } } void push(xarray *a, xint v) { while (a->alloc <= a->len) setsize(a, a->alloc * 2); a->buf[a->len++] = v; } void RS_append(void); xint R(int n) { while (n > rs.len) RS_append(); return rs.buf[n - 1]; } xint S(int n) { while (n > ss.len) RS_append(); return ss.buf[n - 1]; } void RS_append() { int n = rs.len; xint r = R(n) + S(n); xint s = S(ss.len); push(&rs, r); while (++s < r) push(&ss, s); push(&ss, r + 1); } int main(void) { push(&rs, 1); push(&ss, 2); int i; printf("R(1 .. 10):"); for (i = 1; i <= 10; i++) printf(" %llu", R(i)); char seen[1001] = { 0 }; for (i = 1; i <= 40; i++) seen[ R(i) ] = 1; for (i = 1; i <= 960; i++) seen[ S(i) ] = 1; for (i = 1; i <= 1000 && seen[i]; i++); if (i <= 1000) { fprintf(stderr, "%d not seen\n", i); abort(); } puts("\nfirst 1000 ok"); return 0; }
def ffr(n): if n < 1 or type(n) != int: raise ValueError("n must be an int >= 1") try: return ffr.r[n] except IndexError: r, s = ffr.r, ffs.s ffr_n_1 = ffr(n-1) lastr = r[-1] s += list(range(s[-1] + 1, lastr)) if s[-1] < lastr: s += [lastr + 1] len_s = len(s) ffs_n_1 = s[n-1] if len_s > n else (n - len_s) + s[-1] ans = ffr_n_1 + ffs_n_1 r.append(ans) return ans ffr.r = [None, 1] def ffs(n): if n < 1 or type(n) != int: raise ValueError("n must be an int >= 1") try: return ffs.s[n] except IndexError: r, s = ffr.r, ffs.s for i in range(len(r), n+2): ffr(i) if len(s) > n: return s[n] raise Exception("Whoops!") ffs.s = [None, 2] if __name__ == '__main__': first10 = [ffr(i) for i in range(1,11)] assert first10 == [1, 3, 7, 12, 18, 26, 35, 45, 56, 69], "ffr() value error(s)" print("ffr(n) for n = [1..10] is", first10) bin = [None] + [0]*1000 for i in range(40, 0, -1): bin[ffr(i)] += 1 for i in range(960, 0, -1): bin[ffs(i)] += 1 if all(b == 1 for b in bin[1:1000]): print("All Integers 1..1000 found OK") else: print("All Integers 1..1000 NOT found only once: ERROR")
Can you help me rewrite this code in Python instead of C, keeping it the same logically?
#include <stdio.h> #include <stdlib.h> typedef unsigned long long xint; typedef struct { size_t len, alloc; xint *buf; } xarray; xarray rs, ss; void setsize(xarray *a, size_t size) { size_t n = a->alloc; if (!n) n = 1; while (n < size) n <<= 1; if (a->alloc < n) { a->buf = realloc(a->buf, sizeof(xint) * n); if (!a->buf) abort(); a->alloc = n; } } void push(xarray *a, xint v) { while (a->alloc <= a->len) setsize(a, a->alloc * 2); a->buf[a->len++] = v; } void RS_append(void); xint R(int n) { while (n > rs.len) RS_append(); return rs.buf[n - 1]; } xint S(int n) { while (n > ss.len) RS_append(); return ss.buf[n - 1]; } void RS_append() { int n = rs.len; xint r = R(n) + S(n); xint s = S(ss.len); push(&rs, r); while (++s < r) push(&ss, s); push(&ss, r + 1); } int main(void) { push(&rs, 1); push(&ss, 2); int i; printf("R(1 .. 10):"); for (i = 1; i <= 10; i++) printf(" %llu", R(i)); char seen[1001] = { 0 }; for (i = 1; i <= 40; i++) seen[ R(i) ] = 1; for (i = 1; i <= 960; i++) seen[ S(i) ] = 1; for (i = 1; i <= 1000 && seen[i]; i++); if (i <= 1000) { fprintf(stderr, "%d not seen\n", i); abort(); } puts("\nfirst 1000 ok"); return 0; }
def ffr(n): if n < 1 or type(n) != int: raise ValueError("n must be an int >= 1") try: return ffr.r[n] except IndexError: r, s = ffr.r, ffs.s ffr_n_1 = ffr(n-1) lastr = r[-1] s += list(range(s[-1] + 1, lastr)) if s[-1] < lastr: s += [lastr + 1] len_s = len(s) ffs_n_1 = s[n-1] if len_s > n else (n - len_s) + s[-1] ans = ffr_n_1 + ffs_n_1 r.append(ans) return ans ffr.r = [None, 1] def ffs(n): if n < 1 or type(n) != int: raise ValueError("n must be an int >= 1") try: return ffs.s[n] except IndexError: r, s = ffr.r, ffs.s for i in range(len(r), n+2): ffr(i) if len(s) > n: return s[n] raise Exception("Whoops!") ffs.s = [None, 2] if __name__ == '__main__': first10 = [ffr(i) for i in range(1,11)] assert first10 == [1, 3, 7, 12, 18, 26, 35, 45, 56, 69], "ffr() value error(s)" print("ffr(n) for n = [1..10] is", first10) bin = [None] + [0]*1000 for i in range(40, 0, -1): bin[ffr(i)] += 1 for i in range(960, 0, -1): bin[ffs(i)] += 1 if all(b == 1 for b in bin[1:1000]): print("All Integers 1..1000 found OK") else: print("All Integers 1..1000 NOT found only once: ERROR")
Change the following C code into Python without altering its purpose.
#include <stdio.h> #include <stdlib.h> typedef unsigned long long xint; typedef struct { size_t len, alloc; xint *buf; } xarray; xarray rs, ss; void setsize(xarray *a, size_t size) { size_t n = a->alloc; if (!n) n = 1; while (n < size) n <<= 1; if (a->alloc < n) { a->buf = realloc(a->buf, sizeof(xint) * n); if (!a->buf) abort(); a->alloc = n; } } void push(xarray *a, xint v) { while (a->alloc <= a->len) setsize(a, a->alloc * 2); a->buf[a->len++] = v; } void RS_append(void); xint R(int n) { while (n > rs.len) RS_append(); return rs.buf[n - 1]; } xint S(int n) { while (n > ss.len) RS_append(); return ss.buf[n - 1]; } void RS_append() { int n = rs.len; xint r = R(n) + S(n); xint s = S(ss.len); push(&rs, r); while (++s < r) push(&ss, s); push(&ss, r + 1); } int main(void) { push(&rs, 1); push(&ss, 2); int i; printf("R(1 .. 10):"); for (i = 1; i <= 10; i++) printf(" %llu", R(i)); char seen[1001] = { 0 }; for (i = 1; i <= 40; i++) seen[ R(i) ] = 1; for (i = 1; i <= 960; i++) seen[ S(i) ] = 1; for (i = 1; i <= 1000 && seen[i]; i++); if (i <= 1000) { fprintf(stderr, "%d not seen\n", i); abort(); } puts("\nfirst 1000 ok"); return 0; }
def ffr(n): if n < 1 or type(n) != int: raise ValueError("n must be an int >= 1") try: return ffr.r[n] except IndexError: r, s = ffr.r, ffs.s ffr_n_1 = ffr(n-1) lastr = r[-1] s += list(range(s[-1] + 1, lastr)) if s[-1] < lastr: s += [lastr + 1] len_s = len(s) ffs_n_1 = s[n-1] if len_s > n else (n - len_s) + s[-1] ans = ffr_n_1 + ffs_n_1 r.append(ans) return ans ffr.r = [None, 1] def ffs(n): if n < 1 or type(n) != int: raise ValueError("n must be an int >= 1") try: return ffs.s[n] except IndexError: r, s = ffr.r, ffs.s for i in range(len(r), n+2): ffr(i) if len(s) > n: return s[n] raise Exception("Whoops!") ffs.s = [None, 2] if __name__ == '__main__': first10 = [ffr(i) for i in range(1,11)] assert first10 == [1, 3, 7, 12, 18, 26, 35, 45, 56, 69], "ffr() value error(s)" print("ffr(n) for n = [1..10] is", first10) bin = [None] + [0]*1000 for i in range(40, 0, -1): bin[ffr(i)] += 1 for i in range(960, 0, -1): bin[ffs(i)] += 1 if all(b == 1 for b in bin[1:1000]): print("All Integers 1..1000 found OK") else: print("All Integers 1..1000 NOT found only once: ERROR")
Can you help me rewrite this code in Python instead of C, keeping it the same logically?
#include <stdio.h> #include <stdlib.h> int f(int n, int x, int y) { return (x + y*2 + 1)%n; } int main(int argc, char **argv) { int i, j, n; if(argc!=2) return 1; n = atoi(argv[1]); if (n < 3 || (n%2) == 0) return 2; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) printf("% 4d", f(n, n - j - 1, i)*n + f(n, j, i) + 1); putchar('\n'); } printf("\n Magic Constant: %d.\n", (n*n+1)/2*n); return 0; }
>>> def magic(n): for row in range(1, n + 1): print(' '.join('%*i' % (len(str(n**2)), cell) for cell in (n * ((row + col - 1 + n // 2) % n) + ((row + 2 * col - 2) % n) + 1 for col in range(1, n + 1)))) print('\nAll sum to magic number %i' % ((n * n + 1) * n // 2)) >>> for n in (5, 3, 7): print('\nOrder %i\n=======' % n) magic(n) Order 5 ======= 17 24 1 8 15 23 5 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9 All sum to magic number 65 Order 3 ======= 8 1 6 3 5 7 4 9 2 All sum to magic number 15 Order 7 ======= 30 39 48 1 10 19 28 38 47 7 9 18 27 29 46 6 8 17 26 35 37 5 14 16 25 34 36 45 13 15 24 33 42 44 4 21 23 32 41 43 3 12 22 31 40 49 2 11 20 All sum to magic number 175 >>>
Generate a Python translation of this C snippet without changing its computational steps.
#include <stdio.h> #include <stdlib.h> int f(int n, int x, int y) { return (x + y*2 + 1)%n; } int main(int argc, char **argv) { int i, j, n; if(argc!=2) return 1; n = atoi(argv[1]); if (n < 3 || (n%2) == 0) return 2; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) printf("% 4d", f(n, n - j - 1, i)*n + f(n, j, i) + 1); putchar('\n'); } printf("\n Magic Constant: %d.\n", (n*n+1)/2*n); return 0; }
>>> def magic(n): for row in range(1, n + 1): print(' '.join('%*i' % (len(str(n**2)), cell) for cell in (n * ((row + col - 1 + n // 2) % n) + ((row + 2 * col - 2) % n) + 1 for col in range(1, n + 1)))) print('\nAll sum to magic number %i' % ((n * n + 1) * n // 2)) >>> for n in (5, 3, 7): print('\nOrder %i\n=======' % n) magic(n) Order 5 ======= 17 24 1 8 15 23 5 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9 All sum to magic number 65 Order 3 ======= 8 1 6 3 5 7 4 9 2 All sum to magic number 15 Order 7 ======= 30 39 48 1 10 19 28 38 47 7 9 18 27 29 46 6 8 17 26 35 37 5 14 16 25 34 36 45 13 15 24 33 42 44 4 21 23 32 41 43 3 12 22 31 40 49 2 11 20 All sum to magic number 175 >>>
Translate the given C code snippet into Python without altering its behavior.
#include <stdio.h> #include <stdlib.h> int f(int n, int x, int y) { return (x + y*2 + 1)%n; } int main(int argc, char **argv) { int i, j, n; if(argc!=2) return 1; n = atoi(argv[1]); if (n < 3 || (n%2) == 0) return 2; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) printf("% 4d", f(n, n - j - 1, i)*n + f(n, j, i) + 1); putchar('\n'); } printf("\n Magic Constant: %d.\n", (n*n+1)/2*n); return 0; }
>>> def magic(n): for row in range(1, n + 1): print(' '.join('%*i' % (len(str(n**2)), cell) for cell in (n * ((row + col - 1 + n // 2) % n) + ((row + 2 * col - 2) % n) + 1 for col in range(1, n + 1)))) print('\nAll sum to magic number %i' % ((n * n + 1) * n // 2)) >>> for n in (5, 3, 7): print('\nOrder %i\n=======' % n) magic(n) Order 5 ======= 17 24 1 8 15 23 5 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9 All sum to magic number 65 Order 3 ======= 8 1 6 3 5 7 4 9 2 All sum to magic number 15 Order 7 ======= 30 39 48 1 10 19 28 38 47 7 9 18 27 29 46 6 8 17 26 35 37 5 14 16 25 34 36 45 13 15 24 33 42 44 4 21 23 32 41 43 3 12 22 31 40 49 2 11 20 All sum to magic number 175 >>>
Produce a language-to-language conversion: from C to Python, same semantics.
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> typedef struct lnode_t { struct lnode_t *prev; struct lnode_t *next; int v; } Lnode; Lnode *make_list_node(int v) { Lnode *node = malloc(sizeof(Lnode)); if (node == NULL) { return NULL; } node->v = v; node->prev = NULL; node->next = NULL; return node; } void free_lnode(Lnode *node) { if (node == NULL) { return; } node->v = 0; node->prev = NULL; free_lnode(node->next); node->next = NULL; } typedef struct list_t { Lnode *front; Lnode *back; size_t len; } List; List *make_list() { List *list = malloc(sizeof(List)); if (list == NULL) { return NULL; } list->front = NULL; list->back = NULL; list->len = 0; return list; } void free_list(List *list) { if (list == NULL) { return; } list->len = 0; list->back = NULL; free_lnode(list->front); list->front = NULL; } void list_insert(List *list, int v) { Lnode *node; if (list == NULL) { return; } node = make_list_node(v); if (list->front == NULL) { list->front = node; list->back = node; list->len = 1; } else { node->prev = list->back; list->back->next = node; list->back = node; list->len++; } } void list_print(List *list) { Lnode *it; if (list == NULL) { return; } for (it = list->front; it != NULL; it = it->next) { printf("%d ", it->v); } } int list_get(List *list, int idx) { Lnode *it = NULL; if (list != NULL && list->front != NULL) { int i; if (idx < 0) { it = list->back; i = -1; while (it != NULL && i > idx) { it = it->prev; i--; } } else { it = list->front; i = 0; while (it != NULL && i < idx) { it = it->next; i++; } } } if (it == NULL) { return INT_MIN; } return it->v; } typedef struct mnode_t { int k; bool v; struct mnode_t *next; } Mnode; Mnode *make_map_node(int k, bool v) { Mnode *node = malloc(sizeof(Mnode)); if (node == NULL) { return node; } node->k = k; node->v = v; node->next = NULL; return node; } void free_mnode(Mnode *node) { if (node == NULL) { return; } node->k = 0; node->v = false; free_mnode(node->next); node->next = NULL; } typedef struct map_t { Mnode *front; } Map; Map *make_map() { Map *map = malloc(sizeof(Map)); if (map == NULL) { return NULL; } map->front = NULL; return map; } void free_map(Map *map) { if (map == NULL) { return; } free_mnode(map->front); map->front = NULL; } void map_insert(Map *map, int k, bool v) { if (map == NULL) { return; } if (map->front == NULL) { map->front = make_map_node(k, v); } else { Mnode *it = map->front; while (it->next != NULL) { it = it->next; } it->next = make_map_node(k, v); } } bool map_get(Map *map, int k) { if (map != NULL) { Mnode *it = map->front; while (it != NULL && it->k != k) { it = it->next; } if (it != NULL) { return it->v; } } return false; } int gcd(int u, int v) { if (u < 0) u = -u; if (v < 0) v = -v; if (v) { while ((u %= v) && (v %= u)); } return u + v; } List *yellow(size_t n) { List *a; Map *b; int i; a = make_list(); list_insert(a, 1); list_insert(a, 2); list_insert(a, 3); b = make_map(); map_insert(b, 1, true); map_insert(b, 2, true); map_insert(b, 3, true); i = 4; while (n > a->len) { if (!map_get(b, i) && gcd(i, list_get(a, -1)) == 1 && gcd(i, list_get(a, -2)) > 1) { list_insert(a, i); map_insert(b, i, true); i = 4; } i++; } free_map(b); return a; } int main() { List *a = yellow(30); list_print(a); free_list(a); putc('\n', stdout); return 0; }
from itertools import chain, count, islice from operator import itemgetter from math import gcd from matplotlib import pyplot def yellowstone(): def relativelyPrime(a): return lambda b: 1 == gcd(a, b) def nextWindow(triple): p2, p1, rest = triple [rp2, rp1] = map(relativelyPrime, [p2, p1]) def match(xxs): x, xs = uncons(xxs)['Just'] return (x, xs) if rp1(x) and not rp2(x) else ( second(cons(x))( match(xs) ) ) n, residue = match(rest) return (p1, n, residue) return chain( range(1, 3), map( itemgetter(1), iterate(nextWindow)( (2, 3, count(4)) ) ) ) def main(): print(showList( take(30)(yellowstone()) )) pyplot.plot( take(100)(yellowstone()) ) pyplot.xlabel(main.__doc__) pyplot.show() def Just(x): return {'type': 'Maybe', 'Nothing': False, 'Just': x} def Nothing(): return {'type': 'Maybe', 'Nothing': True} def cons(x): return lambda xs: [x] + xs if ( isinstance(xs, list) ) else x + xs if ( isinstance(xs, str) ) else chain([x], xs) def iterate(f): def go(x): v = x while True: yield v v = f(v) return go def second(f): return lambda xy: (xy[0], f(xy[1])) def showList(xs): return '[' + ','.join(repr(x) for x in xs) + ']' def take(n): return lambda xs: ( xs[0:n] if isinstance(xs, (list, tuple)) else list(islice(xs, n)) ) def uncons(xs): if isinstance(xs, list): return Just((xs[0], xs[1:])) if xs else Nothing() else: nxt = take(1)(xs) return Just((nxt[0], xs)) if nxt else Nothing() if __name__ == '__main__': main()
Port the provided C code into Python while preserving the original functionality.
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> typedef struct lnode_t { struct lnode_t *prev; struct lnode_t *next; int v; } Lnode; Lnode *make_list_node(int v) { Lnode *node = malloc(sizeof(Lnode)); if (node == NULL) { return NULL; } node->v = v; node->prev = NULL; node->next = NULL; return node; } void free_lnode(Lnode *node) { if (node == NULL) { return; } node->v = 0; node->prev = NULL; free_lnode(node->next); node->next = NULL; } typedef struct list_t { Lnode *front; Lnode *back; size_t len; } List; List *make_list() { List *list = malloc(sizeof(List)); if (list == NULL) { return NULL; } list->front = NULL; list->back = NULL; list->len = 0; return list; } void free_list(List *list) { if (list == NULL) { return; } list->len = 0; list->back = NULL; free_lnode(list->front); list->front = NULL; } void list_insert(List *list, int v) { Lnode *node; if (list == NULL) { return; } node = make_list_node(v); if (list->front == NULL) { list->front = node; list->back = node; list->len = 1; } else { node->prev = list->back; list->back->next = node; list->back = node; list->len++; } } void list_print(List *list) { Lnode *it; if (list == NULL) { return; } for (it = list->front; it != NULL; it = it->next) { printf("%d ", it->v); } } int list_get(List *list, int idx) { Lnode *it = NULL; if (list != NULL && list->front != NULL) { int i; if (idx < 0) { it = list->back; i = -1; while (it != NULL && i > idx) { it = it->prev; i--; } } else { it = list->front; i = 0; while (it != NULL && i < idx) { it = it->next; i++; } } } if (it == NULL) { return INT_MIN; } return it->v; } typedef struct mnode_t { int k; bool v; struct mnode_t *next; } Mnode; Mnode *make_map_node(int k, bool v) { Mnode *node = malloc(sizeof(Mnode)); if (node == NULL) { return node; } node->k = k; node->v = v; node->next = NULL; return node; } void free_mnode(Mnode *node) { if (node == NULL) { return; } node->k = 0; node->v = false; free_mnode(node->next); node->next = NULL; } typedef struct map_t { Mnode *front; } Map; Map *make_map() { Map *map = malloc(sizeof(Map)); if (map == NULL) { return NULL; } map->front = NULL; return map; } void free_map(Map *map) { if (map == NULL) { return; } free_mnode(map->front); map->front = NULL; } void map_insert(Map *map, int k, bool v) { if (map == NULL) { return; } if (map->front == NULL) { map->front = make_map_node(k, v); } else { Mnode *it = map->front; while (it->next != NULL) { it = it->next; } it->next = make_map_node(k, v); } } bool map_get(Map *map, int k) { if (map != NULL) { Mnode *it = map->front; while (it != NULL && it->k != k) { it = it->next; } if (it != NULL) { return it->v; } } return false; } int gcd(int u, int v) { if (u < 0) u = -u; if (v < 0) v = -v; if (v) { while ((u %= v) && (v %= u)); } return u + v; } List *yellow(size_t n) { List *a; Map *b; int i; a = make_list(); list_insert(a, 1); list_insert(a, 2); list_insert(a, 3); b = make_map(); map_insert(b, 1, true); map_insert(b, 2, true); map_insert(b, 3, true); i = 4; while (n > a->len) { if (!map_get(b, i) && gcd(i, list_get(a, -1)) == 1 && gcd(i, list_get(a, -2)) > 1) { list_insert(a, i); map_insert(b, i, true); i = 4; } i++; } free_map(b); return a; } int main() { List *a = yellow(30); list_print(a); free_list(a); putc('\n', stdout); return 0; }
from itertools import chain, count, islice from operator import itemgetter from math import gcd from matplotlib import pyplot def yellowstone(): def relativelyPrime(a): return lambda b: 1 == gcd(a, b) def nextWindow(triple): p2, p1, rest = triple [rp2, rp1] = map(relativelyPrime, [p2, p1]) def match(xxs): x, xs = uncons(xxs)['Just'] return (x, xs) if rp1(x) and not rp2(x) else ( second(cons(x))( match(xs) ) ) n, residue = match(rest) return (p1, n, residue) return chain( range(1, 3), map( itemgetter(1), iterate(nextWindow)( (2, 3, count(4)) ) ) ) def main(): print(showList( take(30)(yellowstone()) )) pyplot.plot( take(100)(yellowstone()) ) pyplot.xlabel(main.__doc__) pyplot.show() def Just(x): return {'type': 'Maybe', 'Nothing': False, 'Just': x} def Nothing(): return {'type': 'Maybe', 'Nothing': True} def cons(x): return lambda xs: [x] + xs if ( isinstance(xs, list) ) else x + xs if ( isinstance(xs, str) ) else chain([x], xs) def iterate(f): def go(x): v = x while True: yield v v = f(v) return go def second(f): return lambda xy: (xy[0], f(xy[1])) def showList(xs): return '[' + ','.join(repr(x) for x in xs) + ']' def take(n): return lambda xs: ( xs[0:n] if isinstance(xs, (list, tuple)) else list(islice(xs, n)) ) def uncons(xs): if isinstance(xs, list): return Just((xs[0], xs[1:])) if xs else Nothing() else: nxt = take(1)(xs) return Just((nxt[0], xs)) if nxt else Nothing() if __name__ == '__main__': main()
Rewrite this program in Python while keeping its functionality equivalent to the C version.
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> typedef struct lnode_t { struct lnode_t *prev; struct lnode_t *next; int v; } Lnode; Lnode *make_list_node(int v) { Lnode *node = malloc(sizeof(Lnode)); if (node == NULL) { return NULL; } node->v = v; node->prev = NULL; node->next = NULL; return node; } void free_lnode(Lnode *node) { if (node == NULL) { return; } node->v = 0; node->prev = NULL; free_lnode(node->next); node->next = NULL; } typedef struct list_t { Lnode *front; Lnode *back; size_t len; } List; List *make_list() { List *list = malloc(sizeof(List)); if (list == NULL) { return NULL; } list->front = NULL; list->back = NULL; list->len = 0; return list; } void free_list(List *list) { if (list == NULL) { return; } list->len = 0; list->back = NULL; free_lnode(list->front); list->front = NULL; } void list_insert(List *list, int v) { Lnode *node; if (list == NULL) { return; } node = make_list_node(v); if (list->front == NULL) { list->front = node; list->back = node; list->len = 1; } else { node->prev = list->back; list->back->next = node; list->back = node; list->len++; } } void list_print(List *list) { Lnode *it; if (list == NULL) { return; } for (it = list->front; it != NULL; it = it->next) { printf("%d ", it->v); } } int list_get(List *list, int idx) { Lnode *it = NULL; if (list != NULL && list->front != NULL) { int i; if (idx < 0) { it = list->back; i = -1; while (it != NULL && i > idx) { it = it->prev; i--; } } else { it = list->front; i = 0; while (it != NULL && i < idx) { it = it->next; i++; } } } if (it == NULL) { return INT_MIN; } return it->v; } typedef struct mnode_t { int k; bool v; struct mnode_t *next; } Mnode; Mnode *make_map_node(int k, bool v) { Mnode *node = malloc(sizeof(Mnode)); if (node == NULL) { return node; } node->k = k; node->v = v; node->next = NULL; return node; } void free_mnode(Mnode *node) { if (node == NULL) { return; } node->k = 0; node->v = false; free_mnode(node->next); node->next = NULL; } typedef struct map_t { Mnode *front; } Map; Map *make_map() { Map *map = malloc(sizeof(Map)); if (map == NULL) { return NULL; } map->front = NULL; return map; } void free_map(Map *map) { if (map == NULL) { return; } free_mnode(map->front); map->front = NULL; } void map_insert(Map *map, int k, bool v) { if (map == NULL) { return; } if (map->front == NULL) { map->front = make_map_node(k, v); } else { Mnode *it = map->front; while (it->next != NULL) { it = it->next; } it->next = make_map_node(k, v); } } bool map_get(Map *map, int k) { if (map != NULL) { Mnode *it = map->front; while (it != NULL && it->k != k) { it = it->next; } if (it != NULL) { return it->v; } } return false; } int gcd(int u, int v) { if (u < 0) u = -u; if (v < 0) v = -v; if (v) { while ((u %= v) && (v %= u)); } return u + v; } List *yellow(size_t n) { List *a; Map *b; int i; a = make_list(); list_insert(a, 1); list_insert(a, 2); list_insert(a, 3); b = make_map(); map_insert(b, 1, true); map_insert(b, 2, true); map_insert(b, 3, true); i = 4; while (n > a->len) { if (!map_get(b, i) && gcd(i, list_get(a, -1)) == 1 && gcd(i, list_get(a, -2)) > 1) { list_insert(a, i); map_insert(b, i, true); i = 4; } i++; } free_map(b); return a; } int main() { List *a = yellow(30); list_print(a); free_list(a); putc('\n', stdout); return 0; }
from itertools import chain, count, islice from operator import itemgetter from math import gcd from matplotlib import pyplot def yellowstone(): def relativelyPrime(a): return lambda b: 1 == gcd(a, b) def nextWindow(triple): p2, p1, rest = triple [rp2, rp1] = map(relativelyPrime, [p2, p1]) def match(xxs): x, xs = uncons(xxs)['Just'] return (x, xs) if rp1(x) and not rp2(x) else ( second(cons(x))( match(xs) ) ) n, residue = match(rest) return (p1, n, residue) return chain( range(1, 3), map( itemgetter(1), iterate(nextWindow)( (2, 3, count(4)) ) ) ) def main(): print(showList( take(30)(yellowstone()) )) pyplot.plot( take(100)(yellowstone()) ) pyplot.xlabel(main.__doc__) pyplot.show() def Just(x): return {'type': 'Maybe', 'Nothing': False, 'Just': x} def Nothing(): return {'type': 'Maybe', 'Nothing': True} def cons(x): return lambda xs: [x] + xs if ( isinstance(xs, list) ) else x + xs if ( isinstance(xs, str) ) else chain([x], xs) def iterate(f): def go(x): v = x while True: yield v v = f(v) return go def second(f): return lambda xy: (xy[0], f(xy[1])) def showList(xs): return '[' + ','.join(repr(x) for x in xs) + ']' def take(n): return lambda xs: ( xs[0:n] if isinstance(xs, (list, tuple)) else list(islice(xs, n)) ) def uncons(xs): if isinstance(xs, list): return Just((xs[0], xs[1:])) if xs else Nothing() else: nxt = take(1)(xs) return Just((nxt[0], xs)) if nxt else Nothing() if __name__ == '__main__': main()
Produce a language-to-language conversion: from C to Python, same semantics.
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef unsigned char byte; byte *grid = 0; int w, h, len; unsigned long long cnt; static int next[4], dir[4][2] = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}}; void walk(int y, int x) { int i, t; if (!y || y == h || !x || x == w) { cnt += 2; return; } t = y * (w + 1) + x; grid[t]++, grid[len - t]++; for (i = 0; i < 4; i++) if (!grid[t + next[i]]) walk(y + dir[i][0], x + dir[i][1]); grid[t]--, grid[len - t]--; } unsigned long long solve(int hh, int ww, int recur) { int t, cx, cy, x; h = hh, w = ww; if (h & 1) t = w, w = h, h = t; if (h & 1) return 0; if (w == 1) return 1; if (w == 2) return h; if (h == 2) return w; cy = h / 2, cx = w / 2; len = (h + 1) * (w + 1); grid = realloc(grid, len); memset(grid, 0, len--); next[0] = -1; next[1] = -w - 1; next[2] = 1; next[3] = w + 1; if (recur) cnt = 0; for (x = cx + 1; x < w; x++) { t = cy * (w + 1) + x; grid[t] = 1; grid[len - t] = 1; walk(cy - 1, x); } cnt++; if (h == w) cnt *= 2; else if (!(w & 1) && recur) solve(w, h, 0); return cnt; } int main() { int y, x; for (y = 1; y <= 10; y++) for (x = 1; x <= y; x++) if (!(x & 1) || !(y & 1)) printf("%d x %d: %llu\n", y, x, solve(y, x, 1)); return 0; }
def cut_it(h, w): dirs = ((1, 0), (-1, 0), (0, -1), (0, 1)) if h % 2: h, w = w, h if h % 2: return 0 if w == 1: return 1 count = 0 next = [w + 1, -w - 1, -1, 1] blen = (h + 1) * (w + 1) - 1 grid = [False] * (blen + 1) def walk(y, x, count): if not y or y == h or not x or x == w: return count + 1 t = y * (w + 1) + x grid[t] = grid[blen - t] = True if not grid[t + next[0]]: count = walk(y + dirs[0][0], x + dirs[0][1], count) if not grid[t + next[1]]: count = walk(y + dirs[1][0], x + dirs[1][1], count) if not grid[t + next[2]]: count = walk(y + dirs[2][0], x + dirs[2][1], count) if not grid[t + next[3]]: count = walk(y + dirs[3][0], x + dirs[3][1], count) grid[t] = grid[blen - t] = False return count t = h // 2 * (w + 1) + w // 2 if w % 2: grid[t] = grid[t + 1] = True count = walk(h // 2, w // 2 - 1, count) res = count count = 0 count = walk(h // 2 - 1, w // 2, count) return res + count * 2 else: grid[t] = True count = walk(h // 2, w // 2 - 1, count) if h == w: return count * 2 count = walk(h // 2 - 1, w // 2, count) return count def main(): for w in xrange(1, 10): for h in xrange(1, w + 1): if not((w * h) % 2): print "%d x %d: %d" % (w, h, cut_it(w, h)) main()
Port the provided C code into Python while preserving the original functionality.
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef unsigned char byte; byte *grid = 0; int w, h, len; unsigned long long cnt; static int next[4], dir[4][2] = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}}; void walk(int y, int x) { int i, t; if (!y || y == h || !x || x == w) { cnt += 2; return; } t = y * (w + 1) + x; grid[t]++, grid[len - t]++; for (i = 0; i < 4; i++) if (!grid[t + next[i]]) walk(y + dir[i][0], x + dir[i][1]); grid[t]--, grid[len - t]--; } unsigned long long solve(int hh, int ww, int recur) { int t, cx, cy, x; h = hh, w = ww; if (h & 1) t = w, w = h, h = t; if (h & 1) return 0; if (w == 1) return 1; if (w == 2) return h; if (h == 2) return w; cy = h / 2, cx = w / 2; len = (h + 1) * (w + 1); grid = realloc(grid, len); memset(grid, 0, len--); next[0] = -1; next[1] = -w - 1; next[2] = 1; next[3] = w + 1; if (recur) cnt = 0; for (x = cx + 1; x < w; x++) { t = cy * (w + 1) + x; grid[t] = 1; grid[len - t] = 1; walk(cy - 1, x); } cnt++; if (h == w) cnt *= 2; else if (!(w & 1) && recur) solve(w, h, 0); return cnt; } int main() { int y, x; for (y = 1; y <= 10; y++) for (x = 1; x <= y; x++) if (!(x & 1) || !(y & 1)) printf("%d x %d: %llu\n", y, x, solve(y, x, 1)); return 0; }
def cut_it(h, w): dirs = ((1, 0), (-1, 0), (0, -1), (0, 1)) if h % 2: h, w = w, h if h % 2: return 0 if w == 1: return 1 count = 0 next = [w + 1, -w - 1, -1, 1] blen = (h + 1) * (w + 1) - 1 grid = [False] * (blen + 1) def walk(y, x, count): if not y or y == h or not x or x == w: return count + 1 t = y * (w + 1) + x grid[t] = grid[blen - t] = True if not grid[t + next[0]]: count = walk(y + dirs[0][0], x + dirs[0][1], count) if not grid[t + next[1]]: count = walk(y + dirs[1][0], x + dirs[1][1], count) if not grid[t + next[2]]: count = walk(y + dirs[2][0], x + dirs[2][1], count) if not grid[t + next[3]]: count = walk(y + dirs[3][0], x + dirs[3][1], count) grid[t] = grid[blen - t] = False return count t = h // 2 * (w + 1) + w // 2 if w % 2: grid[t] = grid[t + 1] = True count = walk(h // 2, w // 2 - 1, count) res = count count = 0 count = walk(h // 2 - 1, w // 2, count) return res + count * 2 else: grid[t] = True count = walk(h // 2, w // 2 - 1, count) if h == w: return count * 2 count = walk(h // 2 - 1, w // 2, count) return count def main(): for w in xrange(1, 10): for h in xrange(1, w + 1): if not((w * h) % 2): print "%d x %d: %d" % (w, h, cut_it(w, h)) main()
Port the provided C code into Python while preserving the original functionality.
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef unsigned char byte; byte *grid = 0; int w, h, len; unsigned long long cnt; static int next[4], dir[4][2] = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}}; void walk(int y, int x) { int i, t; if (!y || y == h || !x || x == w) { cnt += 2; return; } t = y * (w + 1) + x; grid[t]++, grid[len - t]++; for (i = 0; i < 4; i++) if (!grid[t + next[i]]) walk(y + dir[i][0], x + dir[i][1]); grid[t]--, grid[len - t]--; } unsigned long long solve(int hh, int ww, int recur) { int t, cx, cy, x; h = hh, w = ww; if (h & 1) t = w, w = h, h = t; if (h & 1) return 0; if (w == 1) return 1; if (w == 2) return h; if (h == 2) return w; cy = h / 2, cx = w / 2; len = (h + 1) * (w + 1); grid = realloc(grid, len); memset(grid, 0, len--); next[0] = -1; next[1] = -w - 1; next[2] = 1; next[3] = w + 1; if (recur) cnt = 0; for (x = cx + 1; x < w; x++) { t = cy * (w + 1) + x; grid[t] = 1; grid[len - t] = 1; walk(cy - 1, x); } cnt++; if (h == w) cnt *= 2; else if (!(w & 1) && recur) solve(w, h, 0); return cnt; } int main() { int y, x; for (y = 1; y <= 10; y++) for (x = 1; x <= y; x++) if (!(x & 1) || !(y & 1)) printf("%d x %d: %llu\n", y, x, solve(y, x, 1)); return 0; }
def cut_it(h, w): dirs = ((1, 0), (-1, 0), (0, -1), (0, 1)) if h % 2: h, w = w, h if h % 2: return 0 if w == 1: return 1 count = 0 next = [w + 1, -w - 1, -1, 1] blen = (h + 1) * (w + 1) - 1 grid = [False] * (blen + 1) def walk(y, x, count): if not y or y == h or not x or x == w: return count + 1 t = y * (w + 1) + x grid[t] = grid[blen - t] = True if not grid[t + next[0]]: count = walk(y + dirs[0][0], x + dirs[0][1], count) if not grid[t + next[1]]: count = walk(y + dirs[1][0], x + dirs[1][1], count) if not grid[t + next[2]]: count = walk(y + dirs[2][0], x + dirs[2][1], count) if not grid[t + next[3]]: count = walk(y + dirs[3][0], x + dirs[3][1], count) grid[t] = grid[blen - t] = False return count t = h // 2 * (w + 1) + w // 2 if w % 2: grid[t] = grid[t + 1] = True count = walk(h // 2, w // 2 - 1, count) res = count count = 0 count = walk(h // 2 - 1, w // 2, count) return res + count * 2 else: grid[t] = True count = walk(h // 2, w // 2 - 1, count) if h == w: return count * 2 count = walk(h // 2 - 1, w // 2, count) return count def main(): for w in xrange(1, 10): for h in xrange(1, w + 1): if not((w * h) % 2): print "%d x %d: %d" % (w, h, cut_it(w, h)) main()
Can you help me rewrite this code in Python instead of C, keeping it the same logically?
#include <stdio.h> #include <stdlib.h> int* mertens_numbers(int max) { int* m = malloc((max + 1) * sizeof(int)); if (m == NULL) return m; m[1] = 1; for (int n = 2; n <= max; ++n) { m[n] = 1; for (int k = 2; k <= n; ++k) m[n] -= m[n/k]; } return m; } int main() { const int max = 1000; int* mertens = mertens_numbers(max); if (mertens == NULL) { fprintf(stderr, "Out of memory\n"); return 1; } printf("First 199 Mertens numbers:\n"); const int count = 200; for (int i = 0, column = 0; i < count; ++i) { if (column > 0) printf(" "); if (i == 0) printf(" "); else printf("%2d", mertens[i]); ++column; if (column == 20) { printf("\n"); column = 0; } } int zero = 0, cross = 0, previous = 0; for (int i = 1; i <= max; ++i) { int m = mertens[i]; if (m == 0) { ++zero; if (previous != 0) ++cross; } previous = m; } free(mertens); printf("M(n) is zero %d times for 1 <= n <= %d.\n", zero, max); printf("M(n) crosses zero %d times for 1 <= n <= %d.\n", cross, max); return 0; }
def mertens(count): m = [None, 1] for n in range(2, count+1): m.append(1) for k in range(2, n+1): m[n] -= m[n//k] return m ms = mertens(1000) print("The first 99 Mertens numbers are:") print(" ", end=' ') col = 1 for n in ms[1:100]: print("{:2d}".format(n), end=' ') col += 1 if col == 10: print() col = 0 zeroes = sum(x==0 for x in ms) crosses = sum(a!=0 and b==0 for a,b in zip(ms, ms[1:])) print("M(N) equals zero {} times.".format(zeroes)) print("M(N) crosses zero {} times.".format(crosses))
Translate this program into Python but keep the logic exactly as in C.
#include <stdio.h> #include <string.h> #include <stdlib.h> int interactiveCompare(const void *x1, const void *x2) { const char *s1 = *(const char * const *)x1; const char *s2 = *(const char * const *)x2; static int count = 0; printf("(%d) Is %s <, ==, or > %s? Answer -1, 0, or 1: ", ++count, s1, s2); int response; scanf("%d", &response); return response; } void printOrder(const char *items[], int len) { printf("{ "); for (int i = 0; i < len; ++i) printf("%s ", items[i]); printf("}\n"); } int main(void) { const char *items[] = { "violet", "red", "green", "indigo", "blue", "yellow", "orange" }; qsort(items, sizeof(items)/sizeof(*items), sizeof(*items), interactiveCompare); printOrder(items, sizeof(items)/sizeof(*items)); return 0; }
def _insort_right(a, x, q): lo, hi = 0, len(a) while lo < hi: mid = (lo+hi)//2 q += 1 less = input(f"{q:2}: IS {x:>6} LESS-THAN {a[mid]:>6} ? y/n: ").strip().lower() == 'y' if less: hi = mid else: lo = mid+1 a.insert(lo, x) return q def order(items): ordered, q = [], 0 for item in items: q = _insort_right(ordered, item, q) return ordered, q if __name__ == '__main__': items = 'violet red green indigo blue yellow orange'.split() ans, questions = order(items) print('\n' + ' '.join(ans))
Convert the following code from C to Python, ensuring the logic remains intact.
#include <stdio.h> #include <stdlib.h> #include <math.h> float *benford_distribution(void) { static float prob[9]; for (int i = 1; i < 10; i++) prob[i - 1] = log10f(1 + 1.0 / i); return prob; } float *get_actual_distribution(char *fn) { FILE *input = fopen(fn, "r"); if (!input) { perror("Can't open file"); exit(EXIT_FAILURE); } int tally[9] = { 0 }; char c; int total = 0; while ((c = getc(input)) != EOF) { while (c < '1' || c > '9') c = getc(input); tally[c - '1']++; total++; while ((c = getc(input)) != '\n' && c != EOF) ; } fclose(input); static float freq[9]; for (int i = 0; i < 9; i++) freq[i] = tally[i] / (float) total; return freq; } int main(int argc, char **argv) { if (argc != 2) { printf("Usage: benford <file>\n"); return EXIT_FAILURE; } float *actual = get_actual_distribution(argv[1]); float *expected = benford_distribution(); puts("digit\tactual\texpected"); for (int i = 0; i < 9; i++) printf("%d\t%.3f\t%.3f\n", i + 1, actual[i], expected[i]); return EXIT_SUCCESS; }
from __future__ import division from itertools import islice, count from collections import Counter from math import log10 from random import randint expected = [log10(1+1/d) for d in range(1,10)] def fib(): a,b = 1,1 while True: yield a a,b = b,a+b def power_of_threes(): return (3**k for k in count(0)) def heads(s): for a in s: yield int(str(a)[0]) def show_dist(title, s): c = Counter(s) size = sum(c.values()) res = [c[d]/size for d in range(1,10)] print("\n%s Benfords deviation" % title) for r, e in zip(res, expected): print("%5.1f%% %5.1f%% %5.1f%%" % (r*100., e*100., abs(r - e)*100.)) def rand1000(): while True: yield randint(1,9999) if __name__ == '__main__': show_dist("fibbed", islice(heads(fib()), 1000)) show_dist("threes", islice(heads(power_of_threes()), 1000)) show_dist("random", islice(heads(rand1000()), 10000))
Convert this C snippet to Python and keep its semantics consistent.
#include <stdio.h> #include <stdlib.h> #include <math.h> float *benford_distribution(void) { static float prob[9]; for (int i = 1; i < 10; i++) prob[i - 1] = log10f(1 + 1.0 / i); return prob; } float *get_actual_distribution(char *fn) { FILE *input = fopen(fn, "r"); if (!input) { perror("Can't open file"); exit(EXIT_FAILURE); } int tally[9] = { 0 }; char c; int total = 0; while ((c = getc(input)) != EOF) { while (c < '1' || c > '9') c = getc(input); tally[c - '1']++; total++; while ((c = getc(input)) != '\n' && c != EOF) ; } fclose(input); static float freq[9]; for (int i = 0; i < 9; i++) freq[i] = tally[i] / (float) total; return freq; } int main(int argc, char **argv) { if (argc != 2) { printf("Usage: benford <file>\n"); return EXIT_FAILURE; } float *actual = get_actual_distribution(argv[1]); float *expected = benford_distribution(); puts("digit\tactual\texpected"); for (int i = 0; i < 9; i++) printf("%d\t%.3f\t%.3f\n", i + 1, actual[i], expected[i]); return EXIT_SUCCESS; }
from __future__ import division from itertools import islice, count from collections import Counter from math import log10 from random import randint expected = [log10(1+1/d) for d in range(1,10)] def fib(): a,b = 1,1 while True: yield a a,b = b,a+b def power_of_threes(): return (3**k for k in count(0)) def heads(s): for a in s: yield int(str(a)[0]) def show_dist(title, s): c = Counter(s) size = sum(c.values()) res = [c[d]/size for d in range(1,10)] print("\n%s Benfords deviation" % title) for r, e in zip(res, expected): print("%5.1f%% %5.1f%% %5.1f%%" % (r*100., e*100., abs(r - e)*100.)) def rand1000(): while True: yield randint(1,9999) if __name__ == '__main__': show_dist("fibbed", islice(heads(fib()), 1000)) show_dist("threes", islice(heads(power_of_threes()), 1000)) show_dist("random", islice(heads(rand1000()), 10000))
Transform the following C implementation into Python, maintaining the same output and logic.
#include<unistd.h> #include<stdio.h> #include<time.h> #define SHORTLAG 1000 #define LONGLAG 2000 int main(){ int i,times,hour,min,sec,min1,min2; time_t t; struct tm* currentTime; while(1){ time(&t); currentTime = localtime(&t); hour = currentTime->tm_hour; min = currentTime->tm_min; sec = currentTime->tm_sec; hour = 12; min = 0; sec = 0; if((min==0 || min==30) && sec==0) times = ((hour*60 + min)%240)%8; if(times==0){ times = 8; } if(min==0){ min1 = 0; min2 = 0; } else{ min1 = 3; min2 = 0; } if((min==0 || min==30) && sec==0){ printf("\nIt is now %d:%d%d %s. Sounding the bell %d times.",hour,min1,min2,(hour>11)?"PM":"AM",times); for(i=1;i<=times;i++){ printf("\a"); (i%2==0)?sleep(LONGLAG):sleep(SHORTLAG); } } } return 0; }
import time, calendar, sched, winsound duration = 750 freq = 1280 bellchar = "\u2407" watches = 'Middle,Morning,Forenoon,Afternoon,First/Last dog,First'.split(',') def gap(n=1): time.sleep(n * duration / 1000) off = gap def on(n=1): winsound.Beep(freq, n * duration) def bong(): on(); off(0.5) def bongs(m): for i in range(m): print(bellchar, end=' ') bong() if i % 2: print(' ', end='') off(0.5) print('') scheds = sched.scheduler(time.time, time.sleep) def ships_bell(now=None): def adjust_to_half_hour(atime): atime[4] = (atime[4] // 30) * 30 atime[5] = 0 return atime debug = now is not None rightnow = time.gmtime() if not debug: now = adjust_to_half_hour( list(rightnow) ) then = now[::] then[4] += 30 hr, mn = now[3:5] watch, b = divmod(int(2 * hr + mn // 30 - 1), 8) b += 1 bells = '%i bell%s' % (b, 's' if b > 1 else ' ') if debug: print("%02i:%02i, %-20s %s" % (now[3], now[4], watches[watch] + ' watch', bells), end=' ') else: print("%02i:%02i, %-20s %s" % (rightnow[3], rightnow[4], watches[watch] + ' watch', bells), end=' ') bongs(b) if not debug: scheds.enterabs(calendar.timegm(then), 0, ships_bell) scheds.run() def dbg_tester(): for h in range(24): for m in (0, 30): if (h,m) == (24,30): break ships_bell( [2013, 3, 2, h, m, 15, 5, 61, 0] ) if __name__ == '__main__': ships_bell()
Can you help me rewrite this code in Python instead of C, keeping it the same logically?
#include<unistd.h> #include<stdio.h> #include<time.h> #define SHORTLAG 1000 #define LONGLAG 2000 int main(){ int i,times,hour,min,sec,min1,min2; time_t t; struct tm* currentTime; while(1){ time(&t); currentTime = localtime(&t); hour = currentTime->tm_hour; min = currentTime->tm_min; sec = currentTime->tm_sec; hour = 12; min = 0; sec = 0; if((min==0 || min==30) && sec==0) times = ((hour*60 + min)%240)%8; if(times==0){ times = 8; } if(min==0){ min1 = 0; min2 = 0; } else{ min1 = 3; min2 = 0; } if((min==0 || min==30) && sec==0){ printf("\nIt is now %d:%d%d %s. Sounding the bell %d times.",hour,min1,min2,(hour>11)?"PM":"AM",times); for(i=1;i<=times;i++){ printf("\a"); (i%2==0)?sleep(LONGLAG):sleep(SHORTLAG); } } } return 0; }
import time, calendar, sched, winsound duration = 750 freq = 1280 bellchar = "\u2407" watches = 'Middle,Morning,Forenoon,Afternoon,First/Last dog,First'.split(',') def gap(n=1): time.sleep(n * duration / 1000) off = gap def on(n=1): winsound.Beep(freq, n * duration) def bong(): on(); off(0.5) def bongs(m): for i in range(m): print(bellchar, end=' ') bong() if i % 2: print(' ', end='') off(0.5) print('') scheds = sched.scheduler(time.time, time.sleep) def ships_bell(now=None): def adjust_to_half_hour(atime): atime[4] = (atime[4] // 30) * 30 atime[5] = 0 return atime debug = now is not None rightnow = time.gmtime() if not debug: now = adjust_to_half_hour( list(rightnow) ) then = now[::] then[4] += 30 hr, mn = now[3:5] watch, b = divmod(int(2 * hr + mn // 30 - 1), 8) b += 1 bells = '%i bell%s' % (b, 's' if b > 1 else ' ') if debug: print("%02i:%02i, %-20s %s" % (now[3], now[4], watches[watch] + ' watch', bells), end=' ') else: print("%02i:%02i, %-20s %s" % (rightnow[3], rightnow[4], watches[watch] + ' watch', bells), end=' ') bongs(b) if not debug: scheds.enterabs(calendar.timegm(then), 0, ships_bell) scheds.run() def dbg_tester(): for h in range(24): for m in (0, 30): if (h,m) == (24,30): break ships_bell( [2013, 3, 2, h, m, 15, 5, 61, 0] ) if __name__ == '__main__': ships_bell()
Rewrite this program in Python while keeping its functionality equivalent to the C version.
#include <stdio.h> long fib(long x) { long fib_i(long n) { return n < 2 ? n : fib_i(n - 2) + fib_i(n - 1); }; if (x < 0) { printf("Bad argument: fib(%ld)\n", x); return -1; } return fib_i(x); } long fib_i(long n) { printf("This is not the fib you are looking for\n"); return -1; } int main() { long x; for (x = -1; x < 4; x ++) printf("fib %ld = %ld\n", x, fib(x)); printf("calling fib_i from outside fib:\n"); fib_i(3); return 0; }
>>> Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args))) >>> fib = lambda f: lambda n: None if n < 0 else (0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2))) >>> [ Y(fib)(i) for i in range(-2, 10) ] [None, None, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Write the same algorithm in Python as shown in this C implementation.
#include <stdio.h> long fib(long x) { long fib_i(long n) { return n < 2 ? n : fib_i(n - 2) + fib_i(n - 1); }; if (x < 0) { printf("Bad argument: fib(%ld)\n", x); return -1; } return fib_i(x); } long fib_i(long n) { printf("This is not the fib you are looking for\n"); return -1; } int main() { long x; for (x = -1; x < 4; x ++) printf("fib %ld = %ld\n", x, fib(x)); printf("calling fib_i from outside fib:\n"); fib_i(3); return 0; }
>>> Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args))) >>> fib = lambda f: lambda n: None if n < 0 else (0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2))) >>> [ Y(fib)(i) for i in range(-2, 10) ] [None, None, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Please provide an equivalent version of this C code in Python.
char nonblocking_getch(); void positional_putch(int x, int y, char ch); void millisecond_sleep(int n); void init_screen(); void update_screen(); void close_screen(); #ifdef __linux__ #define _POSIX_C_SOURCE 200809L #include <time.h> #include <ncurses.h> char nonblocking_getch() { return getch(); } void positional_putch(int x, int y, char ch) { mvaddch(x, y, ch); } void millisecond_sleep(int n) { struct timespec t = { 0, n * 1000000 }; nanosleep(&t, 0); } void update_screen() { refresh(); } void init_screen() { initscr(); noecho(); cbreak(); nodelay(stdscr, TRUE); } void close_screen() { endwin(); } #endif #ifdef _WIN32 #error "not implemented" #endif #include <time.h> #include <stdlib.h> #define w 80 #define h 40 int board[w * h]; int head; enum Dir { N, E, S, W } dir; int quit; enum State { SPACE=0, FOOD=1, BORDER=2 }; void age() { int i; for(i = 0; i < w * h; ++i) if(board[i] < 0) ++board[i]; } void plant() { int r; do r = rand() % (w * h); while(board[r] != SPACE); board[r] = FOOD; } void start(void) { int i; for(i = 0; i < w; ++i) board[i] = board[i + (h - 1) * w] = BORDER; for(i = 0; i < h; ++i) board[i * w] = board[i * w + w - 1] = BORDER; head = w * (h - 1 - h % 2) / 2; board[head] = -5; dir = N; quit = 0; srand(time(0)); plant(); } void step() { int len = board[head]; switch(dir) { case N: head -= w; break; case S: head += w; break; case W: --head; break; case E: ++head; break; } switch(board[head]) { case SPACE: board[head] = len - 1; age(); break; case FOOD: board[head] = len - 1; plant(); break; default: quit = 1; } } void show() { const char * symbol = " @."; int i; for(i = 0; i < w * h; ++i) positional_putch(i / w, i % w, board[i] < 0 ? '#' : symbol[board[i]]); update_screen(); } int main (int argc, char * argv[]) { init_screen(); start(); do { show(); switch(nonblocking_getch()) { case 'i': dir = N; break; case 'j': dir = W; break; case 'k': dir = S; break; case 'l': dir = E; break; case 'q': quit = 1; break; } step(); millisecond_sleep(100); } while(!quit); millisecond_sleep(999); close_screen(); return 0; }
from __future__ import annotations import itertools import random from enum import Enum from typing import Any from typing import Tuple import pygame as pg from pygame import Color from pygame import Rect from pygame.surface import Surface from pygame.sprite import AbstractGroup from pygame.sprite import Group from pygame.sprite import RenderUpdates from pygame.sprite import Sprite class Direction(Enum): UP = (0, -1) DOWN = (0, 1) LEFT = (-1, 0) RIGHT = (1, 0) def opposite(self, other: Direction): return (self[0] + other[0], self[1] + other[1]) == (0, 0) def __getitem__(self, i: int): return self.value[i] class SnakeHead(Sprite): def __init__( self, size: int, position: Tuple[int, int], facing: Direction, bounds: Rect, ) -> None: super().__init__() self.image = Surface((size, size)) self.image.fill(Color("aquamarine4")) self.rect = self.image.get_rect() self.rect.center = position self.facing = facing self.size = size self.speed = size self.bounds = bounds def update(self, *args: Any, **kwargs: Any) -> None: self.rect.move_ip( ( self.facing[0] * self.speed, self.facing[1] * self.speed, ) ) if self.rect.right > self.bounds.right: self.rect.left = 0 elif self.rect.left < 0: self.rect.right = self.bounds.right if self.rect.bottom > self.bounds.bottom: self.rect.top = 0 elif self.rect.top < 0: self.rect.bottom = self.bounds.bottom def change_direction(self, direction: Direction): if not self.facing == direction and not direction.opposite(self.facing): self.facing = direction class SnakeBody(Sprite): def __init__( self, size: int, position: Tuple[int, int], colour: str = "white", ) -> None: super().__init__() self.image = Surface((size, size)) self.image.fill(Color(colour)) self.rect = self.image.get_rect() self.rect.center = position class Snake(RenderUpdates): def __init__(self, game: Game) -> None: self.segment_size = game.segment_size self.colours = itertools.cycle(["aquamarine1", "aquamarine3"]) self.head = SnakeHead( size=self.segment_size, position=game.rect.center, facing=Direction.RIGHT, bounds=game.rect, ) neck = [ SnakeBody( size=self.segment_size, position=game.rect.center, colour=next(self.colours), ) for _ in range(2) ] super().__init__(*[self.head, *neck]) self.body = Group() self.tail = neck[-1] def update(self, *args: Any, **kwargs: Any) -> None: self.head.update() segments = self.sprites() for i in range(len(segments) - 1, 0, -1): segments[i].rect.center = segments[i - 1].rect.center def change_direction(self, direction: Direction): self.head.change_direction(direction) def grow(self): tail = SnakeBody( size=self.segment_size, position=self.tail.rect.center, colour=next(self.colours), ) self.tail = tail self.add(self.tail) self.body.add(self.tail) class SnakeFood(Sprite): def __init__(self, game: Game, size: int, *groups: AbstractGroup) -> None: super().__init__(*groups) self.image = Surface((size, size)) self.image.fill(Color("red")) self.rect = self.image.get_rect() self.rect.topleft = ( random.randint(0, game.rect.width), random.randint(0, game.rect.height), ) self.rect.clamp_ip(game.rect) while pg.sprite.spritecollideany(self, game.snake): self.rect.topleft = ( random.randint(0, game.rect.width), random.randint(0, game.rect.height), ) self.rect.clamp_ip(game.rect) class Game: def __init__(self) -> None: self.rect = Rect(0, 0, 640, 480) self.background = Surface(self.rect.size) self.background.fill(Color("black")) self.score = 0 self.framerate = 16 self.segment_size = 10 self.snake = Snake(self) self.food_group = RenderUpdates(SnakeFood(game=self, size=self.segment_size)) pg.init() def _init_display(self) -> Surface: bestdepth = pg.display.mode_ok(self.rect.size, 0, 32) screen = pg.display.set_mode(self.rect.size, 0, bestdepth) pg.display.set_caption("Snake") pg.mouse.set_visible(False) screen.blit(self.background, (0, 0)) pg.display.flip() return screen def draw(self, screen: Surface): dirty = self.snake.draw(screen) pg.display.update(dirty) dirty = self.food_group.draw(screen) pg.display.update(dirty) def update(self, screen): self.food_group.clear(screen, self.background) self.food_group.update() self.snake.clear(screen, self.background) self.snake.update() def main(self) -> int: screen = self._init_display() clock = pg.time.Clock() while self.snake.head.alive(): for event in pg.event.get(): if event.type == pg.QUIT or ( event.type == pg.KEYDOWN and event.key in (pg.K_ESCAPE, pg.K_q) ): return self.score keystate = pg.key.get_pressed() if keystate[pg.K_RIGHT]: self.snake.change_direction(Direction.RIGHT) elif keystate[pg.K_LEFT]: self.snake.change_direction(Direction.LEFT) elif keystate[pg.K_UP]: self.snake.change_direction(Direction.UP) elif keystate[pg.K_DOWN]: self.snake.change_direction(Direction.DOWN) self.update(screen) for food in pg.sprite.spritecollide( self.snake.head, self.food_group, dokill=False ): food.kill() self.snake.grow() self.score += 1 if self.score % 5 == 0: self.framerate += 1 self.food_group.add(SnakeFood(self, self.segment_size)) if pg.sprite.spritecollideany(self.snake.head, self.snake.body): self.snake.head.kill() self.draw(screen) clock.tick(self.framerate) return self.score if __name__ == "__main__": game = Game() score = game.main() print(score)
Convert the following code from C to Python, ensuring the logic remains intact.
#include <string.h> #include <stdlib.h> #include <stdio.h> int main( int argc, char ** argv ){ const char * str_a = "knight"; const char * str_b = "socks"; const char * str_c = "brooms"; char * new_a = malloc( strlen( str_a ) - 1 ); char * new_b = malloc( strlen( str_b ) - 1 ); char * new_c = malloc( strlen( str_c ) - 2 ); strcpy( new_a, str_a + 1 ); strncpy( new_b, str_b, strlen( str_b ) - 1 ); strncpy( new_c, str_c + 1, strlen( str_c ) - 2 ); printf( "%s\n%s\n%s\n", new_a, new_b, new_c ); free( new_a ); free( new_b ); free( new_c ); return 0; }
print "knight"[1:] print "socks"[:-1] print "brooms"[1:-1]
Maintain the same structure and functionality when rewriting this code in Python.
#include <string.h> #include <stdlib.h> #include <stdio.h> int main( int argc, char ** argv ){ const char * str_a = "knight"; const char * str_b = "socks"; const char * str_c = "brooms"; char * new_a = malloc( strlen( str_a ) - 1 ); char * new_b = malloc( strlen( str_b ) - 1 ); char * new_c = malloc( strlen( str_c ) - 2 ); strcpy( new_a, str_a + 1 ); strncpy( new_b, str_b, strlen( str_b ) - 1 ); strncpy( new_c, str_c + 1, strlen( str_c ) - 2 ); printf( "%s\n%s\n%s\n", new_a, new_b, new_c ); free( new_a ); free( new_b ); free( new_c ); return 0; }
print "knight"[1:] print "socks"[:-1] print "brooms"[1:-1]
Produce a language-to-language conversion: from C to Python, same semantics.
#include <stdio.h> #include <math.h> #include <stdlib.h> #include <stdint.h> #include <time.h> const uint8_t masks[8] = {1, 2, 4, 8, 16, 32, 64, 128}; #define half(n) ((int64_t)((n) - 1) >> 1) #define divide(nm, d) ((uint64_t)((double)nm / (double)d)) int64_t countPrimes(uint64_t n) { if (n < 9) return (n < 2) ? 0 : ((int64_t)n + 1) / 2; uint64_t rtlmt = (uint64_t)sqrt((double)n); int64_t mxndx = (int64_t)((rtlmt - 1) / 2); int arrlen = (int)(mxndx + 1); uint32_t *smalls = malloc(arrlen * 4); uint32_t *roughs = malloc(arrlen * 4); int64_t *larges = malloc(arrlen * 8); for (int i = 0; i < arrlen; ++i) { smalls[i] = (uint32_t)i; roughs[i] = (uint32_t)(i + i + 1); larges[i] = (int64_t)((n/(uint64_t)(i + i + 1) - 1) / 2); } int cullbuflen = (int)((mxndx + 8) / 8); uint8_t *cullbuf = calloc(cullbuflen, 1); int64_t nbps = 0; int rilmt = arrlen; for (int64_t i = 1; ; ++i) { int64_t sqri = (i + i) * (i + 1); if (sqri > mxndx) break; if (cullbuf[i >> 3] & masks[i & 7]) continue; cullbuf[i >> 3] |= masks[i & 7]; uint64_t bp = (uint64_t)(i + i + 1); for (int64_t c = sqri; c < (int64_t)arrlen; c += (int64_t)bp) { cullbuf[c >> 3] |= masks[c & 7]; } int nri = 0; for (int ori = 0; ori < rilmt; ++ori) { uint32_t r = roughs[ori]; int64_t rci = (int64_t)(r >> 1); if (cullbuf[rci >> 3] & masks[rci & 7]) continue; uint64_t d = (uint64_t)r * bp; int64_t t = (d <= rtlmt) ? larges[(int64_t)smalls[d >> 1] - nbps] : (int64_t)smalls[half(divide(n, d))]; larges[nri] = larges[ori] - t + nbps; roughs[nri] = r; nri++; } int64_t si = mxndx; for (uint64_t pm = (rtlmt/bp - 1) | 1; pm >= bp; pm -= 2) { uint32_t c = smalls[pm >> 1]; uint64_t e = (pm * bp) >> 1; for ( ; si >= (int64_t)e; --si) smalls[si] -= c - (uint32_t)nbps; } rilmt = nri; nbps++; } int64_t ans = larges[0] + (int64_t)((rilmt + 2*(nbps - 1)) * (rilmt - 1) / 2); int ri, sri; for (ri = 1; ri < rilmt; ++ri) ans -= larges[ri]; for (ri = 1; ; ++ri) { uint64_t p = (uint64_t)roughs[ri]; uint64_t m = n / p; int ei = (int)smalls[half((uint64_t)m/p)] - nbps; if (ei <= ri) break; ans -= (int64_t)((ei - ri) * (nbps + ri - 1)); for (sri = ri + 1; sri < ei + 1; ++sri) { ans += (int64_t)smalls[half(divide(m, (uint64_t)roughs[sri]))]; } } free(smalls); free(roughs); free(larges); free(cullbuf); return ans + 1; } int main() { uint64_t n; int i; clock_t start = clock(); for (i = 0, n = 1; i < 10; ++i, n *= 10) { printf("10^%d %ld\n", i, countPrimes(n)); } clock_t end = clock(); printf("\nTook %f seconds\n", (double) (end - start) / CLOCKS_PER_SEC); return 0; }
from primesieve import primes from math import isqrt from functools import cache p = primes(isqrt(1_000_000_000)) @cache def phi(x, a): res = 0 while True: if not a or not x: return x + res a -= 1 res -= phi(x//p[a], a) def legpi(n): if n < 2: return 0 a = legpi(isqrt(n)) return phi(n, a) + a - 1 for e in range(10): print(f'10^{e}', legpi(10**e))
Ensure the translated Python code behaves exactly like the original C snippet.
#include <stdio.h> extern int Query (char * Data, size_t * Length); int main (int argc, char * argv []) { char Buffer [1024]; size_t Size = sizeof (Buffer); if (0 == Query (Buffer, &Size)) { printf ("failed to call Query\n"); } else { char * Ptr = Buffer; while (Size-- > 0) putchar (*Ptr++); putchar ('\n'); } }
def query(buffer_length): message = b'Here am I' L = len(message) return message[0:L*(L <= buffer_length)]
Transform the following C implementation into Python, maintaining the same output and logic.
#include <stdio.h> #include <string.h> int cmp(const char *p, const char *q) { while (*p && *q) p = &p[1], q = &q[1]; return *p; } int main() { char line[65536]; char buf[1000000] = {0}; char *last = buf; char *next = buf; while (gets(line)) { strcat(line, "\n"); if (cmp(last, line)) continue; if (cmp(line, last)) next = buf; last = next; strcpy(next, line); while (*next) next = &next[1]; } printf("%s", buf); return 0; }
import fileinput def longer(a, b): try: b[len(a)-1] return False except: return True longest, lines = '', '' for x in fileinput.input(): if longer(x, longest): lines, longest = x, x elif not longer(longest, x): lines += x print(lines, end='')
Please provide an equivalent version of this C code in Python.
#include <stdio.h> #include <stdarg.h> #include <stdlib.h> #include <string.h> enum { LEFT, RIGHT, STAY }; typedef struct { int state1; int symbol1; int symbol2; int dir; int state2; } transition_t; typedef struct tape_t tape_t; struct tape_t { int symbol; tape_t *left; tape_t *right; }; typedef struct { int states_len; char **states; int final_states_len; int *final_states; int symbols_len; char *symbols; int blank; int state; int tape_len; tape_t *tape; int transitions_len; transition_t ***transitions; } turing_t; int state_index (turing_t *t, char *state) { int i; for (i = 0; i < t->states_len; i++) { if (!strcmp(t->states[i], state)) { return i; } } return 0; } int symbol_index (turing_t *t, char symbol) { int i; for (i = 0; i < t->symbols_len; i++) { if (t->symbols[i] == symbol) { return i; } } return 0; } void move (turing_t *t, int dir) { tape_t *orig = t->tape; if (dir == RIGHT) { if (orig && orig->right) { t->tape = orig->right; } else { t->tape = calloc(1, sizeof (tape_t)); t->tape->symbol = t->blank; if (orig) { t->tape->left = orig; orig->right = t->tape; } } } else if (dir == LEFT) { if (orig && orig->left) { t->tape = orig->left; } else { t->tape = calloc(1, sizeof (tape_t)); t->tape->symbol = t->blank; if (orig) { t->tape->right = orig; orig->left = t->tape; } } } } turing_t *create (int states_len, ...) { va_list args; va_start(args, states_len); turing_t *t = malloc(sizeof (turing_t)); t->states_len = states_len; t->states = malloc(states_len * sizeof (char *)); int i; for (i = 0; i < states_len; i++) { t->states[i] = va_arg(args, char *); } t->final_states_len = va_arg(args, int); t->final_states = malloc(t->final_states_len * sizeof (int)); for (i = 0; i < t->final_states_len; i++) { t->final_states[i] = state_index(t, va_arg(args, char *)); } t->symbols_len = va_arg(args, int); t->symbols = malloc(t->symbols_len); for (i = 0; i < t->symbols_len; i++) { t->symbols[i] = va_arg(args, int); } t->blank = symbol_index(t, va_arg(args, int)); t->state = state_index(t, va_arg(args, char *)); t->tape_len = va_arg(args, int); t->tape = NULL; for (i = 0; i < t->tape_len; i++) { move(t, RIGHT); t->tape->symbol = symbol_index(t, va_arg(args, int)); } if (!t->tape_len) { move(t, RIGHT); } while (t->tape->left) { t->tape = t->tape->left; } t->transitions_len = va_arg(args, int); t->transitions = malloc(t->states_len * sizeof (transition_t **)); for (i = 0; i < t->states_len; i++) { t->transitions[i] = malloc(t->symbols_len * sizeof (transition_t *)); } for (i = 0; i < t->transitions_len; i++) { transition_t *tran = malloc(sizeof (transition_t)); tran->state1 = state_index(t, va_arg(args, char *)); tran->symbol1 = symbol_index(t, va_arg(args, int)); tran->symbol2 = symbol_index(t, va_arg(args, int)); tran->dir = va_arg(args, int); tran->state2 = state_index(t, va_arg(args, char *)); t->transitions[tran->state1][tran->symbol1] = tran; } va_end(args); return t; } void print_state (turing_t *t) { printf("%-10s ", t->states[t->state]); tape_t *tape = t->tape; while (tape->left) { tape = tape->left; } while (tape) { if (tape == t->tape) { printf("[%c]", t->symbols[tape->symbol]); } else { printf(" %c ", t->symbols[tape->symbol]); } tape = tape->right; } printf("\n"); } void run (turing_t *t) { int i; while (1) { print_state(t); for (i = 0; i < t->final_states_len; i++) { if (t->final_states[i] == t->state) { return; } } transition_t *tran = t->transitions[t->state][t->tape->symbol]; t->tape->symbol = tran->symbol2; move(t, tran->dir); t->state = tran->state2; } } int main () { printf("Simple incrementer\n"); turing_t *t = create( 2, "q0", "qf", 1, "qf", 2, 'B', '1', 'B', "q0", 3, '1', '1', '1', 2, "q0", '1', '1', RIGHT, "q0", "q0", 'B', '1', STAY, "qf" ); run(t); printf("\nThree-state busy beaver\n"); t = create( 4, "a", "b", "c", "halt", 1, "halt", 2, '0', '1', '0', "a", 0, 6, "a", '0', '1', RIGHT, "b", "a", '1', '1', LEFT, "c", "b", '0', '1', LEFT, "a", "b", '1', '1', RIGHT, "b", "c", '0', '1', LEFT, "b", "c", '1', '1', STAY, "halt" ); run(t); return 0; printf("\nFive-state two-symbol probable busy beaver\n"); t = create( 6, "A", "B", "C", "D", "E", "H", 1, "H", 2, '0', '1', '0', "A", 0, 10, "A", '0', '1', RIGHT, "B", "A", '1', '1', LEFT, "C", "B", '0', '1', RIGHT, "C", "B", '1', '1', RIGHT, "B", "C", '0', '1', RIGHT, "D", "C", '1', '0', LEFT, "E", "D", '0', '1', LEFT, "A", "D", '1', '1', LEFT, "D", "E", '0', '1', STAY, "H", "E", '1', '0', LEFT, "A" ); run(t); }
from __future__ import print_function def run_utm( state = None, blank = None, rules = [], tape = [], halt = None, pos = 0): st = state if not tape: tape = [blank] if pos < 0: pos += len(tape) if pos >= len(tape) or pos < 0: raise Error( "bad init position") rules = dict(((s0, v0), (v1, dr, s1)) for (s0, v0, v1, dr, s1) in rules) while True: print(st, '\t', end=" ") for i, v in enumerate(tape): if i == pos: print("[%s]" % (v,), end=" ") else: print(v, end=" ") print() if st == halt: break if (st, tape[pos]) not in rules: break (v1, dr, s1) = rules[(st, tape[pos])] tape[pos] = v1 if dr == 'left': if pos > 0: pos -= 1 else: tape.insert(0, blank) if dr == 'right': pos += 1 if pos >= len(tape): tape.append(blank) st = s1 print("incr machine\n") run_utm( halt = 'qf', state = 'q0', tape = list("111"), blank = 'B', rules = map(tuple, ["q0 1 1 right q0".split(), "q0 B 1 stay qf".split()] ) ) print("\nbusy beaver\n") run_utm( halt = 'halt', state = 'a', blank = '0', rules = map(tuple, ["a 0 1 right b".split(), "a 1 1 left c".split(), "b 0 1 left a".split(), "b 1 1 right b".split(), "c 0 1 left b".split(), "c 1 1 stay halt".split()] ) ) print("\nsorting test\n") run_utm(halt = 'STOP', state = 'A', blank = '0', tape = "2 2 2 1 2 2 1 2 1 2 1 2 1 2".split(), rules = map(tuple, ["A 1 1 right A".split(), "A 2 3 right B".split(), "A 0 0 left E".split(), "B 1 1 right B".split(), "B 2 2 right B".split(), "B 0 0 left C".split(), "C 1 2 left D".split(), "C 2 2 left C".split(), "C 3 2 left E".split(), "D 1 1 left D".split(), "D 2 2 left D".split(), "D 3 1 right A".split(), "E 1 1 left E".split(), "E 0 0 right STOP".split()] ) )
Preserve the algorithm and functionality while converting the code from C to Python.
#include <stdio.h> #include <stdarg.h> #include <stdlib.h> #include <string.h> enum { LEFT, RIGHT, STAY }; typedef struct { int state1; int symbol1; int symbol2; int dir; int state2; } transition_t; typedef struct tape_t tape_t; struct tape_t { int symbol; tape_t *left; tape_t *right; }; typedef struct { int states_len; char **states; int final_states_len; int *final_states; int symbols_len; char *symbols; int blank; int state; int tape_len; tape_t *tape; int transitions_len; transition_t ***transitions; } turing_t; int state_index (turing_t *t, char *state) { int i; for (i = 0; i < t->states_len; i++) { if (!strcmp(t->states[i], state)) { return i; } } return 0; } int symbol_index (turing_t *t, char symbol) { int i; for (i = 0; i < t->symbols_len; i++) { if (t->symbols[i] == symbol) { return i; } } return 0; } void move (turing_t *t, int dir) { tape_t *orig = t->tape; if (dir == RIGHT) { if (orig && orig->right) { t->tape = orig->right; } else { t->tape = calloc(1, sizeof (tape_t)); t->tape->symbol = t->blank; if (orig) { t->tape->left = orig; orig->right = t->tape; } } } else if (dir == LEFT) { if (orig && orig->left) { t->tape = orig->left; } else { t->tape = calloc(1, sizeof (tape_t)); t->tape->symbol = t->blank; if (orig) { t->tape->right = orig; orig->left = t->tape; } } } } turing_t *create (int states_len, ...) { va_list args; va_start(args, states_len); turing_t *t = malloc(sizeof (turing_t)); t->states_len = states_len; t->states = malloc(states_len * sizeof (char *)); int i; for (i = 0; i < states_len; i++) { t->states[i] = va_arg(args, char *); } t->final_states_len = va_arg(args, int); t->final_states = malloc(t->final_states_len * sizeof (int)); for (i = 0; i < t->final_states_len; i++) { t->final_states[i] = state_index(t, va_arg(args, char *)); } t->symbols_len = va_arg(args, int); t->symbols = malloc(t->symbols_len); for (i = 0; i < t->symbols_len; i++) { t->symbols[i] = va_arg(args, int); } t->blank = symbol_index(t, va_arg(args, int)); t->state = state_index(t, va_arg(args, char *)); t->tape_len = va_arg(args, int); t->tape = NULL; for (i = 0; i < t->tape_len; i++) { move(t, RIGHT); t->tape->symbol = symbol_index(t, va_arg(args, int)); } if (!t->tape_len) { move(t, RIGHT); } while (t->tape->left) { t->tape = t->tape->left; } t->transitions_len = va_arg(args, int); t->transitions = malloc(t->states_len * sizeof (transition_t **)); for (i = 0; i < t->states_len; i++) { t->transitions[i] = malloc(t->symbols_len * sizeof (transition_t *)); } for (i = 0; i < t->transitions_len; i++) { transition_t *tran = malloc(sizeof (transition_t)); tran->state1 = state_index(t, va_arg(args, char *)); tran->symbol1 = symbol_index(t, va_arg(args, int)); tran->symbol2 = symbol_index(t, va_arg(args, int)); tran->dir = va_arg(args, int); tran->state2 = state_index(t, va_arg(args, char *)); t->transitions[tran->state1][tran->symbol1] = tran; } va_end(args); return t; } void print_state (turing_t *t) { printf("%-10s ", t->states[t->state]); tape_t *tape = t->tape; while (tape->left) { tape = tape->left; } while (tape) { if (tape == t->tape) { printf("[%c]", t->symbols[tape->symbol]); } else { printf(" %c ", t->symbols[tape->symbol]); } tape = tape->right; } printf("\n"); } void run (turing_t *t) { int i; while (1) { print_state(t); for (i = 0; i < t->final_states_len; i++) { if (t->final_states[i] == t->state) { return; } } transition_t *tran = t->transitions[t->state][t->tape->symbol]; t->tape->symbol = tran->symbol2; move(t, tran->dir); t->state = tran->state2; } } int main () { printf("Simple incrementer\n"); turing_t *t = create( 2, "q0", "qf", 1, "qf", 2, 'B', '1', 'B', "q0", 3, '1', '1', '1', 2, "q0", '1', '1', RIGHT, "q0", "q0", 'B', '1', STAY, "qf" ); run(t); printf("\nThree-state busy beaver\n"); t = create( 4, "a", "b", "c", "halt", 1, "halt", 2, '0', '1', '0', "a", 0, 6, "a", '0', '1', RIGHT, "b", "a", '1', '1', LEFT, "c", "b", '0', '1', LEFT, "a", "b", '1', '1', RIGHT, "b", "c", '0', '1', LEFT, "b", "c", '1', '1', STAY, "halt" ); run(t); return 0; printf("\nFive-state two-symbol probable busy beaver\n"); t = create( 6, "A", "B", "C", "D", "E", "H", 1, "H", 2, '0', '1', '0', "A", 0, 10, "A", '0', '1', RIGHT, "B", "A", '1', '1', LEFT, "C", "B", '0', '1', RIGHT, "C", "B", '1', '1', RIGHT, "B", "C", '0', '1', RIGHT, "D", "C", '1', '0', LEFT, "E", "D", '0', '1', LEFT, "A", "D", '1', '1', LEFT, "D", "E", '0', '1', STAY, "H", "E", '1', '0', LEFT, "A" ); run(t); }
from __future__ import print_function def run_utm( state = None, blank = None, rules = [], tape = [], halt = None, pos = 0): st = state if not tape: tape = [blank] if pos < 0: pos += len(tape) if pos >= len(tape) or pos < 0: raise Error( "bad init position") rules = dict(((s0, v0), (v1, dr, s1)) for (s0, v0, v1, dr, s1) in rules) while True: print(st, '\t', end=" ") for i, v in enumerate(tape): if i == pos: print("[%s]" % (v,), end=" ") else: print(v, end=" ") print() if st == halt: break if (st, tape[pos]) not in rules: break (v1, dr, s1) = rules[(st, tape[pos])] tape[pos] = v1 if dr == 'left': if pos > 0: pos -= 1 else: tape.insert(0, blank) if dr == 'right': pos += 1 if pos >= len(tape): tape.append(blank) st = s1 print("incr machine\n") run_utm( halt = 'qf', state = 'q0', tape = list("111"), blank = 'B', rules = map(tuple, ["q0 1 1 right q0".split(), "q0 B 1 stay qf".split()] ) ) print("\nbusy beaver\n") run_utm( halt = 'halt', state = 'a', blank = '0', rules = map(tuple, ["a 0 1 right b".split(), "a 1 1 left c".split(), "b 0 1 left a".split(), "b 1 1 right b".split(), "c 0 1 left b".split(), "c 1 1 stay halt".split()] ) ) print("\nsorting test\n") run_utm(halt = 'STOP', state = 'A', blank = '0', tape = "2 2 2 1 2 2 1 2 1 2 1 2 1 2".split(), rules = map(tuple, ["A 1 1 right A".split(), "A 2 3 right B".split(), "A 0 0 left E".split(), "B 1 1 right B".split(), "B 2 2 right B".split(), "B 0 0 left C".split(), "C 1 2 left D".split(), "C 2 2 left C".split(), "C 3 2 left E".split(), "D 1 1 left D".split(), "D 2 2 left D".split(), "D 3 1 right A".split(), "E 1 1 left E".split(), "E 0 0 right STOP".split()] ) )
Write the same algorithm in Python as shown in this C implementation.
#include <stdio.h> int main() { FILE *fh = fopen("output.txt", "w"); fclose(fh); return 0; }
import os for directory in ['/', './']: open(directory + 'output.txt', 'w').close() os.mkdir(directory + 'docs')
Generate an equivalent Python version of this C code.
#include <assert.h> #include <locale.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> typedef struct bit_array_tag { uint32_t size; uint32_t* array; } bit_array; bool bit_array_create(bit_array* b, uint32_t size) { uint32_t* array = calloc((size + 31)/32, sizeof(uint32_t)); if (array == NULL) return false; b->size = size; b->array = array; return true; } void bit_array_destroy(bit_array* b) { free(b->array); b->array = NULL; } void bit_array_set(bit_array* b, uint32_t index, bool value) { assert(index < b->size); uint32_t* p = &b->array[index >> 5]; uint32_t bit = 1 << (index & 31); if (value) *p |= bit; else *p &= ~bit; } bool bit_array_get(const bit_array* b, uint32_t index) { assert(index < b->size); uint32_t* p = &b->array[index >> 5]; uint32_t bit = 1 << (index & 31); return (*p & bit) != 0; } typedef struct sieve_tag { uint32_t limit; bit_array not_prime; } sieve; bool sieve_create(sieve* s, uint32_t limit) { if (!bit_array_create(&s->not_prime, limit/2)) return false; for (uint32_t p = 3; p * p <= limit; p += 2) { if (bit_array_get(&s->not_prime, p/2 - 1) == false) { uint32_t inc = 2 * p; for (uint32_t q = p * p; q <= limit; q += inc) bit_array_set(&s->not_prime, q/2 - 1, true); } } s->limit = limit; return true; } void sieve_destroy(sieve* s) { bit_array_destroy(&s->not_prime); } bool is_prime(const sieve* s, uint32_t n) { assert(n <= s->limit); if (n == 2) return true; if (n < 2 || n % 2 == 0) return false; return bit_array_get(&s->not_prime, n/2 - 1) == false; } uint32_t count_digits(uint32_t n) { uint32_t digits = 0; for (; n > 0; ++digits) n /= 10; return digits; } uint32_t change_digit(uint32_t n, uint32_t index, uint32_t new_digit) { uint32_t p = 1; uint32_t changed = 0; for (; index > 0; p *= 10, n /= 10, --index) changed += p * (n % 10); changed += (10 * (n/10) + new_digit) * p; return changed; } bool unprimeable(const sieve* s, uint32_t n) { if (is_prime(s, n)) return false; uint32_t d = count_digits(n); for (uint32_t i = 0; i < d; ++i) { for (uint32_t j = 0; j <= 9; ++j) { uint32_t m = change_digit(n, i, j); if (m != n && is_prime(s, m)) return false; } } return true; } int main() { const uint32_t limit = 10000000; setlocale(LC_ALL, ""); sieve s = { 0 }; if (!sieve_create(&s, limit)) { fprintf(stderr, "Out of memory\n"); return 1; } printf("First 35 unprimeable numbers:\n"); uint32_t n = 100; uint32_t lowest[10] = { 0 }; for (uint32_t count = 0, found = 0; n < limit && (found < 10 || count < 600); ++n) { if (unprimeable(&s, n)) { if (count < 35) { if (count != 0) printf(", "); printf("%'u", n); } ++count; if (count == 600) printf("\n600th unprimeable number: %'u\n", n); uint32_t last_digit = n % 10; if (lowest[last_digit] == 0) { lowest[last_digit] = n; ++found; } } } sieve_destroy(&s); for (uint32_t i = 0; i < 10; ++i) printf("Least unprimeable number ending in %u: %'u\n" , i, lowest[i]); return 0; }
from itertools import count, islice def primes(_cache=[2, 3]): yield from _cache for n in count(_cache[-1]+2, 2): if isprime(n): _cache.append(n) yield n def isprime(n, _seen={0: False, 1: False}): def _isprime(n): for p in primes(): if p*p > n: return True if n%p == 0: return False if n not in _seen: _seen[n] = _isprime(n) return _seen[n] def unprime(): for a in count(1): d = 1 while d <= a: base = (a//(d*10))*(d*10) + (a%d) if any(isprime(y) for y in range(base, base + d*10, d)): break d *= 10 else: yield a print('First 35:') print(' '.join(str(i) for i in islice(unprime(), 35))) print('\nThe 600-th:') print(list(islice(unprime(), 599, 600))[0]) print() first, need = [False]*10, 10 for p in unprime(): i = p%10 if first[i]: continue first[i] = p need -= 1 if not need: break for i,v in enumerate(first): print(f'{i} ending: {v}')
Please provide an equivalent version of this C code in Python.
#include <stdio.h> #include <math.h> void pascal(int a, int b, int mid, int top, int* x, int* y, int* z) { double ytemp = (top - 4 * (a + b)) / 7.; if(fmod(ytemp, 1.) >= 0.0001) { x = 0; return; } *y = ytemp; *x = mid - 2 * a - *y; *z = *y - *x; } int main() { int a = 11, b = 4, mid = 40, top = 151; int x, y, z; pascal(a, b, mid, top, &x, &y, &z); if(x != 0) printf("x: %d, y: %d, z: %d\n", x, y, z); else printf("No solution\n"); return 0; }
def combine( snl, snr ): cl = {} if isinstance(snl, int): cl['1'] = snl elif isinstance(snl, string): cl[snl] = 1 else: cl.update( snl) if isinstance(snr, int): n = cl.get('1', 0) cl['1'] = n + snr elif isinstance(snr, string): n = cl.get(snr, 0) cl[snr] = n + 1 else: for k,v in snr.items(): n = cl.get(k, 0) cl[k] = n+v return cl def constrain(nsum, vn ): nn = {} nn.update(vn) n = nn.get('1', 0) nn['1'] = n - nsum return nn def makeMatrix( constraints ): vmap = set() for c in constraints: vmap.update( c.keys()) vmap.remove('1') nvars = len(vmap) vmap = sorted(vmap) mtx = [] for c in constraints: row = [] for vv in vmap: row.append(float(c.get(vv, 0))) row.append(-float(c.get('1',0))) mtx.append(row) if len(constraints) == nvars: print 'System appears solvable' elif len(constraints) < nvars: print 'System is not solvable - needs more constraints.' return mtx, vmap def SolvePyramid( vl, cnstr ): vl.reverse() constraints = [cnstr] lvls = len(vl) for lvln in range(1,lvls): lvd = vl[lvln] for k in range(lvls - lvln): sn = lvd[k] ll = vl[lvln-1] vn = combine(ll[k], ll[k+1]) if sn is None: lvd[k] = vn else: constraints.append(constrain( sn, vn )) print 'Constraint Equations:' for cstr in constraints: fset = ('%d*%s'%(v,k) for k,v in cstr.items() ) print ' + '.join(fset), ' = 0' mtx,vmap = makeMatrix(constraints) MtxSolve(mtx) d = len(vmap) for j in range(d): print vmap[j],'=', mtx[j][d] def MtxSolve(mtx): mDim = len(mtx) for j in range(mDim): rw0= mtx[j] f = 1.0/rw0[j] for k in range(j, mDim+1): rw0[k] *= f for l in range(1+j,mDim): rwl = mtx[l] f = -rwl[j] for k in range(j, mDim+1): rwl[k] += f * rw0[k] for j1 in range(1,mDim): j = mDim - j1 rw0= mtx[j] for l in range(0, j): rwl = mtx[l] f = -rwl[j] rwl[j] += f * rw0[j] rwl[mDim] += f * rw0[mDim] return mtx p = [ [151], [None,None], [40,None,None], [None,None,None,None], ['X', 11, 'Y', 4, 'Z'] ] addlConstraint = { 'X':1, 'Y':-1, 'Z':1, '1':0 } SolvePyramid( p, addlConstraint)
Preserve the algorithm and functionality while converting the code from C to Python.
#include <stdio.h> #include <math.h> void pascal(int a, int b, int mid, int top, int* x, int* y, int* z) { double ytemp = (top - 4 * (a + b)) / 7.; if(fmod(ytemp, 1.) >= 0.0001) { x = 0; return; } *y = ytemp; *x = mid - 2 * a - *y; *z = *y - *x; } int main() { int a = 11, b = 4, mid = 40, top = 151; int x, y, z; pascal(a, b, mid, top, &x, &y, &z); if(x != 0) printf("x: %d, y: %d, z: %d\n", x, y, z); else printf("No solution\n"); return 0; }
def combine( snl, snr ): cl = {} if isinstance(snl, int): cl['1'] = snl elif isinstance(snl, string): cl[snl] = 1 else: cl.update( snl) if isinstance(snr, int): n = cl.get('1', 0) cl['1'] = n + snr elif isinstance(snr, string): n = cl.get(snr, 0) cl[snr] = n + 1 else: for k,v in snr.items(): n = cl.get(k, 0) cl[k] = n+v return cl def constrain(nsum, vn ): nn = {} nn.update(vn) n = nn.get('1', 0) nn['1'] = n - nsum return nn def makeMatrix( constraints ): vmap = set() for c in constraints: vmap.update( c.keys()) vmap.remove('1') nvars = len(vmap) vmap = sorted(vmap) mtx = [] for c in constraints: row = [] for vv in vmap: row.append(float(c.get(vv, 0))) row.append(-float(c.get('1',0))) mtx.append(row) if len(constraints) == nvars: print 'System appears solvable' elif len(constraints) < nvars: print 'System is not solvable - needs more constraints.' return mtx, vmap def SolvePyramid( vl, cnstr ): vl.reverse() constraints = [cnstr] lvls = len(vl) for lvln in range(1,lvls): lvd = vl[lvln] for k in range(lvls - lvln): sn = lvd[k] ll = vl[lvln-1] vn = combine(ll[k], ll[k+1]) if sn is None: lvd[k] = vn else: constraints.append(constrain( sn, vn )) print 'Constraint Equations:' for cstr in constraints: fset = ('%d*%s'%(v,k) for k,v in cstr.items() ) print ' + '.join(fset), ' = 0' mtx,vmap = makeMatrix(constraints) MtxSolve(mtx) d = len(vmap) for j in range(d): print vmap[j],'=', mtx[j][d] def MtxSolve(mtx): mDim = len(mtx) for j in range(mDim): rw0= mtx[j] f = 1.0/rw0[j] for k in range(j, mDim+1): rw0[k] *= f for l in range(1+j,mDim): rwl = mtx[l] f = -rwl[j] for k in range(j, mDim+1): rwl[k] += f * rw0[k] for j1 in range(1,mDim): j = mDim - j1 rw0= mtx[j] for l in range(0, j): rwl = mtx[l] f = -rwl[j] rwl[j] += f * rw0[j] rwl[mDim] += f * rw0[mDim] return mtx p = [ [151], [None,None], [40,None,None], [None,None,None,None], ['X', 11, 'Y', 4, 'Z'] ] addlConstraint = { 'X':1, 'Y':-1, 'Z':1, '1':0 } SolvePyramid( p, addlConstraint)
Convert this C snippet to Python and keep its semantics consistent.
#include <stdio.h> #include <stdlib.h> #include <gmp.h> typedef unsigned long long int u64; #define TRUE 1 #define FALSE 0 int primality_pretest(u64 k) { if (!(k % 3) || !(k % 5) || !(k % 7) || !(k % 11) || !(k % 13) || !(k % 17) || !(k % 19) || !(k % 23)) return (k <= 23); return TRUE; } int probprime(u64 k, mpz_t n) { mpz_set_ui(n, k); return mpz_probab_prime_p(n, 0); } int is_chernick(int n, u64 m, mpz_t z) { u64 t = 9 * m; if (primality_pretest(6 * m + 1) == FALSE) return FALSE; if (primality_pretest(12 * m + 1) == FALSE) return FALSE; for (int i = 1; i <= n - 2; i++) if (primality_pretest((t << i) + 1) == FALSE) return FALSE; if (probprime(6 * m + 1, z) == FALSE) return FALSE; if (probprime(12 * m + 1, z) == FALSE) return FALSE; for (int i = 1; i <= n - 2; i++) if (probprime((t << i) + 1, z) == FALSE) return FALSE; return TRUE; } int main(int argc, char const *argv[]) { mpz_t z; mpz_inits(z, NULL); for (int n = 3; n <= 10; n ++) { u64 multiplier = (n > 4) ? (1 << (n - 4)) : 1; if (n > 5) multiplier *= 5; for (u64 k = 1; ; k++) { u64 m = k * multiplier; if (is_chernick(n, m, z) == TRUE) { printf("a(%d) has m = %llu\n", n, m); break; } } } return 0; }
from sympy import isprime def primality_pretest(k): if not (k % 3) or not (k % 5) or not (k % 7) or not (k % 11) or not(k % 13) or not (k % 17) or not (k % 19) or not (k % 23): return (k <= 23) return True def is_chernick(n, m): t = 9 * m if not primality_pretest(6 * m + 1): return False if not primality_pretest(12 * m + 1): return False for i in range(1,n-1): if not primality_pretest((t << i) + 1): return False if not isprime(6 * m + 1): return False if not isprime(12 * m + 1): return False for i in range(1,n - 1): if not isprime((t << i) + 1): return False return True for n in range(3,10): if n > 4: multiplier = 1 << (n - 4) else: multiplier = 1 if n > 5: multiplier *= 5 k = 1 while True: m = k * multiplier if is_chernick(n, m): print("a("+str(n)+") has m = "+str(m)) break k += 1
Preserve the algorithm and functionality while converting the code from C to Python.
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> const double EPS = 0.001; const double EPS_SQUARE = 0.000001; double side(double x1, double y1, double x2, double y2, double x, double y) { return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1); } bool naivePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) { double checkSide1 = side(x1, y1, x2, y2, x, y) >= 0; double checkSide2 = side(x2, y2, x3, y3, x, y) >= 0; double checkSide3 = side(x3, y3, x1, y1, x, y) >= 0; return checkSide1 && checkSide2 && checkSide3; } bool pointInTriangleBoundingBox(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) { double xMin = min(x1, min(x2, x3)) - EPS; double xMax = max(x1, max(x2, x3)) + EPS; double yMin = min(y1, min(y2, y3)) - EPS; double yMax = max(y1, max(y2, y3)) + EPS; return !(x < xMin || xMax < x || y < yMin || yMax < y); } double distanceSquarePointToSegment(double x1, double y1, double x2, double y2, double x, double y) { double p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1); double dotProduct = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_squareLength; if (dotProduct < 0) { return (x - x1) * (x - x1) + (y - y1) * (y - y1); } else if (dotProduct <= 1) { double p_p1_squareLength = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y); return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength; } else { return (x - x2) * (x - x2) + (y - y2) * (y - y2); } } bool accuratePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) { if (!pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y)) { return false; } if (naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) { return true; } if (distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE) { return true; } if (distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE) { return true; } if (distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE) { return true; } return false; } void printPoint(double x, double y) { printf("(%f, %f)", x, y); } void printTriangle(double x1, double y1, double x2, double y2, double x3, double y3) { printf("Triangle is ["); printPoint(x1, y1); printf(", "); printPoint(x2, y2); printf(", "); printPoint(x3, y3); printf("] \n"); } void test(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) { printTriangle(x1, y1, x2, y2, x3, y3); printf("Point "); printPoint(x, y); printf(" is within triangle? "); if (accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) { printf("true\n"); } else { printf("false\n"); } } int main() { test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 0); test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 1); test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 3, 1); printf("\n"); test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, 25, 11.11111111111111, 5.414285714285714, 14.349206349206348); printf("\n"); test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, -12.5, 16.666666666666668, 5.414285714285714, 14.349206349206348); printf("\n"); return 0; }
from sympy.geometry import Point, Triangle def sign(pt1, pt2, pt3): return (pt1.x - pt3.x) * (pt2.y - pt3.y) - (pt2.x - pt3.x) * (pt1.y - pt3.y) def iswithin(point, pt1, pt2, pt3): zval1 = sign(point, pt1, pt2) zval2 = sign(point, pt2, pt3) zval3 = sign(point, pt3, pt1) notanyneg = zval1 >= 0 and zval2 >= 0 and zval3 >= 0 notanypos = zval1 <= 0 and zval2 <= 0 and zval3 <= 0 return notanyneg or notanypos if __name__ == "__main__": POINTS = [Point(0, 0)] TRI = Triangle(Point(1.5, 2.4), Point(5.1, -3.1), Point(-3.8, 0.5)) for pnt in POINTS: a, b, c = TRI.vertices isornot = "is" if iswithin(pnt, a, b, c) else "is not" print("Point", pnt, isornot, "within the triangle", TRI)
Can you help me rewrite this code in Python instead of C, keeping it the same logically?
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> const double EPS = 0.001; const double EPS_SQUARE = 0.000001; double side(double x1, double y1, double x2, double y2, double x, double y) { return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1); } bool naivePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) { double checkSide1 = side(x1, y1, x2, y2, x, y) >= 0; double checkSide2 = side(x2, y2, x3, y3, x, y) >= 0; double checkSide3 = side(x3, y3, x1, y1, x, y) >= 0; return checkSide1 && checkSide2 && checkSide3; } bool pointInTriangleBoundingBox(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) { double xMin = min(x1, min(x2, x3)) - EPS; double xMax = max(x1, max(x2, x3)) + EPS; double yMin = min(y1, min(y2, y3)) - EPS; double yMax = max(y1, max(y2, y3)) + EPS; return !(x < xMin || xMax < x || y < yMin || yMax < y); } double distanceSquarePointToSegment(double x1, double y1, double x2, double y2, double x, double y) { double p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1); double dotProduct = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_squareLength; if (dotProduct < 0) { return (x - x1) * (x - x1) + (y - y1) * (y - y1); } else if (dotProduct <= 1) { double p_p1_squareLength = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y); return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength; } else { return (x - x2) * (x - x2) + (y - y2) * (y - y2); } } bool accuratePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) { if (!pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y)) { return false; } if (naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) { return true; } if (distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE) { return true; } if (distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE) { return true; } if (distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE) { return true; } return false; } void printPoint(double x, double y) { printf("(%f, %f)", x, y); } void printTriangle(double x1, double y1, double x2, double y2, double x3, double y3) { printf("Triangle is ["); printPoint(x1, y1); printf(", "); printPoint(x2, y2); printf(", "); printPoint(x3, y3); printf("] \n"); } void test(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) { printTriangle(x1, y1, x2, y2, x3, y3); printf("Point "); printPoint(x, y); printf(" is within triangle? "); if (accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) { printf("true\n"); } else { printf("false\n"); } } int main() { test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 0); test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 1); test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 3, 1); printf("\n"); test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, 25, 11.11111111111111, 5.414285714285714, 14.349206349206348); printf("\n"); test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, -12.5, 16.666666666666668, 5.414285714285714, 14.349206349206348); printf("\n"); return 0; }
from sympy.geometry import Point, Triangle def sign(pt1, pt2, pt3): return (pt1.x - pt3.x) * (pt2.y - pt3.y) - (pt2.x - pt3.x) * (pt1.y - pt3.y) def iswithin(point, pt1, pt2, pt3): zval1 = sign(point, pt1, pt2) zval2 = sign(point, pt2, pt3) zval3 = sign(point, pt3, pt1) notanyneg = zval1 >= 0 and zval2 >= 0 and zval3 >= 0 notanypos = zval1 <= 0 and zval2 <= 0 and zval3 <= 0 return notanyneg or notanypos if __name__ == "__main__": POINTS = [Point(0, 0)] TRI = Triangle(Point(1.5, 2.4), Point(5.1, -3.1), Point(-3.8, 0.5)) for pnt in POINTS: a, b, c = TRI.vertices isornot = "is" if iswithin(pnt, a, b, c) else "is not" print("Point", pnt, isornot, "within the triangle", TRI)
Write the same code in Python as shown below in C.
#include <stdio.h> unsigned int divisor_count(unsigned int n) { unsigned int total = 1; for (; (n & 1) == 0; n >>= 1) { ++total; } for (unsigned int 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; } int main() { const unsigned int limit = 100; unsigned int n; printf("Count of divisors for the first %d positive integers:\n", limit); for (n = 1; n <= limit; ++n) { printf("%3d", divisor_count(n)); if (n % 20 == 0) { printf("\n"); } } return 0; }
def factorize(n): assert(isinstance(n, int)) if n < 0: n = -n if n < 2: return k = 0 while 0 == n%2: k += 1 n //= 2 if 0 < k: yield (2,k) p = 3 while p*p <= n: k = 0 while 0 == n%p: k += 1 n //= p if 0 < k: yield (p,k) p += 2 if 1 < n: yield (n,1) def tau(n): assert(n != 0) ans = 1 for (p,k) in factorize(n): ans *= 1 + k return ans if __name__ == "__main__": print(*map(tau, range(1, 101)))
Change the following C code into Python without altering its purpose.
#include <stdio.h> unsigned int divisor_count(unsigned int n) { unsigned int total = 1; for (; (n & 1) == 0; n >>= 1) { ++total; } for (unsigned int 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; } int main() { const unsigned int limit = 100; unsigned int n; printf("Count of divisors for the first %d positive integers:\n", limit); for (n = 1; n <= limit; ++n) { printf("%3d", divisor_count(n)); if (n % 20 == 0) { printf("\n"); } } return 0; }
def factorize(n): assert(isinstance(n, int)) if n < 0: n = -n if n < 2: return k = 0 while 0 == n%2: k += 1 n //= 2 if 0 < k: yield (2,k) p = 3 while p*p <= n: k = 0 while 0 == n%p: k += 1 n //= p if 0 < k: yield (p,k) p += 2 if 1 < n: yield (n,1) def tau(n): assert(n != 0) ans = 1 for (p,k) in factorize(n): ans *= 1 + k return ans if __name__ == "__main__": print(*map(tau, range(1, 101)))
Produce a language-to-language conversion: from C to Python, same semantics.
#include <gmp.h> int main(void) { mpz_t p, s; mpz_init_set_ui(p, 1); mpz_init_set_ui(s, 1); for (int n = 1, i = 0; i < 20; n++) { mpz_nextprime(s, s); mpz_mul(p, p, s); mpz_add_ui(p, p, 1); if (mpz_probab_prime_p(p, 25)) { mpz_sub_ui(p, p, 1); gmp_printf("%d\n", n); i++; continue; } mpz_sub_ui(p, p, 2); if (mpz_probab_prime_p(p, 25)) { mpz_add_ui(p, p, 1); gmp_printf("%d\n", n); i++; continue; } mpz_add_ui(p, p, 1); } mpz_clear(s); mpz_clear(p); }
import pyprimes def primorial_prime(_pmax=500): isprime = pyprimes.isprime n, primo = 0, 1 for prime in pyprimes.nprimes(_pmax): n, primo = n+1, primo * prime if isprime(primo-1) or isprime(primo+1): yield n if __name__ == '__main__': pyprimes.warn_probably = False for i, n in zip(range(20), primorial_prime()): print('Primorial prime %2i at primorial index: %3i' % (i+1, n))
Maintain the same structure and functionality when rewriting this code in Python.
#include<string.h> #include<stdlib.h> #include<stdio.h> typedef struct genome{ char* strand; int length; struct genome* next; }genome; genome* genomeData; int totalLength = 0, Adenine = 0, Cytosine = 0, Guanine = 0, Thymine = 0; int numDigits(int num){ int len = 1; while(num>10){ num = num/10; len++; } return len; } void buildGenome(char str[100]){ int len = strlen(str),i; genome *genomeIterator, *newGenome; totalLength += len; for(i=0;i<len;i++){ switch(str[i]){ case 'A': Adenine++; break; case 'T': Thymine++; break; case 'C': Cytosine++; break; case 'G': Guanine++; break; }; } if(genomeData==NULL){ genomeData = (genome*)malloc(sizeof(genome)); genomeData->strand = (char*)malloc(len*sizeof(char)); strcpy(genomeData->strand,str); genomeData->length = len; genomeData->next = NULL; } else{ genomeIterator = genomeData; while(genomeIterator->next!=NULL) genomeIterator = genomeIterator->next; newGenome = (genome*)malloc(sizeof(genome)); newGenome->strand = (char*)malloc(len*sizeof(char)); strcpy(newGenome->strand,str); newGenome->length = len; newGenome->next = NULL; genomeIterator->next = newGenome; } } void printGenome(){ genome* genomeIterator = genomeData; int width = numDigits(totalLength), len = 0; printf("Sequence:\n"); while(genomeIterator!=NULL){ printf("\n%*d%3s%3s",width+1,len,":",genomeIterator->strand); len += genomeIterator->length; genomeIterator = genomeIterator->next; } printf("\n\nBase Count\n----------\n\n"); printf("%3c%3s%*d\n",'A',":",width+1,Adenine); printf("%3c%3s%*d\n",'T',":",width+1,Thymine); printf("%3c%3s%*d\n",'C',":",width+1,Cytosine); printf("%3c%3s%*d\n",'G',":",width+1,Guanine); printf("\n%3s%*d\n","Total:",width+1,Adenine + Thymine + Cytosine + Guanine); free(genomeData); } int main(int argc,char** argv) { char str[100]; int counter = 0, len; if(argc!=2){ printf("Usage : %s <Gene file name>\n",argv[0]); return 0; } FILE *fp = fopen(argv[1],"r"); while(fscanf(fp,"%s",str)!=EOF) buildGenome(str); fclose(fp); printGenome(); return 0; }
from collections import Counter def basecount(dna): return sorted(Counter(dna).items()) def seq_split(dna, n=50): return [dna[i: i+n] for i in range(0, len(dna), n)] def seq_pp(dna, n=50): for i, part in enumerate(seq_split(dna, n)): print(f"{i*n:>5}: {part}") print("\n BASECOUNT:") tot = 0 for base, count in basecount(dna): print(f" {base:>3}: {count}") tot += count base, count = 'TOT', tot print(f" {base:>3}= {count}") if __name__ == '__main__': print("SEQUENCE:") sequence = seq_pp(sequence)
Ensure the translated Python code behaves exactly like the original C snippet.
#include<string.h> #include<stdlib.h> #include<stdio.h> typedef struct genome{ char* strand; int length; struct genome* next; }genome; genome* genomeData; int totalLength = 0, Adenine = 0, Cytosine = 0, Guanine = 0, Thymine = 0; int numDigits(int num){ int len = 1; while(num>10){ num = num/10; len++; } return len; } void buildGenome(char str[100]){ int len = strlen(str),i; genome *genomeIterator, *newGenome; totalLength += len; for(i=0;i<len;i++){ switch(str[i]){ case 'A': Adenine++; break; case 'T': Thymine++; break; case 'C': Cytosine++; break; case 'G': Guanine++; break; }; } if(genomeData==NULL){ genomeData = (genome*)malloc(sizeof(genome)); genomeData->strand = (char*)malloc(len*sizeof(char)); strcpy(genomeData->strand,str); genomeData->length = len; genomeData->next = NULL; } else{ genomeIterator = genomeData; while(genomeIterator->next!=NULL) genomeIterator = genomeIterator->next; newGenome = (genome*)malloc(sizeof(genome)); newGenome->strand = (char*)malloc(len*sizeof(char)); strcpy(newGenome->strand,str); newGenome->length = len; newGenome->next = NULL; genomeIterator->next = newGenome; } } void printGenome(){ genome* genomeIterator = genomeData; int width = numDigits(totalLength), len = 0; printf("Sequence:\n"); while(genomeIterator!=NULL){ printf("\n%*d%3s%3s",width+1,len,":",genomeIterator->strand); len += genomeIterator->length; genomeIterator = genomeIterator->next; } printf("\n\nBase Count\n----------\n\n"); printf("%3c%3s%*d\n",'A',":",width+1,Adenine); printf("%3c%3s%*d\n",'T',":",width+1,Thymine); printf("%3c%3s%*d\n",'C',":",width+1,Cytosine); printf("%3c%3s%*d\n",'G',":",width+1,Guanine); printf("\n%3s%*d\n","Total:",width+1,Adenine + Thymine + Cytosine + Guanine); free(genomeData); } int main(int argc,char** argv) { char str[100]; int counter = 0, len; if(argc!=2){ printf("Usage : %s <Gene file name>\n",argv[0]); return 0; } FILE *fp = fopen(argv[1],"r"); while(fscanf(fp,"%s",str)!=EOF) buildGenome(str); fclose(fp); printGenome(); return 0; }
from collections import Counter def basecount(dna): return sorted(Counter(dna).items()) def seq_split(dna, n=50): return [dna[i: i+n] for i in range(0, len(dna), n)] def seq_pp(dna, n=50): for i, part in enumerate(seq_split(dna, n)): print(f"{i*n:>5}: {part}") print("\n BASECOUNT:") tot = 0 for base, count in basecount(dna): print(f" {base:>3}: {count}") tot += count base, count = 'TOT', tot print(f" {base:>3}= {count}") if __name__ == '__main__': print("SEQUENCE:") sequence = seq_pp(sequence)
Please provide an equivalent version of this C code in Python.
#include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <stdarg.h> #define N 5 const char *names[N] = { "Aristotle", "Kant", "Spinoza", "Marx", "Russell" }; pthread_mutex_t forks[N]; #define M 5 const char *topic[M] = { "Spaghetti!", "Life", "Universe", "Everything", "Bathroom" }; #define lock pthread_mutex_lock #define unlock pthread_mutex_unlock #define xy(x, y) printf("\033[%d;%dH", x, y) #define clear_eol(x) print(x, 12, "\033[K") void print(int y, int x, const char *fmt, ...) { static pthread_mutex_t screen = PTHREAD_MUTEX_INITIALIZER; va_list ap; va_start(ap, fmt); lock(&screen); xy(y + 1, x), vprintf(fmt, ap); xy(N + 1, 1), fflush(stdout); unlock(&screen); } void eat(int id) { int f[2], ration, i; f[0] = f[1] = id; f[id & 1] = (id + 1) % N; clear_eol(id); print(id, 12, "..oO (forks, need forks)"); for (i = 0; i < 2; i++) { lock(forks + f[i]); if (!i) clear_eol(id); print(id, 12 + (f[i] != id) * 6, "fork%d", f[i]); sleep(1); } for (i = 0, ration = 3 + rand() % 8; i < ration; i++) print(id, 24 + i * 4, "nom"), sleep(1); for (i = 0; i < 2; i++) unlock(forks + f[i]); } void think(int id) { int i, t; char buf[64] = {0}; do { clear_eol(id); sprintf(buf, "..oO (%s)", topic[t = rand() % M]); for (i = 0; buf[i]; i++) { print(id, i+12, "%c", buf[i]); if (i < 5) usleep(200000); } usleep(500000 + rand() % 1000000); } while (t); } void* philosophize(void *a) { int id = *(int*)a; print(id, 1, "%10s", names[id]); while(1) think(id), eat(id); } int main() { int i, id[N]; pthread_t tid[N]; for (i = 0; i < N; i++) pthread_mutex_init(forks + (id[i] = i), 0); for (i = 0; i < N; i++) pthread_create(tid + i, 0, philosophize, id + i); return pthread_join(tid[0], 0); }
import threading import random import time class Philosopher(threading.Thread): running = True def __init__(self, xname, forkOnLeft, forkOnRight): threading.Thread.__init__(self) self.name = xname self.forkOnLeft = forkOnLeft self.forkOnRight = forkOnRight def run(self): while(self.running): time.sleep( random.uniform(3,13)) print '%s is hungry.' % self.name self.dine() def dine(self): fork1, fork2 = self.forkOnLeft, self.forkOnRight while self.running: fork1.acquire(True) locked = fork2.acquire(False) if locked: break fork1.release() print '%s swaps forks' % self.name fork1, fork2 = fork2, fork1 else: return self.dining() fork2.release() fork1.release() def dining(self): print '%s starts eating '% self.name time.sleep(random.uniform(1,10)) print '%s finishes eating and leaves to think.' % self.name def DiningPhilosophers(): forks = [threading.Lock() for n in range(5)] philosopherNames = ('Aristotle','Kant','Spinoza','Marx', 'Russel') philosophers= [Philosopher(philosopherNames[i], forks[i%5], forks[(i+1)%5]) \ for i in range(5)] random.seed(507129) Philosopher.running = True for p in philosophers: p.start() time.sleep(100) Philosopher.running = False print ("Now we're finishing.") DiningPhilosophers()
Change the following C code into Python without altering its purpose.
#include <stdio.h> int main() { int n, b, d; unsigned long long i, j, sum, fact[12]; fact[0] = 1; for (n = 1; n < 12; ++n) { fact[n] = fact[n-1] * n; } for (b = 9; b <= 12; ++b) { printf("The factorions for base %d are:\n", b); for (i = 1; i < 1500000; ++i) { sum = 0; j = i; while (j > 0) { d = j % b; sum += fact[d]; j /= b; } if (sum == i) printf("%llu ", i); } printf("\n\n"); } return 0; }
fact = [1] for n in range(1, 12): fact.append(fact[n-1] * n) for b in range(9, 12+1): print(f"The factorions for base {b} are:") for i in range(1, 1500000): fact_sum = 0 j = i while j > 0: d = j % b fact_sum += fact[d] j = j//b if fact_sum == i: print(i, end=" ") print("\n")
Rewrite the snippet below in Python so it works the same as the original C code.
#include <stdio.h> int main() { int n, b, d; unsigned long long i, j, sum, fact[12]; fact[0] = 1; for (n = 1; n < 12; ++n) { fact[n] = fact[n-1] * n; } for (b = 9; b <= 12; ++b) { printf("The factorions for base %d are:\n", b); for (i = 1; i < 1500000; ++i) { sum = 0; j = i; while (j > 0) { d = j % b; sum += fact[d]; j /= b; } if (sum == i) printf("%llu ", i); } printf("\n\n"); } return 0; }
fact = [1] for n in range(1, 12): fact.append(fact[n-1] * n) for b in range(9, 12+1): print(f"The factorions for base {b} are:") for i in range(1, 1500000): fact_sum = 0 j = i while j > 0: d = j % b fact_sum += fact[d] j = j//b if fact_sum == i: print(i, end=" ") print("\n")
Convert this C snippet to Python and keep its semantics consistent.
#include <math.h> #include <stdio.h> const double K = 7.8e9; const int n0 = 27; const double actual[] = { 27, 27, 27, 44, 44, 59, 59, 59, 59, 59, 59, 59, 59, 60, 60, 61, 61, 66, 83, 219, 239, 392, 534, 631, 897, 1350, 2023, 2820, 4587, 6067, 7823, 9826, 11946, 14554, 17372, 20615, 24522, 28273, 31491, 34933, 37552, 40540, 43105, 45177, 60328, 64543, 67103, 69265, 71332, 73327, 75191, 75723, 76719, 77804, 78812, 79339, 80132, 80995, 82101, 83365, 85203, 87024, 89068, 90664, 93077, 95316, 98172, 102133, 105824, 109695, 114232, 118610, 125497, 133852, 143227, 151367, 167418, 180096, 194836, 213150, 242364, 271106, 305117, 338133, 377918, 416845, 468049, 527767, 591704, 656866, 715353, 777796, 851308, 928436, 1000249, 1082054, 1174652 }; const size_t actual_size = sizeof(actual) / sizeof(double); double f(double r) { double sq = 0; size_t i; for (i = 0; i < actual_size; ++i) { double eri = exp(r * i); double guess = (n0 * eri) / (1 + n0 * (eri - 1) / K); double diff = guess - actual[i]; sq += diff * diff; } return sq; } double solve(double (*fn)(double), double guess, double epsilon) { double delta, f0, factor; for (delta = guess ? guess : 1, f0 = fn(guess), factor = 2; delta > epsilon && guess != guess - delta; delta *= factor) { double nf = (*fn)(guess - delta); if (nf < f0) { f0 = nf; guess -= delta; } else { nf = fn(guess + delta); if (nf < f0) { f0 = nf; guess += delta; } else { factor = 0.5; } } } return guess; } double solve_default(double (*fn)(double)) { return solve(fn, 0.5, 0); } int main() { double r = solve_default(f); double R0 = exp(12 * r); printf("r = %f, R0 = %f\n", r, R0); return 0; }
import numpy as np import scipy.optimize as opt n0, K = 27, 7_800_000_000 def f(t, r): return (n0 * np.exp(r * t)) / (( 1 + n0 * (np.exp(r * t) - 1) / K)) y = [ 27, 27, 27, 44, 44, 59, 59, 59, 59, 59, 59, 59, 59, 60, 60, 61, 61, 66, 83, 219, 239, 392, 534, 631, 897, 1350, 2023, 2820, 4587, 6067, 7823, 9826, 11946, 14554, 17372, 20615, 24522, 28273, 31491, 34933, 37552, 40540, 43105, 45177, 60328, 64543, 67103, 69265, 71332, 73327, 75191, 75723, 76719, 77804, 78812, 79339, 80132, 80995, 82101, 83365, 85203, 87024, 89068, 90664, 93077, 95316, 98172, 102133, 105824, 109695, 114232, 118610, 125497, 133852, 143227, 151367, 167418, 180096, 194836, 213150, 242364, 271106, 305117, 338133, 377918, 416845, 468049, 527767, 591704, 656866, 715353, 777796, 851308, 928436, 1000249, 1082054, 1174652, ] x = np.linspace(0.0, 96, 97) r, cov = opt.curve_fit(f, x, y, [0.5]) print("The r for the world Covid-19 data is:", r, ", with covariance of", cov) print("The calculated R0 is then", np.exp(12 * r))
Translate this program into Python but keep the logic exactly as in C.
#include <stdio.h> typedef struct node_t *node, node_t; struct node_t { int v; node next; }; typedef struct { node head, tail; } slist; void push(slist *l, node e) { if (!l->head) l->head = e; if (l->tail) l->tail->next = e; l->tail = e; } node removehead(slist *l) { node e = l->head; if (e) { l->head = e->next; e->next = 0; } return e; } void join(slist *a, slist *b) { push(a, b->head); a->tail = b->tail; } void merge(slist *a, slist *b) { slist r = {0}; while (a->head && b->head) push(&r, removehead(a->head->v <= b->head->v ? a : b)); join(&r, a->head ? a : b); *a = r; b->head = b->tail = 0; } void sort(int *ar, int len) { node_t all[len]; for (int i = 0; i < len; i++) all[i].v = ar[i], all[i].next = i < len - 1 ? all + i + 1 : 0; slist list = {all, all + len - 1}, rem, strand = {0}, res = {0}; for (node e = 0; list.head; list = rem) { rem.head = rem.tail = 0; while ((e = removehead(&list))) push((!strand.head || e->v >= strand.tail->v) ? &strand : &rem, e); merge(&res, &strand); } for (int i = 0; res.head; i++, res.head = res.head->next) ar[i] = res.head->v; } void show(const char *title, int *x, int len) { printf("%s ", title); for (int i = 0; i < len; i++) printf("%3d ", x[i]); putchar('\n'); } int main(void) { int x[] = {-2,0,-2,5,5,3,-1,-3,5,5,0,2,-4,4,2}; # define SIZE sizeof(x)/sizeof(int) show("before sort:", x, SIZE); sort(x, sizeof(x)/sizeof(int)); show("after sort: ", x, SIZE); return 0; }
def merge_list(a, b): out = [] while len(a) and len(b): if a[0] < b[0]: out.append(a.pop(0)) else: out.append(b.pop(0)) out += a out += b return out def strand(a): i, s = 0, [a.pop(0)] while i < len(a): if a[i] > s[-1]: s.append(a.pop(i)) else: i += 1 return s def strand_sort(a): out = strand(a) while len(a): out = merge_list(out, strand(a)) return out print strand_sort([1, 6, 3, 2, 1, 7, 5, 3])
Write the same code in Python as shown below in C.
#include <stdbool.h> #include <stdio.h> #include <string.h> void memoizeIsPrime( bool * result, const int N ) { result[2] = true; result[3] = true; int prime[N]; prime[0] = 3; int end = 1; for (int n = 5; n < N; n += 2) { bool n_is_prime = true; for (int i = 0; i < end; ++i) { const int PRIME = prime[i]; if (n % PRIME == 0) { n_is_prime = false; break; } if (PRIME * PRIME > n) { break; } } if (n_is_prime) { prime[end++] = n; result[n] = true; } } } int sumOfDecimalDigits( int n ) { int sum = 0; while (n > 0) { sum += n % 10; n /= 10; } return sum; } int main( void ) { const int N = 500; printf( "Rosetta Code: additive primes less than %d:\n", N ); bool is_prime[N]; memset( is_prime, 0, sizeof(is_prime) ); memoizeIsPrime( is_prime, N ); printf( " 2" ); int count = 1; for (int i = 3; i < N; i += 2) { if (is_prime[i] && is_prime[sumOfDecimalDigits( i )]) { printf( "%4d", i ); ++count; if ((count % 10) == 0) { printf( "\n" ); } } } printf( "\nThose were %d additive primes.\n", count ); return 0; }
def is_prime(n: int) -> bool: if n <= 3: return n > 1 if n % 2 == 0 or n % 3 == 0: return False i = 5 while i ** 2 <= n: if n % i == 0 or n % (i + 2) == 0: return False i += 6 return True def digit_sum(n: int) -> int: sum = 0 while n > 0: sum += n % 10 n //= 10 return sum def main() -> None: additive_primes = 0 for i in range(2, 500): if is_prime(i) and is_prime(digit_sum(i)): additive_primes += 1 print(i, end=" ") print(f"\nFound {additive_primes} additive primes less than 500") if __name__ == "__main__": main()
Port the provided C code into Python while preserving the original functionality.
#include <stdio.h> #include <stdlib.h> #define otherwise do { register int _o = 2; do { switch (_o) { case 1: #define given(Mc) ;case 0: break; case 2: _o = !!(Mc); continue; } break; } while (1); } while (0) int foo() { return 1; } main() { int a = 0; otherwise a = 4 given (foo()); printf("%d\n", a); exit(0); }
x = truevalue if condition else falsevalue
Convert the following code from C to Python, ensuring the logic remains intact.
#include <stdio.h> #include <stdlib.h> #define otherwise do { register int _o = 2; do { switch (_o) { case 1: #define given(Mc) ;case 0: break; case 2: _o = !!(Mc); continue; } break; } while (1); } while (0) int foo() { return 1; } main() { int a = 0; otherwise a = 4 given (foo()); printf("%d\n", a); exit(0); }
x = truevalue if condition else falsevalue
Change the programming language of this snippet from C to Python without modifying what it does.
#include<stdlib.h> #include<stdio.h> long totient(long n){ long 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; } long* perfectTotients(long n){ long *ptList = (long*)malloc(n*sizeof(long)), m,count=0,sum,tot; for(m=1;count<n;m++){ tot = m; sum = 0; while(tot != 1){ tot = totient(tot); sum += tot; } if(sum == m) ptList[count++] = m; } return ptList; } long main(long argC, char* argV[]) { long *ptList,i,n; if(argC!=2) printf("Usage : %s <number of perfect Totient numbers required>",argV[0]); else{ n = atoi(argV[1]); ptList = perfectTotients(n); printf("The first %d perfect Totient numbers are : \n[",n); for(i=0;i<n;i++) printf(" %d,",ptList[i]); printf("\b]"); } return 0; }
from math import gcd from functools import lru_cache from itertools import islice, count @lru_cache(maxsize=None) def φ(n): return sum(1 for k in range(1, n + 1) if gcd(n, k) == 1) def perfect_totient(): for n0 in count(1): parts, n = 0, n0 while n != 1: n = φ(n) parts += n if parts == n0: yield n0 if __name__ == '__main__': print(list(islice(perfect_totient(), 20)))
Preserve the algorithm and functionality while converting the code from C to Python.
#include<stdlib.h> #include<stdio.h> long totient(long n){ long 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; } long* perfectTotients(long n){ long *ptList = (long*)malloc(n*sizeof(long)), m,count=0,sum,tot; for(m=1;count<n;m++){ tot = m; sum = 0; while(tot != 1){ tot = totient(tot); sum += tot; } if(sum == m) ptList[count++] = m; } return ptList; } long main(long argC, char* argV[]) { long *ptList,i,n; if(argC!=2) printf("Usage : %s <number of perfect Totient numbers required>",argV[0]); else{ n = atoi(argV[1]); ptList = perfectTotients(n); printf("The first %d perfect Totient numbers are : \n[",n); for(i=0;i<n;i++) printf(" %d,",ptList[i]); printf("\b]"); } return 0; }
from math import gcd from functools import lru_cache from itertools import islice, count @lru_cache(maxsize=None) def φ(n): return sum(1 for k in range(1, n + 1) if gcd(n, k) == 1) def perfect_totient(): for n0 in count(1): parts, n = 0, n0 while n != 1: n = φ(n) parts += n if parts == n0: yield n0 if __name__ == '__main__': print(list(islice(perfect_totient(), 20)))
Write the same algorithm in Python as shown in this C implementation.
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef const char * (*Responder)( int p1); typedef struct sDelegate { Responder operation; } *Delegate; Delegate NewDelegate( Responder rspndr ) { Delegate dl = malloc(sizeof(struct sDelegate)); dl->operation = rspndr; return dl; } const char *DelegateThing(Delegate dl, int p1) { return (dl->operation)? (*dl->operation)(p1) : NULL; } typedef struct sDelegator { int param; char *phrase; Delegate delegate; } *Delegator; const char * defaultResponse( int p1) { return "default implementation"; } static struct sDelegate defaultDel = { &defaultResponse }; Delegator NewDelegator( int p, char *phrase) { Delegator d = malloc(sizeof(struct sDelegator)); d->param = p; d->phrase = phrase; d->delegate = &defaultDel; return d; } const char *Delegator_Operation( Delegator theDelegator, int p1, Delegate delroy) { const char *rtn; if (delroy) { rtn = DelegateThing(delroy, p1); if (!rtn) { rtn = DelegateThing(theDelegator->delegate, p1); } } else rtn = DelegateThing(theDelegator->delegate, p1); printf("%s\n", theDelegator->phrase ); return rtn; } const char *thing1( int p1) { printf("We're in thing1 with value %d\n" , p1); return "delegate implementation"; } int main() { Delegate del1 = NewDelegate(&thing1); Delegate del2 = NewDelegate(NULL); Delegator theDelegator = NewDelegator( 14, "A stellar vista, Baby."); printf("Delegator returns %s\n\n", Delegator_Operation( theDelegator, 3, NULL)); printf("Delegator returns %s\n\n", Delegator_Operation( theDelegator, 3, del1)); printf("Delegator returns %s\n\n", Delegator_Operation( theDelegator, 3, del2)); return 0; }
class Delegator: def __init__(self): self.delegate = None def operation(self): if hasattr(self.delegate, 'thing') and callable(self.delegate.thing): return self.delegate.thing() return 'default implementation' class Delegate: def thing(self): return 'delegate implementation' if __name__ == '__main__': a = Delegator() assert a.operation() == 'default implementation' a.delegate = 'A delegate may be any object' assert a.operation() == 'default implementation' a.delegate = Delegate() assert a.operation() == 'delegate implementation'
Maintain the same structure and functionality when rewriting this code in Python.
#include <stdio.h> unsigned int divisor_sum(unsigned int n) { unsigned int total = 1, power = 2; unsigned int p; for (; (n & 1) == 0; power <<= 1, n >>= 1) { total += power; } for (p = 3; p * p <= n; p += 2) { unsigned int sum = 1; for (power = p; n % p == 0; power *= p, n /= p) { sum += power; } total *= sum; } if (n > 1) { total *= n + 1; } return total; } int main() { const unsigned int limit = 100; unsigned int n; printf("Sum of divisors for the first %d positive integers:\n", limit); for (n = 1; n <= limit; ++n) { printf("%4d", divisor_sum(n)); if (n % 10 == 0) { printf("\n"); } } return 0; }
def factorize(n): assert(isinstance(n, int)) if n < 0: n = -n if n < 2: return k = 0 while 0 == n%2: k += 1 n //= 2 if 0 < k: yield (2,k) p = 3 while p*p <= n: k = 0 while 0 == n%p: k += 1 n //= p if 0 < k: yield (p,k) p += 2 if 1 < n: yield (n,1) def sum_of_divisors(n): assert(n != 0) ans = 1 for (p,k) in factorize(n): ans *= (pow(p,k+1) - 1)//(p-1) return ans if __name__ == "__main__": print([sum_of_divisors(n) for n in range(1,101)])
Rewrite this program in Python while keeping its functionality equivalent to the C version.
#include <stdio.h> unsigned int divisor_sum(unsigned int n) { unsigned int total = 1, power = 2; unsigned int p; for (; (n & 1) == 0; power <<= 1, n >>= 1) { total += power; } for (p = 3; p * p <= n; p += 2) { unsigned int sum = 1; for (power = p; n % p == 0; power *= p, n /= p) { sum += power; } total *= sum; } if (n > 1) { total *= n + 1; } return total; } int main() { const unsigned int limit = 100; unsigned int n; printf("Sum of divisors for the first %d positive integers:\n", limit); for (n = 1; n <= limit; ++n) { printf("%4d", divisor_sum(n)); if (n % 10 == 0) { printf("\n"); } } return 0; }
def factorize(n): assert(isinstance(n, int)) if n < 0: n = -n if n < 2: return k = 0 while 0 == n%2: k += 1 n //= 2 if 0 < k: yield (2,k) p = 3 while p*p <= n: k = 0 while 0 == n%p: k += 1 n //= p if 0 < k: yield (p,k) p += 2 if 1 < n: yield (n,1) def sum_of_divisors(n): assert(n != 0) ans = 1 for (p,k) in factorize(n): ans *= (pow(p,k+1) - 1)//(p-1) return ans if __name__ == "__main__": print([sum_of_divisors(n) for n in range(1,101)])
Transform the following C implementation into Python, maintaining the same output and logic.
#include <ctype.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> const char* command_table = "Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy " "COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find " "NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput " "Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO " "MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT " "READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT " "RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up"; typedef struct command_tag { char* cmd; size_t length; size_t min_len; struct command_tag* next; } command_t; bool command_match(const command_t* command, const char* str) { size_t olen = strlen(str); return olen >= command->min_len && olen <= command->length && strncmp(str, command->cmd, olen) == 0; } char* uppercase(char* str, size_t n) { for (size_t i = 0; i < n; ++i) str[i] = toupper((unsigned char)str[i]); return str; } size_t get_min_length(const char* str, size_t n) { size_t len = 0; while (len < n && isupper((unsigned char)str[len])) ++len; return len; } void fatal(const char* message) { fprintf(stderr, "%s\n", message); exit(1); } void* xmalloc(size_t n) { void* ptr = malloc(n); if (ptr == NULL) fatal("Out of memory"); return ptr; } void* xrealloc(void* p, size_t n) { void* ptr = realloc(p, n); if (ptr == NULL) fatal("Out of memory"); return ptr; } char** split_into_words(const char* str, size_t* count) { size_t size = 0; size_t capacity = 16; char** words = xmalloc(capacity * sizeof(char*)); size_t len = strlen(str); for (size_t begin = 0; begin < len; ) { size_t i = begin; for (; i < len && isspace((unsigned char)str[i]); ++i) {} begin = i; for (; i < len && !isspace((unsigned char)str[i]); ++i) {} size_t word_len = i - begin; if (word_len == 0) break; char* word = xmalloc(word_len + 1); memcpy(word, str + begin, word_len); word[word_len] = 0; begin += word_len; if (capacity == size) { capacity *= 2; words = xrealloc(words, capacity * sizeof(char*)); } words[size++] = word; } *count = size; return words; } command_t* make_command_list(const char* table) { command_t* cmd = NULL; size_t count = 0; char** words = split_into_words(table, &count); for (size_t i = 0; i < count; ++i) { char* word = words[i]; command_t* new_cmd = xmalloc(sizeof(command_t)); size_t word_len = strlen(word); new_cmd->length = word_len; new_cmd->min_len = get_min_length(word, word_len); new_cmd->cmd = uppercase(word, word_len); new_cmd->next = cmd; cmd = new_cmd; } free(words); return cmd; } void free_command_list(command_t* cmd) { while (cmd != NULL) { command_t* next = cmd->next; free(cmd->cmd); free(cmd); cmd = next; } } const command_t* find_command(const command_t* commands, const char* word) { for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) { if (command_match(cmd, word)) return cmd; } return NULL; } void test(const command_t* commands, const char* input) { printf(" input: %s\n", input); printf("output:"); size_t count = 0; char** words = split_into_words(input, &count); for (size_t i = 0; i < count; ++i) { char* word = words[i]; uppercase(word, strlen(word)); const command_t* cmd_ptr = find_command(commands, word); printf(" %s", cmd_ptr ? cmd_ptr->cmd : "*error*"); free(word); } free(words); printf("\n"); } int main() { command_t* commands = make_command_list(command_table); const char* input = "riG rePEAT copies put mo rest types fup. 6 poweRin"; test(commands, input); free_command_list(commands); return 0; }
command_table_text = \ user_words = "riG rePEAT copies put mo rest types fup. 6 poweRin" def find_abbreviations_length(command_table_text): command_table = dict() for word in command_table_text.split(): abbr_len = sum(1 for c in word if c.isupper()) if abbr_len == 0: abbr_len = len(word) command_table[word] = abbr_len return command_table def find_abbreviations(command_table): abbreviations = dict() for command, min_abbr_len in command_table.items(): for l in range(min_abbr_len, len(command)+1): abbr = command[:l].lower() abbreviations[abbr] = command.upper() return abbreviations def parse_user_string(user_string, abbreviations): user_words = [word.lower() for word in user_string.split()] commands = [abbreviations.get(user_word, "*error*") for user_word in user_words] return " ".join(commands) command_table = find_abbreviations_length(command_table_text) abbreviations_table = find_abbreviations(command_table) full_words = parse_user_string(user_words, abbreviations_table) print("user words:", user_words) print("full words:", full_words)
Can you help me rewrite this code in Python instead of C, keeping it the same logically?
#include <ctype.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> const char* command_table = "Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy " "COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find " "NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput " "Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO " "MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT " "READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT " "RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up"; typedef struct command_tag { char* cmd; size_t length; size_t min_len; struct command_tag* next; } command_t; bool command_match(const command_t* command, const char* str) { size_t olen = strlen(str); return olen >= command->min_len && olen <= command->length && strncmp(str, command->cmd, olen) == 0; } char* uppercase(char* str, size_t n) { for (size_t i = 0; i < n; ++i) str[i] = toupper((unsigned char)str[i]); return str; } size_t get_min_length(const char* str, size_t n) { size_t len = 0; while (len < n && isupper((unsigned char)str[len])) ++len; return len; } void fatal(const char* message) { fprintf(stderr, "%s\n", message); exit(1); } void* xmalloc(size_t n) { void* ptr = malloc(n); if (ptr == NULL) fatal("Out of memory"); return ptr; } void* xrealloc(void* p, size_t n) { void* ptr = realloc(p, n); if (ptr == NULL) fatal("Out of memory"); return ptr; } char** split_into_words(const char* str, size_t* count) { size_t size = 0; size_t capacity = 16; char** words = xmalloc(capacity * sizeof(char*)); size_t len = strlen(str); for (size_t begin = 0; begin < len; ) { size_t i = begin; for (; i < len && isspace((unsigned char)str[i]); ++i) {} begin = i; for (; i < len && !isspace((unsigned char)str[i]); ++i) {} size_t word_len = i - begin; if (word_len == 0) break; char* word = xmalloc(word_len + 1); memcpy(word, str + begin, word_len); word[word_len] = 0; begin += word_len; if (capacity == size) { capacity *= 2; words = xrealloc(words, capacity * sizeof(char*)); } words[size++] = word; } *count = size; return words; } command_t* make_command_list(const char* table) { command_t* cmd = NULL; size_t count = 0; char** words = split_into_words(table, &count); for (size_t i = 0; i < count; ++i) { char* word = words[i]; command_t* new_cmd = xmalloc(sizeof(command_t)); size_t word_len = strlen(word); new_cmd->length = word_len; new_cmd->min_len = get_min_length(word, word_len); new_cmd->cmd = uppercase(word, word_len); new_cmd->next = cmd; cmd = new_cmd; } free(words); return cmd; } void free_command_list(command_t* cmd) { while (cmd != NULL) { command_t* next = cmd->next; free(cmd->cmd); free(cmd); cmd = next; } } const command_t* find_command(const command_t* commands, const char* word) { for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) { if (command_match(cmd, word)) return cmd; } return NULL; } void test(const command_t* commands, const char* input) { printf(" input: %s\n", input); printf("output:"); size_t count = 0; char** words = split_into_words(input, &count); for (size_t i = 0; i < count; ++i) { char* word = words[i]; uppercase(word, strlen(word)); const command_t* cmd_ptr = find_command(commands, word); printf(" %s", cmd_ptr ? cmd_ptr->cmd : "*error*"); free(word); } free(words); printf("\n"); } int main() { command_t* commands = make_command_list(command_table); const char* input = "riG rePEAT copies put mo rest types fup. 6 poweRin"; test(commands, input); free_command_list(commands); return 0; }
command_table_text = \ user_words = "riG rePEAT copies put mo rest types fup. 6 poweRin" def find_abbreviations_length(command_table_text): command_table = dict() for word in command_table_text.split(): abbr_len = sum(1 for c in word if c.isupper()) if abbr_len == 0: abbr_len = len(word) command_table[word] = abbr_len return command_table def find_abbreviations(command_table): abbreviations = dict() for command, min_abbr_len in command_table.items(): for l in range(min_abbr_len, len(command)+1): abbr = command[:l].lower() abbreviations[abbr] = command.upper() return abbreviations def parse_user_string(user_string, abbreviations): user_words = [word.lower() for word in user_string.split()] commands = [abbreviations.get(user_word, "*error*") for user_word in user_words] return " ".join(commands) command_table = find_abbreviations_length(command_table_text) abbreviations_table = find_abbreviations(command_table) full_words = parse_user_string(user_words, abbreviations_table) print("user words:", user_words) print("full words:", full_words)
Translate this program into Python but keep the logic exactly as in C.
#define PI 3.14159265358979323 #define MINSIZE 10 #define MAXSIZE 100
>>> s = "Hello" >>> s[0] = "h" Traceback (most recent call last): File "<pyshell s[0] = "h" TypeError: 'str' object does not support item assignment
Can you help me rewrite this code in Python instead of C, keeping it the same logically?
#include <stdio.h> #include <stdlib.h> #include <math.h> typedef struct { double x, y; } vec_t, *vec; inline double dot(vec a, vec b) { return a->x * b->x + a->y * b->y; } inline double cross(vec a, vec b) { return a->x * b->y - a->y * b->x; } inline vec vsub(vec a, vec b, vec res) { res->x = a->x - b->x; res->y = a->y - b->y; return res; } int left_of(vec a, vec b, vec c) { vec_t tmp1, tmp2; double x; vsub(b, a, &tmp1); vsub(c, b, &tmp2); x = cross(&tmp1, &tmp2); return x < 0 ? -1 : x > 0; } int line_sect(vec x0, vec x1, vec y0, vec y1, vec res) { vec_t dx, dy, d; vsub(x1, x0, &dx); vsub(y1, y0, &dy); vsub(x0, y0, &d); double dyx = cross(&dy, &dx); if (!dyx) return 0; dyx = cross(&d, &dx) / dyx; if (dyx <= 0 || dyx >= 1) return 0; res->x = y0->x + dyx * dy.x; res->y = y0->y + dyx * dy.y; return 1; } typedef struct { int len, alloc; vec v; } poly_t, *poly; poly poly_new() { return (poly)calloc(1, sizeof(poly_t)); } void poly_free(poly p) { free(p->v); free(p); } void poly_append(poly p, vec v) { if (p->len >= p->alloc) { p->alloc *= 2; if (!p->alloc) p->alloc = 4; p->v = (vec)realloc(p->v, sizeof(vec_t) * p->alloc); } p->v[p->len++] = *v; } int poly_winding(poly p) { return left_of(p->v, p->v + 1, p->v + 2); } void poly_edge_clip(poly sub, vec x0, vec x1, int left, poly res) { int i, side0, side1; vec_t tmp; vec v0 = sub->v + sub->len - 1, v1; res->len = 0; side0 = left_of(x0, x1, v0); if (side0 != -left) poly_append(res, v0); for (i = 0; i < sub->len; i++) { v1 = sub->v + i; side1 = left_of(x0, x1, v1); if (side0 + side1 == 0 && side0) if (line_sect(x0, x1, v0, v1, &tmp)) poly_append(res, &tmp); if (i == sub->len - 1) break; if (side1 != -left) poly_append(res, v1); v0 = v1; side0 = side1; } } poly poly_clip(poly sub, poly clip) { int i; poly p1 = poly_new(), p2 = poly_new(), tmp; int dir = poly_winding(clip); poly_edge_clip(sub, clip->v + clip->len - 1, clip->v, dir, p2); for (i = 0; i < clip->len - 1; i++) { tmp = p2; p2 = p1; p1 = tmp; if(p1->len == 0) { p2->len = 0; break; } poly_edge_clip(p1, clip->v + i, clip->v + i + 1, dir, p2); } poly_free(p1); return p2; } int main() { int i; vec_t c[] = {{100,100}, {300,100}, {300,300}, {100,300}}; vec_t s[] = { {50,150}, {200,50}, {350,150}, {350,300},{250,300},{200,250}, {150,350},{100,250},{100,200}}; #define clen (sizeof(c)/sizeof(vec_t)) #define slen (sizeof(s)/sizeof(vec_t)) poly_t clipper = {clen, 0, c}; poly_t subject = {slen, 0, s}; poly res = poly_clip(&subject, &clipper); for (i = 0; i < res->len; i++) printf("%g %g\n", res->v[i].x, res->v[i].y); FILE * eps = fopen("test.eps", "w"); fprintf(eps, "%%!PS-Adobe-3.0\n%%%%BoundingBox: 40 40 360 360\n" "/l {lineto} def /m{moveto} def /s{setrgbcolor} def" "/c {closepath} def /gs {fill grestore stroke} def\n"); fprintf(eps, "0 setlinewidth %g %g m ", c[0].x, c[0].y); for (i = 1; i < clen; i++) fprintf(eps, "%g %g l ", c[i].x, c[i].y); fprintf(eps, "c .5 0 0 s gsave 1 .7 .7 s gs\n"); fprintf(eps, "%g %g m ", s[0].x, s[0].y); for (i = 1; i < slen; i++) fprintf(eps, "%g %g l ", s[i].x, s[i].y); fprintf(eps, "c 0 .2 .5 s gsave .4 .7 1 s gs\n"); fprintf(eps, "2 setlinewidth [10 8] 0 setdash %g %g m ", res->v[0].x, res->v[0].y); for (i = 1; i < res->len; i++) fprintf(eps, "%g %g l ", res->v[i].x, res->v[i].y); fprintf(eps, "c .5 0 .5 s gsave .7 .3 .8 s gs\n"); fprintf(eps, "%%%%EOF"); fclose(eps); printf("test.eps written\n"); return 0; }
def clip(subjectPolygon, clipPolygon): def inside(p): return(cp2[0]-cp1[0])*(p[1]-cp1[1]) > (cp2[1]-cp1[1])*(p[0]-cp1[0]) def computeIntersection(): dc = [ cp1[0] - cp2[0], cp1[1] - cp2[1] ] dp = [ s[0] - e[0], s[1] - e[1] ] n1 = cp1[0] * cp2[1] - cp1[1] * cp2[0] n2 = s[0] * e[1] - s[1] * e[0] n3 = 1.0 / (dc[0] * dp[1] - dc[1] * dp[0]) return [(n1*dp[0] - n2*dc[0]) * n3, (n1*dp[1] - n2*dc[1]) * n3] outputList = subjectPolygon cp1 = clipPolygon[-1] for clipVertex in clipPolygon: cp2 = clipVertex inputList = outputList outputList = [] s = inputList[-1] for subjectVertex in inputList: e = subjectVertex if inside(e): if not inside(s): outputList.append(computeIntersection()) outputList.append(e) elif inside(s): outputList.append(computeIntersection()) s = e cp1 = cp2 return(outputList)
Preserve the algorithm and functionality while converting the code from C to Python.
#include <stdio.h> #include <string.h> #include <stdlib.h> char *codes[] = { "AAAAA", "AAAAB", "AAABA", "AAABB", "AABAA", "AABAB", "AABBA", "AABBB", "ABAAA", "ABAAB", "ABABA", "ABABB", "ABBAA", "ABBAB", "ABBBA", "ABBBB", "BAAAA", "BAAAB", "BAABA", "BAABB", "BABAA", "BABAB", "BABBA", "BABBB", "BBAAA", "BBAAB", "BBBAA" }; char *get_code(const char c) { if (c >= 97 && c <= 122) return codes[c - 97]; return codes[26]; } char get_char(const char *code) { int i; if (!strcmp(codes[26], code)) return ' '; for (i = 0; i < 26; ++i) { if (strcmp(codes[i], code) == 0) return 97 + i; } printf("\nCode \"%s\" is invalid\n", code); exit(1); } void str_tolower(char s[]) { int i; for (i = 0; i < strlen(s); ++i) s[i] = tolower(s[i]); } char *bacon_encode(char plain_text[], char message[]) { int i, count; int plen = strlen(plain_text), mlen = strlen(message); int elen = 5 * plen; char c; char *p, *et, *mt; et = malloc(elen + 1); str_tolower(plain_text); for (i = 0, p = et; i < plen; ++i, p += 5) { c = plain_text[i]; strncpy(p, get_code(c), 5); } *++p = '\0'; str_tolower(message); mt = calloc(mlen + 1, 1); for (i = 0, count = 0; i < mlen; ++i) { c = message[i]; if (c >= 'a' && c <= 'z') { if (et[count] == 'A') mt[i] = c; else mt[i] = c - 32; if (++count == elen) break; } else mt[i] = c; } free(et); return mt; } char *bacon_decode(char cipher_text[]) { int i, count, clen = strlen(cipher_text); int plen; char *p, *ct, *pt; char c, quintet[6]; ct = calloc(clen + 1, 1); for (i = 0, count = 0; i < clen; ++i) { c = cipher_text[i]; if (c >= 'a' && c <= 'z') ct[count++] = 'A'; else if (c >= 'A' && c <= 'Z') ct[count++] = 'B'; } plen = strlen(ct) / 5; pt = malloc(plen + 1); for (i = 0, p = ct; i < plen; ++i, p += 5) { strncpy(quintet, p, 5); quintet[5] = '\0'; pt[i] = get_char(quintet); } pt[plen] = '\0'; free(ct); return pt; } int main() { char plain_text[] = "the quick brown fox jumps over the lazy dog"; char message[] = "bacon's cipher is a method of steganography created by francis bacon." "this task is to implement a program for encryption and decryption of " "plaintext using the simple alphabet of the baconian cipher or some " "other kind of representation of this alphabet (make anything signify anything). " "the baconian alphabet may optionally be extended to encode all lower " "case characters individually and/or adding a few punctuation characters " "such as the space."; char *cipher_text, *hidden_text; cipher_text = bacon_encode(plain_text, message); printf("Cipher text ->\n\n%s\n", cipher_text); hidden_text = bacon_decode(cipher_text); printf("\nHidden text ->\n\n%s\n", hidden_text); free(cipher_text); free(hidden_text); return 0; }
import string sometext = .lower() lc2bin = {ch: '{:05b}'.format(i) for i, ch in enumerate(string.ascii_lowercase + ' .')} bin2lc = {val: key for key, val in lc2bin.items()} phrase = 'Rosetta code Bacon cipher example secret phrase to encode in the capitalisation of peter pan'.lower() def to_5binary(msg): return ( ch == '1' for ch in ''.join(lc2bin.get(ch, '') for ch in msg.lower())) def encrypt(message, text): bin5 = to_5binary(message) textlist = list(text.lower()) out = [] for capitalise in bin5: while textlist: ch = textlist.pop(0) if ch.isalpha(): if capitalise: ch = ch.upper() out.append(ch) break else: out.append(ch) else: raise Exception('ERROR: Ran out of characters in sometext') return ''.join(out) + '...' def decrypt(bacontext): binary = [] bin5 = [] out = [] for ch in bacontext: if ch.isalpha(): binary.append('1' if ch.isupper() else '0') if len(binary) == 5: bin5 = ''.join(binary) out.append(bin2lc[bin5]) binary = [] return ''.join(out) print('PLAINTEXT = \n%s\n' % phrase) encrypted = encrypt(phrase, sometext) print('ENCRYPTED = \n%s\n' % encrypted) decrypted = decrypt(encrypted) print('DECRYPTED = \n%s\n' % decrypted) assert phrase == decrypted, 'Round-tripping error'