Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Translate the given Java code snippet into Python without altering its behavior.
import java.util.ArrayList; import java.util.Collections; import java.util.List; public class ZumkellerNumbers { public static void main(String[] args) { int n = 1; System.out.printf("First 220 Zumkeller numbers:%n"); for ( int count = 1 ; count <= 220 ; n += 1 ) { if ( isZumkeller(n) ) { System.out.printf("%3d ", n); if ( count % 20 == 0 ) { System.out.printf("%n"); } count++; } } n = 1; System.out.printf("%nFirst 40 odd Zumkeller numbers:%n"); for ( int count = 1 ; count <= 40 ; n += 2 ) { if ( isZumkeller(n) ) { System.out.printf("%6d", n); if ( count % 10 == 0 ) { System.out.printf("%n"); } count++; } } n = 1; System.out.printf("%nFirst 40 odd Zumkeller numbers that do not end in a 5:%n"); for ( int count = 1 ; count <= 40 ; n += 2 ) { if ( n % 5 != 0 && isZumkeller(n) ) { System.out.printf("%8d", n); if ( count % 10 == 0 ) { System.out.printf("%n"); } count++; } } } private static boolean isZumkeller(int n) { if ( n % 18 == 6 || n % 18 == 12 ) { return true; } List<Integer> divisors = getDivisors(n); int divisorSum = divisors.stream().mapToInt(i -> i.intValue()).sum(); if ( divisorSum % 2 == 1 ) { return false; } int abundance = divisorSum - 2 * n; if ( n % 2 == 1 && abundance > 0 && abundance % 2 == 0 ) { return true; } Collections.sort(divisors); int j = divisors.size() - 1; int sum = divisorSum/2; if ( divisors.get(j) > sum ) { return false; } return canPartition(j, divisors, sum, new int[2]); } private static boolean canPartition(int j, List<Integer> divisors, int sum, int[] buckets) { if ( j < 0 ) { return true; } for ( int i = 0 ; i < 2 ; i++ ) { if ( buckets[i] + divisors.get(j) <= sum ) { buckets[i] += divisors.get(j); if ( canPartition(j-1, divisors, sum, buckets) ) { return true; } buckets[i] -= divisors.get(j); } if( buckets[i] == 0 ) { break; } } return false; } private static final List<Integer> getDivisors(int number) { List<Integer> divisors = new ArrayList<Integer>(); long sqrt = (long) Math.sqrt(number); for ( int i = 1 ; i <= sqrt ; i++ ) { if ( number % i == 0 ) { divisors.add(i); int div = number / i; if ( div != i ) { divisors.add(div); } } } return divisors; } }
from sympy import divisors from sympy.combinatorics.subsets import Subset def isZumkeller(n): d = divisors(n) s = sum(d) if not s % 2 and max(d) <= s/2: for x in range(1, 2**len(d)): if sum(Subset.unrank_binary(x, d).subset) == s/2: return True return False def printZumkellers(N, oddonly=False): nprinted = 0 for n in range(1, 10**5): if (oddonly == False or n % 2) and isZumkeller(n): print(f'{n:>8}', end='') nprinted += 1 if nprinted % 10 == 0: print() if nprinted >= N: return print("220 Zumkeller numbers:") printZumkellers(220) print("\n\n40 odd Zumkeller numbers:") printZumkellers(40, True)
Can you help me rewrite this code in Python instead of Java, keeping it the same logically?
import java.util.*; class MergeMaps { public static void main(String[] args) { Map<String, Object> base = new HashMap<>(); base.put("name", "Rocket Skates"); base.put("price", 12.75); base.put("color", "yellow"); Map<String, Object> update = new HashMap<>(); update.put("price", 15.25); update.put("color", "red"); update.put("year", 1974); Map<String, Object> result = new HashMap<>(base); result.putAll(update); System.out.println(result); } }
base = {"name":"Rocket Skates", "price":12.75, "color":"yellow"} update = {"price":15.25, "color":"red", "year":1974} result = {**base, **update} print(result)
Write the same code in Python as shown below in Java.
import java.util.*; class MergeMaps { public static void main(String[] args) { Map<String, Object> base = new HashMap<>(); base.put("name", "Rocket Skates"); base.put("price", 12.75); base.put("color", "yellow"); Map<String, Object> update = new HashMap<>(); update.put("price", 15.25); update.put("color", "red"); update.put("year", 1974); Map<String, Object> result = new HashMap<>(base); result.putAll(update); System.out.println(result); } }
base = {"name":"Rocket Skates", "price":12.75, "color":"yellow"} update = {"price":15.25, "color":"red", "year":1974} result = {**base, **update} print(result)
Translate the given Java code snippet into Python without altering its behavior.
import java.math.BigDecimal; import java.math.BigInteger; import java.math.MathContext; import java.util.ArrayList; import java.util.List; public class MetallicRatios { private static String[] ratioDescription = new String[] {"Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminum", "Iron", "Tin", "Lead"}; public static void main(String[] args) { int elements = 15; for ( int b = 0 ; b < 10 ; b++ ) { System.out.printf("Lucas sequence for %s ratio, where b = %d:%n", ratioDescription[b], b); System.out.printf("First %d elements: %s%n", elements, lucasSequence(1, 1, b, elements)); int decimalPlaces = 32; BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1); System.out.printf("Value to %d decimal places after %s iterations : %s%n", decimalPlaces, ratio[1], ratio[0]); System.out.printf("%n"); } int b = 1; int decimalPlaces = 256; System.out.printf("%s ratio, where b = %d:%n", ratioDescription[b], b); BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1); System.out.printf("Value to %d decimal places after %s iterations : %s%n", decimalPlaces, ratio[1], ratio[0]); } private static BigDecimal[] lucasSequenceRatio(int x0, int x1, int b, int digits) { BigDecimal x0Bi = BigDecimal.valueOf(x0); BigDecimal x1Bi = BigDecimal.valueOf(x1); BigDecimal bBi = BigDecimal.valueOf(b); MathContext mc = new MathContext(digits); BigDecimal fractionPrior = x1Bi.divide(x0Bi, mc); int iterations = 0; while ( true ) { iterations++; BigDecimal x = bBi.multiply(x1Bi).add(x0Bi); BigDecimal fractionCurrent = x.divide(x1Bi, mc); if ( fractionCurrent.compareTo(fractionPrior) == 0 ) { break; } x0Bi = x1Bi; x1Bi = x; fractionPrior = fractionCurrent; } return new BigDecimal[] {fractionPrior, BigDecimal.valueOf(iterations)}; } private static List<BigInteger> lucasSequence(int x0, int x1, int b, int n) { List<BigInteger> list = new ArrayList<>(); BigInteger x0Bi = BigInteger.valueOf(x0); BigInteger x1Bi = BigInteger.valueOf(x1); BigInteger bBi = BigInteger.valueOf(b); if ( n > 0 ) { list.add(x0Bi); } if ( n > 1 ) { list.add(x1Bi); } while ( n > 2 ) { BigInteger x = bBi.multiply(x1Bi).add(x0Bi); list.add(x); n--; x0Bi = x1Bi; x1Bi = x; } return list; } }
from itertools import count, islice from _pydecimal import getcontext, Decimal def metallic_ratio(b): m, n = 1, 1 while True: yield m, n m, n = m*b + n, m def stable(b, prec): def to_decimal(b): for m,n in metallic_ratio(b): yield Decimal(m)/Decimal(n) getcontext().prec = prec last = 0 for i,x in zip(count(), to_decimal(b)): if x == last: print(f'after {i} iterations:\n\t{x}') break last = x for b in range(4): coefs = [n for _,n in islice(metallic_ratio(b), 15)] print(f'\nb = {b}: {coefs}') stable(b, 32) print(f'\nb = 1 with 256 digits:') stable(1, 256)
Translate the given Java code snippet into Python without altering its behavior.
import java.math.BigDecimal; import java.math.BigInteger; import java.math.MathContext; import java.util.ArrayList; import java.util.List; public class MetallicRatios { private static String[] ratioDescription = new String[] {"Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminum", "Iron", "Tin", "Lead"}; public static void main(String[] args) { int elements = 15; for ( int b = 0 ; b < 10 ; b++ ) { System.out.printf("Lucas sequence for %s ratio, where b = %d:%n", ratioDescription[b], b); System.out.printf("First %d elements: %s%n", elements, lucasSequence(1, 1, b, elements)); int decimalPlaces = 32; BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1); System.out.printf("Value to %d decimal places after %s iterations : %s%n", decimalPlaces, ratio[1], ratio[0]); System.out.printf("%n"); } int b = 1; int decimalPlaces = 256; System.out.printf("%s ratio, where b = %d:%n", ratioDescription[b], b); BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1); System.out.printf("Value to %d decimal places after %s iterations : %s%n", decimalPlaces, ratio[1], ratio[0]); } private static BigDecimal[] lucasSequenceRatio(int x0, int x1, int b, int digits) { BigDecimal x0Bi = BigDecimal.valueOf(x0); BigDecimal x1Bi = BigDecimal.valueOf(x1); BigDecimal bBi = BigDecimal.valueOf(b); MathContext mc = new MathContext(digits); BigDecimal fractionPrior = x1Bi.divide(x0Bi, mc); int iterations = 0; while ( true ) { iterations++; BigDecimal x = bBi.multiply(x1Bi).add(x0Bi); BigDecimal fractionCurrent = x.divide(x1Bi, mc); if ( fractionCurrent.compareTo(fractionPrior) == 0 ) { break; } x0Bi = x1Bi; x1Bi = x; fractionPrior = fractionCurrent; } return new BigDecimal[] {fractionPrior, BigDecimal.valueOf(iterations)}; } private static List<BigInteger> lucasSequence(int x0, int x1, int b, int n) { List<BigInteger> list = new ArrayList<>(); BigInteger x0Bi = BigInteger.valueOf(x0); BigInteger x1Bi = BigInteger.valueOf(x1); BigInteger bBi = BigInteger.valueOf(b); if ( n > 0 ) { list.add(x0Bi); } if ( n > 1 ) { list.add(x1Bi); } while ( n > 2 ) { BigInteger x = bBi.multiply(x1Bi).add(x0Bi); list.add(x); n--; x0Bi = x1Bi; x1Bi = x; } return list; } }
from itertools import count, islice from _pydecimal import getcontext, Decimal def metallic_ratio(b): m, n = 1, 1 while True: yield m, n m, n = m*b + n, m def stable(b, prec): def to_decimal(b): for m,n in metallic_ratio(b): yield Decimal(m)/Decimal(n) getcontext().prec = prec last = 0 for i,x in zip(count(), to_decimal(b)): if x == last: print(f'after {i} iterations:\n\t{x}') break last = x for b in range(4): coefs = [n for _,n in islice(metallic_ratio(b), 15)] print(f'\nb = {b}: {coefs}') stable(b, 32) print(f'\nb = 1 with 256 digits:') stable(1, 256)
Please provide an equivalent version of this Java code in Python.
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Random; public class MarkovChain { private static Random r = new Random(); private static String markov(String filePath, int keySize, int outputSize) throws IOException { if (keySize < 1) throw new IllegalArgumentException("Key size can't be less than 1"); Path path = Paths.get(filePath); byte[] bytes = Files.readAllBytes(path); String[] words = new String(bytes).trim().split(" "); if (outputSize < keySize || outputSize >= words.length) { throw new IllegalArgumentException("Output size is out of range"); } Map<String, List<String>> dict = new HashMap<>(); for (int i = 0; i < (words.length - keySize); ++i) { StringBuilder key = new StringBuilder(words[i]); for (int j = i + 1; j < i + keySize; ++j) { key.append(' ').append(words[j]); } String value = (i + keySize < words.length) ? words[i + keySize] : ""; if (!dict.containsKey(key.toString())) { ArrayList<String> list = new ArrayList<>(); list.add(value); dict.put(key.toString(), list); } else { dict.get(key.toString()).add(value); } } int n = 0; int rn = r.nextInt(dict.size()); String prefix = (String) dict.keySet().toArray()[rn]; List<String> output = new ArrayList<>(Arrays.asList(prefix.split(" "))); while (true) { List<String> suffix = dict.get(prefix); if (suffix.size() == 1) { if (Objects.equals(suffix.get(0), "")) return output.stream().reduce("", (a, b) -> a + " " + b); output.add(suffix.get(0)); } else { rn = r.nextInt(suffix.size()); output.add(suffix.get(rn)); } if (output.size() >= outputSize) return output.stream().limit(outputSize).reduce("", (a, b) -> a + " " + b); n++; prefix = output.stream().skip(n).limit(keySize).reduce("", (a, b) -> a + " " + b).trim(); } } public static void main(String[] args) throws IOException { System.out.println(markov("alice_oz.txt", 3, 200)); } }
import random, sys def makerule(data, context): rule = {} words = data.split(' ') index = context for word in words[index:]: key = ' '.join(words[index-context:index]) if key in rule: rule[key].append(word) else: rule[key] = [word] index += 1 return rule def makestring(rule, length): oldwords = random.choice(list(rule.keys())).split(' ') string = ' '.join(oldwords) + ' ' for i in range(length): try: key = ' '.join(oldwords) newword = random.choice(rule[key]) string += newword + ' ' for word in range(len(oldwords)): oldwords[word] = oldwords[(word + 1) % len(oldwords)] oldwords[-1] = newword except KeyError: return string return string if __name__ == '__main__': with open(sys.argv[1], encoding='utf8') as f: data = f.read() rule = makerule(data, int(sys.argv[2])) string = makestring(rule, int(sys.argv[3])) print(string)
Rewrite the snippet below in Python so it works the same as the original Java code.
import java.io.*; import java.util.*; public class Dijkstra { private static final Graph.Edge[] GRAPH = { new Graph.Edge("a", "b", 7), new Graph.Edge("a", "c", 9), new Graph.Edge("a", "f", 14), new Graph.Edge("b", "c", 10), new Graph.Edge("b", "d", 15), new Graph.Edge("c", "d", 11), new Graph.Edge("c", "f", 2), new Graph.Edge("d", "e", 6), new Graph.Edge("e", "f", 9), }; private static final String START = "a"; private static final String END = "e"; public static void main(String[] args) { Graph g = new Graph(GRAPH); g.dijkstra(START); g.printPath(END); } } class Graph { private final Map<String, Vertex> graph; public static class Edge { public final String v1, v2; public final int dist; public Edge(String v1, String v2, int dist) { this.v1 = v1; this.v2 = v2; this.dist = dist; } } public static class Vertex implements Comparable<Vertex>{ public final String name; public int dist = Integer.MAX_VALUE; public Vertex previous = null; public final Map<Vertex, Integer> neighbours = new HashMap<>(); public Vertex(String name) { this.name = name; } private void printPath() { if (this == this.previous) { System.out.printf("%s", this.name); } else if (this.previous == null) { System.out.printf("%s(unreached)", this.name); } else { this.previous.printPath(); System.out.printf(" -> %s(%d)", this.name, this.dist); } } public int compareTo(Vertex other) { if (dist == other.dist) return name.compareTo(other.name); return Integer.compare(dist, other.dist); } @Override public String toString() { return "(" + name + ", " + dist + ")"; } } public Graph(Edge[] edges) { graph = new HashMap<>(edges.length); for (Edge e : edges) { if (!graph.containsKey(e.v1)) graph.put(e.v1, new Vertex(e.v1)); if (!graph.containsKey(e.v2)) graph.put(e.v2, new Vertex(e.v2)); } for (Edge e : edges) { graph.get(e.v1).neighbours.put(graph.get(e.v2), e.dist); } } public void dijkstra(String startName) { if (!graph.containsKey(startName)) { System.err.printf("Graph doesn't contain start vertex \"%s\"\n", startName); return; } final Vertex source = graph.get(startName); NavigableSet<Vertex> q = new TreeSet<>(); for (Vertex v : graph.values()) { v.previous = v == source ? source : null; v.dist = v == source ? 0 : Integer.MAX_VALUE; q.add(v); } dijkstra(q); } private void dijkstra(final NavigableSet<Vertex> q) { Vertex u, v; while (!q.isEmpty()) { u = q.pollFirst(); if (u.dist == Integer.MAX_VALUE) break; for (Map.Entry<Vertex, Integer> a : u.neighbours.entrySet()) { v = a.getKey(); final int alternateDist = u.dist + a.getValue(); if (alternateDist < v.dist) { q.remove(v); v.dist = alternateDist; v.previous = u; q.add(v); } } } } public void printPath(String endName) { if (!graph.containsKey(endName)) { System.err.printf("Graph doesn't contain end vertex \"%s\"\n", endName); return; } graph.get(endName).printPath(); System.out.println(); } public void printAllPaths() { for (Vertex v : graph.values()) { v.printPath(); System.out.println(); } } }
from collections import namedtuple, deque from pprint import pprint as pp inf = float('inf') Edge = namedtuple('Edge', ['start', 'end', 'cost']) class Graph(): def __init__(self, edges): self.edges = [Edge(*edge) for edge in edges] self.vertices = {e.start for e in self.edges} | {e.end for e in self.edges} def dijkstra(self, source, dest): assert source in self.vertices dist = {vertex: inf for vertex in self.vertices} previous = {vertex: None for vertex in self.vertices} dist[source] = 0 q = self.vertices.copy() neighbours = {vertex: set() for vertex in self.vertices} for start, end, cost in self.edges: neighbours[start].add((end, cost)) neighbours[end].add((start, cost)) while q: u = min(q, key=lambda vertex: dist[vertex]) q.remove(u) if dist[u] == inf or u == dest: break for v, cost in neighbours[u]: alt = dist[u] + cost if alt < dist[v]: dist[v] = alt previous[v] = u s, u = deque(), dest while previous[u]: s.appendleft(u) u = previous[u] s.appendleft(u) return s graph = Graph([("a", "b", 7), ("a", "c", 9), ("a", "f", 14), ("b", "c", 10), ("b", "d", 15), ("c", "d", 11), ("c", "f", 2), ("d", "e", 6), ("e", "f", 9)]) pp(graph.dijkstra("a", "e"))
Produce a functionally identical Python code for the snippet given in Java.
import java.util.Arrays; import java.util.Random; public class GeometricAlgebra { private static int bitCount(int i) { i -= ((i >> 1) & 0x55555555); i = (i & 0x33333333) + ((i >> 2) & 0x33333333); i = (i + (i >> 4)) & 0x0F0F0F0F; i += (i >> 8); i += (i >> 16); return i & 0x0000003F; } private static double reorderingSign(int i, int j) { int k = i >> 1; int sum = 0; while (k != 0) { sum += bitCount(k & j); k = k >> 1; } return ((sum & 1) == 0) ? 1.0 : -1.0; } static class Vector { private double[] dims; public Vector(double[] dims) { this.dims = dims; } public Vector dot(Vector rhs) { return times(rhs).plus(rhs.times(this)).times(0.5); } public Vector unaryMinus() { return times(-1.0); } public Vector plus(Vector rhs) { double[] result = Arrays.copyOf(dims, 32); for (int i = 0; i < rhs.dims.length; ++i) { result[i] += rhs.get(i); } return new Vector(result); } public Vector times(Vector rhs) { double[] result = new double[32]; for (int i = 0; i < dims.length; ++i) { if (dims[i] != 0.0) { for (int j = 0; j < rhs.dims.length; ++j) { if (rhs.get(j) != 0.0) { double s = reorderingSign(i, j) * dims[i] * rhs.dims[j]; int k = i ^ j; result[k] += s; } } } } return new Vector(result); } public Vector times(double scale) { double[] result = dims.clone(); for (int i = 0; i < 5; ++i) { dims[i] *= scale; } return new Vector(result); } double get(int index) { return dims[index]; } void set(int index, double value) { dims[index] = value; } @Override public String toString() { StringBuilder sb = new StringBuilder("("); boolean first = true; for (double value : dims) { if (first) { first = false; } else { sb.append(", "); } sb.append(value); } return sb.append(")").toString(); } } private static Vector e(int n) { if (n > 4) { throw new IllegalArgumentException("n must be less than 5"); } Vector result = new Vector(new double[32]); result.set(1 << n, 1.0); return result; } private static final Random rand = new Random(); private static Vector randomVector() { Vector result = new Vector(new double[32]); for (int i = 0; i < 5; ++i) { Vector temp = new Vector(new double[]{rand.nextDouble()}); result = result.plus(temp.times(e(i))); } return result; } private static Vector randomMultiVector() { Vector result = new Vector(new double[32]); for (int i = 0; i < 32; ++i) { result.set(i, rand.nextDouble()); } return result; } public static void main(String[] args) { for (int i = 0; i < 5; ++i) { for (int j = 0; j < 5; ++j) { if (i < j) { if (e(i).dot(e(j)).get(0) != 0.0) { System.out.println("Unexpected non-null scalar product."); return; } } } } Vector a = randomMultiVector(); Vector b = randomMultiVector(); Vector c = randomMultiVector(); Vector x = randomVector(); System.out.println(a.times(b).times(c)); System.out.println(a.times(b.times(c))); System.out.println(); System.out.println(a.times(b.plus(c))); System.out.println(a.times(b).plus(a.times(c))); System.out.println(); System.out.println(a.plus(b).times(c)); System.out.println(a.times(c).plus(b.times(c))); System.out.println(); System.out.println(x.times(x)); } }
import copy, random def bitcount(n): return bin(n).count("1") def reoderingSign(i, j): k = i >> 1 sum = 0 while k != 0: sum += bitcount(k & j) k = k >> 1 return 1.0 if ((sum & 1) == 0) else -1.0 class Vector: def __init__(self, da): self.dims = da def dot(self, other): return (self * other + other * self) * 0.5 def __getitem__(self, i): return self.dims[i] def __setitem__(self, i, v): self.dims[i] = v def __neg__(self): return self * -1.0 def __add__(self, other): result = copy.copy(other.dims) for i in xrange(0, len(self.dims)): result[i] += self.dims[i] return Vector(result) def __mul__(self, other): if isinstance(other, Vector): result = [0.0] * 32 for i in xrange(0, len(self.dims)): if self.dims[i] != 0.0: for j in xrange(0, len(self.dims)): if other.dims[j] != 0.0: s = reoderingSign(i, j) * self.dims[i] * other.dims[j] k = i ^ j result[k] += s return Vector(result) else: result = copy.copy(self.dims) for i in xrange(0, len(self.dims)): self.dims[i] *= other return Vector(result) def __str__(self): return str(self.dims) def e(n): assert n <= 4, "n must be less than 5" result = Vector([0.0] * 32) result[1 << n] = 1.0 return result def randomVector(): result = Vector([0.0] * 32) for i in xrange(0, 5): result += Vector([random.uniform(0, 1)]) * e(i) return result def randomMultiVector(): result = Vector([0.0] * 32) for i in xrange(0, 32): result[i] = random.uniform(0, 1) return result def main(): for i in xrange(0, 5): for j in xrange(0, 5): if i < j: if e(i).dot(e(j))[0] != 0.0: print "Unexpected non-null scalar product" return elif i == j: if e(i).dot(e(j))[0] == 0.0: print "Unexpected non-null scalar product" a = randomMultiVector() b = randomMultiVector() c = randomMultiVector() x = randomVector() print (a * b) * c print a * (b * c) print print a * (b + c) print a * b + a * c print print (a + b) * c print a * c + b * c print print x * x main()
Can you help me rewrite this code in Python instead of Java, keeping it the same logically?
import java.util.ArrayList; import java.util.List; public class SuffixTreeProblem { private static class Node { String sub = ""; List<Integer> ch = new ArrayList<>(); } private static class SuffixTree { private List<Node> nodes = new ArrayList<>(); public SuffixTree(String str) { nodes.add(new Node()); for (int i = 0; i < str.length(); ++i) { addSuffix(str.substring(i)); } } private void addSuffix(String suf) { int n = 0; int i = 0; while (i < suf.length()) { char b = suf.charAt(i); List<Integer> children = nodes.get(n).ch; int x2 = 0; int n2; while (true) { if (x2 == children.size()) { n2 = nodes.size(); Node temp = new Node(); temp.sub = suf.substring(i); nodes.add(temp); children.add(n2); return; } n2 = children.get(x2); if (nodes.get(n2).sub.charAt(0) == b) break; x2++; } String sub2 = nodes.get(n2).sub; int j = 0; while (j < sub2.length()) { if (suf.charAt(i + j) != sub2.charAt(j)) { int n3 = n2; n2 = nodes.size(); Node temp = new Node(); temp.sub = sub2.substring(0, j); temp.ch.add(n3); nodes.add(temp); nodes.get(n3).sub = sub2.substring(j); nodes.get(n).ch.set(x2, n2); break; } j++; } i += j; n = n2; } } public void visualize() { if (nodes.isEmpty()) { System.out.println("<empty>"); return; } visualize_f(0, ""); } private void visualize_f(int n, String pre) { List<Integer> children = nodes.get(n).ch; if (children.isEmpty()) { System.out.println("- " + nodes.get(n).sub); return; } System.out.println("┐ " + nodes.get(n).sub); for (int i = 0; i < children.size() - 1; i++) { Integer c = children.get(i); System.out.print(pre + "├─"); visualize_f(c, pre + "│ "); } System.out.print(pre + "└─"); visualize_f(children.get(children.size() - 1), pre + " "); } } public static void main(String[] args) { new SuffixTree("banana$").visualize(); } }
class Node: def __init__(self, sub="", children=None): self.sub = sub self.ch = children or [] class SuffixTree: def __init__(self, str): self.nodes = [Node()] for i in range(len(str)): self.addSuffix(str[i:]) def addSuffix(self, suf): n = 0 i = 0 while i < len(suf): b = suf[i] x2 = 0 while True: children = self.nodes[n].ch if x2 == len(children): n2 = len(self.nodes) self.nodes.append(Node(suf[i:], [])) self.nodes[n].ch.append(n2) return n2 = children[x2] if self.nodes[n2].sub[0] == b: break x2 = x2 + 1 sub2 = self.nodes[n2].sub j = 0 while j < len(sub2): if suf[i + j] != sub2[j]: n3 = n2 n2 = len(self.nodes) self.nodes.append(Node(sub2[:j], [n3])) self.nodes[n3].sub = sub2[j:] self.nodes[n].ch[x2] = n2 break j = j + 1 i = i + j n = n2 def visualize(self): if len(self.nodes) == 0: print "<empty>" return def f(n, pre): children = self.nodes[n].ch if len(children) == 0: print "--", self.nodes[n].sub return print "+-", self.nodes[n].sub for c in children[:-1]: print pre, "+-", f(c, pre + " | ") print pre, "+-", f(children[-1], pre + " ") f(0, "") SuffixTree("banana$").visualize()
Transform the following Java implementation into Python, maintaining the same output and logic.
import java.util.ArrayList; import java.util.List; public class SuffixTreeProblem { private static class Node { String sub = ""; List<Integer> ch = new ArrayList<>(); } private static class SuffixTree { private List<Node> nodes = new ArrayList<>(); public SuffixTree(String str) { nodes.add(new Node()); for (int i = 0; i < str.length(); ++i) { addSuffix(str.substring(i)); } } private void addSuffix(String suf) { int n = 0; int i = 0; while (i < suf.length()) { char b = suf.charAt(i); List<Integer> children = nodes.get(n).ch; int x2 = 0; int n2; while (true) { if (x2 == children.size()) { n2 = nodes.size(); Node temp = new Node(); temp.sub = suf.substring(i); nodes.add(temp); children.add(n2); return; } n2 = children.get(x2); if (nodes.get(n2).sub.charAt(0) == b) break; x2++; } String sub2 = nodes.get(n2).sub; int j = 0; while (j < sub2.length()) { if (suf.charAt(i + j) != sub2.charAt(j)) { int n3 = n2; n2 = nodes.size(); Node temp = new Node(); temp.sub = sub2.substring(0, j); temp.ch.add(n3); nodes.add(temp); nodes.get(n3).sub = sub2.substring(j); nodes.get(n).ch.set(x2, n2); break; } j++; } i += j; n = n2; } } public void visualize() { if (nodes.isEmpty()) { System.out.println("<empty>"); return; } visualize_f(0, ""); } private void visualize_f(int n, String pre) { List<Integer> children = nodes.get(n).ch; if (children.isEmpty()) { System.out.println("- " + nodes.get(n).sub); return; } System.out.println("┐ " + nodes.get(n).sub); for (int i = 0; i < children.size() - 1; i++) { Integer c = children.get(i); System.out.print(pre + "├─"); visualize_f(c, pre + "│ "); } System.out.print(pre + "└─"); visualize_f(children.get(children.size() - 1), pre + " "); } } public static void main(String[] args) { new SuffixTree("banana$").visualize(); } }
class Node: def __init__(self, sub="", children=None): self.sub = sub self.ch = children or [] class SuffixTree: def __init__(self, str): self.nodes = [Node()] for i in range(len(str)): self.addSuffix(str[i:]) def addSuffix(self, suf): n = 0 i = 0 while i < len(suf): b = suf[i] x2 = 0 while True: children = self.nodes[n].ch if x2 == len(children): n2 = len(self.nodes) self.nodes.append(Node(suf[i:], [])) self.nodes[n].ch.append(n2) return n2 = children[x2] if self.nodes[n2].sub[0] == b: break x2 = x2 + 1 sub2 = self.nodes[n2].sub j = 0 while j < len(sub2): if suf[i + j] != sub2[j]: n3 = n2 n2 = len(self.nodes) self.nodes.append(Node(sub2[:j], [n3])) self.nodes[n3].sub = sub2[j:] self.nodes[n].ch[x2] = n2 break j = j + 1 i = i + j n = n2 def visualize(self): if len(self.nodes) == 0: print "<empty>" return def f(n, pre): children = self.nodes[n].ch if len(children) == 0: print "--", self.nodes[n].sub return print "+-", self.nodes[n].sub for c in children[:-1]: print pre, "+-", f(c, pre + " | ") print pre, "+-", f(children[-1], pre + " ") f(0, "") SuffixTree("banana$").visualize()
Generate an equivalent Python version of this Java code.
Map<String, Integer> map = new HashMap<String, Integer>(); map.put("hello", 1); map.put("world", 2); map.put("!", 3); for (Map.Entry<String, Integer> e : map.entrySet()) { String key = e.getKey(); Integer value = e.getValue(); System.out.println("key = " + key + ", value = " + value); } for (String key : map.keySet()) { System.out.println("key = " + key); } for (Integer value : map.values()) { System.out.println("value = " + value); }
myDict = { "hello": 13, "world": 31, "!" : 71 } for key, value in myDict.items(): print ("key = %s, value = %s" % (key, value)) for key in myDict: print ("key = %s" % key) for key in myDict.keys(): print ("key = %s" % key) for value in myDict.values(): print ("value = %s" % value)
Write the same code in Python as shown below in Java.
class BoundedIntOutOfBoundsException extends Exception { public BoundedIntOutOfBoundsException(int v, int l, int u) { super("value " + v + " is out of bounds [" + l + "," + u + "]"); } } class BoundedInt { private int value; private int lower; private int upper; public BoundedInt(int l, int u) { lower = Math.min(l, u); upper = Math.max(l, u); } private boolean checkBounds(int v) { return (v >= this.lower) && (v <= this.upper); } public void assign(BoundedInt i) throws BoundedIntOutOfBoundsException {{ assign(i.value()); } public void assign(int v) throws BoundedIntOutOfBoundsException { if ( checkBounds(v) ) { this.value = v; } else { throw new BoundedIntOutOfBoundsException(v, this.lower, this.upper); } } public int add(BoundedInt i) throws BoundedIntOutOfBoundsException { return add(i.value()); } public int add(int i) throws BoundedIntOutOfBoundsException { if ( checkBounds(this.value + i) ) { this.value += i; } else { throw new BoundedIntOutOfBoundsException(this.value + i, this.lower, this.upper); } return this.value; } public int value() { return this.value; } } public class Bounded { public static void main(String[] args) throws BoundedIntOutOfBoundsException { BoundedInt a = new BoundedInt(1, 10); BoundedInt b = new BoundedInt(1, 10); a.assign(6); try { b.assign(12); } catch (Exception e) { System.out.println(e.getMessage()); } b.assign(9); try { a.add(b.value()); } catch (Exception e) { System.out.println(e.getMessage()); } } }
>>> class num(int): def __init__(self, b): if 1 <= b <= 10: return int.__init__(self+0) else: raise ValueError,"Value %s should be >=0 and <= 10" % b >>> x = num(3) >>> x = num(11) Traceback (most recent call last): File "<pyshell x = num(11) File "<pyshell raise ValueError,"Value %s should be >=0 and <= 10" % b ValueError: Value 11 should be >=0 and <= 10 >>> x 3 >>> type(x) <class '__main__.num'> >>>
Generate an equivalent Python version of this Java code.
import java.awt.*; import java.util.List; import java.awt.geom.Path2D; import java.util.*; import javax.swing.*; import static java.lang.Math.*; import static java.util.stream.Collectors.toList; public class PenroseTiling extends JPanel { class Tile { double x, y, angle, size; Type type; Tile(Type t, double x, double y, double a, double s) { type = t; this.x = x; this.y = y; angle = a; size = s; } @Override public boolean equals(Object o) { if (o instanceof Tile) { Tile t = (Tile) o; return type == t.type && x == t.x && y == t.y && angle == t.angle; } return false; } } enum Type { Kite, Dart } static final double G = (1 + sqrt(5)) / 2; static final double T = toRadians(36); List<Tile> tiles = new ArrayList<>(); public PenroseTiling() { int w = 700, h = 450; setPreferredSize(new Dimension(w, h)); setBackground(Color.white); tiles = deflateTiles(setupPrototiles(w, h), 5); } List<Tile> setupPrototiles(int w, int h) { List<Tile> proto = new ArrayList<>(); for (double a = PI / 2 + T; a < 3 * PI; a += 2 * T) proto.add(new Tile(Type.Kite, w / 2, h / 2, a, w / 2.5)); return proto; } List<Tile> deflateTiles(List<Tile> tls, int generation) { if (generation <= 0) return tls; List<Tile> next = new ArrayList<>(); for (Tile tile : tls) { double x = tile.x, y = tile.y, a = tile.angle, nx, ny; double size = tile.size / G; if (tile.type == Type.Dart) { next.add(new Tile(Type.Kite, x, y, a + 5 * T, size)); for (int i = 0, sign = 1; i < 2; i++, sign *= -1) { nx = x + cos(a - 4 * T * sign) * G * tile.size; ny = y - sin(a - 4 * T * sign) * G * tile.size; next.add(new Tile(Type.Dart, nx, ny, a - 4 * T * sign, size)); } } else { for (int i = 0, sign = 1; i < 2; i++, sign *= -1) { next.add(new Tile(Type.Dart, x, y, a - 4 * T * sign, size)); nx = x + cos(a - T * sign) * G * tile.size; ny = y - sin(a - T * sign) * G * tile.size; next.add(new Tile(Type.Kite, nx, ny, a + 3 * T * sign, size)); } } } tls = next.stream().distinct().collect(toList()); return deflateTiles(tls, generation - 1); } void drawTiles(Graphics2D g) { double[][] dist = {{G, G, G}, {-G, -1, -G}}; for (Tile tile : tiles) { double angle = tile.angle - T; Path2D path = new Path2D.Double(); path.moveTo(tile.x, tile.y); int ord = tile.type.ordinal(); for (int i = 0; i < 3; i++) { double x = tile.x + dist[ord][i] * tile.size * cos(angle); double y = tile.y - dist[ord][i] * tile.size * sin(angle); path.lineTo(x, y); angle += T; } path.closePath(); g.setColor(ord == 0 ? Color.orange : Color.yellow); g.fill(path); g.setColor(Color.darkGray); g.draw(path); } } @Override public void paintComponent(Graphics og) { super.paintComponent(og); Graphics2D g = (Graphics2D) og; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); drawTiles(g); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setTitle("Penrose Tiling"); f.setResizable(false); f.add(new PenroseTiling(), BorderLayout.CENTER); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); }); } }
def penrose(depth): print( <g id="A{d+1}" transform="translate(100, 0) scale(0.6180339887498949)"> <use href=" <use href=" </g> <g id="B{d+1}"> <use href=" <use href=" </g> <g id="G"> <use href=" <use href=" </g> </defs> <g transform="scale(2, 2)"> <use href=" <use href=" <use href=" <use href=" <use href=" </g> </svg>''') penrose(6)
Generate a Python translation of this Java snippet without changing its computational steps.
import java.util.Arrays; import java.util.ArrayList; import java.util.List; public class SphenicNumbers { public static void main(String[] args) { final int limit = 1000000; final int imax = limit / 6; boolean[] sieve = primeSieve(imax + 1); boolean[] sphenic = new boolean[limit + 1]; for (int i = 0; i <= imax; ++i) { if (!sieve[i]) continue; int jmax = Math.min(imax, limit / (i * i)); if (jmax <= i) break; for (int j = i + 1; j <= jmax; ++j) { if (!sieve[j]) continue; int p = i * j; int kmax = Math.min(imax, limit / p); if (kmax <= j) break; for (int k = j + 1; k <= kmax; ++k) { if (!sieve[k]) continue; assert(p * k <= limit); sphenic[p * k] = true; } } } System.out.println("Sphenic numbers < 1000:"); for (int i = 0, n = 0; i < 1000; ++i) { if (!sphenic[i]) continue; ++n; System.out.printf("%3d%c", i, n % 15 == 0 ? '\n' : ' '); } System.out.println("\nSphenic triplets < 10,000:"); for (int i = 0, n = 0; i < 10000; ++i) { if (i > 1 && sphenic[i] && sphenic[i - 1] && sphenic[i - 2]) { ++n; System.out.printf("(%d, %d, %d)%c", i - 2, i - 1, i, n % 3 == 0 ? '\n' : ' '); } } int count = 0, triplets = 0, s200000 = 0, t5000 = 0; for (int i = 0; i < limit; ++i) { if (!sphenic[i]) continue; ++count; if (count == 200000) s200000 = i; if (i > 1 && sphenic[i - 1] && sphenic[i - 2]) { ++triplets; if (triplets == 5000) t5000 = i; } } System.out.printf("\nNumber of sphenic numbers < 1,000,000: %d\n", count); System.out.printf("Number of sphenic triplets < 1,000,000: %d\n", triplets); List<Integer> factors = primeFactors(s200000); assert(factors.size() == 3); System.out.printf("The 200,000th sphenic number: %d = %d * %d * %d\n", s200000, factors.get(0), factors.get(1), factors.get(2)); System.out.printf("The 5,000th sphenic triplet: (%d, %d, %d)\n", t5000 - 2, t5000 - 1, t5000); } private static boolean[] primeSieve(int limit) { boolean[] sieve = new boolean[limit]; Arrays.fill(sieve, true); if (limit > 0) sieve[0] = false; if (limit > 1) sieve[1] = false; for (int i = 4; i < limit; i += 2) sieve[i] = false; for (int p = 3, sq = 9; sq < limit; p += 2) { if (sieve[p]) { for (int q = sq; q < limit; q += p << 1) sieve[q] = false; } sq += (p + 1) << 2; } return sieve; } private static List<Integer> primeFactors(int n) { List<Integer> factors = new ArrayList<>(); if (n > 1 && (n & 1) == 0) { factors.add(2); while ((n & 1) == 0) n >>= 1; } for (int p = 3; p * p <= n; p += 2) { if (n % p == 0) { factors.add(p); while (n % p == 0) n /= p; } } if (n > 1) factors.add(n); return factors; } }
from sympy import factorint sphenics1m, sphenic_triplets1m = [], [] for i in range(3, 1_000_000): d = factorint(i) if len(d) == 3 and sum(d.values()) == 3: sphenics1m.append(i) if len(sphenics1m) > 2 and i - sphenics1m[-3] == 2 and i - sphenics1m[-2] == 1: sphenic_triplets1m.append(i) print('Sphenic numbers less than 1000:') for i, n in enumerate(sphenics1m): if n < 1000: print(f'{n : 5}', end='\n' if (i + 1) % 15 == 0 else '') else: break print('\n\nSphenic triplets less than 10_000:') for i, n in enumerate(sphenic_triplets1m): if n < 10_000: print(f'({n - 2} {n - 1} {n})', end='\n' if (i + 1) % 3 == 0 else ' ') else: break print('\nThere are', len(sphenics1m), 'sphenic numbers and', len(sphenic_triplets1m), 'sphenic triplets less than 1 million.') S2HK = sphenics1m[200_000 - 1] T5K = sphenic_triplets1m[5000 - 1] print(f'The 200_000th sphenic number is {S2HK}, with prime factors {list(factorint(S2HK).keys())}.') print(f'The 5000th sphenic triplet is ({T5K - 2} {T5K - 1} {T5K}).')
Maintain the same structure and functionality when rewriting this code in Python.
import java.io.*; import java.nio.*; import java.nio.file.*; import java.nio.file.attribute.*; import java.security.*; import java.util.*; public class DuplicateFiles { public static void main(String[] args) { if (args.length != 2) { System.err.println("Directory name and minimum file size are required."); System.exit(1); } try { findDuplicateFiles(args[0], Long.parseLong(args[1])); } catch (Exception e) { e.printStackTrace(); } } private static void findDuplicateFiles(String directory, long minimumSize) throws IOException, NoSuchAlgorithmException { System.out.println("Directory: '" + directory + "', minimum size: " + minimumSize + " bytes."); Path path = FileSystems.getDefault().getPath(directory); FileVisitor visitor = new FileVisitor(path, minimumSize); Files.walkFileTree(path, visitor); System.out.println("The following sets of files have the same size and checksum:"); for (Map.Entry<FileKey, Map<Object, List<String>>> e : visitor.fileMap_.entrySet()) { Map<Object, List<String>> map = e.getValue(); if (!containsDuplicates(map)) continue; List<List<String>> fileSets = new ArrayList<>(map.values()); for (List<String> files : fileSets) Collections.sort(files); Collections.sort(fileSets, new StringListComparator()); FileKey key = e.getKey(); System.out.println(); System.out.println("Size: " + key.size_ + " bytes"); for (List<String> files : fileSets) { for (int i = 0, n = files.size(); i < n; ++i) { if (i > 0) System.out.print(" = "); System.out.print(files.get(i)); } System.out.println(); } } } private static class StringListComparator implements Comparator<List<String>> { public int compare(List<String> a, List<String> b) { int len1 = a.size(), len2 = b.size(); for (int i = 0; i < len1 && i < len2; ++i) { int c = a.get(i).compareTo(b.get(i)); if (c != 0) return c; } return Integer.compare(len1, len2); } } private static boolean containsDuplicates(Map<Object, List<String>> map) { if (map.size() > 1) return true; for (List<String> files : map.values()) { if (files.size() > 1) return true; } return false; } private static class FileVisitor extends SimpleFileVisitor<Path> { private MessageDigest digest_; private Path directory_; private long minimumSize_; private Map<FileKey, Map<Object, List<String>>> fileMap_ = new TreeMap<>(); private FileVisitor(Path directory, long minimumSize) throws NoSuchAlgorithmException { directory_ = directory; minimumSize_ = minimumSize; digest_ = MessageDigest.getInstance("MD5"); } public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (attrs.size() >= minimumSize_) { FileKey key = new FileKey(file, attrs, getMD5Sum(file)); Map<Object, List<String>> map = fileMap_.get(key); if (map == null) fileMap_.put(key, map = new HashMap<>()); List<String> files = map.get(attrs.fileKey()); if (files == null) map.put(attrs.fileKey(), files = new ArrayList<>()); Path relative = directory_.relativize(file); files.add(relative.toString()); } return FileVisitResult.CONTINUE; } private byte[] getMD5Sum(Path file) throws IOException { digest_.reset(); try (InputStream in = new FileInputStream(file.toString())) { byte[] buffer = new byte[8192]; int bytes; while ((bytes = in.read(buffer)) != -1) { digest_.update(buffer, 0, bytes); } } return digest_.digest(); } } private static class FileKey implements Comparable<FileKey> { private byte[] hash_; private long size_; private FileKey(Path file, BasicFileAttributes attrs, byte[] hash) throws IOException { size_ = attrs.size(); hash_ = hash; } public int compareTo(FileKey other) { int c = Long.compare(other.size_, size_); if (c == 0) c = hashCompare(hash_, other.hash_); return c; } } private static int hashCompare(byte[] a, byte[] b) { int len1 = a.length, len2 = b.length; for (int i = 0; i < len1 && i < len2; ++i) { int c = Byte.compare(a[i], b[i]); if (c != 0) return c; } return Integer.compare(len1, len2); } }
from __future__ import print_function import os import hashlib import datetime def FindDuplicateFiles(pth, minSize = 0, hashName = "md5"): knownFiles = {} for root, dirs, files in os.walk(pth): for fina in files: fullFina = os.path.join(root, fina) isSymLink = os.path.islink(fullFina) if isSymLink: continue si = os.path.getsize(fullFina) if si < minSize: continue if si not in knownFiles: knownFiles[si] = {} h = hashlib.new(hashName) h.update(open(fullFina, "rb").read()) hashed = h.digest() if hashed in knownFiles[si]: fileRec = knownFiles[si][hashed] fileRec.append(fullFina) else: knownFiles[si][hashed] = [fullFina] sizeList = list(knownFiles.keys()) sizeList.sort(reverse=True) for si in sizeList: filesAtThisSize = knownFiles[si] for hashVal in filesAtThisSize: if len(filesAtThisSize[hashVal]) < 2: continue fullFinaLi = filesAtThisSize[hashVal] print ("=======Duplicate=======") for fullFina in fullFinaLi: st = os.stat(fullFina) isHardLink = st.st_nlink > 1 infoStr = [] if isHardLink: infoStr.append("(Hard linked)") fmtModTime = datetime.datetime.utcfromtimestamp(st.st_mtime).strftime('%Y-%m-%dT%H:%M:%SZ') print (fmtModTime, si, os.path.relpath(fullFina, pth), " ".join(infoStr)) if __name__=="__main__": FindDuplicateFiles('/home/tim/Dropbox', 1024*1024)
Produce a functionally identical Python code for the snippet given in Java.
import java.util.*; public class HolyKnightsTour { final static String[] board = { " xxx ", " x xx ", " xxxxxxx", "xxx x x", "x x xxx", "1xxxxxx ", " xx x ", " xxx "}; private final static int base = 12; private final static int[][] moves = {{1, -2}, {2, -1}, {2, 1}, {1, 2}, {-1, 2}, {-2, 1}, {-2, -1}, {-1, -2}}; private static int[][] grid; private static int total = 2; public static void main(String[] args) { int row = 0, col = 0; grid = new int[base][base]; for (int r = 0; r < base; r++) { Arrays.fill(grid[r], -1); for (int c = 2; c < base - 2; c++) { if (r >= 2 && r < base - 2) { if (board[r - 2].charAt(c - 2) == 'x') { grid[r][c] = 0; total++; } if (board[r - 2].charAt(c - 2) == '1') { row = r; col = c; } } } } grid[row][col] = 1; if (solve(row, col, 2)) printResult(); } private static boolean solve(int r, int c, int count) { if (count == total) return true; List<int[]> nbrs = neighbors(r, c); if (nbrs.isEmpty() && count != total) return false; Collections.sort(nbrs, (a, b) -> a[2] - b[2]); for (int[] nb : nbrs) { r = nb[0]; c = nb[1]; grid[r][c] = count; if (solve(r, c, count + 1)) return true; grid[r][c] = 0; } return false; } private static List<int[]> neighbors(int r, int c) { List<int[]> nbrs = new ArrayList<>(); for (int[] m : moves) { int x = m[0]; int y = m[1]; if (grid[r + y][c + x] == 0) { int num = countNeighbors(r + y, c + x) - 1; nbrs.add(new int[]{r + y, c + x, num}); } } return nbrs; } private static int countNeighbors(int r, int c) { int num = 0; for (int[] m : moves) if (grid[r + m[1]][c + m[0]] == 0) num++; return num; } private static void printResult() { for (int[] row : grid) { for (int i : row) { if (i == -1) System.out.printf("%2s ", ' '); else System.out.printf("%2d ", i); } System.out.println(); } } }
from sys import stdout moves = [ [-1, -2], [1, -2], [-1, 2], [1, 2], [-2, -1], [-2, 1], [2, -1], [2, 1] ] def solve(pz, sz, sx, sy, idx, cnt): if idx > cnt: return 1 for i in range(len(moves)): x = sx + moves[i][0] y = sy + moves[i][1] if sz > x > -1 and sz > y > -1 and pz[x][y] == 0: pz[x][y] = idx if 1 == solve(pz, sz, x, y, idx + 1, cnt): return 1 pz[x][y] = 0 return 0 def find_solution(pz, sz): p = [[-1 for j in range(sz)] for i in range(sz)] idx = x = y = cnt = 0 for j in range(sz): for i in range(sz): if pz[idx] == "x": p[i][j] = 0 cnt += 1 elif pz[idx] == "s": p[i][j] = 1 cnt += 1 x = i y = j idx += 1 if 1 == solve(p, sz, x, y, 2, cnt): for j in range(sz): for i in range(sz): if p[i][j] != -1: stdout.write(" {:0{}d}".format(p[i][j], 2)) else: stdout.write(" ") print() else: print("Cannot solve this puzzle!") find_solution(".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..", 8) print() find_solution(".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....", 13)
Preserve the algorithm and functionality while converting the code from Java to Python.
import java.util.*; public class HolyKnightsTour { final static String[] board = { " xxx ", " x xx ", " xxxxxxx", "xxx x x", "x x xxx", "1xxxxxx ", " xx x ", " xxx "}; private final static int base = 12; private final static int[][] moves = {{1, -2}, {2, -1}, {2, 1}, {1, 2}, {-1, 2}, {-2, 1}, {-2, -1}, {-1, -2}}; private static int[][] grid; private static int total = 2; public static void main(String[] args) { int row = 0, col = 0; grid = new int[base][base]; for (int r = 0; r < base; r++) { Arrays.fill(grid[r], -1); for (int c = 2; c < base - 2; c++) { if (r >= 2 && r < base - 2) { if (board[r - 2].charAt(c - 2) == 'x') { grid[r][c] = 0; total++; } if (board[r - 2].charAt(c - 2) == '1') { row = r; col = c; } } } } grid[row][col] = 1; if (solve(row, col, 2)) printResult(); } private static boolean solve(int r, int c, int count) { if (count == total) return true; List<int[]> nbrs = neighbors(r, c); if (nbrs.isEmpty() && count != total) return false; Collections.sort(nbrs, (a, b) -> a[2] - b[2]); for (int[] nb : nbrs) { r = nb[0]; c = nb[1]; grid[r][c] = count; if (solve(r, c, count + 1)) return true; grid[r][c] = 0; } return false; } private static List<int[]> neighbors(int r, int c) { List<int[]> nbrs = new ArrayList<>(); for (int[] m : moves) { int x = m[0]; int y = m[1]; if (grid[r + y][c + x] == 0) { int num = countNeighbors(r + y, c + x) - 1; nbrs.add(new int[]{r + y, c + x, num}); } } return nbrs; } private static int countNeighbors(int r, int c) { int num = 0; for (int[] m : moves) if (grid[r + m[1]][c + m[0]] == 0) num++; return num; } private static void printResult() { for (int[] row : grid) { for (int i : row) { if (i == -1) System.out.printf("%2s ", ' '); else System.out.printf("%2d ", i); } System.out.println(); } } }
from sys import stdout moves = [ [-1, -2], [1, -2], [-1, 2], [1, 2], [-2, -1], [-2, 1], [2, -1], [2, 1] ] def solve(pz, sz, sx, sy, idx, cnt): if idx > cnt: return 1 for i in range(len(moves)): x = sx + moves[i][0] y = sy + moves[i][1] if sz > x > -1 and sz > y > -1 and pz[x][y] == 0: pz[x][y] = idx if 1 == solve(pz, sz, x, y, idx + 1, cnt): return 1 pz[x][y] = 0 return 0 def find_solution(pz, sz): p = [[-1 for j in range(sz)] for i in range(sz)] idx = x = y = cnt = 0 for j in range(sz): for i in range(sz): if pz[idx] == "x": p[i][j] = 0 cnt += 1 elif pz[idx] == "s": p[i][j] = 1 cnt += 1 x = i y = j idx += 1 if 1 == solve(p, sz, x, y, 2, cnt): for j in range(sz): for i in range(sz): if p[i][j] != -1: stdout.write(" {:0{}d}".format(p[i][j], 2)) else: stdout.write(" ") print() else: print("Cannot solve this puzzle!") find_solution(".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..", 8) print() find_solution(".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....", 13)
Write a version of this Java function in Python with identical behavior.
import java.util.Arrays; import java.util.BitSet; import org.apache.commons.lang3.ArrayUtils; public class OrderDisjointItems { public static void main(String[] args) { final String[][] MNs = {{"the cat sat on the mat", "mat cat"}, {"the cat sat on the mat", "cat mat"}, {"A B C A B C A B C", "C A C A"}, {"A B C A B D A B E", "E A D A"}, {"A B", "B"}, {"A B", "B A"}, {"A B B A", "B A"}, {"X X Y", "X"}}; for (String[] a : MNs) { String[] r = orderDisjointItems(a[0].split(" "), a[1].split(" ")); System.out.printf("%s | %s -> %s%n", a[0], a[1], Arrays.toString(r)); } } static String[] orderDisjointItems(String[] m, String[] n) { for (String e : n) { int idx = ArrayUtils.indexOf(m, e); if (idx != -1) m[idx] = null; } for (int i = 0, j = 0; i < m.length; i++) { if (m[i] == null) m[i] = n[j++]; } return m; } static String[] orderDisjointItems2(String[] m, String[] n) { BitSet bitSet = new BitSet(m.length); for (String e : n) { int idx = -1; do { idx = ArrayUtils.indexOf(m, e, idx + 1); } while (idx != -1 && bitSet.get(idx)); if (idx != -1) bitSet.set(idx); } for (int i = 0, j = 0; i < m.length; i++) { if (bitSet.get(i)) m[i] = n[j++]; } return m; } }
from __future__ import print_function def order_disjoint_list_items(data, items): itemindices = [] for item in set(items): itemcount = items.count(item) lastindex = [-1] for i in range(itemcount): lastindex.append(data.index(item, lastindex[-1] + 1)) itemindices += lastindex[1:] itemindices.sort() for index, item in zip(itemindices, items): data[index] = item if __name__ == '__main__': tostring = ' '.join for data, items in [ (str.split('the cat sat on the mat'), str.split('mat cat')), (str.split('the cat sat on the mat'), str.split('cat mat')), (list('ABCABCABC'), list('CACA')), (list('ABCABDABE'), list('EADA')), (list('AB'), list('B')), (list('AB'), list('BA')), (list('ABBA'), list('BA')), (list(''), list('')), (list('A'), list('A')), (list('AB'), list('')), (list('ABBA'), list('AB')), (list('ABAB'), list('AB')), (list('ABAB'), list('BABA')), (list('ABCCBA'), list('ACAC')), (list('ABCCBA'), list('CACA')), ]: print('Data M: %-24r Order N: %-9r' % (tostring(data), tostring(items)), end=' ') order_disjoint_list_items(data, items) print("-> M' %r" % tostring(data))
Port the provided Java code into Python while preserving the original functionality.
package rosettacode.heredoc; public class MainApp { public static void main(String[] args) { String hereDoc = """ This is a multiline string. It includes all of this text, but on separate lines in the code. """; System.out.println(hereDoc); } }
print()
Please provide an equivalent version of this Java code in Python.
package rosettacode.heredoc; public class MainApp { public static void main(String[] args) { String hereDoc = """ This is a multiline string. It includes all of this text, but on separate lines in the code. """; System.out.println(hereDoc); } }
print()
Write the same algorithm in Python as shown in this Java implementation.
import java.util.*; public class HashJoin { public static void main(String[] args) { String[][] table1 = {{"27", "Jonah"}, {"18", "Alan"}, {"28", "Glory"}, {"18", "Popeye"}, {"28", "Alan"}}; String[][] table2 = {{"Jonah", "Whales"}, {"Jonah", "Spiders"}, {"Alan", "Ghosts"}, {"Alan", "Zombies"}, {"Glory", "Buffy"}, {"Bob", "foo"}}; hashJoin(table1, 1, table2, 0).stream() .forEach(r -> System.out.println(Arrays.deepToString(r))); } static List<String[][]> hashJoin(String[][] records1, int idx1, String[][] records2, int idx2) { List<String[][]> result = new ArrayList<>(); Map<String, List<String[]>> map = new HashMap<>(); for (String[] record : records1) { List<String[]> v = map.getOrDefault(record[idx1], new ArrayList<>()); v.add(record); map.put(record[idx1], v); } for (String[] record : records2) { List<String[]> lst = map.get(record[idx2]); if (lst != null) { lst.stream().forEach(r -> { result.add(new String[][]{r, record}); }); } } return result; } }
from collections import defaultdict def hashJoin(table1, index1, table2, index2): h = defaultdict(list) for s in table1: h[s[index1]].append(s) return [(s, r) for r in table2 for s in h[r[index2]]] table1 = [(27, "Jonah"), (18, "Alan"), (28, "Glory"), (18, "Popeye"), (28, "Alan")] table2 = [("Jonah", "Whales"), ("Jonah", "Spiders"), ("Alan", "Ghosts"), ("Alan", "Zombies"), ("Glory", "Buffy")] for row in hashJoin(table1, 1, table2, 0): print(row)
Translate this program into Python but keep the logic exactly as in Java.
import java.io.*; public class SierpinskiCurve { public static void main(final String[] args) { try (Writer writer = new BufferedWriter(new FileWriter("sierpinski_curve.svg"))) { SierpinskiCurve s = new SierpinskiCurve(writer); s.currentAngle = 45; s.currentX = 5; s.currentY = 10; s.lineLength = 7; s.begin(545); s.execute(rewrite(5)); s.end(); } catch (final Exception ex) { ex.printStackTrace(); } } private SierpinskiCurve(final Writer writer) { this.writer = writer; } private void begin(final int size) throws IOException { write("<svg xmlns='http: write("<rect width='100%%' height='100%%' fill='white'/>\n"); write("<path stroke-width='1' stroke='black' fill='none' d='"); } private void end() throws IOException { write("'/>\n</svg>\n"); } private void execute(final String s) throws IOException { write("M%g,%g\n", currentX, currentY); for (int i = 0, n = s.length(); i < n; ++i) { switch (s.charAt(i)) { case 'F': case 'G': line(lineLength); break; case '+': turn(ANGLE); break; case '-': turn(-ANGLE); break; } } } private void line(final double length) throws IOException { final double theta = (Math.PI * currentAngle) / 180.0; currentX += length * Math.cos(theta); currentY -= length * Math.sin(theta); write("L%g,%g\n", currentX, currentY); } private void turn(final int angle) { currentAngle = (currentAngle + angle) % 360; } private void write(final String format, final Object... args) throws IOException { writer.write(String.format(format, args)); } private static String rewrite(final int order) { String s = AXIOM; for (int i = 0; i < order; ++i) { final StringBuilder sb = new StringBuilder(); for (int j = 0, n = s.length(); j < n; ++j) { final char ch = s.charAt(j); if (ch == 'X') sb.append(PRODUCTION); else sb.append(ch); } s = sb.toString(); } return s; } private final Writer writer; private double lineLength; private double currentX; private double currentY; private int currentAngle; private static final String AXIOM = "F--XF--F--XF"; private static final String PRODUCTION = "XF+G+XF--F--XF+G+X"; private static final int ANGLE = 45; }
import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import hsv_to_rgb as hsv def curve(axiom, rules, angle, depth): for _ in range(depth): axiom = ''.join(rules[c] if c in rules else c for c in axiom) a, x, y = 0, [0], [0] for c in axiom: match c: case '+': a += 1 case '-': a -= 1 case 'F' | 'G': x.append(x[-1] + np.cos(a*angle*np.pi/180)) y.append(y[-1] + np.sin(a*angle*np.pi/180)) l = len(x) for i in range(l - 1): plt.plot(x[i:i+2], y[i:i+2], color=hsv([i/l, 1, .7])) plt.gca().set_aspect(1) plt.show() curve('F--XF--F--XF', {'X': 'XF+G+XF--F--XF+G+X'}, 45, 5)
Rewrite this program in Python while keeping its functionality equivalent to the Java version.
import java.io.*; public class SierpinskiCurve { public static void main(final String[] args) { try (Writer writer = new BufferedWriter(new FileWriter("sierpinski_curve.svg"))) { SierpinskiCurve s = new SierpinskiCurve(writer); s.currentAngle = 45; s.currentX = 5; s.currentY = 10; s.lineLength = 7; s.begin(545); s.execute(rewrite(5)); s.end(); } catch (final Exception ex) { ex.printStackTrace(); } } private SierpinskiCurve(final Writer writer) { this.writer = writer; } private void begin(final int size) throws IOException { write("<svg xmlns='http: write("<rect width='100%%' height='100%%' fill='white'/>\n"); write("<path stroke-width='1' stroke='black' fill='none' d='"); } private void end() throws IOException { write("'/>\n</svg>\n"); } private void execute(final String s) throws IOException { write("M%g,%g\n", currentX, currentY); for (int i = 0, n = s.length(); i < n; ++i) { switch (s.charAt(i)) { case 'F': case 'G': line(lineLength); break; case '+': turn(ANGLE); break; case '-': turn(-ANGLE); break; } } } private void line(final double length) throws IOException { final double theta = (Math.PI * currentAngle) / 180.0; currentX += length * Math.cos(theta); currentY -= length * Math.sin(theta); write("L%g,%g\n", currentX, currentY); } private void turn(final int angle) { currentAngle = (currentAngle + angle) % 360; } private void write(final String format, final Object... args) throws IOException { writer.write(String.format(format, args)); } private static String rewrite(final int order) { String s = AXIOM; for (int i = 0; i < order; ++i) { final StringBuilder sb = new StringBuilder(); for (int j = 0, n = s.length(); j < n; ++j) { final char ch = s.charAt(j); if (ch == 'X') sb.append(PRODUCTION); else sb.append(ch); } s = sb.toString(); } return s; } private final Writer writer; private double lineLength; private double currentX; private double currentY; private int currentAngle; private static final String AXIOM = "F--XF--F--XF"; private static final String PRODUCTION = "XF+G+XF--F--XF+G+X"; private static final int ANGLE = 45; }
import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import hsv_to_rgb as hsv def curve(axiom, rules, angle, depth): for _ in range(depth): axiom = ''.join(rules[c] if c in rules else c for c in axiom) a, x, y = 0, [0], [0] for c in axiom: match c: case '+': a += 1 case '-': a -= 1 case 'F' | 'G': x.append(x[-1] + np.cos(a*angle*np.pi/180)) y.append(y[-1] + np.sin(a*angle*np.pi/180)) l = len(x) for i in range(l - 1): plt.plot(x[i:i+2], y[i:i+2], color=hsv([i/l, 1, .7])) plt.gca().set_aspect(1) plt.show() curve('F--XF--F--XF', {'X': 'XF+G+XF--F--XF+G+X'}, 45, 5)
Keep all operations the same but rewrite the snippet in Python.
import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.ArrayList; import java.util.List; import java.util.Map; public class SDF { public static HashMap<Character, Integer> countElementOcurrences(char[] array) { HashMap<Character, Integer> countMap = new HashMap<Character, Integer>(); for (char element : array) { Integer count = countMap.get(element); count = (count == null) ? 1 : count + 1; countMap.put(element, count); } return countMap; } private static <K, V extends Comparable<? super V>> HashMap<K, V> descendingSortByValues(HashMap<K, V> map) { List<Map.Entry<K, V>> list = new ArrayList<Map.Entry<K, V>>(map.entrySet()); Collections.sort(list, new Comparator<Map.Entry<K, V>>() { public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) { return o2.getValue().compareTo(o1.getValue()); } }); HashMap<K, V> sortedHashMap = new LinkedHashMap<K, V>(); for (Map.Entry<K, V> entry : list) { sortedHashMap.put(entry.getKey(), entry.getValue()); } return sortedHashMap; } public static String mostOcurrencesElement(char[] array, int k) { HashMap<Character, Integer> countMap = countElementOcurrences(array); System.out.println(countMap); Map<Character, Integer> map = descendingSortByValues(countMap); System.out.println(map); int i = 0; String output = ""; for (Map.Entry<Character, Integer> pairs : map.entrySet()) { if (i++ >= k) break; output += "" + pairs.getKey() + pairs.getValue(); } return output; } public static int getDiff(String str1, String str2, int limit) { int similarity = 0; int k = 0; for (int i = 0; i < str1.length() ; i = k) { k ++; if (Character.isLetter(str1.charAt(i))) { int pos = str2.indexOf(str1.charAt(i)); if (pos >= 0) { String digitStr1 = ""; while ( k < str1.length() && !Character.isLetter(str1.charAt(k))) { digitStr1 += str1.charAt(k); k++; } int k2 = pos+1; String digitStr2 = ""; while (k2 < str2.length() && !Character.isLetter(str2.charAt(k2)) ) { digitStr2 += str2.charAt(k2); k2++; } similarity += Integer.parseInt(digitStr2) + Integer.parseInt(digitStr1); } } } return Math.abs(limit - similarity); } public static int SDFfunc(String str1, String str2, int limit) { return getDiff(mostOcurrencesElement(str1.toCharArray(), 2), mostOcurrencesElement(str2.toCharArray(), 2), limit); } public static void main(String[] args) { String input1 = "LCLYTHIGRNIYYGSYLYSETWNTGIMLLLITMATAFMGYVLPWGQMSFWGATVITNLFSAIPYIGTNLV"; String input2 = "EWIWGGFSVDKATLNRFFAFHFILPFTMVALAGVHLTFLHETGSNNPLGLTSDSDKIPFHPYYTIKDFLG"; System.out.println(SDF.SDFfunc(input1,input2,100)); } }
import collections def MostFreqKHashing(inputString, K): occuDict = collections.defaultdict(int) for c in inputString: occuDict[c] += 1 occuList = sorted(occuDict.items(), key = lambda x: x[1], reverse = True) outputStr = ''.join(c + str(cnt) for c, cnt in occuList[:K]) return outputStr def MostFreqKSimilarity(inputStr1, inputStr2): similarity = 0 for i in range(0, len(inputStr1), 2): c = inputStr1[i] cnt1 = int(inputStr1[i + 1]) for j in range(0, len(inputStr2), 2): if inputStr2[j] == c: cnt2 = int(inputStr2[j + 1]) similarity += cnt1 + cnt2 break return similarity def MostFreqKSDF(inputStr1, inputStr2, K, maxDistance): return maxDistance - MostFreqKSimilarity(MostFreqKHashing(inputStr1,K), MostFreqKHashing(inputStr2,K))
Change the following Java code into Python without altering its purpose.
import java.util.Scanner; public class Pigdice { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int players = 0; while(true) { System.out.println("Hello, welcome to Pig Dice the game! How many players? "); if(scan.hasNextInt()) { int nextInt = scan.nextInt(); if(nextInt > 0) { players = nextInt; break; } } else { System.out.println("That wasn't an integer. Try again. \n"); scan.next(); } } System.out.println("Alright, starting with " + players + " players. \n"); play(players, scan); scan.close(); } public static void play(int group, Scanner scan) { final int STRATEGIES = 5; Dice dice = new Dice(); Player[] players = new Player[group]; for(int count = 0; count < group; count++) { players[count] = new Player(count); System.out.println("Player " + players[count].getNumber() + " is alive! "); } System.out.println("Each strategy is numbered 0 - " + (STRATEGIES - 1) + ". They are as follows: "); System.out.println(">> Enter '0' for a human player. "); System.out.println(">> Strategy 1 is a basic strategy where the AI rolls until 20+ points and holds unless the current max is 75+."); System.out.println(">> Strategy 2 is a basic strategy where the AI, after 3 successful rolls, will randomly decide to roll or hold. "); System.out.println(">> Strategy 3 is similar to strategy 2, except it's a little gutsier and will attempt 5 successful rolls. "); System.out.println(">> Strategy 4 is like a mix between strategies 1 and 3. After turn points are >= 20 and while max points are still less than 75, it will randomly hold or roll. "); for(Player player : players) { System.out.println("\nWhat strategy would you like player " + player.getNumber() + " to use? "); while(true) { if(scan.hasNextInt()) { int nextInt = scan.nextInt(); if (nextInt < Strategy.STRATEGIES.length) { player.setStrategy(Strategy.STRATEGIES[nextInt]); break; } } else { System.out.println("That wasn't an option. Try again. "); scan.next(); } } } int max = 0; while(max < 100) { for(Player player : players) { System.out.println(">> Beginning Player " + player.getNumber() + "'s turn. "); player.setTurnPoints(0); player.setMax(max); while(true) { Move choice = player.choose(); if(choice == Move.ROLL) { int roll = dice.roll(); System.out.println(" A " + roll + " was rolled. "); player.setTurnPoints(player.getTurnPoints() + roll); player.incIter(); if(roll == 1) { player.setTurnPoints(0); break; } } else { System.out.println(" The player has held. "); break; } } player.addPoints(player.getTurnPoints()); System.out.println(" Player " + player.getNumber() + "'s turn is now over. Their total is " + player.getPoints() + ". \n"); player.resetIter(); if(max < player.getPoints()) { max = player.getPoints(); } if(max >= 100) { System.out.println("Player " + player.getNumber() + " wins with " + max + " points! End scores: "); for(Player p : players) { System.out.println("Player " + p.getNumber() + " had " + p.getPoints() + " points. "); } break; } } } } }
from random import randint from collections import namedtuple import random from pprint import pprint as pp from collections import Counter playercount = 2 maxscore = 100 maxgames = 100000 Game = namedtuple('Game', 'players, maxscore, rounds') Round = namedtuple('Round', 'who, start, scores, safe') class Player(): def __init__(self, player_index): self.player_index = player_index def __repr__(self): return '%s(%i)' % (self.__class__.__name__, self.player_index) def __call__(self, safescore, scores, game): 'Returns boolean True to roll again' pass class RandPlay(Player): def __call__(self, safe, scores, game): 'Returns random boolean choice of whether to roll again' return bool(random.randint(0, 1)) class RollTo20(Player): def __call__(self, safe, scores, game): 'Roll again if this rounds score < 20' return (((sum(scores) + safe[self.player_index]) < maxscore) and(sum(scores) < 20)) class Desparat(Player): def __call__(self, safe, scores, game): 'Roll again if this rounds score < 20 or someone is within 20 of winning' return (((sum(scores) + safe[self.player_index]) < maxscore) and( (sum(scores) < 20) or max(safe) >= (maxscore - 20))) def game__str__(self): 'Pretty printer for Game class' return ("Game(players=%r, maxscore=%i,\n rounds=[\n %s\n ])" % (self.players, self.maxscore, ',\n '.join(repr(round) for round in self.rounds))) Game.__str__ = game__str__ def winningorder(players, safescores): 'Return (players in winning order, their scores)' return tuple(zip(*sorted(zip(players, safescores), key=lambda x: x[1], reverse=True))) def playpig(game): players, maxscore, rounds = game playercount = len(players) safescore = [0] * playercount player = 0 scores=[] while max(safescore) < maxscore: startscore = safescore[player] rolling = players[player](safescore, scores, game) if rolling: rolled = randint(1, 6) scores.append(rolled) if rolled == 1: round = Round(who=players[player], start=startscore, scores=scores, safe=safescore[player]) rounds.append(round) scores, player = [], (player + 1) % playercount else: safescore[player] += sum(scores) round = Round(who=players[player], start=startscore, scores=scores, safe=safescore[player]) rounds.append(round) if safescore[player] >= maxscore: break scores, player = [], (player + 1) % playercount return winningorder(players, safescore) if __name__ == '__main__': game = Game(players=tuple(RandPlay(i) for i in range(playercount)), maxscore=20, rounds=[]) print('ONE GAME') print('Winning order: %r; Respective scores: %r\n' % playpig(game)) print(game) game = Game(players=tuple(RandPlay(i) for i in range(playercount)), maxscore=maxscore, rounds=[]) algos = (RollTo20, RandPlay, Desparat) print('\n\nMULTIPLE STATISTICS using %r\n for %i GAMES' % (', '.join(p.__name__ for p in algos), maxgames,)) winners = Counter(repr(playpig(game._replace(players=tuple(random.choice(algos)(i) for i in range(playercount)), rounds=[]))[0]) for i in range(maxgames)) print(' Players(position) winning on left; occurrences on right:\n %s' % ',\n '.join(str(w) for w in winners.most_common()))
Convert this Java snippet to Python and keep its semantics consistent.
import java.util.Scanner; public class Pigdice { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int players = 0; while(true) { System.out.println("Hello, welcome to Pig Dice the game! How many players? "); if(scan.hasNextInt()) { int nextInt = scan.nextInt(); if(nextInt > 0) { players = nextInt; break; } } else { System.out.println("That wasn't an integer. Try again. \n"); scan.next(); } } System.out.println("Alright, starting with " + players + " players. \n"); play(players, scan); scan.close(); } public static void play(int group, Scanner scan) { final int STRATEGIES = 5; Dice dice = new Dice(); Player[] players = new Player[group]; for(int count = 0; count < group; count++) { players[count] = new Player(count); System.out.println("Player " + players[count].getNumber() + " is alive! "); } System.out.println("Each strategy is numbered 0 - " + (STRATEGIES - 1) + ". They are as follows: "); System.out.println(">> Enter '0' for a human player. "); System.out.println(">> Strategy 1 is a basic strategy where the AI rolls until 20+ points and holds unless the current max is 75+."); System.out.println(">> Strategy 2 is a basic strategy where the AI, after 3 successful rolls, will randomly decide to roll or hold. "); System.out.println(">> Strategy 3 is similar to strategy 2, except it's a little gutsier and will attempt 5 successful rolls. "); System.out.println(">> Strategy 4 is like a mix between strategies 1 and 3. After turn points are >= 20 and while max points are still less than 75, it will randomly hold or roll. "); for(Player player : players) { System.out.println("\nWhat strategy would you like player " + player.getNumber() + " to use? "); while(true) { if(scan.hasNextInt()) { int nextInt = scan.nextInt(); if (nextInt < Strategy.STRATEGIES.length) { player.setStrategy(Strategy.STRATEGIES[nextInt]); break; } } else { System.out.println("That wasn't an option. Try again. "); scan.next(); } } } int max = 0; while(max < 100) { for(Player player : players) { System.out.println(">> Beginning Player " + player.getNumber() + "'s turn. "); player.setTurnPoints(0); player.setMax(max); while(true) { Move choice = player.choose(); if(choice == Move.ROLL) { int roll = dice.roll(); System.out.println(" A " + roll + " was rolled. "); player.setTurnPoints(player.getTurnPoints() + roll); player.incIter(); if(roll == 1) { player.setTurnPoints(0); break; } } else { System.out.println(" The player has held. "); break; } } player.addPoints(player.getTurnPoints()); System.out.println(" Player " + player.getNumber() + "'s turn is now over. Their total is " + player.getPoints() + ". \n"); player.resetIter(); if(max < player.getPoints()) { max = player.getPoints(); } if(max >= 100) { System.out.println("Player " + player.getNumber() + " wins with " + max + " points! End scores: "); for(Player p : players) { System.out.println("Player " + p.getNumber() + " had " + p.getPoints() + " points. "); } break; } } } } }
from random import randint from collections import namedtuple import random from pprint import pprint as pp from collections import Counter playercount = 2 maxscore = 100 maxgames = 100000 Game = namedtuple('Game', 'players, maxscore, rounds') Round = namedtuple('Round', 'who, start, scores, safe') class Player(): def __init__(self, player_index): self.player_index = player_index def __repr__(self): return '%s(%i)' % (self.__class__.__name__, self.player_index) def __call__(self, safescore, scores, game): 'Returns boolean True to roll again' pass class RandPlay(Player): def __call__(self, safe, scores, game): 'Returns random boolean choice of whether to roll again' return bool(random.randint(0, 1)) class RollTo20(Player): def __call__(self, safe, scores, game): 'Roll again if this rounds score < 20' return (((sum(scores) + safe[self.player_index]) < maxscore) and(sum(scores) < 20)) class Desparat(Player): def __call__(self, safe, scores, game): 'Roll again if this rounds score < 20 or someone is within 20 of winning' return (((sum(scores) + safe[self.player_index]) < maxscore) and( (sum(scores) < 20) or max(safe) >= (maxscore - 20))) def game__str__(self): 'Pretty printer for Game class' return ("Game(players=%r, maxscore=%i,\n rounds=[\n %s\n ])" % (self.players, self.maxscore, ',\n '.join(repr(round) for round in self.rounds))) Game.__str__ = game__str__ def winningorder(players, safescores): 'Return (players in winning order, their scores)' return tuple(zip(*sorted(zip(players, safescores), key=lambda x: x[1], reverse=True))) def playpig(game): players, maxscore, rounds = game playercount = len(players) safescore = [0] * playercount player = 0 scores=[] while max(safescore) < maxscore: startscore = safescore[player] rolling = players[player](safescore, scores, game) if rolling: rolled = randint(1, 6) scores.append(rolled) if rolled == 1: round = Round(who=players[player], start=startscore, scores=scores, safe=safescore[player]) rounds.append(round) scores, player = [], (player + 1) % playercount else: safescore[player] += sum(scores) round = Round(who=players[player], start=startscore, scores=scores, safe=safescore[player]) rounds.append(round) if safescore[player] >= maxscore: break scores, player = [], (player + 1) % playercount return winningorder(players, safescore) if __name__ == '__main__': game = Game(players=tuple(RandPlay(i) for i in range(playercount)), maxscore=20, rounds=[]) print('ONE GAME') print('Winning order: %r; Respective scores: %r\n' % playpig(game)) print(game) game = Game(players=tuple(RandPlay(i) for i in range(playercount)), maxscore=maxscore, rounds=[]) algos = (RollTo20, RandPlay, Desparat) print('\n\nMULTIPLE STATISTICS using %r\n for %i GAMES' % (', '.join(p.__name__ for p in algos), maxgames,)) winners = Counter(repr(playpig(game._replace(players=tuple(random.choice(algos)(i) for i in range(playercount)), rounds=[]))[0]) for i in range(maxgames)) print(' Players(position) winning on left; occurrences on right:\n %s' % ',\n '.join(str(w) for w in winners.most_common()))
Port the following code from Java to Python with equivalent syntax and logic.
import java.math.BigInteger; import java.util.*; public class Lychrel { static Map<BigInteger, Tuple> cache = new HashMap<>(); static class Tuple { final Boolean flag; final BigInteger bi; Tuple(boolean f, BigInteger b) { flag = f; bi = b; } } static BigInteger rev(BigInteger bi) { String s = new StringBuilder(bi.toString()).reverse().toString(); return new BigInteger(s); } static Tuple lychrel(BigInteger n) { Tuple res; if ((res = cache.get(n)) != null) return res; BigInteger r = rev(n); res = new Tuple(true, n); List<BigInteger> seen = new ArrayList<>(); for (int i = 0; i < 500; i++) { n = n.add(r); r = rev(n); if (n.equals(r)) { res = new Tuple(false, BigInteger.ZERO); break; } if (cache.containsKey(n)) { res = cache.get(n); break; } seen.add(n); } for (BigInteger bi : seen) cache.put(bi, res); return res; } public static void main(String[] args) { List<BigInteger> seeds = new ArrayList<>(); List<BigInteger> related = new ArrayList<>(); List<BigInteger> palin = new ArrayList<>(); for (int i = 1; i <= 10_000; i++) { BigInteger n = BigInteger.valueOf(i); Tuple t = lychrel(n); if (!t.flag) continue; if (n.equals(t.bi)) seeds.add(t.bi); else related.add(t.bi); if (n.equals(t.bi)) palin.add(t.bi); } System.out.printf("%d Lychrel seeds: %s%n", seeds.size(), seeds); System.out.printf("%d Lychrel related%n", related.size()); System.out.printf("%d Lychrel palindromes: %s%n", palin.size(), palin); } }
from __future__ import print_function def add_reverse(num, max_iter=1000): i, nums = 0, {num} while True: i, num = i+1, num + reverse_int(num) nums.add(num) if reverse_int(num) == num or i >= max_iter: break return nums def reverse_int(num): return int(str(num)[::-1]) def split_roots_from_relateds(roots_and_relateds): roots = roots_and_relateds[::] i = 1 while i < len(roots): this = roots[i] if any(this.intersection(prev) for prev in roots[:i]): del roots[i] else: i += 1 root = [min(each_set) for each_set in roots] related = [min(each_set) for each_set in roots_and_relateds] related = [n for n in related if n not in root] return root, related def find_lychrel(maxn, max_reversions): 'Lychrel number generator' series = [add_reverse(n, max_reversions*2) for n in range(1, maxn + 1)] roots_and_relateds = [s for s in series if len(s) > max_reversions] return split_roots_from_relateds(roots_and_relateds) if __name__ == '__main__': maxn, reversion_limit = 10000, 500 print("Calculations using n = 1..%i and limiting each search to 2*%i reverse-digits-and-adds" % (maxn, reversion_limit)) lychrel, l_related = find_lychrel(maxn, reversion_limit) print(' Number of Lychrel numbers:', len(lychrel)) print(' Lychrel numbers:', ', '.join(str(n) for n in lychrel)) print(' Number of Lychrel related:', len(l_related)) pals = [x for x in lychrel + l_related if x == reverse_int(x)] print(' Number of Lychrel palindromes:', len(pals)) print(' Lychrel palindromes:', ', '.join(str(n) for n in pals))
Change the following Java code into Python without altering its purpose.
import java.math.BigInteger; import java.util.*; public class Lychrel { static Map<BigInteger, Tuple> cache = new HashMap<>(); static class Tuple { final Boolean flag; final BigInteger bi; Tuple(boolean f, BigInteger b) { flag = f; bi = b; } } static BigInteger rev(BigInteger bi) { String s = new StringBuilder(bi.toString()).reverse().toString(); return new BigInteger(s); } static Tuple lychrel(BigInteger n) { Tuple res; if ((res = cache.get(n)) != null) return res; BigInteger r = rev(n); res = new Tuple(true, n); List<BigInteger> seen = new ArrayList<>(); for (int i = 0; i < 500; i++) { n = n.add(r); r = rev(n); if (n.equals(r)) { res = new Tuple(false, BigInteger.ZERO); break; } if (cache.containsKey(n)) { res = cache.get(n); break; } seen.add(n); } for (BigInteger bi : seen) cache.put(bi, res); return res; } public static void main(String[] args) { List<BigInteger> seeds = new ArrayList<>(); List<BigInteger> related = new ArrayList<>(); List<BigInteger> palin = new ArrayList<>(); for (int i = 1; i <= 10_000; i++) { BigInteger n = BigInteger.valueOf(i); Tuple t = lychrel(n); if (!t.flag) continue; if (n.equals(t.bi)) seeds.add(t.bi); else related.add(t.bi); if (n.equals(t.bi)) palin.add(t.bi); } System.out.printf("%d Lychrel seeds: %s%n", seeds.size(), seeds); System.out.printf("%d Lychrel related%n", related.size()); System.out.printf("%d Lychrel palindromes: %s%n", palin.size(), palin); } }
from __future__ import print_function def add_reverse(num, max_iter=1000): i, nums = 0, {num} while True: i, num = i+1, num + reverse_int(num) nums.add(num) if reverse_int(num) == num or i >= max_iter: break return nums def reverse_int(num): return int(str(num)[::-1]) def split_roots_from_relateds(roots_and_relateds): roots = roots_and_relateds[::] i = 1 while i < len(roots): this = roots[i] if any(this.intersection(prev) for prev in roots[:i]): del roots[i] else: i += 1 root = [min(each_set) for each_set in roots] related = [min(each_set) for each_set in roots_and_relateds] related = [n for n in related if n not in root] return root, related def find_lychrel(maxn, max_reversions): 'Lychrel number generator' series = [add_reverse(n, max_reversions*2) for n in range(1, maxn + 1)] roots_and_relateds = [s for s in series if len(s) > max_reversions] return split_roots_from_relateds(roots_and_relateds) if __name__ == '__main__': maxn, reversion_limit = 10000, 500 print("Calculations using n = 1..%i and limiting each search to 2*%i reverse-digits-and-adds" % (maxn, reversion_limit)) lychrel, l_related = find_lychrel(maxn, reversion_limit) print(' Number of Lychrel numbers:', len(lychrel)) print(' Lychrel numbers:', ', '.join(str(n) for n in lychrel)) print(' Number of Lychrel related:', len(l_related)) pals = [x for x in lychrel + l_related if x == reverse_int(x)] print(' Number of Lychrel palindromes:', len(pals)) print(' Lychrel palindromes:', ', '.join(str(n) for n in pals))
Generate an equivalent Python version of this Java code.
import java.io.*; public class SierpinskiSquareCurve { public static void main(final String[] args) { try (Writer writer = new BufferedWriter(new FileWriter("sierpinski_square.svg"))) { SierpinskiSquareCurve s = new SierpinskiSquareCurve(writer); int size = 635, length = 5; s.currentAngle = 0; s.currentX = (size - length)/2; s.currentY = length; s.lineLength = length; s.begin(size); s.execute(rewrite(5)); s.end(); } catch (final Exception ex) { ex.printStackTrace(); } } private SierpinskiSquareCurve(final Writer writer) { this.writer = writer; } private void begin(final int size) throws IOException { write("<svg xmlns='http: write("<rect width='100%%' height='100%%' fill='white'/>\n"); write("<path stroke-width='1' stroke='black' fill='none' d='"); } private void end() throws IOException { write("'/>\n</svg>\n"); } private void execute(final String s) throws IOException { write("M%g,%g\n", currentX, currentY); for (int i = 0, n = s.length(); i < n; ++i) { switch (s.charAt(i)) { case 'F': line(lineLength); break; case '+': turn(ANGLE); break; case '-': turn(-ANGLE); break; } } } private void line(final double length) throws IOException { final double theta = (Math.PI * currentAngle) / 180.0; currentX += length * Math.cos(theta); currentY += length * Math.sin(theta); write("L%g,%g\n", currentX, currentY); } private void turn(final int angle) { currentAngle = (currentAngle + angle) % 360; } private void write(final String format, final Object... args) throws IOException { writer.write(String.format(format, args)); } private static String rewrite(final int order) { String s = AXIOM; for (int i = 0; i < order; ++i) { final StringBuilder sb = new StringBuilder(); for (int j = 0, n = s.length(); j < n; ++j) { final char ch = s.charAt(j); if (ch == 'X') sb.append(PRODUCTION); else sb.append(ch); } s = sb.toString(); } return s; } private final Writer writer; private double lineLength; private double currentX; private double currentY; private int currentAngle; private static final String AXIOM = "F+XF+F+XF"; private static final String PRODUCTION = "XF-F+F-XF+F+XF-F+F-X"; private static final int ANGLE = 90; }
import matplotlib.pyplot as plt import math def nextPoint(x, y, angle): a = math.pi * angle / 180 x2 = (int)(round(x + (1 * math.cos(a)))) y2 = (int)(round(y + (1 * math.sin(a)))) return x2, y2 def expand(axiom, rules, level): for l in range(0, level): a2 = "" for c in axiom: if c in rules: a2 += rules[c] else: a2 += c axiom = a2 return axiom def draw_lsystem(axiom, rules, angle, iterations): xp = [1] yp = [1] direction = 0 for c in expand(axiom, rules, iterations): if c == "F": xn, yn = nextPoint(xp[-1], yp[-1], direction) xp.append(xn) yp.append(yn) elif c == "-": direction = direction - angle if direction < 0: direction = 360 + direction elif c == "+": direction = (direction + angle) % 360 plt.plot(xp, yp) plt.show() if __name__ == '__main__': s_axiom = "F+XF+F+XF" s_rules = {"X": "XF-F+F-XF+F+XF-F+F-X"} s_angle = 90 draw_lsystem(s_axiom, s_rules, s_angle, 3)
Produce a language-to-language conversion: from Java to Python, same semantics.
import java.math.BigInteger; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; public class PowerfulNumbers { public static void main(String[] args) { System.out.printf("Task: For k = 2..10, generate the set of k-powerful numbers <= 10^k and show the first 5 and the last 5 terms, along with the length of the set%n"); for ( int k = 2 ; k <= 10 ; k++ ) { BigInteger max = BigInteger.valueOf(10).pow(k); List<BigInteger> powerfulNumbers = getPowerFulNumbers(max, k); System.out.printf("There are %d %d-powerful numbers between 1 and %d. %nList: %s%n", powerfulNumbers.size(), k, max, getList(powerfulNumbers)); } System.out.printf("%nTask: For k = 2..10, show the number of k-powerful numbers less than or equal to 10^j, for 0 <= j < k+10%n"); for ( int k = 2 ; k <= 10 ; k++ ) { List<Integer> powCount = new ArrayList<>(); for ( int j = 0 ; j < k+10 ; j++ ) { BigInteger max = BigInteger.valueOf(10).pow(j); powCount.add(countPowerFulNumbers(max, k)); } System.out.printf("Count of %2d-powerful numbers <= 10^j, j in [0, %d]: %s%n", k, k+9, powCount); } } private static String getList(List<BigInteger> list) { StringBuilder sb = new StringBuilder(); sb.append(list.subList(0, 5).toString().replace("]", "")); sb.append(" ... "); sb.append(list.subList(list.size()-5, list.size()).toString().replace("[", "")); return sb.toString(); } private static int countPowerFulNumbers(BigInteger max, int k) { return potentialPowerful(max, k).size(); } private static List<BigInteger> getPowerFulNumbers(BigInteger max, int k) { List<BigInteger> powerfulNumbers = new ArrayList<>(potentialPowerful(max, k)); Collections.sort(powerfulNumbers); return powerfulNumbers; } private static Set<BigInteger> potentialPowerful(BigInteger max, int k) { int[] indexes = new int[k]; for ( int i = 0 ; i < k ; i++ ) { indexes[i] = 1; } Set<BigInteger> powerful = new HashSet<>(); boolean foundPower = true; while ( foundPower ) { boolean genPowerful = false; for ( int index = 0 ; index < k ; index++ ) { BigInteger power = BigInteger.ONE; for ( int i = 0 ; i < k ; i++ ) { power = power.multiply(BigInteger.valueOf(indexes[i]).pow(k+i)); } if ( power.compareTo(max) <= 0 ) { powerful.add(power); indexes[0] += 1; genPowerful = true; break; } else { indexes[index] = 1; if ( index < k-1 ) { indexes[index+1] += 1; } } } if ( ! genPowerful ) { foundPower = false; } } return powerful; } }
from primesieve import primes import math def primepowers(k, upper_bound): ub = int(math.pow(upper_bound, 1/k) + .5) res = [(1,)] for p in primes(ub): a = [p**k] u = upper_bound // a[-1] while u >= p: a.append(a[-1]*p) u //= p res.append(tuple(a)) return res def kpowerful(k, upper_bound, count_only=True): ps = primepowers(k, upper_bound) def accu(i, ub): c = 0 if count_only else [] for p in ps[i]: u = ub//p if not u: break c += 1 if count_only else [p] for j in range(i + 1, len(ps)): if u < ps[j][0]: break c += accu(j, u) if count_only else [p*x for x in accu(j, u)] return c res = accu(0, upper_bound) return res if count_only else sorted(res) for k in range(2, 11): res = kpowerful(k, 10**k, count_only=False) print(f'{len(res)} {k}-powerfuls up to 10^{k}:', ' '.join(str(x) for x in res[:5]), '...', ' '.join(str(x) for x in res[-5:]) ) for k in range(2, 11): res = [kpowerful(k, 10**n) for n in range(k+10)] print(f'{k}-powerful up to 10^{k+10}:', ' '.join(str(x) for x in res))
Ensure the translated Python code behaves exactly like the original Java snippet.
import java.math.BigInteger; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; public class PowerfulNumbers { public static void main(String[] args) { System.out.printf("Task: For k = 2..10, generate the set of k-powerful numbers <= 10^k and show the first 5 and the last 5 terms, along with the length of the set%n"); for ( int k = 2 ; k <= 10 ; k++ ) { BigInteger max = BigInteger.valueOf(10).pow(k); List<BigInteger> powerfulNumbers = getPowerFulNumbers(max, k); System.out.printf("There are %d %d-powerful numbers between 1 and %d. %nList: %s%n", powerfulNumbers.size(), k, max, getList(powerfulNumbers)); } System.out.printf("%nTask: For k = 2..10, show the number of k-powerful numbers less than or equal to 10^j, for 0 <= j < k+10%n"); for ( int k = 2 ; k <= 10 ; k++ ) { List<Integer> powCount = new ArrayList<>(); for ( int j = 0 ; j < k+10 ; j++ ) { BigInteger max = BigInteger.valueOf(10).pow(j); powCount.add(countPowerFulNumbers(max, k)); } System.out.printf("Count of %2d-powerful numbers <= 10^j, j in [0, %d]: %s%n", k, k+9, powCount); } } private static String getList(List<BigInteger> list) { StringBuilder sb = new StringBuilder(); sb.append(list.subList(0, 5).toString().replace("]", "")); sb.append(" ... "); sb.append(list.subList(list.size()-5, list.size()).toString().replace("[", "")); return sb.toString(); } private static int countPowerFulNumbers(BigInteger max, int k) { return potentialPowerful(max, k).size(); } private static List<BigInteger> getPowerFulNumbers(BigInteger max, int k) { List<BigInteger> powerfulNumbers = new ArrayList<>(potentialPowerful(max, k)); Collections.sort(powerfulNumbers); return powerfulNumbers; } private static Set<BigInteger> potentialPowerful(BigInteger max, int k) { int[] indexes = new int[k]; for ( int i = 0 ; i < k ; i++ ) { indexes[i] = 1; } Set<BigInteger> powerful = new HashSet<>(); boolean foundPower = true; while ( foundPower ) { boolean genPowerful = false; for ( int index = 0 ; index < k ; index++ ) { BigInteger power = BigInteger.ONE; for ( int i = 0 ; i < k ; i++ ) { power = power.multiply(BigInteger.valueOf(indexes[i]).pow(k+i)); } if ( power.compareTo(max) <= 0 ) { powerful.add(power); indexes[0] += 1; genPowerful = true; break; } else { indexes[index] = 1; if ( index < k-1 ) { indexes[index+1] += 1; } } } if ( ! genPowerful ) { foundPower = false; } } return powerful; } }
from primesieve import primes import math def primepowers(k, upper_bound): ub = int(math.pow(upper_bound, 1/k) + .5) res = [(1,)] for p in primes(ub): a = [p**k] u = upper_bound // a[-1] while u >= p: a.append(a[-1]*p) u //= p res.append(tuple(a)) return res def kpowerful(k, upper_bound, count_only=True): ps = primepowers(k, upper_bound) def accu(i, ub): c = 0 if count_only else [] for p in ps[i]: u = ub//p if not u: break c += 1 if count_only else [p] for j in range(i + 1, len(ps)): if u < ps[j][0]: break c += accu(j, u) if count_only else [p*x for x in accu(j, u)] return c res = accu(0, upper_bound) return res if count_only else sorted(res) for k in range(2, 11): res = kpowerful(k, 10**k, count_only=False) print(f'{len(res)} {k}-powerfuls up to 10^{k}:', ' '.join(str(x) for x in res[:5]), '...', ' '.join(str(x) for x in res[-5:]) ) for k in range(2, 11): res = [kpowerful(k, 10**n) for n in range(k+10)] print(f'{k}-powerful up to 10^{k+10}:', ' '.join(str(x) for x in res))
Generate a Python translation of this Java snippet without changing its computational steps.
import java.math.BigInteger; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; public class PowerfulNumbers { public static void main(String[] args) { System.out.printf("Task: For k = 2..10, generate the set of k-powerful numbers <= 10^k and show the first 5 and the last 5 terms, along with the length of the set%n"); for ( int k = 2 ; k <= 10 ; k++ ) { BigInteger max = BigInteger.valueOf(10).pow(k); List<BigInteger> powerfulNumbers = getPowerFulNumbers(max, k); System.out.printf("There are %d %d-powerful numbers between 1 and %d. %nList: %s%n", powerfulNumbers.size(), k, max, getList(powerfulNumbers)); } System.out.printf("%nTask: For k = 2..10, show the number of k-powerful numbers less than or equal to 10^j, for 0 <= j < k+10%n"); for ( int k = 2 ; k <= 10 ; k++ ) { List<Integer> powCount = new ArrayList<>(); for ( int j = 0 ; j < k+10 ; j++ ) { BigInteger max = BigInteger.valueOf(10).pow(j); powCount.add(countPowerFulNumbers(max, k)); } System.out.printf("Count of %2d-powerful numbers <= 10^j, j in [0, %d]: %s%n", k, k+9, powCount); } } private static String getList(List<BigInteger> list) { StringBuilder sb = new StringBuilder(); sb.append(list.subList(0, 5).toString().replace("]", "")); sb.append(" ... "); sb.append(list.subList(list.size()-5, list.size()).toString().replace("[", "")); return sb.toString(); } private static int countPowerFulNumbers(BigInteger max, int k) { return potentialPowerful(max, k).size(); } private static List<BigInteger> getPowerFulNumbers(BigInteger max, int k) { List<BigInteger> powerfulNumbers = new ArrayList<>(potentialPowerful(max, k)); Collections.sort(powerfulNumbers); return powerfulNumbers; } private static Set<BigInteger> potentialPowerful(BigInteger max, int k) { int[] indexes = new int[k]; for ( int i = 0 ; i < k ; i++ ) { indexes[i] = 1; } Set<BigInteger> powerful = new HashSet<>(); boolean foundPower = true; while ( foundPower ) { boolean genPowerful = false; for ( int index = 0 ; index < k ; index++ ) { BigInteger power = BigInteger.ONE; for ( int i = 0 ; i < k ; i++ ) { power = power.multiply(BigInteger.valueOf(indexes[i]).pow(k+i)); } if ( power.compareTo(max) <= 0 ) { powerful.add(power); indexes[0] += 1; genPowerful = true; break; } else { indexes[index] = 1; if ( index < k-1 ) { indexes[index+1] += 1; } } } if ( ! genPowerful ) { foundPower = false; } } return powerful; } }
from primesieve import primes import math def primepowers(k, upper_bound): ub = int(math.pow(upper_bound, 1/k) + .5) res = [(1,)] for p in primes(ub): a = [p**k] u = upper_bound // a[-1] while u >= p: a.append(a[-1]*p) u //= p res.append(tuple(a)) return res def kpowerful(k, upper_bound, count_only=True): ps = primepowers(k, upper_bound) def accu(i, ub): c = 0 if count_only else [] for p in ps[i]: u = ub//p if not u: break c += 1 if count_only else [p] for j in range(i + 1, len(ps)): if u < ps[j][0]: break c += accu(j, u) if count_only else [p*x for x in accu(j, u)] return c res = accu(0, upper_bound) return res if count_only else sorted(res) for k in range(2, 11): res = kpowerful(k, 10**k, count_only=False) print(f'{len(res)} {k}-powerfuls up to 10^{k}:', ' '.join(str(x) for x in res[:5]), '...', ' '.join(str(x) for x in res[-5:]) ) for k in range(2, 11): res = [kpowerful(k, 10**n) for n in range(k+10)] print(f'{k}-powerful up to 10^{k+10}:', ' '.join(str(x) for x in res))
Translate this program into Python but keep the logic exactly as in Java.
import java.util.Arrays; public class Test { public static void main(String[] args) { int[] N = {1, -12, 0, -42}; int[] D = {1, -3}; System.out.printf("%s / %s = %s", Arrays.toString(N), Arrays.toString(D), Arrays.deepToString(extendedSyntheticDivision(N, D))); } static int[][] extendedSyntheticDivision(int[] dividend, int[] divisor) { int[] out = dividend.clone(); int normalizer = divisor[0]; for (int i = 0; i < dividend.length - (divisor.length - 1); i++) { out[i] /= normalizer; int coef = out[i]; if (coef != 0) { for (int j = 1; j < divisor.length; j++) out[i + j] += -divisor[j] * coef; } } int separator = out.length - (divisor.length - 1); return new int[][]{ Arrays.copyOfRange(out, 0, separator), Arrays.copyOfRange(out, separator, out.length) }; } }
from __future__ import print_function from __future__ import division def extended_synthetic_division(dividend, divisor): out = list(dividend) normalizer = divisor[0] for i in xrange(len(dividend)-(len(divisor)-1)): out[i] /= normalizer coef = out[i] if coef != 0: for j in xrange(1, len(divisor)): out[i + j] += -divisor[j] * coef separator = -(len(divisor)-1) return out[:separator], out[separator:] if __name__ == '__main__': print("POLYNOMIAL SYNTHETIC DIVISION") N = [1, -12, 0, -42] D = [1, -3] print(" %s / %s =" % (N,D), " %s remainder %s" % extended_synthetic_division(N, D))
Produce a functionally identical Python code for the snippet given in Java.
import java.util.Arrays; public class Test { public static void main(String[] args) { int[] N = {1, -12, 0, -42}; int[] D = {1, -3}; System.out.printf("%s / %s = %s", Arrays.toString(N), Arrays.toString(D), Arrays.deepToString(extendedSyntheticDivision(N, D))); } static int[][] extendedSyntheticDivision(int[] dividend, int[] divisor) { int[] out = dividend.clone(); int normalizer = divisor[0]; for (int i = 0; i < dividend.length - (divisor.length - 1); i++) { out[i] /= normalizer; int coef = out[i]; if (coef != 0) { for (int j = 1; j < divisor.length; j++) out[i + j] += -divisor[j] * coef; } } int separator = out.length - (divisor.length - 1); return new int[][]{ Arrays.copyOfRange(out, 0, separator), Arrays.copyOfRange(out, separator, out.length) }; } }
from __future__ import print_function from __future__ import division def extended_synthetic_division(dividend, divisor): out = list(dividend) normalizer = divisor[0] for i in xrange(len(dividend)-(len(divisor)-1)): out[i] /= normalizer coef = out[i] if coef != 0: for j in xrange(1, len(divisor)): out[i + j] += -divisor[j] * coef separator = -(len(divisor)-1) return out[:separator], out[separator:] if __name__ == '__main__': print("POLYNOMIAL SYNTHETIC DIVISION") N = [1, -12, 0, -42] D = [1, -3] print(" %s / %s =" % (N,D), " %s remainder %s" % extended_synthetic_division(N, D))
Generate an equivalent Python version of this Java code.
import java.io.*; import java.util.*; public class OddWords { public static void main(String[] args) { try { Set<String> dictionary = new TreeSet<>(); final int minLength = 5; String fileName = "unixdict.txt"; if (args.length != 0) fileName = args[0]; try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) { String line; while ((line = reader.readLine()) != null) { if (line.length() >= minLength) dictionary.add(line); } } StringBuilder word1 = new StringBuilder(); StringBuilder word2 = new StringBuilder(); List<StringPair> evenWords = new ArrayList<>(); List<StringPair> oddWords = new ArrayList<>(); for (String word : dictionary) { int length = word.length(); if (length < minLength + 2 * (minLength/2)) continue; word1.setLength(0); word2.setLength(0); for (int i = 0; i < length; ++i) { if ((i & 1) == 0) word1.append(word.charAt(i)); else word2.append(word.charAt(i)); } String oddWord = word1.toString(); String evenWord = word2.toString(); if (dictionary.contains(oddWord)) oddWords.add(new StringPair(word, oddWord)); if (dictionary.contains(evenWord)) evenWords.add(new StringPair(word, evenWord)); } System.out.println("Odd words:"); printWords(oddWords); System.out.println("\nEven words:"); printWords(evenWords); } catch (Exception e) { e.printStackTrace(); } } private static void printWords(List<StringPair> strings) { int n = 1; for (StringPair pair : strings) { System.out.printf("%2d: %-14s%s\n", n++, pair.string1, pair.string2); } } private static class StringPair { private String string1; private String string2; private StringPair(String s1, String s2) { string1 = s1; string2 = s2; } } }
import urllib.request urllib.request.urlretrieve("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt", "unixdict.txt") dictionary = open("unixdict.txt","r") wordList = dictionary.read().split('\n') dictionary.close() oddWordSet = set({}) for word in wordList: if len(word)>=9 and word[::2] in wordList: oddWordSet.add(word[::2]) [print(i) for i in sorted(oddWordSet)]
Generate an equivalent Python version of this Java code.
import java.math.BigDecimal; import java.math.MathContext; import java.util.Arrays; import java.util.List; public class RamanujanConstant { public static void main(String[] args) { System.out.printf("Ramanujan's Constant to 100 digits = %s%n%n", ramanujanConstant(163, 100)); System.out.printf("Heegner numbers yielding 'almost' integers:%n"); List<Integer> heegnerNumbers = Arrays.asList(19, 43, 67, 163); List<Integer> heegnerVals = Arrays.asList(96, 960, 5280, 640320); for ( int i = 0 ; i < heegnerNumbers.size() ; i++ ) { int heegnerNumber = heegnerNumbers.get(i); int heegnerVal = heegnerVals.get(i); BigDecimal integer = BigDecimal.valueOf(heegnerVal).pow(3).add(BigDecimal.valueOf(744)); BigDecimal compute = ramanujanConstant(heegnerNumber, 50); System.out.printf("%3d : %50s ~ %18s (diff ~ %s)%n", heegnerNumber, compute, integer, integer.subtract(compute, new MathContext(30)).toPlainString()); } } public static BigDecimal ramanujanConstant(int sqrt, int digits) { MathContext mc = new MathContext(digits + 5); return bigE(bigPi(mc).multiply(bigSquareRoot(BigDecimal.valueOf(sqrt), mc), mc), mc).round(new MathContext(digits)); } public static BigDecimal bigE(BigDecimal exponent, MathContext mc) { BigDecimal e = BigDecimal.ONE; BigDecimal ak = e; int k = 0; BigDecimal min = BigDecimal.ONE.divide(BigDecimal.TEN.pow(mc.getPrecision())); while ( true ) { k++; ak = ak.multiply(exponent).divide(BigDecimal.valueOf(k), mc); e = e.add(ak, mc); if ( ak.compareTo(min) < 0 ) { break; } } return e; } public static BigDecimal bigPi(MathContext mc) { int k = 0; BigDecimal ak = BigDecimal.ONE; BigDecimal a = ak; BigDecimal b = BigDecimal.ZERO; BigDecimal c = BigDecimal.valueOf(640320); BigDecimal c3 = c.pow(3); double digitePerTerm = Math.log10(c.pow(3).divide(BigDecimal.valueOf(24), mc).doubleValue()) - Math.log10(72); double digits = 0; while ( digits < mc.getPrecision() ) { k++; digits += digitePerTerm; BigDecimal top = BigDecimal.valueOf(-24).multiply(BigDecimal.valueOf(6*k-5)).multiply(BigDecimal.valueOf(2*k-1)).multiply(BigDecimal.valueOf(6*k-1)); BigDecimal term = top.divide(BigDecimal.valueOf(k*k*k).multiply(c3), mc); ak = ak.multiply(term, mc); a = a.add(ak, mc); b = b.add(BigDecimal.valueOf(k).multiply(ak, mc), mc); } BigDecimal total = BigDecimal.valueOf(13591409).multiply(a, mc).add(BigDecimal.valueOf(545140134).multiply(b, mc), mc); return BigDecimal.valueOf(426880).multiply(bigSquareRoot(BigDecimal.valueOf(10005), mc), mc).divide(total, mc); } public static BigDecimal bigSquareRoot(BigDecimal squareDecimal, MathContext mc) { double sqrt = Math.sqrt(squareDecimal.doubleValue()); BigDecimal x0 = new BigDecimal(sqrt, mc); BigDecimal two = BigDecimal.valueOf(2); while ( true ) { BigDecimal x1 = x0.subtract(x0.multiply(x0, mc).subtract(squareDecimal).divide(two.multiply(x0, mc), mc), mc); String x1String = x1.toPlainString(); String x0String = x0.toPlainString(); if ( x1String.substring(0, x1String.length()-1).compareTo(x0String.substring(0, x0String.length()-1)) == 0 ) { break; } x0 = x1; } return x0; } }
from mpmath import mp heegner = [19,43,67,163] mp.dps = 50 x = mp.exp(mp.pi*mp.sqrt(163)) print("calculated Ramanujan's constant: {}".format(x)) print("Heegner numbers yielding 'almost' integers:") for i in heegner: print(" for {}: {} ~ {} error: {}".format(str(i),mp.exp(mp.pi*mp.sqrt(i)),round(mp.exp(mp.pi*mp.sqrt(i))),(mp.pi*mp.sqrt(i)) - round(mp.pi*mp.sqrt(i))))
Write a version of this Java function in Python with identical behavior.
import java.math.BigDecimal; import java.math.MathContext; import java.util.Arrays; import java.util.List; public class RamanujanConstant { public static void main(String[] args) { System.out.printf("Ramanujan's Constant to 100 digits = %s%n%n", ramanujanConstant(163, 100)); System.out.printf("Heegner numbers yielding 'almost' integers:%n"); List<Integer> heegnerNumbers = Arrays.asList(19, 43, 67, 163); List<Integer> heegnerVals = Arrays.asList(96, 960, 5280, 640320); for ( int i = 0 ; i < heegnerNumbers.size() ; i++ ) { int heegnerNumber = heegnerNumbers.get(i); int heegnerVal = heegnerVals.get(i); BigDecimal integer = BigDecimal.valueOf(heegnerVal).pow(3).add(BigDecimal.valueOf(744)); BigDecimal compute = ramanujanConstant(heegnerNumber, 50); System.out.printf("%3d : %50s ~ %18s (diff ~ %s)%n", heegnerNumber, compute, integer, integer.subtract(compute, new MathContext(30)).toPlainString()); } } public static BigDecimal ramanujanConstant(int sqrt, int digits) { MathContext mc = new MathContext(digits + 5); return bigE(bigPi(mc).multiply(bigSquareRoot(BigDecimal.valueOf(sqrt), mc), mc), mc).round(new MathContext(digits)); } public static BigDecimal bigE(BigDecimal exponent, MathContext mc) { BigDecimal e = BigDecimal.ONE; BigDecimal ak = e; int k = 0; BigDecimal min = BigDecimal.ONE.divide(BigDecimal.TEN.pow(mc.getPrecision())); while ( true ) { k++; ak = ak.multiply(exponent).divide(BigDecimal.valueOf(k), mc); e = e.add(ak, mc); if ( ak.compareTo(min) < 0 ) { break; } } return e; } public static BigDecimal bigPi(MathContext mc) { int k = 0; BigDecimal ak = BigDecimal.ONE; BigDecimal a = ak; BigDecimal b = BigDecimal.ZERO; BigDecimal c = BigDecimal.valueOf(640320); BigDecimal c3 = c.pow(3); double digitePerTerm = Math.log10(c.pow(3).divide(BigDecimal.valueOf(24), mc).doubleValue()) - Math.log10(72); double digits = 0; while ( digits < mc.getPrecision() ) { k++; digits += digitePerTerm; BigDecimal top = BigDecimal.valueOf(-24).multiply(BigDecimal.valueOf(6*k-5)).multiply(BigDecimal.valueOf(2*k-1)).multiply(BigDecimal.valueOf(6*k-1)); BigDecimal term = top.divide(BigDecimal.valueOf(k*k*k).multiply(c3), mc); ak = ak.multiply(term, mc); a = a.add(ak, mc); b = b.add(BigDecimal.valueOf(k).multiply(ak, mc), mc); } BigDecimal total = BigDecimal.valueOf(13591409).multiply(a, mc).add(BigDecimal.valueOf(545140134).multiply(b, mc), mc); return BigDecimal.valueOf(426880).multiply(bigSquareRoot(BigDecimal.valueOf(10005), mc), mc).divide(total, mc); } public static BigDecimal bigSquareRoot(BigDecimal squareDecimal, MathContext mc) { double sqrt = Math.sqrt(squareDecimal.doubleValue()); BigDecimal x0 = new BigDecimal(sqrt, mc); BigDecimal two = BigDecimal.valueOf(2); while ( true ) { BigDecimal x1 = x0.subtract(x0.multiply(x0, mc).subtract(squareDecimal).divide(two.multiply(x0, mc), mc), mc); String x1String = x1.toPlainString(); String x0String = x0.toPlainString(); if ( x1String.substring(0, x1String.length()-1).compareTo(x0String.substring(0, x0String.length()-1)) == 0 ) { break; } x0 = x1; } return x0; } }
from mpmath import mp heegner = [19,43,67,163] mp.dps = 50 x = mp.exp(mp.pi*mp.sqrt(163)) print("calculated Ramanujan's constant: {}".format(x)) print("Heegner numbers yielding 'almost' integers:") for i in heegner: print(" for {}: {} ~ {} error: {}".format(str(i),mp.exp(mp.pi*mp.sqrt(i)),round(mp.exp(mp.pi*mp.sqrt(i))),(mp.pi*mp.sqrt(i)) - round(mp.pi*mp.sqrt(i))))
Change the following Java code into Python without altering its purpose.
import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.Queue; public class WordBreak { public static void main(String[] args) { List<String> dict = Arrays.asList("a", "aa", "b", "ab", "aab"); for ( String testString : Arrays.asList("aab", "aa b") ) { List<List<String>> matches = wordBreak(testString, dict); System.out.printf("String = %s, Dictionary = %s. Solutions = %d:%n", testString, dict, matches.size()); for ( List<String> match : matches ) { System.out.printf(" Word Break = %s%n", match); } System.out.printf("%n"); } dict = Arrays.asList("abc", "a", "ac", "b", "c", "cb", "d"); for ( String testString : Arrays.asList("abcd", "abbc", "abcbcd", "acdbc", "abcdd") ) { List<List<String>> matches = wordBreak(testString, dict); System.out.printf("String = %s, Dictionary = %s. Solutions = %d:%n", testString, dict, matches.size()); for ( List<String> match : matches ) { System.out.printf(" Word Break = %s%n", match); } System.out.printf("%n"); } } private static List<List<String>> wordBreak(String s, List<String> dictionary) { List<List<String>> matches = new ArrayList<>(); Queue<Node> queue = new LinkedList<>(); queue.add(new Node(s)); while ( ! queue.isEmpty() ) { Node node = queue.remove(); if ( node.val.length() == 0 ) { matches.add(node.parsed); } else { for ( String word : dictionary ) { if ( node.val.startsWith(word) ) { String valNew = node.val.substring(word.length(), node.val.length()); List<String> parsedNew = new ArrayList<>(); parsedNew.addAll(node.parsed); parsedNew.add(word); queue.add(new Node(valNew, parsedNew)); } } } } return matches; } private static class Node { private String val; private List<String> parsed; public Node(String initial) { val = initial; parsed = new ArrayList<>(); } public Node(String s, List<String> p) { val = s; parsed = p; } } }
from itertools import (chain) def stringParse(lexicon): return lambda s: Node(s)( tokenTrees(lexicon)(s) ) def tokenTrees(wds): def go(s): return [Node(s)([])] if s in wds else ( concatMap(nxt(s))(wds) ) def nxt(s): return lambda w: parse( w, go(s[len(w):]) ) if s.startswith(w) else [] def parse(w, xs): return [Node(w)(xs)] if xs else xs return lambda s: go(s) def showParse(tree): def showTokens(x): xs = x['nest'] return ' ' + x['root'] + (showTokens(xs[0]) if xs else '') parses = tree['nest'] return tree['root'] + ':\n' + ( '\n'.join( map(showTokens, parses) ) if parses else ' ( Not parseable in terms of these words )' ) def main(): lexicon = 'a bc abc cd b'.split() testSamples = 'abcd abbc abcbcd acdbc abcdd'.split() print(unlines( map( showParse, map( stringParse(lexicon), testSamples ) ) )) def Node(v): return lambda xs: {'type': 'Node', 'root': v, 'nest': xs} def concatMap(f): return lambda xs: list( chain.from_iterable(map(f, xs)) ) def unlines(xs): return '\n'.join(xs) if __name__ == '__main__': main()
Port the provided Java code into Python while preserving the original functionality.
import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.Queue; public class WordBreak { public static void main(String[] args) { List<String> dict = Arrays.asList("a", "aa", "b", "ab", "aab"); for ( String testString : Arrays.asList("aab", "aa b") ) { List<List<String>> matches = wordBreak(testString, dict); System.out.printf("String = %s, Dictionary = %s. Solutions = %d:%n", testString, dict, matches.size()); for ( List<String> match : matches ) { System.out.printf(" Word Break = %s%n", match); } System.out.printf("%n"); } dict = Arrays.asList("abc", "a", "ac", "b", "c", "cb", "d"); for ( String testString : Arrays.asList("abcd", "abbc", "abcbcd", "acdbc", "abcdd") ) { List<List<String>> matches = wordBreak(testString, dict); System.out.printf("String = %s, Dictionary = %s. Solutions = %d:%n", testString, dict, matches.size()); for ( List<String> match : matches ) { System.out.printf(" Word Break = %s%n", match); } System.out.printf("%n"); } } private static List<List<String>> wordBreak(String s, List<String> dictionary) { List<List<String>> matches = new ArrayList<>(); Queue<Node> queue = new LinkedList<>(); queue.add(new Node(s)); while ( ! queue.isEmpty() ) { Node node = queue.remove(); if ( node.val.length() == 0 ) { matches.add(node.parsed); } else { for ( String word : dictionary ) { if ( node.val.startsWith(word) ) { String valNew = node.val.substring(word.length(), node.val.length()); List<String> parsedNew = new ArrayList<>(); parsedNew.addAll(node.parsed); parsedNew.add(word); queue.add(new Node(valNew, parsedNew)); } } } } return matches; } private static class Node { private String val; private List<String> parsed; public Node(String initial) { val = initial; parsed = new ArrayList<>(); } public Node(String s, List<String> p) { val = s; parsed = p; } } }
from itertools import (chain) def stringParse(lexicon): return lambda s: Node(s)( tokenTrees(lexicon)(s) ) def tokenTrees(wds): def go(s): return [Node(s)([])] if s in wds else ( concatMap(nxt(s))(wds) ) def nxt(s): return lambda w: parse( w, go(s[len(w):]) ) if s.startswith(w) else [] def parse(w, xs): return [Node(w)(xs)] if xs else xs return lambda s: go(s) def showParse(tree): def showTokens(x): xs = x['nest'] return ' ' + x['root'] + (showTokens(xs[0]) if xs else '') parses = tree['nest'] return tree['root'] + ':\n' + ( '\n'.join( map(showTokens, parses) ) if parses else ' ( Not parseable in terms of these words )' ) def main(): lexicon = 'a bc abc cd b'.split() testSamples = 'abcd abbc abcbcd acdbc abcdd'.split() print(unlines( map( showParse, map( stringParse(lexicon), testSamples ) ) )) def Node(v): return lambda xs: {'type': 'Node', 'root': v, 'nest': xs} def concatMap(f): return lambda xs: list( chain.from_iterable(map(f, xs)) ) def unlines(xs): return '\n'.join(xs) if __name__ == '__main__': main()
Produce a functionally identical Python code for the snippet given in Java.
import java.util.*; public class BrilliantNumbers { public static void main(String[] args) { var primesByDigits = getPrimesByDigits(100000000); System.out.println("First 100 brilliant numbers:"); List<Integer> brilliantNumbers = new ArrayList<>(); for (var primes : primesByDigits) { int n = primes.size(); for (int i = 0; i < n; ++i) { int prime1 = primes.get(i); for (int j = i; j < n; ++j) { int prime2 = primes.get(j); brilliantNumbers.add(prime1 * prime2); } } if (brilliantNumbers.size() >= 100) break; } Collections.sort(brilliantNumbers); for (int i = 0; i < 100; ++i) { char c = (i + 1) % 10 == 0 ? '\n' : ' '; System.out.printf("%,5d%c", brilliantNumbers.get(i), c); } System.out.println(); long power = 10; long count = 0; for (int p = 1; p < 2 * primesByDigits.size(); ++p) { var primes = primesByDigits.get(p / 2); long position = count + 1; long minProduct = 0; int n = primes.size(); for (int i = 0; i < n; ++i) { long prime1 = primes.get(i); var primes2 = primes.subList(i, n); int q = (int)((power + prime1 - 1) / prime1); int j = Collections.binarySearch(primes2, q); if (j == n) continue; if (j < 0) j = -(j + 1); long prime2 = primes2.get(j); long product = prime1 * prime2; if (minProduct == 0 || product < minProduct) minProduct = product; position += j; if (prime1 >= prime2) break; } System.out.printf("First brilliant number >= 10^%d is %,d at position %,d\n", p, minProduct, position); power *= 10; if (p % 2 == 1) { long size = primes.size(); count += size * (size + 1) / 2; } } } private static List<List<Integer>> getPrimesByDigits(int limit) { PrimeGenerator primeGen = new PrimeGenerator(100000, 100000); List<List<Integer>> primesByDigits = new ArrayList<>(); List<Integer> primes = new ArrayList<>(); for (int p = 10; p <= limit; ) { int prime = primeGen.nextPrime(); if (prime > p) { primesByDigits.add(primes); primes = new ArrayList<>(); p *= 10; } primes.add(prime); } return primesByDigits; } }
from primesieve.numpy import primes from math import isqrt import numpy as np max_order = 9 blocks = [primes(10**n, 10**(n + 1)) for n in range(max_order)] def smallest_brilliant(lb): pos = 1 root = isqrt(lb) for blk in blocks: n = len(blk) if blk[-1]*blk[-1] < lb: pos += n*(n + 1)//2 continue i = np.searchsorted(blk, root, 'left') i += blk[i]*blk[i] < lb if not i: return blk[0]*blk[0], pos p = blk[:i + 1] q = (lb - 1)//p idx = np.searchsorted(blk, q, 'right') sel = idx < n p, idx = p[sel], idx[sel] q = blk[idx] sel = q >= p p, q, idx = p[sel], q[sel], idx[sel] pos += np.sum(idx - np.arange(len(idx))) return np.min(p*q), pos res = [] p = 0 for i in range(100): p, _ = smallest_brilliant(p + 1) res.append(p) print(f'first 100 are {res}') for i in range(max_order*2): thresh = 10**i p, pos = smallest_brilliant(thresh) print(f'Above 10^{i:2d}: {p:20d} at
Change the programming language of this snippet from Java to Python without modifying what it does.
import java.util.*; public class BrilliantNumbers { public static void main(String[] args) { var primesByDigits = getPrimesByDigits(100000000); System.out.println("First 100 brilliant numbers:"); List<Integer> brilliantNumbers = new ArrayList<>(); for (var primes : primesByDigits) { int n = primes.size(); for (int i = 0; i < n; ++i) { int prime1 = primes.get(i); for (int j = i; j < n; ++j) { int prime2 = primes.get(j); brilliantNumbers.add(prime1 * prime2); } } if (brilliantNumbers.size() >= 100) break; } Collections.sort(brilliantNumbers); for (int i = 0; i < 100; ++i) { char c = (i + 1) % 10 == 0 ? '\n' : ' '; System.out.printf("%,5d%c", brilliantNumbers.get(i), c); } System.out.println(); long power = 10; long count = 0; for (int p = 1; p < 2 * primesByDigits.size(); ++p) { var primes = primesByDigits.get(p / 2); long position = count + 1; long minProduct = 0; int n = primes.size(); for (int i = 0; i < n; ++i) { long prime1 = primes.get(i); var primes2 = primes.subList(i, n); int q = (int)((power + prime1 - 1) / prime1); int j = Collections.binarySearch(primes2, q); if (j == n) continue; if (j < 0) j = -(j + 1); long prime2 = primes2.get(j); long product = prime1 * prime2; if (minProduct == 0 || product < minProduct) minProduct = product; position += j; if (prime1 >= prime2) break; } System.out.printf("First brilliant number >= 10^%d is %,d at position %,d\n", p, minProduct, position); power *= 10; if (p % 2 == 1) { long size = primes.size(); count += size * (size + 1) / 2; } } } private static List<List<Integer>> getPrimesByDigits(int limit) { PrimeGenerator primeGen = new PrimeGenerator(100000, 100000); List<List<Integer>> primesByDigits = new ArrayList<>(); List<Integer> primes = new ArrayList<>(); for (int p = 10; p <= limit; ) { int prime = primeGen.nextPrime(); if (prime > p) { primesByDigits.add(primes); primes = new ArrayList<>(); p *= 10; } primes.add(prime); } return primesByDigits; } }
from primesieve.numpy import primes from math import isqrt import numpy as np max_order = 9 blocks = [primes(10**n, 10**(n + 1)) for n in range(max_order)] def smallest_brilliant(lb): pos = 1 root = isqrt(lb) for blk in blocks: n = len(blk) if blk[-1]*blk[-1] < lb: pos += n*(n + 1)//2 continue i = np.searchsorted(blk, root, 'left') i += blk[i]*blk[i] < lb if not i: return blk[0]*blk[0], pos p = blk[:i + 1] q = (lb - 1)//p idx = np.searchsorted(blk, q, 'right') sel = idx < n p, idx = p[sel], idx[sel] q = blk[idx] sel = q >= p p, q, idx = p[sel], q[sel], idx[sel] pos += np.sum(idx - np.arange(len(idx))) return np.min(p*q), pos res = [] p = 0 for i in range(100): p, _ = smallest_brilliant(p + 1) res.append(p) print(f'first 100 are {res}') for i in range(max_order*2): thresh = 10**i p, pos = smallest_brilliant(thresh) print(f'Above 10^{i:2d}: {p:20d} at
Please provide an equivalent version of this Java code in Python.
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import java.util.Set; import java.util.stream.IntStream; public class WordLadder { private static int distance(String s1, String s2) { assert s1.length() == s2.length(); return (int) IntStream.range(0, s1.length()) .filter(i -> s1.charAt(i) != s2.charAt(i)) .count(); } private static void wordLadder(Map<Integer, Set<String>> words, String fw, String tw) { wordLadder(words, fw, tw, 8); } private static void wordLadder(Map<Integer, Set<String>> words, String fw, String tw, int limit) { if (fw.length() != tw.length()) { throw new IllegalArgumentException("From word and to word must have the same length"); } Set<String> ws = words.get(fw.length()); if (ws.contains(fw)) { List<String> primeList = new ArrayList<>(); primeList.add(fw); PriorityQueue<List<String>> queue = new PriorityQueue<>((chain1, chain2) -> { int cmp1 = Integer.compare(chain1.size(), chain2.size()); if (cmp1 == 0) { String last1 = chain1.get(chain1.size() - 1); int d1 = distance(last1, tw); String last2 = chain2.get(chain2.size() - 1); int d2 = distance(last2, tw); return Integer.compare(d1, d2); } return cmp1; }); queue.add(primeList); while (queue.size() > 0) { List<String> curr = queue.remove(); if (curr.size() > limit) { continue; } String last = curr.get(curr.size() - 1); for (String word : ws) { if (distance(last, word) == 1) { if (word.equals(tw)) { curr.add(word); System.out.println(String.join(" -> ", curr)); return; } if (!curr.contains(word)) { List<String> cp = new ArrayList<>(curr); cp.add(word); queue.add(cp); } } } } } System.err.printf("Cannot turn `%s` into `%s`%n", fw, tw); } public static void main(String[] args) throws IOException { Map<Integer, Set<String>> words = new HashMap<>(); for (String line : Files.readAllLines(Path.of("unixdict.txt"))) { Set<String> wl = words.computeIfAbsent(line.length(), HashSet::new); wl.add(line); } wordLadder(words, "boy", "man"); wordLadder(words, "girl", "lady"); wordLadder(words, "john", "jane"); wordLadder(words, "child", "adult"); wordLadder(words, "cat", "dog"); wordLadder(words, "lead", "gold"); wordLadder(words, "white", "black"); wordLadder(words, "bubble", "tickle", 12); } }
import os,sys,zlib,urllib.request def h ( str,x=9 ): for c in str : x = ( x*33 + ord( c )) & 0xffffffffff return x def cache ( func,*param ): n = 'cache_%x.bin'%abs( h( repr( param ))) try : return eval( zlib.decompress( open( n,'rb' ).read())) except : pass s = func( *param ) open( n,'wb' ).write( zlib.compress( bytes( repr( s ),'ascii' ))) return s dico_url = 'https://raw.githubusercontent.com/quinnj/Rosetta-Julia/master/unixdict.txt' read_url = lambda url : urllib.request.urlopen( url ).read() load_dico = lambda url : tuple( cache( read_url,url ).split( b'\n')) isnext = lambda w1,w2 : len( w1 ) == len( w2 ) and len( list( filter( lambda l : l[0]!=l[1] , zip( w1,w2 )))) == 1 def build_map ( words ): map = [(w.decode('ascii'),[]) for w in words] for i1,(w1,n1) in enumerate( map ): for i2,(w2,n2) in enumerate( map[i1+1:],i1+1 ): if isnext( w1,w2 ): n1.append( i2 ) n2.append( i1 ) return map def find_path ( words,w1,w2 ): i = [w[0] for w in words].index( w1 ) front,done,res = [i],{i:-1},[] while front : i = front.pop(0) word,next = words[i] for n in next : if n in done : continue done[n] = i if words[n][0] == w2 : while n >= 0 : res = [words[n][0]] + res n = done[n] return ' '.join( res ) front.append( n ) return '%s can not be turned into %s'%( w1,w2 ) for w in ('boy man','girl lady','john jane','alien drool','child adult'): print( find_path( cache( build_map,load_dico( dico_url )),*w.split()))
Convert this Java block to Python, preserving its control flow and logic.
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import java.util.Set; import java.util.stream.IntStream; public class WordLadder { private static int distance(String s1, String s2) { assert s1.length() == s2.length(); return (int) IntStream.range(0, s1.length()) .filter(i -> s1.charAt(i) != s2.charAt(i)) .count(); } private static void wordLadder(Map<Integer, Set<String>> words, String fw, String tw) { wordLadder(words, fw, tw, 8); } private static void wordLadder(Map<Integer, Set<String>> words, String fw, String tw, int limit) { if (fw.length() != tw.length()) { throw new IllegalArgumentException("From word and to word must have the same length"); } Set<String> ws = words.get(fw.length()); if (ws.contains(fw)) { List<String> primeList = new ArrayList<>(); primeList.add(fw); PriorityQueue<List<String>> queue = new PriorityQueue<>((chain1, chain2) -> { int cmp1 = Integer.compare(chain1.size(), chain2.size()); if (cmp1 == 0) { String last1 = chain1.get(chain1.size() - 1); int d1 = distance(last1, tw); String last2 = chain2.get(chain2.size() - 1); int d2 = distance(last2, tw); return Integer.compare(d1, d2); } return cmp1; }); queue.add(primeList); while (queue.size() > 0) { List<String> curr = queue.remove(); if (curr.size() > limit) { continue; } String last = curr.get(curr.size() - 1); for (String word : ws) { if (distance(last, word) == 1) { if (word.equals(tw)) { curr.add(word); System.out.println(String.join(" -> ", curr)); return; } if (!curr.contains(word)) { List<String> cp = new ArrayList<>(curr); cp.add(word); queue.add(cp); } } } } } System.err.printf("Cannot turn `%s` into `%s`%n", fw, tw); } public static void main(String[] args) throws IOException { Map<Integer, Set<String>> words = new HashMap<>(); for (String line : Files.readAllLines(Path.of("unixdict.txt"))) { Set<String> wl = words.computeIfAbsent(line.length(), HashSet::new); wl.add(line); } wordLadder(words, "boy", "man"); wordLadder(words, "girl", "lady"); wordLadder(words, "john", "jane"); wordLadder(words, "child", "adult"); wordLadder(words, "cat", "dog"); wordLadder(words, "lead", "gold"); wordLadder(words, "white", "black"); wordLadder(words, "bubble", "tickle", 12); } }
import os,sys,zlib,urllib.request def h ( str,x=9 ): for c in str : x = ( x*33 + ord( c )) & 0xffffffffff return x def cache ( func,*param ): n = 'cache_%x.bin'%abs( h( repr( param ))) try : return eval( zlib.decompress( open( n,'rb' ).read())) except : pass s = func( *param ) open( n,'wb' ).write( zlib.compress( bytes( repr( s ),'ascii' ))) return s dico_url = 'https://raw.githubusercontent.com/quinnj/Rosetta-Julia/master/unixdict.txt' read_url = lambda url : urllib.request.urlopen( url ).read() load_dico = lambda url : tuple( cache( read_url,url ).split( b'\n')) isnext = lambda w1,w2 : len( w1 ) == len( w2 ) and len( list( filter( lambda l : l[0]!=l[1] , zip( w1,w2 )))) == 1 def build_map ( words ): map = [(w.decode('ascii'),[]) for w in words] for i1,(w1,n1) in enumerate( map ): for i2,(w2,n2) in enumerate( map[i1+1:],i1+1 ): if isnext( w1,w2 ): n1.append( i2 ) n2.append( i1 ) return map def find_path ( words,w1,w2 ): i = [w[0] for w in words].index( w1 ) front,done,res = [i],{i:-1},[] while front : i = front.pop(0) word,next = words[i] for n in next : if n in done : continue done[n] = i if words[n][0] == w2 : while n >= 0 : res = [words[n][0]] + res n = done[n] return ' '.join( res ) front.append( n ) return '%s can not be turned into %s'%( w1,w2 ) for w in ('boy man','girl lady','john jane','alien drool','child adult'): print( find_path( cache( build_map,load_dico( dico_url )),*w.split()))
Change the programming language of this snippet from Java to Python without modifying what it does.
import java.util.HashMap; import java.util.Map; public class PrimeGaps { private Map<Integer, Integer> gapStarts = new HashMap<>(); private int lastPrime; private PrimeGenerator primeGenerator = new PrimeGenerator(1000, 500000); public static void main(String[] args) { final int limit = 100000000; PrimeGaps pg = new PrimeGaps(); for (int pm = 10, gap1 = 2;;) { int start1 = pg.findGapStart(gap1); int gap2 = gap1 + 2; int start2 = pg.findGapStart(gap2); int diff = start2 > start1 ? start2 - start1 : start1 - start2; if (diff > pm) { System.out.printf( "Earliest difference > %,d between adjacent prime gap starting primes:\n" + "Gap %,d starts at %,d, gap %,d starts at %,d, difference is %,d.\n\n", pm, gap1, start1, gap2, start2, diff); if (pm == limit) break; pm *= 10; } else { gap1 = gap2; } } } private int findGapStart(int gap) { Integer start = gapStarts.get(gap); if (start != null) return start; for (;;) { int prev = lastPrime; lastPrime = primeGenerator.nextPrime(); int diff = lastPrime - prev; gapStarts.putIfAbsent(diff, prev); if (diff == gap) return prev; } } }
from primesieve import primes LIMIT = 10**9 pri = primes(LIMIT * 5) gapstarts = {} for i in range(1, len(pri)): if pri[i] - pri[i - 1] not in gapstarts: gapstarts[pri[i] - pri[i - 1]] = pri[i - 1] PM, GAP1, = 10, 2 while True: while GAP1 not in gapstarts: GAP1 += 2 start1 = gapstarts[GAP1] GAP2 = GAP1 + 2 if GAP2 not in gapstarts: GAP1 = GAP2 + 2 continue start2 = gapstarts[GAP2] diff = abs(start2 - start1) if diff > PM: print(f"Earliest difference >{PM: ,} between adjacent prime gap starting primes:") print(f"Gap {GAP1} starts at{start1: ,}, gap {GAP2} starts at{start2: ,}, difference is{diff: ,}.\n") if PM == LIMIT: break PM *= 10 else: GAP1 = GAP2
Ensure the translated Python code behaves exactly like the original Java snippet.
import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class LatinSquaresInReducedForm { public static void main(String[] args) { System.out.printf("Reduced latin squares of order 4:%n"); for ( LatinSquare square : getReducedLatinSquares(4) ) { System.out.printf("%s%n", square); } System.out.printf("Compute the number of latin squares from count of reduced latin squares:%n(Reduced Latin Square Count) * n! * (n-1)! = Latin Square Count%n"); for ( int n = 1 ; n <= 6 ; n++ ) { List<LatinSquare> list = getReducedLatinSquares(n); System.out.printf("Size = %d, %d * %d * %d = %,d%n", n, list.size(), fact(n), fact(n-1), list.size()*fact(n)*fact(n-1)); } } private static long fact(int n) { if ( n == 0 ) { return 1; } int prod = 1; for ( int i = 1 ; i <= n ; i++ ) { prod *= i; } return prod; } private static List<LatinSquare> getReducedLatinSquares(int n) { List<LatinSquare> squares = new ArrayList<>(); squares.add(new LatinSquare(n)); PermutationGenerator permGen = new PermutationGenerator(n); for ( int fillRow = 1 ; fillRow < n ; fillRow++ ) { List<LatinSquare> squaresNext = new ArrayList<>(); for ( LatinSquare square : squares ) { while ( permGen.hasMore() ) { int[] perm = permGen.getNext(); if ( (perm[0]+1) != (fillRow+1) ) { continue; } boolean permOk = true; done: for ( int row = 0 ; row < fillRow ; row++ ) { for ( int col = 0 ; col < n ; col++ ) { if ( square.get(row, col) == (perm[col]+1) ) { permOk = false; break done; } } } if ( permOk ) { LatinSquare newSquare = new LatinSquare(square); for ( int col = 0 ; col < n ; col++ ) { newSquare.set(fillRow, col, perm[col]+1); } squaresNext.add(newSquare); } } permGen.reset(); } squares = squaresNext; } return squares; } @SuppressWarnings("unused") private static int[] display(int[] in) { int [] out = new int[in.length]; for ( int i = 0 ; i < in.length ; i++ ) { out[i] = in[i] + 1; } return out; } private static class LatinSquare { int[][] square; int size; public LatinSquare(int n) { square = new int[n][n]; size = n; for ( int col = 0 ; col < n ; col++ ) { set(0, col, col + 1); } } public LatinSquare(LatinSquare ls) { int n = ls.size; square = new int[n][n]; size = n; for ( int row = 0 ; row < n ; row++ ) { for ( int col = 0 ; col < n ; col++ ) { set(row, col, ls.get(row, col)); } } } public void set(int row, int col, int value) { square[row][col] = value; } public int get(int row, int col) { return square[row][col]; } @Override public String toString() { StringBuilder sb = new StringBuilder(); for ( int row = 0 ; row < size ; row++ ) { sb.append(Arrays.toString(square[row])); sb.append("\n"); } return sb.toString(); } } private static class PermutationGenerator { private int[] a; private BigInteger numLeft; private BigInteger total; public PermutationGenerator (int n) { if (n < 1) { throw new IllegalArgumentException ("Min 1"); } a = new int[n]; total = getFactorial(n); reset(); } private void reset () { for ( int i = 0 ; i < a.length ; i++ ) { a[i] = i; } numLeft = new BigInteger(total.toString()); } public boolean hasMore() { return numLeft.compareTo(BigInteger.ZERO) == 1; } private static BigInteger getFactorial (int n) { BigInteger fact = BigInteger.ONE; for ( int i = n ; i > 1 ; i-- ) { fact = fact.multiply(new BigInteger(Integer.toString(i))); } return fact; } public int[] getNext() { if ( numLeft.equals(total) ) { numLeft = numLeft.subtract (BigInteger.ONE); return a; } int j = a.length - 2; while ( a[j] > a[j+1] ) { j--; } int k = a.length - 1; while ( a[j] > a[k] ) { k--; } int temp = a[k]; a[k] = a[j]; a[j] = temp; int r = a.length - 1; int s = j + 1; while (r > s) { int temp2 = a[s]; a[s] = a[r]; a[r] = temp2; r--; s++; } numLeft = numLeft.subtract(BigInteger.ONE); return a; } } }
def dList(n, start): start -= 1 a = range(n) a[start] = a[0] a[0] = start a[1:] = sorted(a[1:]) first = a[1] r = [] def recurse(last): if (last == first): for j,v in enumerate(a[1:]): if j + 1 == v: return b = [x + 1 for x in a] r.append(b) return for i in xrange(last, 0, -1): a[i], a[last] = a[last], a[i] recurse(last - 1) a[i], a[last] = a[last], a[i] recurse(n - 1) return r def printSquare(latin,n): for row in latin: print row print def reducedLatinSquares(n,echo): if n <= 0: if echo: print [] return 0 elif n == 1: if echo: print [1] return 1 rlatin = [None] * n for i in xrange(n): rlatin[i] = [None] * n for j in xrange(0, n): rlatin[0][j] = j + 1 class OuterScope: count = 0 def recurse(i): rows = dList(n, i) for r in xrange(len(rows)): rlatin[i - 1] = rows[r] justContinue = False k = 0 while not justContinue and k < i - 1: for j in xrange(1, n): if rlatin[k][j] == rlatin[i - 1][j]: if r < len(rows) - 1: justContinue = True break if i > 2: return k += 1 if not justContinue: if i < n: recurse(i + 1) else: OuterScope.count += 1 if echo: printSquare(rlatin, n) recurse(2) return OuterScope.count def factorial(n): if n == 0: return 1 prod = 1 for i in xrange(2, n + 1): prod *= i return prod print "The four reduced latin squares of order 4 are:\n" reducedLatinSquares(4,True) print "The size of the set of reduced latin squares for the following orders" print "and hence the total number of latin squares of these orders are:\n" for n in xrange(1, 7): size = reducedLatinSquares(n, False) f = factorial(n - 1) f *= f * n * size print "Order %d: Size %-4d x %d! x %d! => Total %d" % (n, size, n, n - 1, f)
Transform the following Java implementation into Python, maintaining the same output and logic.
import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.function.Consumer; import java.util.function.Function; import java.util.stream.Collectors; public class UPC { private static final int SEVEN = 7; private static final Map<String, Integer> LEFT_DIGITS = Map.of( " ## #", 0, " ## #", 1, " # ##", 2, " #### #", 3, " # ##", 4, " ## #", 5, " # ####", 6, " ### ##", 7, " ## ###", 8, " # ##", 9 ); private static final Map<String, Integer> RIGHT_DIGITS = LEFT_DIGITS.entrySet() .stream() .collect(Collectors.toMap( entry -> entry.getKey() .replace(' ', 's') .replace('#', ' ') .replace('s', '#'), Map.Entry::getValue )); private static final String END_SENTINEL = "# #"; private static final String MID_SENTINEL = " # # "; private static void decodeUPC(String input) { Function<String, Map.Entry<Boolean, List<Integer>>> decode = (String candidate) -> { int pos = 0; var part = candidate.substring(pos, pos + END_SENTINEL.length()); List<Integer> output = new ArrayList<>(); if (END_SENTINEL.equals(part)) { pos += END_SENTINEL.length(); } else { return Map.entry(false, output); } for (int i = 1; i < SEVEN; i++) { part = candidate.substring(pos, pos + SEVEN); pos += SEVEN; if (LEFT_DIGITS.containsKey(part)) { output.add(LEFT_DIGITS.get(part)); } else { return Map.entry(false, output); } } part = candidate.substring(pos, pos + MID_SENTINEL.length()); if (MID_SENTINEL.equals(part)) { pos += MID_SENTINEL.length(); } else { return Map.entry(false, output); } for (int i = 1; i < SEVEN; i++) { part = candidate.substring(pos, pos + SEVEN); pos += SEVEN; if (RIGHT_DIGITS.containsKey(part)) { output.add(RIGHT_DIGITS.get(part)); } else { return Map.entry(false, output); } } part = candidate.substring(pos, pos + END_SENTINEL.length()); if (!END_SENTINEL.equals(part)) { return Map.entry(false, output); } int sum = 0; for (int i = 0; i < output.size(); i++) { if (i % 2 == 0) { sum += 3 * output.get(i); } else { sum += output.get(i); } } return Map.entry(sum % 10 == 0, output); }; Consumer<List<Integer>> printList = list -> { var it = list.iterator(); System.out.print('['); if (it.hasNext()) { System.out.print(it.next()); } while (it.hasNext()) { System.out.print(", "); System.out.print(it.next()); } System.out.print(']'); }; var candidate = input.trim(); var out = decode.apply(candidate); if (out.getKey()) { printList.accept(out.getValue()); System.out.println(); } else { StringBuilder builder = new StringBuilder(candidate); builder.reverse(); out = decode.apply(builder.toString()); if (out.getKey()) { printList.accept(out.getValue()); System.out.println(" Upside down"); } else if (out.getValue().size() == 12) { System.out.println("Invalid checksum"); } else { System.out.println("Invalid digit(s)"); } } } public static void main(String[] args) { var barcodes = List.of( " # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # ", " # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # ", " # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # ", " # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # ", " # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # ", " # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # ", " # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # ", " # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # ", " # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # ", " # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # " ); barcodes.forEach(UPC::decodeUPC); } }
import itertools import re RE_BARCODE = re.compile( r"^(?P<s_quiet> +)" r"(?P<s_guard> r"(?P<left>[ r"(?P<m_guard> r"(?P<right>[ r"(?P<e_guard> r"(?P<e_quiet> +)$" ) LEFT_DIGITS = { (0, 0, 0, 1, 1, 0, 1): 0, (0, 0, 1, 1, 0, 0, 1): 1, (0, 0, 1, 0, 0, 1, 1): 2, (0, 1, 1, 1, 1, 0, 1): 3, (0, 1, 0, 0, 0, 1, 1): 4, (0, 1, 1, 0, 0, 0, 1): 5, (0, 1, 0, 1, 1, 1, 1): 6, (0, 1, 1, 1, 0, 1, 1): 7, (0, 1, 1, 0, 1, 1, 1): 8, (0, 0, 0, 1, 0, 1, 1): 9, } RIGHT_DIGITS = { (1, 1, 1, 0, 0, 1, 0): 0, (1, 1, 0, 0, 1, 1, 0): 1, (1, 1, 0, 1, 1, 0, 0): 2, (1, 0, 0, 0, 0, 1, 0): 3, (1, 0, 1, 1, 1, 0, 0): 4, (1, 0, 0, 1, 1, 1, 0): 5, (1, 0, 1, 0, 0, 0, 0): 6, (1, 0, 0, 0, 1, 0, 0): 7, (1, 0, 0, 1, 0, 0, 0): 8, (1, 1, 1, 0, 1, 0, 0): 9, } MODULES = { " ": 0, " } DIGITS_PER_SIDE = 6 MODULES_PER_DIGIT = 7 class ParityError(Exception): class ChecksumError(Exception): def group(iterable, n): args = [iter(iterable)] * n return tuple(itertools.zip_longest(*args)) def parse(barcode): match = RE_BARCODE.match(barcode) left = group((MODULES[c] for c in match.group("left")), MODULES_PER_DIGIT) right = group((MODULES[c] for c in match.group("right")), MODULES_PER_DIGIT) left, right = check_parity(left, right) return tuple( itertools.chain( (LEFT_DIGITS[d] for d in left), (RIGHT_DIGITS[d] for d in right), ) ) def check_parity(left, right): left_parity = sum(sum(d) % 2 for d in left) right_parity = sum(sum(d) % 2 for d in right) if left_parity == 0 and right_parity == DIGITS_PER_SIDE: _left = tuple(tuple(reversed(d)) for d in reversed(right)) right = tuple(tuple(reversed(d)) for d in reversed(left)) left = _left elif left_parity != DIGITS_PER_SIDE or right_parity != 0: error = tuple( itertools.chain( (LEFT_DIGITS.get(d, "_") for d in left), (RIGHT_DIGITS.get(d, "_") for d in right), ) ) raise ParityError(" ".join(str(d) for d in error)) return left, right def checksum(digits): odds = (digits[i] for i in range(0, 11, 2)) evens = (digits[i] for i in range(1, 10, 2)) check_digit = (sum(odds) * 3 + sum(evens)) % 10 if check_digit != 0: check_digit = 10 - check_digit if digits[-1] != check_digit: raise ChecksumError(str(check_digit)) return check_digit def main(): barcodes = [ " " " " " " " " " " " ] for barcode in barcodes: try: digits = parse(barcode) except ParityError as err: print(f"{err} parity error!") continue try: check_digit = checksum(digits) except ChecksumError as err: print(f"{' '.join(str(d) for d in digits)} checksum error! ({err})") continue print(f"{' '.join(str(d) for d in digits)}") if __name__ == "__main__": main()
Rewrite the snippet below in Python so it works the same as the original Java code.
import java.awt.Point; import java.util.Scanner; public class PlayfairCipher { private static char[][] charTable; private static Point[] positions; public static void main(String[] args) { Scanner sc = new Scanner(System.in); String key = prompt("Enter an encryption key (min length 6): ", sc, 6); String txt = prompt("Enter the message: ", sc, 1); String jti = prompt("Replace J with I? y/n: ", sc, 1); boolean changeJtoI = jti.equalsIgnoreCase("y"); createTable(key, changeJtoI); String enc = encode(prepareText(txt, changeJtoI)); System.out.printf("%nEncoded message: %n%s%n", enc); System.out.printf("%nDecoded message: %n%s%n", decode(enc)); } private static String prompt(String promptText, Scanner sc, int minLen) { String s; do { System.out.print(promptText); s = sc.nextLine().trim(); } while (s.length() < minLen); return s; } private static String prepareText(String s, boolean changeJtoI) { s = s.toUpperCase().replaceAll("[^A-Z]", ""); return changeJtoI ? s.replace("J", "I") : s.replace("Q", ""); } private static void createTable(String key, boolean changeJtoI) { charTable = new char[5][5]; positions = new Point[26]; String s = prepareText(key + "ABCDEFGHIJKLMNOPQRSTUVWXYZ", changeJtoI); int len = s.length(); for (int i = 0, k = 0; i < len; i++) { char c = s.charAt(i); if (positions[c - 'A'] == null) { charTable[k / 5][k % 5] = c; positions[c - 'A'] = new Point(k % 5, k / 5); k++; } } } private static String encode(String s) { StringBuilder sb = new StringBuilder(s); for (int i = 0; i < sb.length(); i += 2) { if (i == sb.length() - 1) sb.append(sb.length() % 2 == 1 ? 'X' : ""); else if (sb.charAt(i) == sb.charAt(i + 1)) sb.insert(i + 1, 'X'); } return codec(sb, 1); } private static String decode(String s) { return codec(new StringBuilder(s), 4); } private static String codec(StringBuilder text, int direction) { int len = text.length(); for (int i = 0; i < len; i += 2) { char a = text.charAt(i); char b = text.charAt(i + 1); int row1 = positions[a - 'A'].y; int row2 = positions[b - 'A'].y; int col1 = positions[a - 'A'].x; int col2 = positions[b - 'A'].x; if (row1 == row2) { col1 = (col1 + direction) % 5; col2 = (col2 + direction) % 5; } else if (col1 == col2) { row1 = (row1 + direction) % 5; row2 = (row2 + direction) % 5; } else { int tmp = col1; col1 = col2; col2 = tmp; } text.setCharAt(i, charTable[row1][col1]); text.setCharAt(i + 1, charTable[row2][col2]); } return text.toString(); } }
from string import ascii_uppercase from itertools import product from re import findall def uniq(seq): seen = {} return [seen.setdefault(x, x) for x in seq if x not in seen] def partition(seq, n): return [seq[i : i + n] for i in xrange(0, len(seq), n)] def playfair(key, from_ = 'J', to = None): if to is None: to = 'I' if from_ == 'J' else '' def canonicalize(s): return filter(str.isupper, s.upper()).replace(from_, to) m = partition(uniq(canonicalize(key + ascii_uppercase)), 5) enc = {} for row in m: for i, j in product(xrange(5), repeat=2): if i != j: enc[row[i] + row[j]] = row[(i + 1) % 5] + row[(j + 1) % 5] for c in zip(*m): for i, j in product(xrange(5), repeat=2): if i != j: enc[c[i] + c[j]] = c[(i + 1) % 5] + c[(j + 1) % 5] for i1, j1, i2, j2 in product(xrange(5), repeat=4): if i1 != i2 and j1 != j2: enc[m[i1][j1] + m[i2][j2]] = m[i1][j2] + m[i2][j1] dec = dict((v, k) for k, v in enc.iteritems()) def sub_enc(txt): lst = findall(r"(.)(?:(?!\1)(.))?", canonicalize(txt)) return " ".join(enc[a + (b if b else 'X')] for a, b in lst) def sub_dec(encoded): return " ".join(dec[p] for p in partition(canonicalize(encoded), 2)) return sub_enc, sub_dec (encode, decode) = playfair("Playfair example") orig = "Hide the gold in...the TREESTUMP!!!" print "Original:", orig enc = encode(orig) print "Encoded:", enc print "Decoded:", decode(enc)
Generate an equivalent Python version of this Java code.
import java.awt.Point; import java.util.Scanner; public class PlayfairCipher { private static char[][] charTable; private static Point[] positions; public static void main(String[] args) { Scanner sc = new Scanner(System.in); String key = prompt("Enter an encryption key (min length 6): ", sc, 6); String txt = prompt("Enter the message: ", sc, 1); String jti = prompt("Replace J with I? y/n: ", sc, 1); boolean changeJtoI = jti.equalsIgnoreCase("y"); createTable(key, changeJtoI); String enc = encode(prepareText(txt, changeJtoI)); System.out.printf("%nEncoded message: %n%s%n", enc); System.out.printf("%nDecoded message: %n%s%n", decode(enc)); } private static String prompt(String promptText, Scanner sc, int minLen) { String s; do { System.out.print(promptText); s = sc.nextLine().trim(); } while (s.length() < minLen); return s; } private static String prepareText(String s, boolean changeJtoI) { s = s.toUpperCase().replaceAll("[^A-Z]", ""); return changeJtoI ? s.replace("J", "I") : s.replace("Q", ""); } private static void createTable(String key, boolean changeJtoI) { charTable = new char[5][5]; positions = new Point[26]; String s = prepareText(key + "ABCDEFGHIJKLMNOPQRSTUVWXYZ", changeJtoI); int len = s.length(); for (int i = 0, k = 0; i < len; i++) { char c = s.charAt(i); if (positions[c - 'A'] == null) { charTable[k / 5][k % 5] = c; positions[c - 'A'] = new Point(k % 5, k / 5); k++; } } } private static String encode(String s) { StringBuilder sb = new StringBuilder(s); for (int i = 0; i < sb.length(); i += 2) { if (i == sb.length() - 1) sb.append(sb.length() % 2 == 1 ? 'X' : ""); else if (sb.charAt(i) == sb.charAt(i + 1)) sb.insert(i + 1, 'X'); } return codec(sb, 1); } private static String decode(String s) { return codec(new StringBuilder(s), 4); } private static String codec(StringBuilder text, int direction) { int len = text.length(); for (int i = 0; i < len; i += 2) { char a = text.charAt(i); char b = text.charAt(i + 1); int row1 = positions[a - 'A'].y; int row2 = positions[b - 'A'].y; int col1 = positions[a - 'A'].x; int col2 = positions[b - 'A'].x; if (row1 == row2) { col1 = (col1 + direction) % 5; col2 = (col2 + direction) % 5; } else if (col1 == col2) { row1 = (row1 + direction) % 5; row2 = (row2 + direction) % 5; } else { int tmp = col1; col1 = col2; col2 = tmp; } text.setCharAt(i, charTable[row1][col1]); text.setCharAt(i + 1, charTable[row2][col2]); } return text.toString(); } }
from string import ascii_uppercase from itertools import product from re import findall def uniq(seq): seen = {} return [seen.setdefault(x, x) for x in seq if x not in seen] def partition(seq, n): return [seq[i : i + n] for i in xrange(0, len(seq), n)] def playfair(key, from_ = 'J', to = None): if to is None: to = 'I' if from_ == 'J' else '' def canonicalize(s): return filter(str.isupper, s.upper()).replace(from_, to) m = partition(uniq(canonicalize(key + ascii_uppercase)), 5) enc = {} for row in m: for i, j in product(xrange(5), repeat=2): if i != j: enc[row[i] + row[j]] = row[(i + 1) % 5] + row[(j + 1) % 5] for c in zip(*m): for i, j in product(xrange(5), repeat=2): if i != j: enc[c[i] + c[j]] = c[(i + 1) % 5] + c[(j + 1) % 5] for i1, j1, i2, j2 in product(xrange(5), repeat=4): if i1 != i2 and j1 != j2: enc[m[i1][j1] + m[i2][j2]] = m[i1][j2] + m[i2][j1] dec = dict((v, k) for k, v in enc.iteritems()) def sub_enc(txt): lst = findall(r"(.)(?:(?!\1)(.))?", canonicalize(txt)) return " ".join(enc[a + (b if b else 'X')] for a, b in lst) def sub_dec(encoded): return " ".join(dec[p] for p in partition(canonicalize(encoded), 2)) return sub_enc, sub_dec (encode, decode) = playfair("Playfair example") orig = "Hide the gold in...the TREESTUMP!!!" print "Original:", orig enc = encode(orig) print "Encoded:", enc print "Decoded:", decode(enc)
Convert the following code from Java to Python, ensuring the logic remains intact.
import java.util.*; public class ClosestPair { public static class Point { public final double x; public final double y; public Point(double x, double y) { this.x = x; this.y = y; } public String toString() { return "(" + x + ", " + y + ")"; } } public static class Pair { public Point point1 = null; public Point point2 = null; public double distance = 0.0; public Pair() { } public Pair(Point point1, Point point2) { this.point1 = point1; this.point2 = point2; calcDistance(); } public void update(Point point1, Point point2, double distance) { this.point1 = point1; this.point2 = point2; this.distance = distance; } public void calcDistance() { this.distance = distance(point1, point2); } public String toString() { return point1 + "-" + point2 + " : " + distance; } } public static double distance(Point p1, Point p2) { double xdist = p2.x - p1.x; double ydist = p2.y - p1.y; return Math.hypot(xdist, ydist); } public static Pair bruteForce(List<? extends Point> points) { int numPoints = points.size(); if (numPoints < 2) return null; Pair pair = new Pair(points.get(0), points.get(1)); if (numPoints > 2) { for (int i = 0; i < numPoints - 1; i++) { Point point1 = points.get(i); for (int j = i + 1; j < numPoints; j++) { Point point2 = points.get(j); double distance = distance(point1, point2); if (distance < pair.distance) pair.update(point1, point2, distance); } } } return pair; } public static void sortByX(List<? extends Point> points) { Collections.sort(points, new Comparator<Point>() { public int compare(Point point1, Point point2) { if (point1.x < point2.x) return -1; if (point1.x > point2.x) return 1; return 0; } } ); } public static void sortByY(List<? extends Point> points) { Collections.sort(points, new Comparator<Point>() { public int compare(Point point1, Point point2) { if (point1.y < point2.y) return -1; if (point1.y > point2.y) return 1; return 0; } } ); } public static Pair divideAndConquer(List<? extends Point> points) { List<Point> pointsSortedByX = new ArrayList<Point>(points); sortByX(pointsSortedByX); List<Point> pointsSortedByY = new ArrayList<Point>(points); sortByY(pointsSortedByY); return divideAndConquer(pointsSortedByX, pointsSortedByY); } private static Pair divideAndConquer(List<? extends Point> pointsSortedByX, List<? extends Point> pointsSortedByY) { int numPoints = pointsSortedByX.size(); if (numPoints <= 3) return bruteForce(pointsSortedByX); int dividingIndex = numPoints >>> 1; List<? extends Point> leftOfCenter = pointsSortedByX.subList(0, dividingIndex); List<? extends Point> rightOfCenter = pointsSortedByX.subList(dividingIndex, numPoints); List<Point> tempList = new ArrayList<Point>(leftOfCenter); sortByY(tempList); Pair closestPair = divideAndConquer(leftOfCenter, tempList); tempList.clear(); tempList.addAll(rightOfCenter); sortByY(tempList); Pair closestPairRight = divideAndConquer(rightOfCenter, tempList); if (closestPairRight.distance < closestPair.distance) closestPair = closestPairRight; tempList.clear(); double shortestDistance =closestPair.distance; double centerX = rightOfCenter.get(0).x; for (Point point : pointsSortedByY) if (Math.abs(centerX - point.x) < shortestDistance) tempList.add(point); for (int i = 0; i < tempList.size() - 1; i++) { Point point1 = tempList.get(i); for (int j = i + 1; j < tempList.size(); j++) { Point point2 = tempList.get(j); if ((point2.y - point1.y) >= shortestDistance) break; double distance = distance(point1, point2); if (distance < closestPair.distance) { closestPair.update(point1, point2, distance); shortestDistance = distance; } } } return closestPair; } public static void main(String[] args) { int numPoints = (args.length == 0) ? 1000 : Integer.parseInt(args[0]); List<Point> points = new ArrayList<Point>(); Random r = new Random(); for (int i = 0; i < numPoints; i++) points.add(new Point(r.nextDouble(), r.nextDouble())); System.out.println("Generated " + numPoints + " random points"); long startTime = System.currentTimeMillis(); Pair bruteForceClosestPair = bruteForce(points); long elapsedTime = System.currentTimeMillis() - startTime; System.out.println("Brute force (" + elapsedTime + " ms): " + bruteForceClosestPair); startTime = System.currentTimeMillis(); Pair dqClosestPair = divideAndConquer(points); elapsedTime = System.currentTimeMillis() - startTime; System.out.println("Divide and conquer (" + elapsedTime + " ms): " + dqClosestPair); if (bruteForceClosestPair.distance != dqClosestPair.distance) System.out.println("MISMATCH"); } }
from random import randint, randrange from operator import itemgetter, attrgetter infinity = float('inf') def bruteForceClosestPair(point): numPoints = len(point) if numPoints < 2: return infinity, (None, None) return min( ((abs(point[i] - point[j]), (point[i], point[j])) for i in range(numPoints-1) for j in range(i+1,numPoints)), key=itemgetter(0)) def closestPair(point): xP = sorted(point, key= attrgetter('real')) yP = sorted(point, key= attrgetter('imag')) return _closestPair(xP, yP) def _closestPair(xP, yP): numPoints = len(xP) if numPoints <= 3: return bruteForceClosestPair(xP) Pl = xP[:numPoints/2] Pr = xP[numPoints/2:] Yl, Yr = [], [] xDivider = Pl[-1].real for p in yP: if p.real <= xDivider: Yl.append(p) else: Yr.append(p) dl, pairl = _closestPair(Pl, Yl) dr, pairr = _closestPair(Pr, Yr) dm, pairm = (dl, pairl) if dl < dr else (dr, pairr) closeY = [p for p in yP if abs(p.real - xDivider) < dm] numCloseY = len(closeY) if numCloseY > 1: closestY = min( ((abs(closeY[i] - closeY[j]), (closeY[i], closeY[j])) for i in range(numCloseY-1) for j in range(i+1,min(i+8, numCloseY))), key=itemgetter(0)) return (dm, pairm) if dm <= closestY[0] else closestY else: return dm, pairm def times(): import timeit functions = [bruteForceClosestPair, closestPair] for f in functions: print 'Time for', f.__name__, timeit.Timer( '%s(pointList)' % f.__name__, 'from closestpair import %s, pointList' % f.__name__).timeit(number=1) pointList = [randint(0,1000)+1j*randint(0,1000) for i in range(2000)] if __name__ == '__main__': pointList = [(5+9j), (9+3j), (2+0j), (8+4j), (7+4j), (9+10j), (1+9j), (8+2j), 10j, (9+6j)] print pointList print ' bruteForceClosestPair:', bruteForceClosestPair(pointList) print ' closestPair:', closestPair(pointList) for i in range(10): pointList = [randrange(11)+1j*randrange(11) for i in range(10)] print '\n', pointList print ' bruteForceClosestPair:', bruteForceClosestPair(pointList) print ' closestPair:', closestPair(pointList) print '\n' times() times() times()
Port the following code from Java to Python with equivalent syntax and logic.
public class Animal{ }
class Animal: pass class Dog(Animal): pass class Cat(Animal): pass class Lab(Dog): pass class Collie(Dog): pass
Convert this Java block to Python, preserving its control flow and logic.
Map<String, Int> map = new HashMap(); map["foo"] = 5; map["bar"] = 10; map["baz"] = 15; map["foo"] = 6;
hash = dict() hash = dict(red="FF0000", green="00FF00", blue="0000FF") hash = { 'key1':1, 'key2':2, } value = hash[key]
Translate this program into Python but keep the logic exactly as in Java.
import java.awt.*; import javax.swing.*; public class ColorWheel { public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { ColorWheelFrame frame = new ColorWheelFrame(); frame.setVisible(true); } }); } private static class ColorWheelFrame extends JFrame { private ColorWheelFrame() { super("Color Wheel"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); getContentPane().add(new ColorWheelPanel()); pack(); } } private static class ColorWheelPanel extends JComponent { private ColorWheelPanel() { setPreferredSize(new Dimension(400, 400)); } public void paint(Graphics g) { Graphics2D g2 = (Graphics2D)g; int w = getWidth(); int h = getHeight(); int margin = 10; int radius = (Math.min(w, h) - 2 * margin)/2; int cx = w/2; int cy = h/2; float[] dist = {0.F, 1.0F}; g2.setColor(Color.BLACK); g2.fillRect(0, 0, w, h); for (int angle = 0; angle < 360; ++angle) { Color color = hsvToRgb(angle, 1.0, 1.0); Color[] colors = {Color.WHITE, color}; RadialGradientPaint paint = new RadialGradientPaint(cx, cy, radius, dist, colors); g2.setPaint(paint); g2.fillArc(cx - radius, cy - radius, radius*2, radius*2, angle, 1); } } } private static Color hsvToRgb(int h, double s, double v) { double hp = h/60.0; double c = s * v; double x = c * (1 - Math.abs(hp % 2.0 - 1)); double m = v - c; double r = 0, g = 0, b = 0; if (hp <= 1) { r = c; g = x; } else if (hp <= 2) { r = x; g = c; } else if (hp <= 3) { g = c; b = x; } else if (hp <= 4) { g = x; b = c; } else if (hp <= 5) { r = x; b = c; } else { r = c; b = x; } r += m; g += m; b += m; return new Color((int)(r * 255), (int)(g * 255), (int)(b * 255)); } }
size(300, 300) background(0) radius = min(width, height) / 2.0 cx, cy = width / 2, width / 2 for x in range(width): for y in range(height): rx = x - cx ry = y - cy s = sqrt(rx ** 2 + ry ** 2) / radius if s <= 1.0: h = ((atan2(ry, rx) / PI) + 1.0) / 2.0 colorMode(HSB) c = color(int(h * 255), int(s * 255), 255) set(x, y, c)
Produce a functionally identical Python code for the snippet given in Java.
import java.awt.*; import java.awt.event.*; import java.awt.image.*; import static java.awt.image.BufferedImage.*; import static java.lang.Math.*; import javax.swing.*; public class PlasmaEffect extends JPanel { float[][] plasma; float hueShift = 0; BufferedImage img; public PlasmaEffect() { Dimension dim = new Dimension(640, 640); setPreferredSize(dim); setBackground(Color.white); img = new BufferedImage(dim.width, dim.height, TYPE_INT_RGB); plasma = createPlasma(dim.height, dim.width); new Timer(42, (ActionEvent e) -> { hueShift = (hueShift + 0.02f) % 1; repaint(); }).start(); } float[][] createPlasma(int w, int h) { float[][] buffer = new float[h][w]; for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) { double value = sin(x / 16.0); value += sin(y / 8.0); value += sin((x + y) / 16.0); value += sin(sqrt(x * x + y * y) / 8.0); value += 4; value /= 8; assert (value >= 0.0 && value <= 1.0) : "Hue value out of bounds"; buffer[y][x] = (float) value; } return buffer; } void drawPlasma(Graphics2D g) { int h = plasma.length; int w = plasma[0].length; for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) { float hue = hueShift + plasma[y][x] % 1; img.setRGB(x, y, Color.HSBtoRGB(hue, 1, 1)); } g.drawImage(img, 0, 0, null); } @Override public void paintComponent(Graphics gg) { super.paintComponent(gg); Graphics2D g = (Graphics2D) gg; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); drawPlasma(g); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setTitle("Plasma Effect"); f.setResizable(false); f.add(new PlasmaEffect(), BorderLayout.CENTER); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); }); } }
pal = [0] * 128 r = 42 g = 84 b = 126 rd = gd = bd = False def setup(): global buffer size(600, 600) frameRate(25) buffer = [None] * width * height for x in range(width): for y in range(width): value = int(((128 + (128 * sin(x / 32.0))) + (128 + (128 * cos(y / 32.0))) + (128 + (128 * sin(sqrt((x * x + y * y)) / 32.0)))) / 4) buffer[x + y * width] = value def draw(): global r, g, b, rd, gd, bd if r > 128: rd = True if not rd: r += 1 else: r-=1 if r < 0: rd = False if g > 128: gd = True if not gd: g += 1 else: g- = 1 if r < 0: gd = False if b > 128: bd = True if not bd: b += 1 else: b- = 1 if b < 0: bd = False for i in range(128): s_1 = sin(i * PI / 25) s_2 = sin(i * PI / 50 + PI / 4) pal[i] = color(r + s_1 * 128, g + s_2 * 128, b + s_1 * 128) loadPixels() for i, b in enumerate(buffer): pixels[i] = pal[(b + frameCount) % 127] updatePixels()
Preserve the algorithm and functionality while converting the code from Java to Python.
import java.awt.*; import java.awt.event.*; import java.awt.image.*; import static java.awt.image.BufferedImage.*; import static java.lang.Math.*; import javax.swing.*; public class PlasmaEffect extends JPanel { float[][] plasma; float hueShift = 0; BufferedImage img; public PlasmaEffect() { Dimension dim = new Dimension(640, 640); setPreferredSize(dim); setBackground(Color.white); img = new BufferedImage(dim.width, dim.height, TYPE_INT_RGB); plasma = createPlasma(dim.height, dim.width); new Timer(42, (ActionEvent e) -> { hueShift = (hueShift + 0.02f) % 1; repaint(); }).start(); } float[][] createPlasma(int w, int h) { float[][] buffer = new float[h][w]; for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) { double value = sin(x / 16.0); value += sin(y / 8.0); value += sin((x + y) / 16.0); value += sin(sqrt(x * x + y * y) / 8.0); value += 4; value /= 8; assert (value >= 0.0 && value <= 1.0) : "Hue value out of bounds"; buffer[y][x] = (float) value; } return buffer; } void drawPlasma(Graphics2D g) { int h = plasma.length; int w = plasma[0].length; for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) { float hue = hueShift + plasma[y][x] % 1; img.setRGB(x, y, Color.HSBtoRGB(hue, 1, 1)); } g.drawImage(img, 0, 0, null); } @Override public void paintComponent(Graphics gg) { super.paintComponent(gg); Graphics2D g = (Graphics2D) gg; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); drawPlasma(g); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setTitle("Plasma Effect"); f.setResizable(false); f.add(new PlasmaEffect(), BorderLayout.CENTER); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); }); } }
pal = [0] * 128 r = 42 g = 84 b = 126 rd = gd = bd = False def setup(): global buffer size(600, 600) frameRate(25) buffer = [None] * width * height for x in range(width): for y in range(width): value = int(((128 + (128 * sin(x / 32.0))) + (128 + (128 * cos(y / 32.0))) + (128 + (128 * sin(sqrt((x * x + y * y)) / 32.0)))) / 4) buffer[x + y * width] = value def draw(): global r, g, b, rd, gd, bd if r > 128: rd = True if not rd: r += 1 else: r-=1 if r < 0: rd = False if g > 128: gd = True if not gd: g += 1 else: g- = 1 if r < 0: gd = False if b > 128: bd = True if not bd: b += 1 else: b- = 1 if b < 0: bd = False for i in range(128): s_1 = sin(i * PI / 25) s_2 = sin(i * PI / 50 + PI / 4) pal[i] = color(r + s_1 * 128, g + s_2 * 128, b + s_1 * 128) loadPixels() for i, b in enumerate(buffer): pixels[i] = pal[(b + frameCount) % 127] updatePixels()
Write the same code in Python as shown below in Java.
public class HelloWorld { public static void main(String[] args) { System.out.println("Hello world!"); } }
print "Goodbye, World!"
Port the provided Java code into Python while preserving the original functionality.
public class HelloWorld { public static void main(String[] args) { System.out.println("Hello world!"); } }
print "Goodbye, World!"
Can you help me rewrite this code in Python instead of Java, keeping it the same logically?
class Point { protected int x, y; public Point() { this(0); } public Point(int x) { this(x, 0); } public Point(int x, int y) { this.x = x; this.y = y; } public Point(Point p) { this(p.x, p.y); } public int getX() { return this.x; } public int getY() { return this.y; } public void setX(int x) { this.x = x; } public void setY(int y) { this.y = y; } public void print() { System.out.println("Point x: " + this.x + " y: " + this.y); } } class Circle extends Point { private int r; public Circle(Point p) { this(p, 0); } public Circle(Point p, int r) { super(p); this.r = r; } public Circle() { this(0); } public Circle(int x) { this(x, 0); } public Circle(int x, int y) { this(x, y, 0); } public Circle(int x, int y, int r) { super(x, y); this.r = r; } public Circle(Circle c) { this(c.x, c.y, c.r); } public int getR() { return this.r; } public void setR(int r) { this.r = r; } public void print() { System.out.println("Circle x: " + this.x + " y: " + this.y + " r: " + this.r); } } public class test { public static void main(String args[]) { Point p = new Point(); Point c = new Circle(); p.print(); c.print(); } }
class Point(object): def __init__(self, x=0.0, y=0.0): self.x = x self.y = y def __repr__(self): return '<Point 0x%x x: %f y: %f>' % (id(self), self.x, self.y) class Circle(object): def __init__(self, center=None, radius=1.0): self.center = center or Point() self.radius = radius def __repr__(self): return '<Circle 0x%x x: %f y: %f radius: %f>' % ( id(self), self.center.x, self.center.y, self.radius)
Rewrite the snippet below in Python so it works the same as the original Java code.
import java.math.BigInteger; public class Main { public static void main(String[] args) { BigInteger d = new BigInteger("3"), a; int lmt = 25, sl, c = 0; for (int i = 3; i < 5808; ) { a = BigInteger.ONE.shiftLeft(i).add(BigInteger.ONE).divide(d); if (a.isProbablePrime(1)) { System.out.printf("%2d %4d ", ++c, i); String s = a.toString(); sl = s.length(); if (sl < lmt) System.out.println(a); else System.out.println(s.substring(0, 11) + ".." + s.substring(sl - 11, sl) + " " + sl + " digits"); } i = BigInteger.valueOf(i).nextProbablePrime().intValue(); } } }
from sympy import isprime def wagstaff(N): pri, wcount = 1, 0 while wcount < N: pri += 2 if isprime(pri): wag = (2**pri + 1) // 3 if isprime(wag): wcount += 1 print(f'{wcount: 3}: {pri: 5} => ', f'{wag:,}' if wcount < 11 else f'[{len(str(wag))} digit number]') wagstaff(24)
Produce a functionally identical Python code for the snippet given in Java.
import java.math.BigInteger; public class Main { public static void main(String[] args) { BigInteger d = new BigInteger("3"), a; int lmt = 25, sl, c = 0; for (int i = 3; i < 5808; ) { a = BigInteger.ONE.shiftLeft(i).add(BigInteger.ONE).divide(d); if (a.isProbablePrime(1)) { System.out.printf("%2d %4d ", ++c, i); String s = a.toString(); sl = s.length(); if (sl < lmt) System.out.println(a); else System.out.println(s.substring(0, 11) + ".." + s.substring(sl - 11, sl) + " " + sl + " digits"); } i = BigInteger.valueOf(i).nextProbablePrime().intValue(); } } }
from sympy import isprime def wagstaff(N): pri, wcount = 1, 0 while wcount < N: pri += 2 if isprime(pri): wag = (2**pri + 1) // 3 if isprime(wag): wcount += 1 print(f'{wcount: 3}: {pri: 5} => ', f'{wag:,}' if wcount < 11 else f'[{len(str(wag))} digit number]') wagstaff(24)
Produce a functionally identical Python code for the snippet given in Java.
import java.math.BigInteger; public class Main { public static void main(String[] args) { BigInteger d = new BigInteger("3"), a; int lmt = 25, sl, c = 0; for (int i = 3; i < 5808; ) { a = BigInteger.ONE.shiftLeft(i).add(BigInteger.ONE).divide(d); if (a.isProbablePrime(1)) { System.out.printf("%2d %4d ", ++c, i); String s = a.toString(); sl = s.length(); if (sl < lmt) System.out.println(a); else System.out.println(s.substring(0, 11) + ".." + s.substring(sl - 11, sl) + " " + sl + " digits"); } i = BigInteger.valueOf(i).nextProbablePrime().intValue(); } } }
from sympy import isprime def wagstaff(N): pri, wcount = 1, 0 while wcount < N: pri += 2 if isprime(pri): wag = (2**pri + 1) // 3 if isprime(wag): wcount += 1 print(f'{wcount: 3}: {pri: 5} => ', f'{wag:,}' if wcount < 11 else f'[{len(str(wag))} digit number]') wagstaff(24)
Convert this Java block to Python, preserving its control flow and logic.
import java.util.Collections; import java.util.HashMap; import java.util.Map; public class ImmutableMap { public static void main(String[] args) { Map<String,Integer> hashMap = getImmutableMap(); try { hashMap.put("Test", 23); } catch (UnsupportedOperationException e) { System.out.println("ERROR: Unable to put new value."); } try { hashMap.clear(); } catch (UnsupportedOperationException e) { System.out.println("ERROR: Unable to clear map."); } try { hashMap.putIfAbsent("Test", 23); } catch (UnsupportedOperationException e) { System.out.println("ERROR: Unable to put if absent."); } for ( String key : hashMap.keySet() ) { System.out.printf("key = %s, value = %s%n", key, hashMap.get(key)); } } private static Map<String,Integer> getImmutableMap() { Map<String,Integer> hashMap = new HashMap<>(); hashMap.put("Key 1", 34); hashMap.put("Key 2", 105); hashMap.put("Key 3", 144); return Collections.unmodifiableMap(hashMap); } }
from collections import UserDict import copy class Dict(UserDict): def __init__(self, dict=None, **kwargs): self.__init = True super().__init__(dict, **kwargs) self.default = copy.deepcopy(self.data) self.__init = False def __delitem__(self, key): if key in self.default: self.data[key] = self.default[key] else: raise NotImplementedError def __setitem__(self, key, item): if self.__init: super().__setitem__(key, item) elif key in self.data: self.data[key] = item else: raise KeyError def __repr__(self): return "%s(%s)" % (type(self).__name__, super().__repr__()) def fromkeys(cls, iterable, value=None): if self.__init: super().fromkeys(cls, iterable, value) else: for key in iterable: if key in self.data: self.data[key] = value else: raise KeyError def clear(self): self.data.update(copy.deepcopy(self.default)) def pop(self, key, default=None): raise NotImplementedError def popitem(self): raise NotImplementedError def update(self, E, **F): if self.__init: super().update(E, **F) else: haskeys = False try: keys = E.keys() haskeys = Ture except AttributeError: pass if haskeys: for key in keys: self[key] = E[key] else: for key, val in E: self[key] = val for key in F: self[key] = F[key] def setdefault(self, key, default=None): if key not in self.data: raise KeyError else: return super().setdefault(key, default)
Rewrite this program in Python while keeping its functionality equivalent to the Java version.
import java.time.Duration; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; public class RareNumbers { public interface Consumer5<A, B, C, D, E> { void apply(A a, B b, C c, D d, E e); } public interface Consumer7<A, B, C, D, E, F, G> { void apply(A a, B b, C c, D d, E e, F f, G g); } public interface Recursable5<A, B, C, D, E> { void apply(A a, B b, C c, D d, E e, Recursable5<A, B, C, D, E> r); } public interface Recursable7<A, B, C, D, E, F, G> { void apply(A a, B b, C c, D d, E e, F f, G g, Recursable7<A, B, C, D, E, F, G> r); } public static <A, B, C, D, E> Consumer5<A, B, C, D, E> recurse(Recursable5<A, B, C, D, E> r) { return (a, b, c, d, e) -> r.apply(a, b, c, d, e, r); } public static <A, B, C, D, E, F, G> Consumer7<A, B, C, D, E, F, G> recurse(Recursable7<A, B, C, D, E, F, G> r) { return (a, b, c, d, e, f, g) -> r.apply(a, b, c, d, e, f, g, r); } private static class Term { long coeff; byte ix1, ix2; public Term(long coeff, byte ix1, byte ix2) { this.coeff = coeff; this.ix1 = ix1; this.ix2 = ix2; } } private static final int MAX_DIGITS = 16; private static long toLong(List<Byte> digits, boolean reverse) { long sum = 0; if (reverse) { for (int i = digits.size() - 1; i >= 0; --i) { sum = sum * 10 + digits.get(i); } } else { for (Byte digit : digits) { sum = sum * 10 + digit; } } return sum; } private static boolean isNotSquare(long n) { long root = (long) Math.sqrt(n); return root * root != n; } private static List<Byte> seq(byte from, byte to, byte step) { List<Byte> res = new ArrayList<>(); for (byte i = from; i <= to; i += step) { res.add(i); } return res; } private static String commatize(long n) { String s = String.valueOf(n); int le = s.length(); int i = le - 3; while (i >= 1) { s = s.substring(0, i) + "," + s.substring(i); i -= 3; } return s; } public static void main(String[] args) { final LocalDateTime startTime = LocalDateTime.now(); long pow = 1L; System.out.println("Aggregate timings to process all numbers up to:"); List<List<Term>> allTerms = new ArrayList<>(); for (int i = 0; i < MAX_DIGITS - 1; ++i) { allTerms.add(new ArrayList<>()); } for (int r = 2; r <= MAX_DIGITS; ++r) { List<Term> terms = new ArrayList<>(); pow *= 10; long pow1 = pow; long pow2 = 1; byte i1 = 0; byte i2 = (byte) (r - 1); while (i1 < i2) { terms.add(new Term(pow1 - pow2, i1, i2)); pow1 /= 10; pow2 *= 10; i1++; i2--; } allTerms.set(r - 2, terms); } Map<Byte, List<List<Byte>>> fml = Map.of( (byte) 0, List.of(List.of((byte) 2, (byte) 2), List.of((byte) 8, (byte) 8)), (byte) 1, List.of(List.of((byte) 6, (byte) 5), List.of((byte) 8, (byte) 7)), (byte) 4, List.of(List.of((byte) 4, (byte) 0)), (byte) 6, List.of(List.of((byte) 6, (byte) 0), List.of((byte) 8, (byte) 2)) ); Map<Byte, List<List<Byte>>> dmd = new HashMap<>(); for (int i = 0; i < 100; ++i) { List<Byte> a = List.of((byte) (i / 10), (byte) (i % 10)); int d = a.get(0) - a.get(1); dmd.computeIfAbsent((byte) d, k -> new ArrayList<>()).add(a); } List<Byte> fl = List.of((byte) 0, (byte) 1, (byte) 4, (byte) 6); List<Byte> dl = seq((byte) -9, (byte) 9, (byte) 1); List<Byte> zl = List.of((byte) 0); List<Byte> el = seq((byte) -8, (byte) 8, (byte) 2); List<Byte> ol = seq((byte) -9, (byte) 9, (byte) 2); List<Byte> il = seq((byte) 0, (byte) 9, (byte) 1); List<Long> rares = new ArrayList<>(); List<List<List<Byte>>> lists = new ArrayList<>(); for (int i = 0; i < 4; ++i) { lists.add(new ArrayList<>()); } for (int i = 0; i < fl.size(); ++i) { List<List<Byte>> temp1 = new ArrayList<>(); List<Byte> temp2 = new ArrayList<>(); temp2.add(fl.get(i)); temp1.add(temp2); lists.set(i, temp1); } final AtomicReference<List<Byte>> digits = new AtomicReference<>(new ArrayList<>()); AtomicInteger count = new AtomicInteger(); Consumer7<List<Byte>, List<Byte>, List<List<Byte>>, List<List<Byte>>, Long, Integer, Integer> fnpr = recurse((cand, di, dis, indicies, nmr, nd, level, func) -> { if (level == dis.size()) { digits.get().set(indicies.get(0).get(0), fml.get(cand.get(0)).get(di.get(0)).get(0)); digits.get().set(indicies.get(0).get(1), fml.get(cand.get(0)).get(di.get(0)).get(1)); int le = di.size(); if (nd % 2 == 1) { le--; digits.get().set(nd / 2, di.get(le)); } for (int i = 1; i < le; ++i) { digits.get().set(indicies.get(i).get(0), dmd.get(cand.get(i)).get(di.get(i)).get(0)); digits.get().set(indicies.get(i).get(1), dmd.get(cand.get(i)).get(di.get(i)).get(1)); } long r = toLong(digits.get(), true); long npr = nmr + 2 * r; if (isNotSquare(npr)) { return; } count.getAndIncrement(); System.out.printf(" R/N %2d:", count.get()); LocalDateTime checkPoint = LocalDateTime.now(); long elapsed = Duration.between(startTime, checkPoint).toMillis(); System.out.printf(" %9sms", elapsed); long n = toLong(digits.get(), false); System.out.printf(" (%s)\n", commatize(n)); rares.add(n); } else { for (Byte num : dis.get(level)) { di.set(level, num); func.apply(cand, di, dis, indicies, nmr, nd, level + 1, func); } } }); Consumer5<List<Byte>, List<List<Byte>>, List<List<Byte>>, Integer, Integer> fnmr = recurse((cand, list, indicies, nd, level, func) -> { if (level == list.size()) { long nmr = 0; long nmr2 = 0; List<Term> terms = allTerms.get(nd - 2); for (int i = 0; i < terms.size(); ++i) { Term t = terms.get(i); if (cand.get(i) >= 0) { nmr += t.coeff * cand.get(i); } else { nmr2 += t.coeff * -cand.get(i); if (nmr >= nmr2) { nmr -= nmr2; nmr2 = 0; } else { nmr2 -= nmr; nmr = 0; } } } if (nmr2 >= nmr) { return; } nmr -= nmr2; if (isNotSquare(nmr)) { return; } List<List<Byte>> dis = new ArrayList<>(); dis.add(seq((byte) 0, (byte) (fml.get(cand.get(0)).size() - 1), (byte) 1)); for (int i = 1; i < cand.size(); ++i) { dis.add(seq((byte) 0, (byte) (dmd.get(cand.get(i)).size() - 1), (byte) 1)); } if (nd % 2 == 1) { dis.add(il); } List<Byte> di = new ArrayList<>(); for (int i = 0; i < dis.size(); ++i) { di.add((byte) 0); } fnpr.apply(cand, di, dis, indicies, nmr, nd, 0); } else { for (Byte num : list.get(level)) { cand.set(level, num); func.apply(cand, list, indicies, nd, level + 1, func); } } }); for (int nd = 2; nd <= MAX_DIGITS; ++nd) { digits.set(new ArrayList<>()); for (int i = 0; i < nd; ++i) { digits.get().add((byte) 0); } if (nd == 4) { lists.get(0).add(zl); lists.get(1).add(ol); lists.get(2).add(el); lists.get(3).add(ol); } else if (allTerms.get(nd - 2).size() > lists.get(0).size()) { for (int i = 0; i < 4; ++i) { lists.get(i).add(dl); } } List<List<Byte>> indicies = new ArrayList<>(); for (Term t : allTerms.get(nd - 2)) { indicies.add(List.of(t.ix1, t.ix2)); } for (List<List<Byte>> list : lists) { List<Byte> cand = new ArrayList<>(); for (int i = 0; i < list.size(); ++i) { cand.add((byte) 0); } fnmr.apply(cand, list, indicies, nd, 0); } LocalDateTime checkPoint = LocalDateTime.now(); long elapsed = Duration.between(startTime, checkPoint).toMillis(); System.out.printf(" %2d digits: %9sms\n", nd, elapsed); } Collections.sort(rares); System.out.printf("\nThe rare numbers with up to %d digits are:\n", MAX_DIGITS); for (int i = 0; i < rares.size(); ++i) { System.out.printf(" %2d: %25s\n", i + 1, commatize(rares.get(i))); } } }
from math import floor, sqrt from datetime import datetime def main(): start = datetime.now() for i in xrange(1, 10 ** 11): if rare(i): print "found a rare:", i end = datetime.now() print "time elapsed:", end - start def is_square(n): s = floor(sqrt(n + 0.5)) return s * s == n def reverse(n): return int(str(n)[::-1]) def is_palindrome(n): return n == reverse(n) def rare(n): r = reverse(n) return ( not is_palindrome(n) and n > r and is_square(n+r) and is_square(n-r) ) if __name__ == '__main__': main()
Translate this program into Python but keep the logic exactly as in Java.
import java.util.Stack; public class ArithmeticEvaluation { public interface Expression { BigRational eval(); } public enum Parentheses {LEFT} public enum BinaryOperator { ADD('+', 1), SUB('-', 1), MUL('*', 2), DIV('/', 2); public final char symbol; public final int precedence; BinaryOperator(char symbol, int precedence) { this.symbol = symbol; this.precedence = precedence; } public BigRational eval(BigRational leftValue, BigRational rightValue) { switch (this) { case ADD: return leftValue.add(rightValue); case SUB: return leftValue.subtract(rightValue); case MUL: return leftValue.multiply(rightValue); case DIV: return leftValue.divide(rightValue); } throw new IllegalStateException(); } public static BinaryOperator forSymbol(char symbol) { for (BinaryOperator operator : values()) { if (operator.symbol == symbol) { return operator; } } throw new IllegalArgumentException(String.valueOf(symbol)); } } public static class Number implements Expression { private final BigRational number; public Number(BigRational number) { this.number = number; } @Override public BigRational eval() { return number; } @Override public String toString() { return number.toString(); } } public static class BinaryExpression implements Expression { public final Expression leftOperand; public final BinaryOperator operator; public final Expression rightOperand; public BinaryExpression(Expression leftOperand, BinaryOperator operator, Expression rightOperand) { this.leftOperand = leftOperand; this.operator = operator; this.rightOperand = rightOperand; } @Override public BigRational eval() { BigRational leftValue = leftOperand.eval(); BigRational rightValue = rightOperand.eval(); return operator.eval(leftValue, rightValue); } @Override public String toString() { return "(" + leftOperand + " " + operator.symbol + " " + rightOperand + ")"; } } private static void createNewOperand(BinaryOperator operator, Stack<Expression> operands) { Expression rightOperand = operands.pop(); Expression leftOperand = operands.pop(); operands.push(new BinaryExpression(leftOperand, operator, rightOperand)); } public static Expression parse(String input) { int curIndex = 0; boolean afterOperand = false; Stack<Expression> operands = new Stack<>(); Stack<Object> operators = new Stack<>(); while (curIndex < input.length()) { int startIndex = curIndex; char c = input.charAt(curIndex++); if (Character.isWhitespace(c)) continue; if (afterOperand) { if (c == ')') { Object operator; while (!operators.isEmpty() && ((operator = operators.pop()) != Parentheses.LEFT)) createNewOperand((BinaryOperator) operator, operands); continue; } afterOperand = false; BinaryOperator operator = BinaryOperator.forSymbol(c); while (!operators.isEmpty() && (operators.peek() != Parentheses.LEFT) && (((BinaryOperator) operators.peek()).precedence >= operator.precedence)) createNewOperand((BinaryOperator) operators.pop(), operands); operators.push(operator); continue; } if (c == '(') { operators.push(Parentheses.LEFT); continue; } afterOperand = true; while (curIndex < input.length()) { c = input.charAt(curIndex); if (((c < '0') || (c > '9')) && (c != '.')) break; curIndex++; } operands.push(new Number(BigRational.valueOf(input.substring(startIndex, curIndex)))); } while (!operators.isEmpty()) { Object operator = operators.pop(); if (operator == Parentheses.LEFT) throw new IllegalArgumentException(); createNewOperand((BinaryOperator) operator, operands); } Expression expression = operands.pop(); if (!operands.isEmpty()) throw new IllegalArgumentException(); return expression; } public static void main(String[] args) { String[] testExpressions = { "2+3", "2+3/4", "2*3-4", "2*(3+4)+5/6", "2 * (3 + (4 * 5 + (6 * 7) * 8) - 9) * 10", "2*-3--4+-.25"}; for (String testExpression : testExpressions) { Expression expression = parse(testExpression); System.out.printf("Input: \"%s\", AST: \"%s\", value=%s%n", testExpression, expression, expression.eval()); } } }
import operator class AstNode(object): def __init__( self, opr, left, right ): self.opr = opr self.l = left self.r = right def eval(self): return self.opr(self.l.eval(), self.r.eval()) class LeafNode(object): def __init__( self, valStrg ): self.v = int(valStrg) def eval(self): return self.v class Yaccer(object): def __init__(self): self.operstak = [] self.nodestak =[] self.__dict__.update(self.state1) def v1( self, valStrg ): self.nodestak.append( LeafNode(valStrg)) self.__dict__.update(self.state2) def o2( self, operchar ): def openParen(a,b): return 0 opDict= { '+': ( operator.add, 2, 2 ), '-': (operator.sub, 2, 2 ), '*': (operator.mul, 3, 3 ), '/': (operator.div, 3, 3 ), '^': ( pow, 4, 5 ), '(': ( openParen, 0, 8 ) } operPrecidence = opDict[operchar][2] self.redeuce(operPrecidence) self.operstak.append(opDict[operchar]) self.__dict__.update(self.state1) def syntaxErr(self, char ): print 'parse error - near operator "%s"' %char def pc2( self,operchar ): self.redeuce( 1 ) if len(self.operstak)>0: self.operstak.pop() else: print 'Error - no open parenthesis matches close parens.' self.__dict__.update(self.state2) def end(self): self.redeuce(0) return self.nodestak.pop() def redeuce(self, precidence): while len(self.operstak)>0: tailOper = self.operstak[-1] if tailOper[1] < precidence: break tailOper = self.operstak.pop() vrgt = self.nodestak.pop() vlft= self.nodestak.pop() self.nodestak.append( AstNode(tailOper[0], vlft, vrgt)) state1 = { 'v': v1, 'o':syntaxErr, 'po':o2, 'pc':syntaxErr } state2 = { 'v': syntaxErr, 'o':o2, 'po':syntaxErr, 'pc':pc2 } def Lex( exprssn, p ): bgn = None cp = -1 for c in exprssn: cp += 1 if c in '+-/*^()': if bgn is not None: p.v(p, exprssn[bgn:cp]) bgn = None if c=='(': p.po(p, c) elif c==')':p.pc(p, c) else: p.o(p, c) elif c in ' \t': if bgn is not None: p.v(p, exprssn[bgn:cp]) bgn = None elif c in '0123456789': if bgn is None: bgn = cp else: print 'Invalid character in expression' if bgn is not None: p.v(p, exprssn[bgn:cp]) bgn = None if bgn is not None: p.v(p, exprssn[bgn:cp+1]) bgn = None return p.end() expr = raw_input("Expression:") astTree = Lex( expr, Yaccer()) print expr, '=',astTree.eval()
Translate this program into Python but keep the logic exactly as in Java.
import java.util.Stack; public class ArithmeticEvaluation { public interface Expression { BigRational eval(); } public enum Parentheses {LEFT} public enum BinaryOperator { ADD('+', 1), SUB('-', 1), MUL('*', 2), DIV('/', 2); public final char symbol; public final int precedence; BinaryOperator(char symbol, int precedence) { this.symbol = symbol; this.precedence = precedence; } public BigRational eval(BigRational leftValue, BigRational rightValue) { switch (this) { case ADD: return leftValue.add(rightValue); case SUB: return leftValue.subtract(rightValue); case MUL: return leftValue.multiply(rightValue); case DIV: return leftValue.divide(rightValue); } throw new IllegalStateException(); } public static BinaryOperator forSymbol(char symbol) { for (BinaryOperator operator : values()) { if (operator.symbol == symbol) { return operator; } } throw new IllegalArgumentException(String.valueOf(symbol)); } } public static class Number implements Expression { private final BigRational number; public Number(BigRational number) { this.number = number; } @Override public BigRational eval() { return number; } @Override public String toString() { return number.toString(); } } public static class BinaryExpression implements Expression { public final Expression leftOperand; public final BinaryOperator operator; public final Expression rightOperand; public BinaryExpression(Expression leftOperand, BinaryOperator operator, Expression rightOperand) { this.leftOperand = leftOperand; this.operator = operator; this.rightOperand = rightOperand; } @Override public BigRational eval() { BigRational leftValue = leftOperand.eval(); BigRational rightValue = rightOperand.eval(); return operator.eval(leftValue, rightValue); } @Override public String toString() { return "(" + leftOperand + " " + operator.symbol + " " + rightOperand + ")"; } } private static void createNewOperand(BinaryOperator operator, Stack<Expression> operands) { Expression rightOperand = operands.pop(); Expression leftOperand = operands.pop(); operands.push(new BinaryExpression(leftOperand, operator, rightOperand)); } public static Expression parse(String input) { int curIndex = 0; boolean afterOperand = false; Stack<Expression> operands = new Stack<>(); Stack<Object> operators = new Stack<>(); while (curIndex < input.length()) { int startIndex = curIndex; char c = input.charAt(curIndex++); if (Character.isWhitespace(c)) continue; if (afterOperand) { if (c == ')') { Object operator; while (!operators.isEmpty() && ((operator = operators.pop()) != Parentheses.LEFT)) createNewOperand((BinaryOperator) operator, operands); continue; } afterOperand = false; BinaryOperator operator = BinaryOperator.forSymbol(c); while (!operators.isEmpty() && (operators.peek() != Parentheses.LEFT) && (((BinaryOperator) operators.peek()).precedence >= operator.precedence)) createNewOperand((BinaryOperator) operators.pop(), operands); operators.push(operator); continue; } if (c == '(') { operators.push(Parentheses.LEFT); continue; } afterOperand = true; while (curIndex < input.length()) { c = input.charAt(curIndex); if (((c < '0') || (c > '9')) && (c != '.')) break; curIndex++; } operands.push(new Number(BigRational.valueOf(input.substring(startIndex, curIndex)))); } while (!operators.isEmpty()) { Object operator = operators.pop(); if (operator == Parentheses.LEFT) throw new IllegalArgumentException(); createNewOperand((BinaryOperator) operator, operands); } Expression expression = operands.pop(); if (!operands.isEmpty()) throw new IllegalArgumentException(); return expression; } public static void main(String[] args) { String[] testExpressions = { "2+3", "2+3/4", "2*3-4", "2*(3+4)+5/6", "2 * (3 + (4 * 5 + (6 * 7) * 8) - 9) * 10", "2*-3--4+-.25"}; for (String testExpression : testExpressions) { Expression expression = parse(testExpression); System.out.printf("Input: \"%s\", AST: \"%s\", value=%s%n", testExpression, expression, expression.eval()); } } }
import operator class AstNode(object): def __init__( self, opr, left, right ): self.opr = opr self.l = left self.r = right def eval(self): return self.opr(self.l.eval(), self.r.eval()) class LeafNode(object): def __init__( self, valStrg ): self.v = int(valStrg) def eval(self): return self.v class Yaccer(object): def __init__(self): self.operstak = [] self.nodestak =[] self.__dict__.update(self.state1) def v1( self, valStrg ): self.nodestak.append( LeafNode(valStrg)) self.__dict__.update(self.state2) def o2( self, operchar ): def openParen(a,b): return 0 opDict= { '+': ( operator.add, 2, 2 ), '-': (operator.sub, 2, 2 ), '*': (operator.mul, 3, 3 ), '/': (operator.div, 3, 3 ), '^': ( pow, 4, 5 ), '(': ( openParen, 0, 8 ) } operPrecidence = opDict[operchar][2] self.redeuce(operPrecidence) self.operstak.append(opDict[operchar]) self.__dict__.update(self.state1) def syntaxErr(self, char ): print 'parse error - near operator "%s"' %char def pc2( self,operchar ): self.redeuce( 1 ) if len(self.operstak)>0: self.operstak.pop() else: print 'Error - no open parenthesis matches close parens.' self.__dict__.update(self.state2) def end(self): self.redeuce(0) return self.nodestak.pop() def redeuce(self, precidence): while len(self.operstak)>0: tailOper = self.operstak[-1] if tailOper[1] < precidence: break tailOper = self.operstak.pop() vrgt = self.nodestak.pop() vlft= self.nodestak.pop() self.nodestak.append( AstNode(tailOper[0], vlft, vrgt)) state1 = { 'v': v1, 'o':syntaxErr, 'po':o2, 'pc':syntaxErr } state2 = { 'v': syntaxErr, 'o':o2, 'po':syntaxErr, 'pc':pc2 } def Lex( exprssn, p ): bgn = None cp = -1 for c in exprssn: cp += 1 if c in '+-/*^()': if bgn is not None: p.v(p, exprssn[bgn:cp]) bgn = None if c=='(': p.po(p, c) elif c==')':p.pc(p, c) else: p.o(p, c) elif c in ' \t': if bgn is not None: p.v(p, exprssn[bgn:cp]) bgn = None elif c in '0123456789': if bgn is None: bgn = cp else: print 'Invalid character in expression' if bgn is not None: p.v(p, exprssn[bgn:cp]) bgn = None if bgn is not None: p.v(p, exprssn[bgn:cp+1]) bgn = None return p.end() expr = raw_input("Expression:") astTree = Lex( expr, Yaccer()) print expr, '=',astTree.eval()
Produce a functionally identical Python code for the snippet given in Java.
import java.util.Arrays; public class SpecialVariables { public static void main(String[] args) { System.out.println(Arrays.toString(args)); System.out.println(SpecialVariables.class); System.out.println(System.getenv()); System.out.println(System.getProperties()); System.out.println(Runtime.getRuntime().availableProcessors()); } }
names = sorted((set(globals().keys()) | set(__builtins__.__dict__.keys())) - set('_ names i'.split())) print( '\n'.join(' '.join(names[i:i+8]) for i in range(0, len(names), 8)) )
Write a version of this Java function in Python with identical behavior.
import java.io.File; import java.nio.file.Files; import java.util.ArrayList; import java.util.Arrays; public class Copypasta { public static void fatal_error(String errtext) { StackTraceElement[] stack = Thread.currentThread().getStackTrace(); StackTraceElement main = stack[stack.length - 1]; String mainClass = main.getClassName(); System.out.println("%" + errtext); System.out.println("usage: " + mainClass + " [filename.cp]"); System.exit(1); } public static void main(String[] args) { String fname = null; String source = null; try { fname = args[0]; source = new String(Files.readAllBytes(new File(fname).toPath())); } catch(Exception e) { fatal_error("error while trying to read from specified file"); } ArrayList<String> lines = new ArrayList<String>(Arrays.asList(source.split("\n"))); String clipboard = ""; int loc = 0; while(loc < lines.size()) { String command = lines.get(loc).trim(); try { if(command.equals("Copy")) clipboard += lines.get(loc + 1); else if(command.equals("CopyFile")) { if(lines.get(loc + 1).equals("TheF*ckingCode")) clipboard += source; else { String filetext = new String(Files.readAllBytes(new File(lines.get(loc + 1)).toPath())); clipboard += filetext; } } else if(command.equals("Duplicate")) { String origClipboard = clipboard; int amount = Integer.parseInt(lines.get(loc + 1)) - 1; for(int i = 0; i < amount; i++) clipboard += origClipboard; } else if(command.equals("Pasta!")) { System.out.println(clipboard); System.exit(0); } else fatal_error("unknown command '" + command + "' encountered on line " + new Integer(loc + 1).toString()); } catch(Exception e) { fatal_error("error while executing command '" + command + "' on line " + new Integer(loc + 1).toString()); } loc += 2; } } }
import sys def fatal_error(errtext): print("%" + errtext) print("usage: " + sys.argv[0] + " [filename.cp]") sys.exit(1) fname = None source = None try: fname = sys.argv[1] source = open(fname).read() except: fatal_error("error while trying to read from specified file") lines = source.split("\n") clipboard = "" loc = 0 while(loc < len(lines)): command = lines[loc].strip() try: if(command == "Copy"): clipboard += lines[loc + 1] elif(command == "CopyFile"): if(lines[loc + 1] == "TheF*ckingCode"): clipboard += source else: filetext = open(lines[loc+1]).read() clipboard += filetext elif(command == "Duplicate"): clipboard += clipboard * ((int(lines[loc + 1])) - 1) elif(command == "Pasta!"): print(clipboard) sys.exit(0) else: fatal_error("unknown command '" + command + "' encountered on line " + str(loc + 1)) except Exception as e: fatal_error("error while executing command '" + command + "' on line " + str(loc + 1) + ": " + e) loc += 2
Produce a language-to-language conversion: from Java to Python, same semantics.
import java.lang.reflect.Field; public class ListFields { public int examplePublicField = 42; private boolean examplePrivateField = true; public static void main(String[] args) throws IllegalAccessException { ListFields obj = new ListFields(); Class clazz = obj.getClass(); System.out.println("All public fields (including inherited):"); for (Field f : clazz.getFields()) { System.out.printf("%s\t%s\n", f, f.get(obj)); } System.out.println(); System.out.println("All declared fields (excluding inherited):"); for (Field f : clazz.getDeclaredFields()) { System.out.printf("%s\t%s\n", f, f.get(obj)); } } }
class Parent(object): __priv = 'private' def __init__(self, name): self.name = name def __repr__(self): return '%s(%s)' % (type(self).__name__, self.name) def doNothing(self): pass import re class Child(Parent): __rePrivate = re.compile('^_(Child|Parent)__') __reBleh = re.compile('\Wbleh$') @property def reBleh(self): return self.__reBleh def __init__(self, name, *args): super(Child, self).__init__(name) self.args = args def __dir__(self): myDir = filter( lambda p: not self.__rePrivate.match(p), list(set( \ sum([dir(base) for base in type(self).__bases__], []) \ + type(self).__dict__.keys() \ + self.__dict__.keys() \ ))) return myDir + map( lambda p: p + '_bleh', filter( lambda p: (p[:2] != '__' or p[-2:] != '__') and not callable(getattr(self, p)), myDir)) def __getattr__(self, name): if name[-5:] == '_bleh': return str(getattr(self, name[:-5])) + ' bleh' if hasattr(super(Child, chld), '__getattr__'): return super(Child, self).__getattr__(name) raise AttributeError("'%s' object has no attribute '%s'" % (type(self).__name__, name)) def __setattr__(self, name, value): if name[-5:] == '_bleh': if not (hasattr(self, name[:-5]) and callable(getattr(self, name[:-5]))): setattr(self, name[:-5], self.reBleh.sub('', value)) elif hasattr(super(Child, self), '__setattr__'): super(Child, self).__setattr__(name, value) elif hasattr(self, '__dict__'): self.__dict__[name] = value def __repr__(self): return '%s(%s, %s)' % (type(self).__name__, self.name, str(self.args).strip('[]()')) def doStuff(self): return (1+1.0/1e6) ** 1e6 par = Parent('par') par.parent = True dir(par) inspect.getmembers(par) chld = Child('chld', 0, 'I', 'two') chld.own = "chld's own" dir(chld) inspect.getmembers(chld)
Rewrite this program in Python while keeping its functionality equivalent to the Java version.
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class MinimalStepsDownToOne { public static void main(String[] args) { runTasks(getFunctions1()); runTasks(getFunctions2()); runTasks(getFunctions3()); } private static void runTasks(List<Function> functions) { Map<Integer,List<String>> minPath = getInitialMap(functions, 5); int max = 10; populateMap(minPath, functions, max); System.out.printf("%nWith functions: %s%n", functions); System.out.printf(" Minimum steps to 1:%n"); for ( int n = 2 ; n <= max ; n++ ) { int steps = minPath.get(n).size(); System.out.printf(" %2d: %d step%1s: %s%n", n, steps, steps == 1 ? "" : "s", minPath.get(n)); } displayMaxMin(minPath, functions, 2000); displayMaxMin(minPath, functions, 20000); displayMaxMin(minPath, functions, 100000); } private static void displayMaxMin(Map<Integer,List<String>> minPath, List<Function> functions, int max) { populateMap(minPath, functions, max); List<Integer> maxIntegers = getMaxMin(minPath, max); int maxSteps = maxIntegers.remove(0); int numCount = maxIntegers.size(); System.out.printf(" There %s %d number%s in the range 1-%d that have maximum 'minimal steps' of %d:%n %s%n", numCount == 1 ? "is" : "are", numCount, numCount == 1 ? "" : "s", max, maxSteps, maxIntegers); } private static List<Integer> getMaxMin(Map<Integer,List<String>> minPath, int max) { int maxSteps = Integer.MIN_VALUE; List<Integer> maxIntegers = new ArrayList<Integer>(); for ( int n = 2 ; n <= max ; n++ ) { int len = minPath.get(n).size(); if ( len > maxSteps ) { maxSteps = len; maxIntegers.clear(); maxIntegers.add(n); } else if ( len == maxSteps ) { maxIntegers.add(n); } } maxIntegers.add(0, maxSteps); return maxIntegers; } private static void populateMap(Map<Integer,List<String>> minPath, List<Function> functions, int max) { for ( int n = 2 ; n <= max ; n++ ) { if ( minPath.containsKey(n) ) { continue; } Function minFunction = null; int minSteps = Integer.MAX_VALUE; for ( Function f : functions ) { if ( f.actionOk(n) ) { int result = f.action(n); int steps = 1 + minPath.get(result).size(); if ( steps < minSteps ) { minFunction = f; minSteps = steps; } } } int result = minFunction.action(n); List<String> path = new ArrayList<String>(); path.add(minFunction.toString(n)); path.addAll(minPath.get(result)); minPath.put(n, path); } } private static Map<Integer,List<String>> getInitialMap(List<Function> functions, int max) { Map<Integer,List<String>> minPath = new HashMap<>(); for ( int i = 2 ; i <= max ; i++ ) { for ( Function f : functions ) { if ( f.actionOk(i) ) { int result = f.action(i); if ( result == 1 ) { List<String> path = new ArrayList<String>(); path.add(f.toString(i)); minPath.put(i, path); } } } } return minPath; } private static List<Function> getFunctions3() { List<Function> functions = new ArrayList<>(); functions.add(new Divide2Function()); functions.add(new Divide3Function()); functions.add(new Subtract2Function()); functions.add(new Subtract1Function()); return functions; } private static List<Function> getFunctions2() { List<Function> functions = new ArrayList<>(); functions.add(new Divide3Function()); functions.add(new Divide2Function()); functions.add(new Subtract2Function()); return functions; } private static List<Function> getFunctions1() { List<Function> functions = new ArrayList<>(); functions.add(new Divide3Function()); functions.add(new Divide2Function()); functions.add(new Subtract1Function()); return functions; } public abstract static class Function { abstract public int action(int n); abstract public boolean actionOk(int n); abstract public String toString(int n); } public static class Divide2Function extends Function { @Override public int action(int n) { return n/2; } @Override public boolean actionOk(int n) { return n % 2 == 0; } @Override public String toString(int n) { return "/2 -> " + n/2; } @Override public String toString() { return "Divisor 2"; } } public static class Divide3Function extends Function { @Override public int action(int n) { return n/3; } @Override public boolean actionOk(int n) { return n % 3 == 0; } @Override public String toString(int n) { return "/3 -> " + n/3; } @Override public String toString() { return "Divisor 3"; } } public static class Subtract1Function extends Function { @Override public int action(int n) { return n-1; } @Override public boolean actionOk(int n) { return true; } @Override public String toString(int n) { return "-1 -> " + (n-1); } @Override public String toString() { return "Subtractor 1"; } } public static class Subtract2Function extends Function { @Override public int action(int n) { return n-2; } @Override public boolean actionOk(int n) { return n > 2; } @Override public String toString(int n) { return "-2 -> " + (n-2); } @Override public String toString() { return "Subtractor 2"; } } }
from functools import lru_cache DIVS = {2, 3} SUBS = {1} class Minrec(): "Recursive, memoised minimised steps to 1" def __init__(self, divs=DIVS, subs=SUBS): self.divs, self.subs = divs, subs @lru_cache(maxsize=None) def _minrec(self, n): "Recursive, memoised" if n == 1: return 0, ['=1'] possibles = {} for d in self.divs: if n % d == 0: possibles[f'/{d}=>{n // d:2}'] = self._minrec(n // d) for s in self.subs: if n > s: possibles[f'-{s}=>{n - s:2}'] = self._minrec(n - s) thiskind, (count, otherkinds) = min(possibles.items(), key=lambda x: x[1]) ret = 1 + count, [thiskind] + otherkinds return ret def __call__(self, n): "Recursive, memoised" ans = self._minrec(n)[1][:-1] return len(ans), ans if __name__ == '__main__': for DIVS, SUBS in [({2, 3}, {1}), ({2, 3}, {2})]: minrec = Minrec(DIVS, SUBS) print('\nMINIMUM STEPS TO 1: Recursive algorithm') print(' Possible divisors: ', DIVS) print(' Possible decrements:', SUBS) for n in range(1, 11): steps, how = minrec(n) print(f' minrec({n:2}) in {steps:2} by: ', ', '.join(how)) upto = 2000 print(f'\n Those numbers up to {upto} that take the maximum, "minimal steps down to 1":') stepn = sorted((minrec(n)[0], n) for n in range(upto, 0, -1)) mx = stepn[-1][0] ans = [x[1] for x in stepn if x[0] == mx] print(' Taking', mx, f'steps is/are the {len(ans)} numbers:', ', '.join(str(n) for n in sorted(ans))) print()
Produce a functionally identical Python code for the snippet given in Java.
import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.StringUtils; public class ColumnAligner { private List<String[]> words = new ArrayList<>(); private int columns = 0; private List<Integer> columnWidths = new ArrayList<>(); public ColumnAligner(String s) { String[] lines = s.split("\\n"); for (String line : lines) { processInputLine(line); } } public ColumnAligner(List<String> lines) { for (String line : lines) { processInputLine(line); } } private void processInputLine(String line) { String[] lineWords = line.split("\\$"); words.add(lineWords); columns = Math.max(columns, lineWords.length); for (int i = 0; i < lineWords.length; i++) { String word = lineWords[i]; if (i >= columnWidths.size()) { columnWidths.add(word.length()); } else { columnWidths.set(i, Math.max(columnWidths.get(i), word.length())); } } } interface AlignFunction { String align(String s, int length); } public String alignLeft() { return align(new AlignFunction() { @Override public String align(String s, int length) { return StringUtils.rightPad(s, length); } }); } public String alignRight() { return align(new AlignFunction() { @Override public String align(String s, int length) { return StringUtils.leftPad(s, length); } }); } public String alignCenter() { return align(new AlignFunction() { @Override public String align(String s, int length) { return StringUtils.center(s, length); } }); } private String align(AlignFunction a) { StringBuilder result = new StringBuilder(); for (String[] lineWords : words) { for (int i = 0; i < lineWords.length; i++) { String word = lineWords[i]; if (i == 0) { result.append("|"); } result.append(a.align(word, columnWidths.get(i)) + "|"); } result.append("\n"); } return result.toString(); } public static void main(String args[]) throws IOException { if (args.length < 1) { System.out.println("Usage: ColumnAligner file [left|right|center]"); return; } String filePath = args[0]; String alignment = "left"; if (args.length >= 2) { alignment = args[1]; } ColumnAligner ca = new ColumnAligner(Files.readAllLines(Paths.get(filePath), StandardCharsets.UTF_8)); switch (alignment) { case "left": System.out.print(ca.alignLeft()); break; case "right": System.out.print(ca.alignRight()); break; case "center": System.out.print(ca.alignCenter()); break; default: System.err.println(String.format("Error! Unknown alignment: '%s'", alignment)); break; } } }
from itertools import zip_longest txt = parts = [line.rstrip("$").split("$") for line in txt.splitlines()] widths = [max(len(word) for word in col) for col in zip_longest(*parts, fillvalue='')] for justify in "<_Left ^_Center >_Right".split(): j, jtext = justify.split('_') print(f"{jtext} column-aligned output:\n") for line in parts: print(' '.join(f"{wrd:{j}{wdth}}" for wdth, wrd in zip(widths, line))) print("- " * 52)
Translate the given Java code snippet into Python without altering its behavior.
import java.net.URI; import java.net.URISyntaxException; public class WebAddressParser{ public static void main(String[] args){ parseAddress("foo: parseAddress("urn:example:animal:ferret:nose"); } static void parseAddress(String a){ System.out.println("Parsing " + a); try{ URI u = new URI(a); System.out.println("\tscheme = " + u.getScheme()); System.out.println("\tdomain = " + u.getHost()); System.out.println("\tport = " + (-1==u.getPort()?"default":u.getPort())); System.out.println("\tpath = " + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath())); System.out.println("\tquery = " + u.getQuery()); System.out.println("\tfragment = " + u.getFragment()); } catch (URISyntaxException x){ System.err.println("Oops: " + x); } } }
import urllib.parse as up url = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1 print('url.scheme = ', url.scheme) print('url.netloc = ', url.netloc) print('url.hostname = ', url.hostname) print('url.port = ', url.port) print('url.path = ', url.path) print('url.params = ', url.params) print('url.query = ', url.query) print('url.fragment = ', url.fragment) print('url.username = ', url.username) print('url.password = ', url.password)
Rewrite this program in Python while keeping its functionality equivalent to the Java version.
import java.net.URI; import java.net.URISyntaxException; public class WebAddressParser{ public static void main(String[] args){ parseAddress("foo: parseAddress("urn:example:animal:ferret:nose"); } static void parseAddress(String a){ System.out.println("Parsing " + a); try{ URI u = new URI(a); System.out.println("\tscheme = " + u.getScheme()); System.out.println("\tdomain = " + u.getHost()); System.out.println("\tport = " + (-1==u.getPort()?"default":u.getPort())); System.out.println("\tpath = " + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath())); System.out.println("\tquery = " + u.getQuery()); System.out.println("\tfragment = " + u.getFragment()); } catch (URISyntaxException x){ System.err.println("Oops: " + x); } } }
import urllib.parse as up url = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1 print('url.scheme = ', url.scheme) print('url.netloc = ', url.netloc) print('url.hostname = ', url.hostname) print('url.port = ', url.port) print('url.path = ', url.path) print('url.params = ', url.params) print('url.query = ', url.query) print('url.fragment = ', url.fragment) print('url.username = ', url.username) print('url.password = ', url.password)
Rewrite the snippet below in Python so it works the same as the original Java code.
import java.math.BigInteger; import java.util.List; public class Base58CheckEncoding { private static final String ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; private static final BigInteger BIG0 = BigInteger.ZERO; private static final BigInteger BIG58 = BigInteger.valueOf(58); private static String convertToBase58(String hash) { return convertToBase58(hash, 16); } private static String convertToBase58(String hash, int base) { BigInteger x; if (base == 16 && hash.substring(0, 2).equals("0x")) { x = new BigInteger(hash.substring(2), 16); } else { x = new BigInteger(hash, base); } StringBuilder sb = new StringBuilder(); while (x.compareTo(BIG0) > 0) { int r = x.mod(BIG58).intValue(); sb.append(ALPHABET.charAt(r)); x = x.divide(BIG58); } return sb.reverse().toString(); } public static void main(String[] args) { String s = "25420294593250030202636073700053352635053786165627414518"; String b = convertToBase58(s, 10); System.out.printf("%s -> %s\n", s, b); List<String> hashes = List.of( "0x61", "0x626262", "0x636363", "0x73696d706c792061206c6f6e6720737472696e67", "0x516b6fcd0f", "0xbf4f89001e670274dd", "0x572e4794", "0xecac89cad93923c02321", "0x10c8511e" ); for (String hash : hashes) { String b58 = convertToBase58(hash); System.out.printf("%-56s -> %s\n", hash, b58); } } }
ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" def convertToBase58(num): sb = '' while (num > 0): r = num % 58 sb = sb + ALPHABET[r] num = num // 58; return sb[::-1] s = 25420294593250030202636073700053352635053786165627414518 b = convertToBase58(s) print("%-56d -> %s" % (s, b)) hash_arr = [0x61, 0x626262, 0x636363, 0x73696d706c792061206c6f6e6720737472696e67, 0x516b6fcd0f, 0xbf4f89001e670274dd, 0x572e4794, 0xecac89cad93923c02321, 0x10c8511e] for num in hash_arr: b = convertToBase58(num) print("0x%-54x -> %s" % (num, b))
Write a version of this Java function in Python with identical behavior.
import java.math.BigInteger; import java.util.List; public class Base58CheckEncoding { private static final String ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; private static final BigInteger BIG0 = BigInteger.ZERO; private static final BigInteger BIG58 = BigInteger.valueOf(58); private static String convertToBase58(String hash) { return convertToBase58(hash, 16); } private static String convertToBase58(String hash, int base) { BigInteger x; if (base == 16 && hash.substring(0, 2).equals("0x")) { x = new BigInteger(hash.substring(2), 16); } else { x = new BigInteger(hash, base); } StringBuilder sb = new StringBuilder(); while (x.compareTo(BIG0) > 0) { int r = x.mod(BIG58).intValue(); sb.append(ALPHABET.charAt(r)); x = x.divide(BIG58); } return sb.reverse().toString(); } public static void main(String[] args) { String s = "25420294593250030202636073700053352635053786165627414518"; String b = convertToBase58(s, 10); System.out.printf("%s -> %s\n", s, b); List<String> hashes = List.of( "0x61", "0x626262", "0x636363", "0x73696d706c792061206c6f6e6720737472696e67", "0x516b6fcd0f", "0xbf4f89001e670274dd", "0x572e4794", "0xecac89cad93923c02321", "0x10c8511e" ); for (String hash : hashes) { String b58 = convertToBase58(hash); System.out.printf("%-56s -> %s\n", hash, b58); } } }
ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" def convertToBase58(num): sb = '' while (num > 0): r = num % 58 sb = sb + ALPHABET[r] num = num // 58; return sb[::-1] s = 25420294593250030202636073700053352635053786165627414518 b = convertToBase58(s) print("%-56d -> %s" % (s, b)) hash_arr = [0x61, 0x626262, 0x636363, 0x73696d706c792061206c6f6e6720737472696e67, 0x516b6fcd0f, 0xbf4f89001e670274dd, 0x572e4794, 0xecac89cad93923c02321, 0x10c8511e] for num in hash_arr: b = convertToBase58(num) print("0x%-54x -> %s" % (num, b))
Transform the following Java implementation into Python, maintaining the same output and logic.
public static void main(String... args){ HashMap<String, Integer> vars = new HashMap<String, Integer>(); vars.put("Variable name", 3); vars.put("Next variable name", 5); Scanner sc = new Scanner(System.in); String str = sc.next(); vars.put(str, sc.nextInt()); System.out.println(vars.get("Variable name")); System.out.println(vars.get(str)); }
>>> name = raw_input("Enter a variable name: ") Enter a variable name: X >>> globals()[name] = 42 >>> X 42
Produce a language-to-language conversion: from Java to Python, same semantics.
import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; public class DataEncryptionStandard { private static byte[] toHexByteArray(String self) { byte[] bytes = new byte[self.length() / 2]; for (int i = 0; i < bytes.length; ++i) { bytes[i] = ((byte) Integer.parseInt(self.substring(i * 2, i * 2 + 2), 16)); } return bytes; } private static void printHexBytes(byte[] self, String label) { System.out.printf("%s: ", label); for (byte b : self) { int bb = (b >= 0) ? ((int) b) : b + 256; String ts = Integer.toString(bb, 16); if (ts.length() < 2) { ts = "0" + ts; } System.out.print(ts); } System.out.println(); } public static void main(String[] args) throws Exception { String strKey = "0e329232ea6d0d73"; byte[] keyBytes = toHexByteArray(strKey); SecretKeySpec key = new SecretKeySpec(keyBytes, "DES"); Cipher encCipher = Cipher.getInstance("DES"); encCipher.init(Cipher.ENCRYPT_MODE, key); String strPlain = "8787878787878787"; byte[] plainBytes = toHexByteArray(strPlain); byte[] encBytes = encCipher.doFinal(plainBytes); printHexBytes(encBytes, "Encoded"); Cipher decCipher = Cipher.getInstance("DES"); decCipher.init(Cipher.DECRYPT_MODE, key); byte[] decBytes = decCipher.doFinal(encBytes); printHexBytes(decBytes, "Decoded"); } }
IP = ( 58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4, 62, 54, 46, 38, 30, 22, 14, 6, 64, 56, 48, 40, 32, 24, 16, 8, 57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3, 61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7 ) IP_INV = ( 40, 8, 48, 16, 56, 24, 64, 32, 39, 7, 47, 15, 55, 23, 63, 31, 38, 6, 46, 14, 54, 22, 62, 30, 37, 5, 45, 13, 53, 21, 61, 29, 36, 4, 44, 12, 52, 20, 60, 28, 35, 3, 43, 11, 51, 19, 59, 27, 34, 2, 42, 10, 50, 18, 58, 26, 33, 1, 41, 9, 49, 17, 57, 25 ) PC1 = ( 57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35, 27, 19, 11, 3, 60, 52, 44, 36, 63, 55, 47, 39, 31, 23, 15, 7, 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 28, 20, 12, 4 ) PC2 = ( 14, 17, 11, 24, 1, 5, 3, 28, 15, 6, 21, 10, 23, 19, 12, 4, 26, 8, 16, 7, 27, 20, 13, 2, 41, 52, 31, 37, 47, 55, 30, 40, 51, 45, 33, 48, 44, 49, 39, 56, 34, 53, 46, 42, 50, 36, 29, 32 ) E = ( 32, 1, 2, 3, 4, 5, 4, 5, 6, 7, 8, 9, 8, 9, 10, 11, 12, 13, 12, 13, 14, 15, 16, 17, 16, 17, 18, 19, 20, 21, 20, 21, 22, 23, 24, 25, 24, 25, 26, 27, 28, 29, 28, 29, 30, 31, 32, 1 ) Sboxes = { 0: ( 14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7, 0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8, 4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0, 15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13 ), 1: ( 15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10, 3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5, 0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15, 13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9 ), 2: ( 10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8, 13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1, 13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7, 1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12 ), 3: ( 7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15, 13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9, 10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4, 3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14 ), 4: ( 2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9, 14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6, 4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14, 11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3 ), 5: ( 12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11, 10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8, 9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6, 4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13 ), 6: ( 4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1, 13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6, 1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2, 6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12 ), 7: ( 13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7, 1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2, 7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8, 2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11 ) } P = ( 16, 7, 20, 21, 29, 12, 28, 17, 1, 15, 23, 26, 5, 18, 31, 10, 2, 8, 24, 14, 32, 27, 3, 9, 19, 13, 30, 6, 22, 11, 4, 25 ) def encrypt(msg, key, decrypt=False): assert isinstance(msg, int) and isinstance(key, int) assert not msg.bit_length() > 64 assert not key.bit_length() > 64 key = permutation_by_table(key, 64, PC1) C0 = key >> 28 D0 = key & (2**28-1) round_keys = generate_round_keys(C0, D0) msg_block = permutation_by_table(msg, 64, IP) L0 = msg_block >> 32 R0 = msg_block & (2**32-1) L_last = L0 R_last = R0 for i in range(1,17): if decrypt: i = 17-i L_round = R_last R_round = L_last ^ round_function(R_last, round_keys[i]) L_last = L_round R_last = R_round cipher_block = (R_round<<32) + L_round cipher_block = permutation_by_table(cipher_block, 64, IP_INV) return cipher_block def round_function(Ri, Ki): Ri = permutation_by_table(Ri, 32, E) Ri ^= Ki Ri_blocks = [((Ri & (0b111111 << shift_val)) >> shift_val) for shift_val in (42,36,30,24,18,12,6,0)] for i, block in enumerate(Ri_blocks): row = ((0b100000 & block) >> 4) + (0b1 & block) col = (0b011110 & block) >> 1 Ri_blocks[i] = Sboxes[i][16*row+col] Ri_blocks = zip(Ri_blocks, (28,24,20,16,12,8,4,0)) Ri = 0 for block, lshift_val in Ri_blocks: Ri += (block << lshift_val) Ri = permutation_by_table(Ri, 32, P) return Ri def permutation_by_table(block, block_len, table): block_str = bin(block)[2:].zfill(block_len) perm = [] for pos in range(len(table)): perm.append(block_str[table[pos]-1]) return int(''.join(perm), 2) def generate_round_keys(C0, D0): round_keys = dict.fromkeys(range(0,17)) lrot_values = (1,1,2,2,2,2,2,2,1,2,2,2,2,2,2,1) lrot = lambda val, r_bits, max_bits: \ (val << r_bits%max_bits) & (2**max_bits-1) | \ ((val & (2**max_bits-1)) >> (max_bits-(r_bits%max_bits))) C0 = lrot(C0, 0, 28) D0 = lrot(D0, 0, 28) round_keys[0] = (C0, D0) for i, rot_val in enumerate(lrot_values): i+=1 Ci = lrot(round_keys[i-1][0], rot_val, 28) Di = lrot(round_keys[i-1][1], rot_val, 28) round_keys[i] = (Ci, Di) del round_keys[0] for i, (Ci, Di) in round_keys.items(): Ki = (Ci << 28) + Di round_keys[i] = permutation_by_table(Ki, 56, PC2) return round_keys k = 0x0e329232ea6d0d73 k2 = 0x133457799BBCDFF1 m = 0x8787878787878787 m2 = 0x0123456789ABCDEF def prove(key, msg): print('key: {:x}'.format(key)) print('message: {:x}'.format(msg)) cipher_text = encrypt(msg, key) print('encrypted: {:x}'.format(cipher_text)) plain_text = encrypt(cipher_text, key, decrypt=True) print('decrypted: {:x}'.format(plain_text)) prove(k, m) print('----------') prove(k2, m2)
Convert this Java block to Python, preserving its control flow and logic.
import java.math.BigInteger; import java.util.Arrays; public class FibonacciMatrixExponentiation { public static void main(String[] args) { BigInteger mod = BigInteger.TEN.pow(20); for ( int exp : Arrays.asList(32, 64) ) { System.out.printf("Last 20 digits of fib(2^%d) = %s%n", exp, fibMod(BigInteger.valueOf(2).pow(exp), mod)); } for ( int i = 1 ; i <= 7 ; i++ ) { BigInteger n = BigInteger.TEN.pow(i); System.out.printf("fib(%,d) = %s%n", n, displayFib(fib(n))); } } private static String displayFib(BigInteger fib) { String s = fib.toString(); if ( s.length() <= 40 ) { return s; } return s.substring(0, 20) + " ... " + s.subSequence(s.length()-20, s.length()); } private static BigInteger fib(BigInteger k) { BigInteger aRes = BigInteger.ZERO; BigInteger bRes = BigInteger.ONE; BigInteger cRes = BigInteger.ONE; BigInteger aBase = BigInteger.ZERO; BigInteger bBase = BigInteger.ONE; BigInteger cBase = BigInteger.ONE; while ( k.compareTo(BigInteger.ZERO) > 0 ) { if ( k.mod(BigInteger.valueOf(2)).compareTo(BigInteger.ONE) == 0 ) { BigInteger temp1 = aRes.multiply(aBase).add(bRes.multiply(bBase)); BigInteger temp2 = aBase.multiply(bRes).add(bBase.multiply(cRes)); BigInteger temp3 = bBase.multiply(bRes).add(cBase.multiply(cRes)); aRes = temp1; bRes = temp2; cRes = temp3; } k = k.shiftRight(1); BigInteger temp1 = aBase.multiply(aBase).add(bBase.multiply(bBase)); BigInteger temp2 = aBase.multiply(bBase).add(bBase.multiply(cBase)); BigInteger temp3 = bBase.multiply(bBase).add(cBase.multiply(cBase)); aBase = temp1; bBase = temp2; cBase = temp3; } return aRes; } private static BigInteger fibMod(BigInteger k, BigInteger mod) { BigInteger aRes = BigInteger.ZERO; BigInteger bRes = BigInteger.ONE; BigInteger cRes = BigInteger.ONE; BigInteger aBase = BigInteger.ZERO; BigInteger bBase = BigInteger.ONE; BigInteger cBase = BigInteger.ONE; while ( k.compareTo(BigInteger.ZERO) > 0 ) { if ( k.mod(BigInteger.valueOf(2)).compareTo(BigInteger.ONE) == 0 ) { BigInteger temp1 = aRes.multiply(aBase).add(bRes.multiply(bBase)).mod(mod); BigInteger temp2 = aBase.multiply(bRes).add(bBase.multiply(cRes)).mod(mod); BigInteger temp3 = bBase.multiply(bRes).add(cBase.multiply(cRes)).mod(mod); aRes = temp1; bRes = temp2; cRes = temp3; } k = k.shiftRight(1); BigInteger temp1 = aBase.multiply(aBase).add(bBase.multiply(bBase)).mod(mod); BigInteger temp2 = aBase.multiply(bBase).add(bBase.multiply(cBase)).mod(mod); BigInteger temp3 = bBase.multiply(bBase).add(cBase.multiply(cBase)).mod(mod); aBase = temp1; bBase = temp2; cBase = temp3; } return aRes.mod(mod); } }
class Head(): def __init__(self, lo, hi=None, shift=0): if hi is None: hi = lo d = hi - lo ds, ls, hs = str(d), str(lo), str(hi) if d and len(ls) > len(ds): assert(len(ls) - len(ds) + 1 > 21) lo = int(str(lo)[:len(ls) - len(ds) + 1]) hi = int(str(hi)[:len(hs) - len(ds) + 1]) + 1 shift += len(ds) - 1 elif len(ls) > 100: lo = int(str(ls)[:100]) hi = lo + 1 shift = len(ls) - 100 self.lo, self.hi, self.shift = lo, hi, shift def __mul__(self, other): lo = self.lo*other.lo hi = self.hi*other.hi shift = self.shift + other.shift return Head(lo, hi, shift) def __add__(self, other): if self.shift < other.shift: return other + self sh = self.shift - other.shift if sh >= len(str(other.hi)): return Head(self.lo, self.hi, self.shift) ls = str(other.lo) hs = str(other.hi) lo = self.lo + int(ls[:len(ls)-sh]) hi = self.hi + int(hs[:len(hs)-sh]) return Head(lo, hi, self.shift) def __repr__(self): return str(self.hi)[:20] class Tail(): def __init__(self, v): self.v = int(f'{v:020d}'[-20:]) def __add__(self, other): return Tail(self.v + other.v) def __mul__(self, other): return Tail(self.v*other.v) def __repr__(self): return f'{self.v:020d}'[-20:] def mul(a, b): return a[0]*b[0] + a[1]*b[1], a[0]*b[1] + a[1]*b[2], a[1]*b[1] + a[2]*b[2] def fibo(n, cls): n -= 1 zero, one = cls(0), cls(1) m = (one, one, zero) e = (one, zero, one) while n: if n&1: e = mul(m, e) m = mul(m, m) n >>= 1 return f'{e[0]}' for i in range(2, 10): n = 10**i print(f'10^{i} :', fibo(n, Head), '...', fibo(n, Tail)) for i in range(3, 8): n = 2**i s = f'2^{n}' print(f'{s:5s}:', fibo(2**n, Head), '...', fibo(2**n, Tail))
Preserve the algorithm and functionality while converting the code from Java to Python.
import java.math.BigInteger; import java.util.Arrays; public class FibonacciMatrixExponentiation { public static void main(String[] args) { BigInteger mod = BigInteger.TEN.pow(20); for ( int exp : Arrays.asList(32, 64) ) { System.out.printf("Last 20 digits of fib(2^%d) = %s%n", exp, fibMod(BigInteger.valueOf(2).pow(exp), mod)); } for ( int i = 1 ; i <= 7 ; i++ ) { BigInteger n = BigInteger.TEN.pow(i); System.out.printf("fib(%,d) = %s%n", n, displayFib(fib(n))); } } private static String displayFib(BigInteger fib) { String s = fib.toString(); if ( s.length() <= 40 ) { return s; } return s.substring(0, 20) + " ... " + s.subSequence(s.length()-20, s.length()); } private static BigInteger fib(BigInteger k) { BigInteger aRes = BigInteger.ZERO; BigInteger bRes = BigInteger.ONE; BigInteger cRes = BigInteger.ONE; BigInteger aBase = BigInteger.ZERO; BigInteger bBase = BigInteger.ONE; BigInteger cBase = BigInteger.ONE; while ( k.compareTo(BigInteger.ZERO) > 0 ) { if ( k.mod(BigInteger.valueOf(2)).compareTo(BigInteger.ONE) == 0 ) { BigInteger temp1 = aRes.multiply(aBase).add(bRes.multiply(bBase)); BigInteger temp2 = aBase.multiply(bRes).add(bBase.multiply(cRes)); BigInteger temp3 = bBase.multiply(bRes).add(cBase.multiply(cRes)); aRes = temp1; bRes = temp2; cRes = temp3; } k = k.shiftRight(1); BigInteger temp1 = aBase.multiply(aBase).add(bBase.multiply(bBase)); BigInteger temp2 = aBase.multiply(bBase).add(bBase.multiply(cBase)); BigInteger temp3 = bBase.multiply(bBase).add(cBase.multiply(cBase)); aBase = temp1; bBase = temp2; cBase = temp3; } return aRes; } private static BigInteger fibMod(BigInteger k, BigInteger mod) { BigInteger aRes = BigInteger.ZERO; BigInteger bRes = BigInteger.ONE; BigInteger cRes = BigInteger.ONE; BigInteger aBase = BigInteger.ZERO; BigInteger bBase = BigInteger.ONE; BigInteger cBase = BigInteger.ONE; while ( k.compareTo(BigInteger.ZERO) > 0 ) { if ( k.mod(BigInteger.valueOf(2)).compareTo(BigInteger.ONE) == 0 ) { BigInteger temp1 = aRes.multiply(aBase).add(bRes.multiply(bBase)).mod(mod); BigInteger temp2 = aBase.multiply(bRes).add(bBase.multiply(cRes)).mod(mod); BigInteger temp3 = bBase.multiply(bRes).add(cBase.multiply(cRes)).mod(mod); aRes = temp1; bRes = temp2; cRes = temp3; } k = k.shiftRight(1); BigInteger temp1 = aBase.multiply(aBase).add(bBase.multiply(bBase)).mod(mod); BigInteger temp2 = aBase.multiply(bBase).add(bBase.multiply(cBase)).mod(mod); BigInteger temp3 = bBase.multiply(bBase).add(cBase.multiply(cBase)).mod(mod); aBase = temp1; bBase = temp2; cBase = temp3; } return aRes.mod(mod); } }
class Head(): def __init__(self, lo, hi=None, shift=0): if hi is None: hi = lo d = hi - lo ds, ls, hs = str(d), str(lo), str(hi) if d and len(ls) > len(ds): assert(len(ls) - len(ds) + 1 > 21) lo = int(str(lo)[:len(ls) - len(ds) + 1]) hi = int(str(hi)[:len(hs) - len(ds) + 1]) + 1 shift += len(ds) - 1 elif len(ls) > 100: lo = int(str(ls)[:100]) hi = lo + 1 shift = len(ls) - 100 self.lo, self.hi, self.shift = lo, hi, shift def __mul__(self, other): lo = self.lo*other.lo hi = self.hi*other.hi shift = self.shift + other.shift return Head(lo, hi, shift) def __add__(self, other): if self.shift < other.shift: return other + self sh = self.shift - other.shift if sh >= len(str(other.hi)): return Head(self.lo, self.hi, self.shift) ls = str(other.lo) hs = str(other.hi) lo = self.lo + int(ls[:len(ls)-sh]) hi = self.hi + int(hs[:len(hs)-sh]) return Head(lo, hi, self.shift) def __repr__(self): return str(self.hi)[:20] class Tail(): def __init__(self, v): self.v = int(f'{v:020d}'[-20:]) def __add__(self, other): return Tail(self.v + other.v) def __mul__(self, other): return Tail(self.v*other.v) def __repr__(self): return f'{self.v:020d}'[-20:] def mul(a, b): return a[0]*b[0] + a[1]*b[1], a[0]*b[1] + a[1]*b[2], a[1]*b[1] + a[2]*b[2] def fibo(n, cls): n -= 1 zero, one = cls(0), cls(1) m = (one, one, zero) e = (one, zero, one) while n: if n&1: e = mul(m, e) m = mul(m, m) n >>= 1 return f'{e[0]}' for i in range(2, 10): n = 10**i print(f'10^{i} :', fibo(n, Head), '...', fibo(n, Tail)) for i in range(3, 8): n = 2**i s = f'2^{n}' print(f'{s:5s}:', fibo(2**n, Head), '...', fibo(2**n, Tail))
Port the following code from Java to Python with equivalent syntax and logic.
import java.io.File; import java.util.*; import java.util.regex.*; public class CommatizingNumbers { public static void main(String[] args) throws Exception { commatize("pi=3.14159265358979323846264338327950288419716939937510582" + "097494459231", 6, 5, " "); commatize("The author has two Z$100000000000000 Zimbabwe notes (100 " + "trillion).", 0, 3, "."); try (Scanner sc = new Scanner(new File("input.txt"))) { while(sc.hasNext()) commatize(sc.nextLine()); } } static void commatize(String s) { commatize(s, 0, 3, ","); } static void commatize(String s, int start, int step, String ins) { if (start < 0 || start > s.length() || step < 1 || step > s.length()) return; Matcher m = Pattern.compile("([1-9][0-9]*)").matcher(s.substring(start)); StringBuffer result = new StringBuffer(s.substring(0, start)); if (m.find()) { StringBuilder sb = new StringBuilder(m.group(1)).reverse(); for (int i = step; i < sb.length(); i += step) sb.insert(i++, ins); m.appendReplacement(result, sb.reverse().toString()); } System.out.println(m.appendTail(result)); } }
import re as RegEx def Commatize( _string, _startPos=0, _periodLen=3, _separator="," ): outString = "" strPos = 0 matches = RegEx.findall( "[0-9]*", _string ) for match in matches[:-1]: if not match: outString += _string[ strPos ] strPos += 1 else: if len(match) > _periodLen: leadIn = match[:_startPos] periods = [ match [ i:i + _periodLen ] for i in range ( _startPos, len ( match ), _periodLen ) ] outString += leadIn + _separator.join( periods ) else: outString += match strPos += len( match ) return outString print ( Commatize( "pi=3.14159265358979323846264338327950288419716939937510582097494459231", 0, 5, " " ) ) print ( Commatize( "The author has two Z$100000000000000 Zimbabwe notes (100 trillion).", 0, 3, "." )) print ( Commatize( "\"-in Aus$+1411.8millions\"" )) print ( Commatize( "===US$0017440 millions=== (in 2000 dollars)" )) print ( Commatize( "123.e8000 is pretty big." )) print ( Commatize( "The land area of the earth is 57268900(29% of the surface) square miles." )) print ( Commatize( "Ain't no numbers in this here words, nohow, no way, Jose." )) print ( Commatize( "James was never known as 0000000007" )) print ( Commatize( "Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe." )) print ( Commatize( "␢␢␢$-140000±100 millions." )) print ( Commatize( "6/9/1946 was a good year for some." ))
Produce a language-to-language conversion: from Java to Python, same semantics.
import java.math.BigInteger; import java.util.HashMap; import java.util.Map; import java.util.Objects; public class ArithmeticCoding { private static class Triple<A, B, C> { A a; B b; C c; Triple(A a, B b, C c) { this.a = a; this.b = b; this.c = c; } } private static class Freq extends HashMap<Character, Long> { } private static Freq cumulativeFreq(Freq freq) { long total = 0; Freq cf = new Freq(); for (int i = 0; i < 256; ++i) { char c = (char) i; Long v = freq.get(c); if (v != null) { cf.put(c, total); total += v; } } return cf; } private static Triple<BigInteger, Integer, Freq> arithmeticCoding(String str, Long radix) { char[] chars = str.toCharArray(); Freq freq = new Freq(); for (char c : chars) { if (!freq.containsKey(c)) freq.put(c, 1L); else freq.put(c, freq.get(c) + 1); } Freq cf = cumulativeFreq(freq); BigInteger base = BigInteger.valueOf(chars.length); BigInteger lower = BigInteger.ZERO; BigInteger pf = BigInteger.ONE; for (char c : chars) { BigInteger x = BigInteger.valueOf(cf.get(c)); lower = lower.multiply(base).add(x.multiply(pf)); pf = pf.multiply(BigInteger.valueOf(freq.get(c))); } BigInteger upper = lower.add(pf); int powr = 0; BigInteger bigRadix = BigInteger.valueOf(radix); while (true) { pf = pf.divide(bigRadix); if (pf.equals(BigInteger.ZERO)) break; powr++; } BigInteger diff = upper.subtract(BigInteger.ONE).divide(bigRadix.pow(powr)); return new Triple<>(diff, powr, freq); } private static String arithmeticDecoding(BigInteger num, long radix, int pwr, Freq freq) { BigInteger powr = BigInteger.valueOf(radix); BigInteger enc = num.multiply(powr.pow(pwr)); long base = 0; for (Long v : freq.values()) base += v; Freq cf = cumulativeFreq(freq); Map<Long, Character> dict = new HashMap<>(); for (Map.Entry<Character, Long> entry : cf.entrySet()) dict.put(entry.getValue(), entry.getKey()); long lchar = -1; for (long i = 0; i < base; ++i) { Character v = dict.get(i); if (v != null) { lchar = v; } else if (lchar != -1) { dict.put(i, (char) lchar); } } StringBuilder decoded = new StringBuilder((int) base); BigInteger bigBase = BigInteger.valueOf(base); for (long i = base - 1; i >= 0; --i) { BigInteger pow = bigBase.pow((int) i); BigInteger div = enc.divide(pow); Character c = dict.get(div.longValue()); BigInteger fv = BigInteger.valueOf(freq.get(c)); BigInteger cv = BigInteger.valueOf(cf.get(c)); BigInteger diff = enc.subtract(pow.multiply(cv)); enc = diff.divide(fv); decoded.append(c); } return decoded.toString(); } public static void main(String[] args) { long radix = 10; String[] strings = {"DABDDB", "DABDDBBDDBA", "ABRACADABRA", "TOBEORNOTTOBEORTOBEORNOT"}; String fmt = "%-25s=> %19s * %d^%s\n"; for (String str : strings) { Triple<BigInteger, Integer, Freq> encoded = arithmeticCoding(str, radix); String dec = arithmeticDecoding(encoded.a, radix, encoded.b, encoded.c); System.out.printf(fmt, str, encoded.a, radix, encoded.b); if (!Objects.equals(str, dec)) throw new RuntimeException("\tHowever that is incorrect!"); } } }
from collections import Counter def cumulative_freq(freq): cf = {} total = 0 for b in range(256): if b in freq: cf[b] = total total += freq[b] return cf def arithmethic_coding(bytes, radix): freq = Counter(bytes) cf = cumulative_freq(freq) base = len(bytes) lower = 0 pf = 1 for b in bytes: lower = lower*base + cf[b]*pf pf *= freq[b] upper = lower+pf pow = 0 while True: pf //= radix if pf==0: break pow += 1 enc = (upper-1) // radix**pow return enc, pow, freq def arithmethic_decoding(enc, radix, pow, freq): enc *= radix**pow; base = sum(freq.values()) cf = cumulative_freq(freq) dict = {} for k,v in cf.items(): dict[v] = k lchar = None for i in range(base): if i in dict: lchar = dict[i] elif lchar is not None: dict[i] = lchar decoded = bytearray() for i in range(base-1, -1, -1): pow = base**i div = enc//pow c = dict[div] fv = freq[c] cv = cf[c] rem = (enc - pow*cv) // fv enc = rem decoded.append(c) return bytes(decoded) radix = 10 for str in b'DABDDB DABDDBBDDBA ABRACADABRA TOBEORNOTTOBEORTOBEORNOT'.split(): enc, pow, freq = arithmethic_coding(str, radix) dec = arithmethic_decoding(enc, radix, pow, freq) print("%-25s=> %19s * %d^%s" % (str, enc, radix, pow)) if str != dec: raise Exception("\tHowever that is incorrect!")
Port the provided Java code into Python while preserving the original functionality.
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.BiConsumer; import java.util.function.IntConsumer; import java.util.stream.Collectors; public class Kosaraju { static class Recursive<I> { I func; } private static List<Integer> kosaraju(List<List<Integer>> g) { int size = g.size(); boolean[] vis = new boolean[size]; int[] l = new int[size]; AtomicInteger x = new AtomicInteger(size); List<List<Integer>> t = new ArrayList<>(); for (int i = 0; i < size; ++i) { t.add(new ArrayList<>()); } Recursive<IntConsumer> visit = new Recursive<>(); visit.func = (int u) -> { if (!vis[u]) { vis[u] = true; for (Integer v : g.get(u)) { visit.func.accept(v); t.get(v).add(u); } int xval = x.decrementAndGet(); l[xval] = u; } }; for (int i = 0; i < size; ++i) { visit.func.accept(i); } int[] c = new int[size]; Recursive<BiConsumer<Integer, Integer>> assign = new Recursive<>(); assign.func = (Integer u, Integer root) -> { if (vis[u]) { vis[u] = false; c[u] = root; for (Integer v : t.get(u)) { assign.func.accept(v, root); } } }; for (int u : l) { assign.func.accept(u, u); } return Arrays.stream(c).boxed().collect(Collectors.toList()); } public static void main(String[] args) { List<List<Integer>> g = new ArrayList<>(); for (int i = 0; i < 8; ++i) { g.add(new ArrayList<>()); } g.get(0).add(1); g.get(1).add(2); g.get(2).add(0); g.get(3).add(1); g.get(3).add(2); g.get(3).add(4); g.get(4).add(3); g.get(4).add(5); g.get(5).add(2); g.get(5).add(6); g.get(6).add(5); g.get(7).add(4); g.get(7).add(6); g.get(7).add(7); List<Integer> output = kosaraju(g); System.out.println(output); } }
def kosaraju(g): class nonlocal: pass size = len(g) vis = [False]*size l = [0]*size nonlocal.x = size t = [[]]*size def visit(u): if not vis[u]: vis[u] = True for v in g[u]: visit(v) t[v] = t[v] + [u] nonlocal.x = nonlocal.x - 1 l[nonlocal.x] = u for u in range(len(g)): visit(u) c = [0]*size def assign(u, root): if vis[u]: vis[u] = False c[u] = root for v in t[u]: assign(v, root) for u in l: assign(u, u) return c g = [[1], [2], [0], [1,2,4], [3,5], [2,6], [5], [4,6,7]] print kosaraju(g)
Change the programming language of this snippet from Java to Python without modifying what it does.
import java.lang.reflect.Method; public class ListMethods { public int examplePublicInstanceMethod(char c, double d) { return 42; } private boolean examplePrivateInstanceMethod(String s) { return true; } public static void main(String[] args) { Class clazz = ListMethods.class; System.out.println("All public methods (including inherited):"); for (Method m : clazz.getMethods()) { System.out.println(m); } System.out.println(); System.out.println("All declared methods (excluding inherited):"); for (Method m : clazz.getDeclaredMethods()) { System.out.println(m); } } }
import inspect class Super(object): def __init__(self, name): self.name = name def __str__(self): return "Super(%s)" % (self.name,) def doSup(self): return 'did super stuff' @classmethod def cls(cls): return 'cls method (in sup)' @classmethod def supCls(cls): return 'Super method' @staticmethod def supStatic(): return 'static method' class Other(object): def otherMethod(self): return 'other method' class Sub(Other, Super): def __init__(self, name, *args): super(Sub, self).__init__(name); self.rest = args; self.methods = {} def __dir__(self): return list(set( \ sum([dir(base) for base in type(self).__bases__], []) \ + type(self).__dict__.keys() \ + self.__dict__.keys() \ + self.methods.keys() \ )) def __getattr__(self, name): if name in self.methods: if callable(self.methods[name]) and self.methods[name].__code__.co_argcount > 0: if self.methods[name].__code__.co_varnames[0] == 'self': return self.methods[name].__get__(self, type(self)) if self.methods[name].__code__.co_varnames[0] == 'cls': return self.methods[name].__get__(type(self), type) return self.methods[name] raise AttributeError("'%s' object has no attribute '%s'" % (type(self).__name__, name)) def __str__(self): return "Sub(%s)" % self.name def doSub(): return 'did sub stuff' @classmethod def cls(cls): return 'cls method (in Sub)' @classmethod def subCls(cls): return 'Sub method' @staticmethod def subStatic(): return 'Sub method' sup = Super('sup') sub = Sub('sub', 0, 'I', 'two') sub.methods['incr'] = lambda x: x+1 sub.methods['strs'] = lambda self, x: str(self) * x [method for method in dir(sub) if callable(getattr(sub, method))] [method for method in dir(sub) if callable(getattr(sub, method)) and hasattr(getattr(sub, method), '__self__') and getattr(sub, method).__self__ == sub] [method for method in dir(sub) if callable(getattr(sub, method)) and hasattr(getattr(sub, method), '__self__') and getattr(sub, method).__self__ == type(sub)] [method for method in dir(sub) if callable(getattr(sub, method)) and type(getattr(sub, method)) == type(lambda:nil)] inspect.getmembers(sub, predicate=inspect.ismethod) map(lambda t: t[0], inspect.getmembers(sub, predicate=inspect.ismethod))
Convert the following code from Java to Python, ensuring the logic remains intact.
Int i = 0;
var x = 0 var y = 0 There are also multi-line comments Everything inside of ] discard
Change the following Java code into Python without altering its purpose.
package pentominotiling; import java.util.*; public class PentominoTiling { static final char[] symbols = "FILNPTUVWXYZ-".toCharArray(); static final Random rand = new Random(); static final int nRows = 8; static final int nCols = 8; static final int blank = 12; static int[][] grid = new int[nRows][nCols]; static boolean[] placed = new boolean[symbols.length - 1]; public static void main(String[] args) { shuffleShapes(); for (int r = 0; r < nRows; r++) Arrays.fill(grid[r], -1); for (int i = 0; i < 4; i++) { int randRow, randCol; do { randRow = rand.nextInt(nRows); randCol = rand.nextInt(nCols); } while (grid[randRow][randCol] == blank); grid[randRow][randCol] = blank; } if (solve(0, 0)) { printResult(); } else { System.out.println("no solution"); } } static void shuffleShapes() { int n = shapes.length; while (n > 1) { int r = rand.nextInt(n--); int[][] tmp = shapes[r]; shapes[r] = shapes[n]; shapes[n] = tmp; char tmpSymbol = symbols[r]; symbols[r] = symbols[n]; symbols[n] = tmpSymbol; } } static void printResult() { for (int[] r : grid) { for (int i : r) System.out.printf("%c ", symbols[i]); System.out.println(); } } static boolean tryPlaceOrientation(int[] o, int r, int c, int shapeIndex) { for (int i = 0; i < o.length; i += 2) { int x = c + o[i + 1]; int y = r + o[i]; if (x < 0 || x >= nCols || y < 0 || y >= nRows || grid[y][x] != -1) return false; } grid[r][c] = shapeIndex; for (int i = 0; i < o.length; i += 2) grid[r + o[i]][c + o[i + 1]] = shapeIndex; return true; } static void removeOrientation(int[] o, int r, int c) { grid[r][c] = -1; for (int i = 0; i < o.length; i += 2) grid[r + o[i]][c + o[i + 1]] = -1; } static boolean solve(int pos, int numPlaced) { if (numPlaced == shapes.length) return true; int row = pos / nCols; int col = pos % nCols; if (grid[row][col] != -1) return solve(pos + 1, numPlaced); for (int i = 0; i < shapes.length; i++) { if (!placed[i]) { for (int[] orientation : shapes[i]) { if (!tryPlaceOrientation(orientation, row, col, i)) continue; placed[i] = true; if (solve(pos + 1, numPlaced + 1)) return true; removeOrientation(orientation, row, col); placed[i] = false; } } } return false; } static final int[][] F = {{1, -1, 1, 0, 1, 1, 2, 1}, {0, 1, 1, -1, 1, 0, 2, 0}, {1, 0, 1, 1, 1, 2, 2, 1}, {1, 0, 1, 1, 2, -1, 2, 0}, {1, -2, 1, -1, 1, 0, 2, -1}, {0, 1, 1, 1, 1, 2, 2, 1}, {1, -1, 1, 0, 1, 1, 2, -1}, {1, -1, 1, 0, 2, 0, 2, 1}}; static final int[][] I = {{0, 1, 0, 2, 0, 3, 0, 4}, {1, 0, 2, 0, 3, 0, 4, 0}}; static final int[][] L = {{1, 0, 1, 1, 1, 2, 1, 3}, {1, 0, 2, 0, 3, -1, 3, 0}, {0, 1, 0, 2, 0, 3, 1, 3}, {0, 1, 1, 0, 2, 0, 3, 0}, {0, 1, 1, 1, 2, 1, 3, 1}, {0, 1, 0, 2, 0, 3, 1, 0}, {1, 0, 2, 0, 3, 0, 3, 1}, {1, -3, 1, -2, 1, -1, 1, 0}}; static final int[][] N = {{0, 1, 1, -2, 1, -1, 1, 0}, {1, 0, 1, 1, 2, 1, 3, 1}, {0, 1, 0, 2, 1, -1, 1, 0}, {1, 0, 2, 0, 2, 1, 3, 1}, {0, 1, 1, 1, 1, 2, 1, 3}, {1, 0, 2, -1, 2, 0, 3, -1}, {0, 1, 0, 2, 1, 2, 1, 3}, {1, -1, 1, 0, 2, -1, 3, -1}}; static final int[][] P = {{0, 1, 1, 0, 1, 1, 2, 1}, {0, 1, 0, 2, 1, 0, 1, 1}, {1, 0, 1, 1, 2, 0, 2, 1}, {0, 1, 1, -1, 1, 0, 1, 1}, {0, 1, 1, 0, 1, 1, 1, 2}, {1, -1, 1, 0, 2, -1, 2, 0}, {0, 1, 0, 2, 1, 1, 1, 2}, {0, 1, 1, 0, 1, 1, 2, 0}}; static final int[][] T = {{0, 1, 0, 2, 1, 1, 2, 1}, {1, -2, 1, -1, 1, 0, 2, 0}, {1, 0, 2, -1, 2, 0, 2, 1}, {1, 0, 1, 1, 1, 2, 2, 0}}; static final int[][] U = {{0, 1, 0, 2, 1, 0, 1, 2}, {0, 1, 1, 1, 2, 0, 2, 1}, {0, 2, 1, 0, 1, 1, 1, 2}, {0, 1, 1, 0, 2, 0, 2, 1}}; static final int[][] V = {{1, 0, 2, 0, 2, 1, 2, 2}, {0, 1, 0, 2, 1, 0, 2, 0}, {1, 0, 2, -2, 2, -1, 2, 0}, {0, 1, 0, 2, 1, 2, 2, 2}}; static final int[][] W = {{1, 0, 1, 1, 2, 1, 2, 2}, {1, -1, 1, 0, 2, -2, 2, -1}, {0, 1, 1, 1, 1, 2, 2, 2}, {0, 1, 1, -1, 1, 0, 2, -1}}; static final int[][] X = {{1, -1, 1, 0, 1, 1, 2, 0}}; static final int[][] Y = {{1, -2, 1, -1, 1, 0, 1, 1}, {1, -1, 1, 0, 2, 0, 3, 0}, {0, 1, 0, 2, 0, 3, 1, 1}, {1, 0, 2, 0, 2, 1, 3, 0}, {0, 1, 0, 2, 0, 3, 1, 2}, {1, 0, 1, 1, 2, 0, 3, 0}, {1, -1, 1, 0, 1, 1, 1, 2}, {1, 0, 2, -1, 2, 0, 3, 0}}; static final int[][] Z = {{0, 1, 1, 0, 2, -1, 2, 0}, {1, 0, 1, 1, 1, 2, 2, 2}, {0, 1, 1, 1, 2, 1, 2, 2}, {1, -2, 1, -1, 1, 0, 2, -2}}; static final int[][][] shapes = {F, I, L, N, P, T, U, V, W, X, Y, Z}; }
from itertools import product minos = (((197123, 7, 6), (1797, 6, 7), (1287, 6, 7), (196867, 7, 6)), ((263937, 6, 6), (197126, 6, 6), (393731, 6, 6), (67332, 6, 6)), ((16843011, 7, 5), (2063, 5, 7), (3841, 5, 7), (271, 5, 7), (3848, 5, 7), (50463234, 7, 5), (50397441, 7, 5), (33686019, 7, 5)), ((131843, 7, 6), (1798, 6, 7), (775, 6, 7), (1795, 6, 7), (1543, 6, 7), (197377, 7, 6), (197378, 7, 6), (66307, 7, 6)), ((132865, 6, 6), (131846, 6, 6), (198146, 6, 6), (132611, 6, 6), (393986, 6, 6), (263938, 6, 6), (67330, 6, 6), (132868, 6, 6)), ((1039, 5, 7), (33751554, 7, 5), (16843521, 7, 5), (16974081, 7, 5), (33686274, 7, 5), (3842, 5, 7), (3844, 5, 7), (527, 5, 7)), ((1804, 5, 7), (33751297, 7, 5), (33686273, 7, 5), (16974338, 7, 5), (16843522, 7, 5), (782, 5, 7), (3079, 5, 7), (3587, 5, 7)), ((263683, 6, 6), (198148, 6, 6), (66310, 6, 6), (393985, 6, 6)), ((67329, 6, 6), (131591, 6, 6), (459266, 6, 6), (263940, 6, 6)), ((459780, 6, 6), (459009, 6, 6), (263175, 6, 6), (65799, 6, 6)), ((4311810305, 8, 4), (31, 4, 8)), ((132866, 6, 6),)) boxchar_double_width = ' ╶╺╵└┕╹┖┗╴─╼┘┴┶┚┸┺╸╾━┙┵┷┛┹┻╷┌┍│├┝╿┞┡┐┬┮┤┼┾┦╀╄┑┭┯┥┽┿┩╃╇╻┎┏╽┟┢┃┠┣┒┰┲┧╁╆┨╂╊┓┱┳┪╅╈┫╉╋' boxchar_single_width = [c + ' ─━'[i%3] for i, c in enumerate(boxchar_double_width)] patterns = boxchar_single_width tiles = [] for row in reversed(minos): tiles.append([]) for n, x, y in row: for shift in (b*8 + a for a, b in product(range(x), range(y))): tiles[-1].append(n << shift) def img(seq): b = [[0]*10 for _ in range(10)] for i, s in enumerate(seq): for j, k in product(range(8), range(8)): if s & (1<<(j*8 + k)): b[j + 1][k + 1] = i + 1 idices = [[0]*9 for _ in range(9)] for i, j in product(range(9), range(9)): n = (b[i+1][j+1], b[i][j+1], b[i][j], b[i+1][j], b[i+1][j+1]) idices[i][j] = sum((a != b)*(1 + (not a or not b))*3**i for i, (a,b) in enumerate(zip(n, n[1:]))) return '\n'.join(''.join(patterns[i] for i in row) for row in idices) def tile(board=0, seq=tuple(), tiles=tiles): if not tiles: yield img(seq) return for c in tiles[0]: b = board | c tnext = [] for t in tiles[1:]: tnext.append(tuple(n for n in t if not n&b)) if not tnext[-1]: break else: yield from tile(b, seq + (c,), tnext) for x in tile(): print(x)
Can you help me rewrite this code in Python instead of Java, keeping it the same logically?
package pentominotiling; import java.util.*; public class PentominoTiling { static final char[] symbols = "FILNPTUVWXYZ-".toCharArray(); static final Random rand = new Random(); static final int nRows = 8; static final int nCols = 8; static final int blank = 12; static int[][] grid = new int[nRows][nCols]; static boolean[] placed = new boolean[symbols.length - 1]; public static void main(String[] args) { shuffleShapes(); for (int r = 0; r < nRows; r++) Arrays.fill(grid[r], -1); for (int i = 0; i < 4; i++) { int randRow, randCol; do { randRow = rand.nextInt(nRows); randCol = rand.nextInt(nCols); } while (grid[randRow][randCol] == blank); grid[randRow][randCol] = blank; } if (solve(0, 0)) { printResult(); } else { System.out.println("no solution"); } } static void shuffleShapes() { int n = shapes.length; while (n > 1) { int r = rand.nextInt(n--); int[][] tmp = shapes[r]; shapes[r] = shapes[n]; shapes[n] = tmp; char tmpSymbol = symbols[r]; symbols[r] = symbols[n]; symbols[n] = tmpSymbol; } } static void printResult() { for (int[] r : grid) { for (int i : r) System.out.printf("%c ", symbols[i]); System.out.println(); } } static boolean tryPlaceOrientation(int[] o, int r, int c, int shapeIndex) { for (int i = 0; i < o.length; i += 2) { int x = c + o[i + 1]; int y = r + o[i]; if (x < 0 || x >= nCols || y < 0 || y >= nRows || grid[y][x] != -1) return false; } grid[r][c] = shapeIndex; for (int i = 0; i < o.length; i += 2) grid[r + o[i]][c + o[i + 1]] = shapeIndex; return true; } static void removeOrientation(int[] o, int r, int c) { grid[r][c] = -1; for (int i = 0; i < o.length; i += 2) grid[r + o[i]][c + o[i + 1]] = -1; } static boolean solve(int pos, int numPlaced) { if (numPlaced == shapes.length) return true; int row = pos / nCols; int col = pos % nCols; if (grid[row][col] != -1) return solve(pos + 1, numPlaced); for (int i = 0; i < shapes.length; i++) { if (!placed[i]) { for (int[] orientation : shapes[i]) { if (!tryPlaceOrientation(orientation, row, col, i)) continue; placed[i] = true; if (solve(pos + 1, numPlaced + 1)) return true; removeOrientation(orientation, row, col); placed[i] = false; } } } return false; } static final int[][] F = {{1, -1, 1, 0, 1, 1, 2, 1}, {0, 1, 1, -1, 1, 0, 2, 0}, {1, 0, 1, 1, 1, 2, 2, 1}, {1, 0, 1, 1, 2, -1, 2, 0}, {1, -2, 1, -1, 1, 0, 2, -1}, {0, 1, 1, 1, 1, 2, 2, 1}, {1, -1, 1, 0, 1, 1, 2, -1}, {1, -1, 1, 0, 2, 0, 2, 1}}; static final int[][] I = {{0, 1, 0, 2, 0, 3, 0, 4}, {1, 0, 2, 0, 3, 0, 4, 0}}; static final int[][] L = {{1, 0, 1, 1, 1, 2, 1, 3}, {1, 0, 2, 0, 3, -1, 3, 0}, {0, 1, 0, 2, 0, 3, 1, 3}, {0, 1, 1, 0, 2, 0, 3, 0}, {0, 1, 1, 1, 2, 1, 3, 1}, {0, 1, 0, 2, 0, 3, 1, 0}, {1, 0, 2, 0, 3, 0, 3, 1}, {1, -3, 1, -2, 1, -1, 1, 0}}; static final int[][] N = {{0, 1, 1, -2, 1, -1, 1, 0}, {1, 0, 1, 1, 2, 1, 3, 1}, {0, 1, 0, 2, 1, -1, 1, 0}, {1, 0, 2, 0, 2, 1, 3, 1}, {0, 1, 1, 1, 1, 2, 1, 3}, {1, 0, 2, -1, 2, 0, 3, -1}, {0, 1, 0, 2, 1, 2, 1, 3}, {1, -1, 1, 0, 2, -1, 3, -1}}; static final int[][] P = {{0, 1, 1, 0, 1, 1, 2, 1}, {0, 1, 0, 2, 1, 0, 1, 1}, {1, 0, 1, 1, 2, 0, 2, 1}, {0, 1, 1, -1, 1, 0, 1, 1}, {0, 1, 1, 0, 1, 1, 1, 2}, {1, -1, 1, 0, 2, -1, 2, 0}, {0, 1, 0, 2, 1, 1, 1, 2}, {0, 1, 1, 0, 1, 1, 2, 0}}; static final int[][] T = {{0, 1, 0, 2, 1, 1, 2, 1}, {1, -2, 1, -1, 1, 0, 2, 0}, {1, 0, 2, -1, 2, 0, 2, 1}, {1, 0, 1, 1, 1, 2, 2, 0}}; static final int[][] U = {{0, 1, 0, 2, 1, 0, 1, 2}, {0, 1, 1, 1, 2, 0, 2, 1}, {0, 2, 1, 0, 1, 1, 1, 2}, {0, 1, 1, 0, 2, 0, 2, 1}}; static final int[][] V = {{1, 0, 2, 0, 2, 1, 2, 2}, {0, 1, 0, 2, 1, 0, 2, 0}, {1, 0, 2, -2, 2, -1, 2, 0}, {0, 1, 0, 2, 1, 2, 2, 2}}; static final int[][] W = {{1, 0, 1, 1, 2, 1, 2, 2}, {1, -1, 1, 0, 2, -2, 2, -1}, {0, 1, 1, 1, 1, 2, 2, 2}, {0, 1, 1, -1, 1, 0, 2, -1}}; static final int[][] X = {{1, -1, 1, 0, 1, 1, 2, 0}}; static final int[][] Y = {{1, -2, 1, -1, 1, 0, 1, 1}, {1, -1, 1, 0, 2, 0, 3, 0}, {0, 1, 0, 2, 0, 3, 1, 1}, {1, 0, 2, 0, 2, 1, 3, 0}, {0, 1, 0, 2, 0, 3, 1, 2}, {1, 0, 1, 1, 2, 0, 3, 0}, {1, -1, 1, 0, 1, 1, 1, 2}, {1, 0, 2, -1, 2, 0, 3, 0}}; static final int[][] Z = {{0, 1, 1, 0, 2, -1, 2, 0}, {1, 0, 1, 1, 1, 2, 2, 2}, {0, 1, 1, 1, 2, 1, 2, 2}, {1, -2, 1, -1, 1, 0, 2, -2}}; static final int[][][] shapes = {F, I, L, N, P, T, U, V, W, X, Y, Z}; }
from itertools import product minos = (((197123, 7, 6), (1797, 6, 7), (1287, 6, 7), (196867, 7, 6)), ((263937, 6, 6), (197126, 6, 6), (393731, 6, 6), (67332, 6, 6)), ((16843011, 7, 5), (2063, 5, 7), (3841, 5, 7), (271, 5, 7), (3848, 5, 7), (50463234, 7, 5), (50397441, 7, 5), (33686019, 7, 5)), ((131843, 7, 6), (1798, 6, 7), (775, 6, 7), (1795, 6, 7), (1543, 6, 7), (197377, 7, 6), (197378, 7, 6), (66307, 7, 6)), ((132865, 6, 6), (131846, 6, 6), (198146, 6, 6), (132611, 6, 6), (393986, 6, 6), (263938, 6, 6), (67330, 6, 6), (132868, 6, 6)), ((1039, 5, 7), (33751554, 7, 5), (16843521, 7, 5), (16974081, 7, 5), (33686274, 7, 5), (3842, 5, 7), (3844, 5, 7), (527, 5, 7)), ((1804, 5, 7), (33751297, 7, 5), (33686273, 7, 5), (16974338, 7, 5), (16843522, 7, 5), (782, 5, 7), (3079, 5, 7), (3587, 5, 7)), ((263683, 6, 6), (198148, 6, 6), (66310, 6, 6), (393985, 6, 6)), ((67329, 6, 6), (131591, 6, 6), (459266, 6, 6), (263940, 6, 6)), ((459780, 6, 6), (459009, 6, 6), (263175, 6, 6), (65799, 6, 6)), ((4311810305, 8, 4), (31, 4, 8)), ((132866, 6, 6),)) boxchar_double_width = ' ╶╺╵└┕╹┖┗╴─╼┘┴┶┚┸┺╸╾━┙┵┷┛┹┻╷┌┍│├┝╿┞┡┐┬┮┤┼┾┦╀╄┑┭┯┥┽┿┩╃╇╻┎┏╽┟┢┃┠┣┒┰┲┧╁╆┨╂╊┓┱┳┪╅╈┫╉╋' boxchar_single_width = [c + ' ─━'[i%3] for i, c in enumerate(boxchar_double_width)] patterns = boxchar_single_width tiles = [] for row in reversed(minos): tiles.append([]) for n, x, y in row: for shift in (b*8 + a for a, b in product(range(x), range(y))): tiles[-1].append(n << shift) def img(seq): b = [[0]*10 for _ in range(10)] for i, s in enumerate(seq): for j, k in product(range(8), range(8)): if s & (1<<(j*8 + k)): b[j + 1][k + 1] = i + 1 idices = [[0]*9 for _ in range(9)] for i, j in product(range(9), range(9)): n = (b[i+1][j+1], b[i][j+1], b[i][j], b[i+1][j], b[i+1][j+1]) idices[i][j] = sum((a != b)*(1 + (not a or not b))*3**i for i, (a,b) in enumerate(zip(n, n[1:]))) return '\n'.join(''.join(patterns[i] for i in row) for row in idices) def tile(board=0, seq=tuple(), tiles=tiles): if not tiles: yield img(seq) return for c in tiles[0]: b = board | c tnext = [] for t in tiles[1:]: tnext.append(tuple(n for n in t if not n&b)) if not tnext[-1]: break else: yield from tile(b, seq + (c,), tnext) for x in tile(): print(x)
Rewrite the snippet below in Python so it works the same as the original Java code.
import java.lang.reflect.Method; class Example { public int foo(int x) { return 42 + x; } } public class Main { public static void main(String[] args) throws Exception { Object example = new Example(); String name = "foo"; Class<?> clazz = example.getClass(); Method meth = clazz.getMethod(name, int.class); Object result = meth.invoke(example, 5); System.out.println(result); } }
class Example(object): def foo(self, x): return 42 + x name = "foo" getattr(Example(), name)(5)
Keep all operations the same but rewrite the snippet in Python.
int a; double b; AClassNameHere c;
example1 = 3 example2 = 3.0 example3 = True example4 = "hello" example1 = "goodbye"
Generate a Python translation of this Java snippet without changing its computational steps.
import java.util.Arrays; import java.util.Objects; import java.util.Random; import java.util.function.Function; public class App { static class Parameters { double omega; double phip; double phig; Parameters(double omega, double phip, double phig) { this.omega = omega; this.phip = phip; this.phig = phig; } } static class State { int iter; double[] gbpos; double gbval; double[] min; double[] max; Parameters parameters; double[][] pos; double[][] vel; double[][] bpos; double[] bval; int nParticles; int nDims; State(int iter, double[] gbpos, double gbval, double[] min, double[] max, Parameters parameters, double[][] pos, double[][] vel, double[][] bpos, double[] bval, int nParticles, int nDims) { this.iter = iter; this.gbpos = gbpos; this.gbval = gbval; this.min = min; this.max = max; this.parameters = parameters; this.pos = pos; this.vel = vel; this.bpos = bpos; this.bval = bval; this.nParticles = nParticles; this.nDims = nDims; } void report(String testfunc) { System.out.printf("Test Function  : %s\n", testfunc); System.out.printf("Iterations  : %d\n", iter); System.out.printf("Global Best Position : %s\n", Arrays.toString(gbpos)); System.out.printf("Global Best value  : %.15f\n", gbval); } } private static State psoInit(double[] min, double[] max, Parameters parameters, int nParticles) { int nDims = min.length; double[][] pos = new double[nParticles][]; for (int i = 0; i < nParticles; ++i) { pos[i] = min.clone(); } double[][] vel = new double[nParticles][nDims]; double[][] bpos = new double[nParticles][]; for (int i = 0; i < nParticles; ++i) { bpos[i] = min.clone(); } double[] bval = new double[nParticles]; for (int i = 0; i < bval.length; ++i) { bval[i] = Double.POSITIVE_INFINITY; } int iter = 0; double[] gbpos = new double[nDims]; for (int i = 0; i < gbpos.length; ++i) { gbpos[i] = Double.POSITIVE_INFINITY; } double gbval = Double.POSITIVE_INFINITY; return new State(iter, gbpos, gbval, min, max, parameters, pos, vel, bpos, bval, nParticles, nDims); } private static Random r = new Random(); private static State pso(Function<double[], Double> fn, State y) { Parameters p = y.parameters; double[] v = new double[y.nParticles]; double[][] bpos = new double[y.nParticles][]; for (int i = 0; i < y.nParticles; ++i) { bpos[i] = y.min.clone(); } double[] bval = new double[y.nParticles]; double[] gbpos = new double[y.nDims]; double gbval = Double.POSITIVE_INFINITY; for (int j = 0; j < y.nParticles; ++j) { v[j] = fn.apply(y.pos[j]); if (v[j] < y.bval[j]) { bpos[j] = y.pos[j]; bval[j] = v[j]; } else { bpos[j] = y.bpos[j]; bval[j] = y.bval[j]; } if (bval[j] < gbval) { gbval = bval[j]; gbpos = bpos[j]; } } double rg = r.nextDouble(); double[][] pos = new double[y.nParticles][y.nDims]; double[][] vel = new double[y.nParticles][y.nDims]; for (int j = 0; j < y.nParticles; ++j) { double rp = r.nextDouble(); boolean ok = true; Arrays.fill(vel[j], 0.0); Arrays.fill(pos[j], 0.0); for (int k = 0; k < y.nDims; ++k) { vel[j][k] = p.omega * y.vel[j][k] + p.phip * rp * (bpos[j][k] - y.pos[j][k]) + p.phig * rg * (gbpos[k] - y.pos[j][k]); pos[j][k] = y.pos[j][k] + vel[j][k]; ok = ok && y.min[k] < pos[j][k] && y.max[k] > pos[j][k]; } if (!ok) { for (int k = 0; k < y.nDims; ++k) { pos[j][k] = y.min[k] + (y.max[k] - y.min[k]) * r.nextDouble(); } } } int iter = 1 + y.iter; return new State( iter, gbpos, gbval, y.min, y.max, y.parameters, pos, vel, bpos, bval, y.nParticles, y.nDims ); } private static State iterate(Function<double[], Double> fn, int n, State y) { State r = y; if (n == Integer.MAX_VALUE) { State old = y; while (true) { r = pso(fn, r); if (Objects.equals(r, old)) break; old = r; } } else { for (int i = 0; i < n; ++i) { r = pso(fn, r); } } return r; } private static double mccormick(double[] x) { double a = x[0]; double b = x[1]; return Math.sin(a + b) + (a - b) * (a - b) + 1.0 + 2.5 * b - 1.5 * a; } private static double michalewicz(double[] x) { int m = 10; int d = x.length; double sum = 0.0; for (int i = 1; i < d; ++i) { double j = x[i - 1]; double k = Math.sin(i * j * j / Math.PI); sum += Math.sin(j) * Math.pow(k, 2.0 * m); } return -sum; } public static void main(String[] args) { State state = psoInit( new double[]{-1.5, -3.0}, new double[]{4.0, 4.0}, new Parameters(0.0, 0.6, 0.3), 100 ); state = iterate(App::mccormick, 40, state); state.report("McCormick"); System.out.printf("f(-.54719, -1.54719) : %.15f\n", mccormick(new double[]{-.54719, -1.54719})); System.out.println(); state = psoInit( new double[]{0.0, 0.0}, new double[]{Math.PI, Math.PI}, new Parameters(0.3, 3.0, 0.3), 1000 ); state = iterate(App::michalewicz, 30, state); state.report("Michalewicz (2D)"); System.out.printf("f(2.20, 1.57)  : %.15f\n", michalewicz(new double[]{2.20, 1.57})); } }
import math import random INFINITY = 1 << 127 MAX_INT = 1 << 31 class Parameters: def __init__(self, omega, phip, phig): self.omega = omega self.phip = phip self.phig = phig class State: def __init__(self, iter, gbpos, gbval, min, max, parameters, pos, vel, bpos, bval, nParticles, nDims): self.iter = iter self.gbpos = gbpos self.gbval = gbval self.min = min self.max = max self.parameters = parameters self.pos = pos self.vel = vel self.bpos = bpos self.bval = bval self.nParticles = nParticles self.nDims = nDims def report(self, testfunc): print "Test Function :", testfunc print "Iterations  :", self.iter print "Global Best Position :", self.gbpos print "Global Best Value  : %.16f" % self.gbval def uniform01(): v = random.random() assert 0.0 <= v and v < 1.0 return v def psoInit(min, max, parameters, nParticles): nDims = len(min) pos = [min[:]] * nParticles vel = [[0.0] * nDims] * nParticles bpos = [min[:]] * nParticles bval = [INFINITY] * nParticles iter = 0 gbpos = [INFINITY] * nDims gbval = INFINITY return State(iter, gbpos, gbval, min, max, parameters, pos, vel, bpos, bval, nParticles, nDims); def pso(fn, y): p = y.parameters v = [0.0] * (y.nParticles) bpos = [y.min[:]] * (y.nParticles) bval = [0.0] * (y.nParticles) gbpos = [0.0] * (y.nDims) gbval = INFINITY for j in xrange(0, y.nParticles): v[j] = fn(y.pos[j]) if v[j] < y.bval[j]: bpos[j] = y.pos[j][:] bval[j] = v[j] else: bpos[j] = y.bpos[j][:] bval[j] = y.bval[j] if bval[j] < gbval: gbval = bval[j] gbpos = bpos[j][:] rg = uniform01() pos = [[None] * (y.nDims)] * (y.nParticles) vel = [[None] * (y.nDims)] * (y.nParticles) for j in xrange(0, y.nParticles): rp = uniform01() ok = True vel[j] = [0.0] * (len(vel[j])) pos[j] = [0.0] * (len(pos[j])) for k in xrange(0, y.nDims): vel[j][k] = p.omega * y.vel[j][k] \ + p.phip * rp * (bpos[j][k] - y.pos[j][k]) \ + p.phig * rg * (gbpos[k] - y.pos[j][k]) pos[j][k] = y.pos[j][k] + vel[j][k] ok = ok and y.min[k] < pos[j][k] and y.max[k] > pos[j][k] if not ok: for k in xrange(0, y.nDims): pos[j][k] = y.min[k] + (y.max[k] - y.min[k]) * uniform01() iter = 1 + y.iter return State(iter, gbpos, gbval, y.min, y.max, y.parameters, pos, vel, bpos, bval, y.nParticles, y.nDims); def iterate(fn, n, y): r = y old = y if n == MAX_INT: while True: r = pso(fn, r) if r == old: break old = r else: for _ in xrange(0, n): r = pso(fn, r) return r def mccormick(x): (a, b) = x return math.sin(a + b) + (a - b) * (a - b) + 1.0 + 2.5 * b - 1.5 * a def michalewicz(x): m = 10 d = len(x) sum = 0.0 for i in xrange(1, d): j = x[i - 1] k = math.sin(i * j * j / math.pi) sum += math.sin(j) * k ** (2.0 * m) return -sum def main(): state = psoInit([-1.5, -3.0], [4.0, 4.0], Parameters(0.0, 0.6, 0.3), 100) state = iterate(mccormick, 40, state) state.report("McCormick") print "f(-.54719, -1.54719) : %.16f" % (mccormick([-.54719, -1.54719])) print state = psoInit([0.0, 0.0], [math.pi, math.pi], Parameters(0.3, 0.3, 0.3), 1000) state = iterate(michalewicz, 30, state) state.report("Michalewicz (2D)") print "f(2.20, 1.57)  : %.16f" % (michalewicz([2.2, 1.57])) main()
Please provide an equivalent version of this Java code in Python.
public static void main(String[] args) { System.out.println(concat("Rosetta", "Code", ":")); } public static String concat(String a, String b, String c) { return a + c + c + b; } Rosetta::Code
python Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> def f(string1, string2, separator): return separator.join([string1, '', string2]) >>> f('Rosetta', 'Code', ':') 'Rosetta::Code' >>>
Write the same code in Python as shown below in Java.
import java.math.BigInteger; import static java.util.Arrays.stream; import java.util.*; import static java.util.stream.Collectors.*; public class Test3 { static BigInteger rank(int[] x) { String s = stream(x).mapToObj(String::valueOf).collect(joining("F")); return new BigInteger(s, 16); } static List<BigInteger> unrank(BigInteger n) { BigInteger sixteen = BigInteger.valueOf(16); String s = ""; while (!n.equals(BigInteger.ZERO)) { s = "0123456789ABCDEF".charAt(n.mod(sixteen).intValue()) + s; n = n.divide(sixteen); } return stream(s.split("F")).map(x -> new BigInteger(x)).collect(toList()); } public static void main(String[] args) { int[] s = {1, 2, 3, 10, 100, 987654321}; System.out.println(Arrays.toString(s)); System.out.println(rank(s)); System.out.println(unrank(rank(s))); } }
def rank(x): return int('a'.join(map(str, [1] + x)), 11) def unrank(n): s = '' while n: s,n = "0123456789a"[n%11] + s, n//11 return map(int, s.split('a'))[1:] l = [1, 2, 3, 10, 100, 987654321] print l n = rank(l) print n l = unrank(n) print l
Rewrite the snippet below in Python so it works the same as the original Java code.
import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.nio.file.*; public class Backup { public static void saveWithBackup(String filename, String... data) throws IOException { Path file = Paths.get(filename).toRealPath(); File backFile = new File(filename + ".backup"); if(!backFile.exists()) { backFile.createNewFile(); } Path back = Paths.get(filename + ".backup").toRealPath(); Files.move(file, back, StandardCopyOption.REPLACE_EXISTING); try(PrintWriter out = new PrintWriter(file.toFile())){ for(int i = 0; i < data.length; i++) { out.print(data[i]); if(i < data.length - 1) { out.println(); } } } } public static void main(String[] args) { try { saveWithBackup("original.txt", "fourth", "fifth", "sixth"); } catch (IOException e) { System.err.println(e); } } }
import os targetfile = "pycon-china" os.rename(os.path.realpath(targetfile), os.path.realpath(targetfile)+".bak") f = open(os.path.realpath(targetfile), "w") f.write("this task was solved during a talk about rosettacode at the PyCon China in 2011") f.close()
Generate a Python translation of this Java snippet without changing its computational steps.
import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.nio.file.*; public class Backup { public static void saveWithBackup(String filename, String... data) throws IOException { Path file = Paths.get(filename).toRealPath(); File backFile = new File(filename + ".backup"); if(!backFile.exists()) { backFile.createNewFile(); } Path back = Paths.get(filename + ".backup").toRealPath(); Files.move(file, back, StandardCopyOption.REPLACE_EXISTING); try(PrintWriter out = new PrintWriter(file.toFile())){ for(int i = 0; i < data.length; i++) { out.print(data[i]); if(i < data.length - 1) { out.println(); } } } } public static void main(String[] args) { try { saveWithBackup("original.txt", "fourth", "fifth", "sixth"); } catch (IOException e) { System.err.println(e); } } }
import os targetfile = "pycon-china" os.rename(os.path.realpath(targetfile), os.path.realpath(targetfile)+".bak") f = open(os.path.realpath(targetfile), "w") f.write("this task was solved during a talk about rosettacode at the PyCon China in 2011") f.close()
Change the programming language of this snippet from Java to Python without modifying what it does.
public class ReallyLameTranslationOfJ { public static void main(String[] args) { String s = "She was a soul stripper. She took my heart!"; System.out.println(cheapTrick(s)); System.out.println(cheapTrick(cheapTrick(s))); } static String cheapTrick(String s) { if (s.contains("She")) return s.replaceAll("She", "He"); else if(s.contains("He")) return s.replaceAll("He", "She"); return s; } }
import re male2female=u re_nl=re.compile(r",[ \n]*") m2f=[ tok.split(" ") for tok in re_nl.split(male2female) ] switch={} words=[] re_plural=re.compile("E*S$") re_ES=re.compile("ES$") def gen_pluralize(m,f): yield re_plural.sub("",m),re_plural.sub("",f) yield re_ES.sub("es",m),re_ES.sub("es",f) yield re_plural.sub("s",m),re_plural.sub("s",f) def gen_capitalize_pluralize(m,f): for m,f in gen_pluralize(m,f): yield m.capitalize(), f.capitalize() yield m,f def gen_switch_role_capitalize_pluralize(m,f): for m,f in gen_capitalize_pluralize(m,f): yield m,f yield f,m for m,f in m2f: for xy,xx in gen_switch_role_capitalize_pluralize(m,f): if xy not in switch: switch[xy]=xx words.append(xy) words="|".join(words) re_word=re.compile(ur"\b("+words+ur")\b") text=u def rev_gender(text): text=re_word.split(text) return "".join([ word+switch[gen] for word,gen in zip(text[::2],text[1::2])])+text[-1] print rev_gender(text)
Translate this program into Python but keep the logic exactly as in Java.
public class ReallyLameTranslationOfJ { public static void main(String[] args) { String s = "She was a soul stripper. She took my heart!"; System.out.println(cheapTrick(s)); System.out.println(cheapTrick(cheapTrick(s))); } static String cheapTrick(String s) { if (s.contains("She")) return s.replaceAll("She", "He"); else if(s.contains("He")) return s.replaceAll("He", "She"); return s; } }
import re male2female=u re_nl=re.compile(r",[ \n]*") m2f=[ tok.split(" ") for tok in re_nl.split(male2female) ] switch={} words=[] re_plural=re.compile("E*S$") re_ES=re.compile("ES$") def gen_pluralize(m,f): yield re_plural.sub("",m),re_plural.sub("",f) yield re_ES.sub("es",m),re_ES.sub("es",f) yield re_plural.sub("s",m),re_plural.sub("s",f) def gen_capitalize_pluralize(m,f): for m,f in gen_pluralize(m,f): yield m.capitalize(), f.capitalize() yield m,f def gen_switch_role_capitalize_pluralize(m,f): for m,f in gen_capitalize_pluralize(m,f): yield m,f yield f,m for m,f in m2f: for xy,xx in gen_switch_role_capitalize_pluralize(m,f): if xy not in switch: switch[xy]=xx words.append(xy) words="|".join(words) re_word=re.compile(ur"\b("+words+ur")\b") text=u def rev_gender(text): text=re_word.split(text) return "".join([ word+switch[gen] for word,gen in zip(text[::2],text[1::2])])+text[-1] print rev_gender(text)
Write the same code in Python as shown below in Java.
import com.sun.javafx.application.PlatformImpl; import java.io.File; import java.util.Scanner; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import javafx.scene.media.Media; import javafx.scene.media.MediaPlayer; public class AudioAlarm { public static void main(String[] args) throws InterruptedException { Scanner input = new Scanner(System.in); System.out.print("Enter a number of seconds: "); int seconds = Integer.parseInt(input.nextLine()); System.out.print("Enter a filename (must end with .mp3 or .wav): "); String audio = input.nextLine(); TimeUnit.SECONDS.sleep(seconds); Media media = new Media(new File(audio).toURI().toString()); AtomicBoolean stop = new AtomicBoolean(); Runnable onEnd = () -> stop.set(true); PlatformImpl.startup(() -> {}); MediaPlayer player = new MediaPlayer(media); player.setOnEndOfMedia(onEnd); player.setOnError(onEnd); player.setOnHalted(onEnd); player.play(); while (!stop.get()) { Thread.sleep(100); } System.exit(0); } }
import time import os seconds = input("Enter a number of seconds: ") sound = input("Enter an mp3 filename: ") time.sleep(float(seconds)) os.startfile(sound + ".mp3")
Produce a functionally identical Python code for the snippet given in Java.
import java.math.BigDecimal; import java.math.MathContext; import java.math.RoundingMode; public class DecimalToBinary { public static void main(String[] args) { for ( String s : new String[] {"23.34375", ".1", "3.1415926535897932"} ) { String binary = decimalToBinary(new BigDecimal(s)); System.out.printf("%s => %s%n", s, binary); System.out.printf("%s => %s%n", binary, binaryToDecimal(binary)); } } private static BigDecimal binaryToDecimal(String binary) { return binaryToDecimal(binary, 50); } private static BigDecimal binaryToDecimal(String binary, int digits) { int decimalPosition = binary.indexOf("."); String integer = decimalPosition >= 0 ? binary.substring(0, decimalPosition) : binary; String fractional = decimalPosition >= 0 ? binary.substring(decimalPosition+1) : ""; BigDecimal result = BigDecimal.ZERO; BigDecimal powTwo = BigDecimal.ONE; BigDecimal two = BigDecimal.valueOf(2); for ( char c : new StringBuilder(integer).reverse().toString().toCharArray() ) { result = result.add(powTwo.multiply(BigDecimal.valueOf(c - '0'))); powTwo = powTwo.multiply(two); } MathContext mc = new MathContext(digits); powTwo = BigDecimal.ONE; for ( char c : fractional.toCharArray() ) { powTwo = powTwo.divide(two); result = result.add(powTwo.multiply(BigDecimal.valueOf(c - '0')), mc); } return result; } private static String decimalToBinary(BigDecimal decimal) { return decimalToBinary(decimal, 50); } private static String decimalToBinary(BigDecimal decimal, int digits) { BigDecimal integer = decimal.setScale(0, RoundingMode.FLOOR); BigDecimal fractional = decimal.subtract(integer); StringBuilder sb = new StringBuilder(); BigDecimal two = BigDecimal.valueOf(2); BigDecimal zero = BigDecimal.ZERO; while ( integer.compareTo(zero) > 0 ) { BigDecimal[] result = integer.divideAndRemainder(two); sb.append(result[1]); integer = result[0]; } sb.reverse(); int count = 0; if ( fractional.compareTo(zero) != 0 ) { sb.append("."); } while ( fractional.compareTo(zero) != 0 ) { count++; fractional = fractional.multiply(two); sb.append(fractional.setScale(0, RoundingMode.FLOOR)); if ( fractional.compareTo(BigDecimal.ONE) >= 0 ) { fractional = fractional.subtract(BigDecimal.ONE); } if ( count >= digits ) { break; } } return sb.toString(); } }
hex2bin = dict('{:x} {:04b}'.format(x,x).split() for x in range(16)) bin2hex = dict('{:b} {:x}'.format(x,x).split() for x in range(16)) def float_dec2bin(d): neg = False if d < 0: d = -d neg = True hx = float(d).hex() p = hx.index('p') bn = ''.join(hex2bin.get(char, char) for char in hx[2:p]) return (('-' if neg else '') + bn.strip('0') + hx[p:p+2] + bin(int(hx[p+2:]))[2:]) def float_bin2dec(bn): neg = False if bn[0] == '-': bn = bn[1:] neg = True dp = bn.index('.') extra0 = '0' * (4 - (dp % 4)) bn2 = extra0 + bn dp = bn2.index('.') p = bn2.index('p') hx = ''.join(bin2hex.get(bn2[i:min(i+4, p)].lstrip('0'), bn2[i]) for i in range(0, dp+1, 4)) bn3 = bn2[dp+1:p] extra0 = '0' * (4 - (len(bn3) % 4)) bn4 = bn3 + extra0 hx += ''.join(bin2hex.get(bn4[i:i+4].lstrip('0')) for i in range(0, len(bn4), 4)) hx = (('-' if neg else '') + '0x' + hx + bn2[p:p+2] + str(int('0b' + bn2[p+2:], 2))) return float.fromhex(hx)
Ensure the translated Python code behaves exactly like the original Java snippet.
import java.math.BigDecimal; import java.math.MathContext; import java.math.RoundingMode; public class DecimalToBinary { public static void main(String[] args) { for ( String s : new String[] {"23.34375", ".1", "3.1415926535897932"} ) { String binary = decimalToBinary(new BigDecimal(s)); System.out.printf("%s => %s%n", s, binary); System.out.printf("%s => %s%n", binary, binaryToDecimal(binary)); } } private static BigDecimal binaryToDecimal(String binary) { return binaryToDecimal(binary, 50); } private static BigDecimal binaryToDecimal(String binary, int digits) { int decimalPosition = binary.indexOf("."); String integer = decimalPosition >= 0 ? binary.substring(0, decimalPosition) : binary; String fractional = decimalPosition >= 0 ? binary.substring(decimalPosition+1) : ""; BigDecimal result = BigDecimal.ZERO; BigDecimal powTwo = BigDecimal.ONE; BigDecimal two = BigDecimal.valueOf(2); for ( char c : new StringBuilder(integer).reverse().toString().toCharArray() ) { result = result.add(powTwo.multiply(BigDecimal.valueOf(c - '0'))); powTwo = powTwo.multiply(two); } MathContext mc = new MathContext(digits); powTwo = BigDecimal.ONE; for ( char c : fractional.toCharArray() ) { powTwo = powTwo.divide(two); result = result.add(powTwo.multiply(BigDecimal.valueOf(c - '0')), mc); } return result; } private static String decimalToBinary(BigDecimal decimal) { return decimalToBinary(decimal, 50); } private static String decimalToBinary(BigDecimal decimal, int digits) { BigDecimal integer = decimal.setScale(0, RoundingMode.FLOOR); BigDecimal fractional = decimal.subtract(integer); StringBuilder sb = new StringBuilder(); BigDecimal two = BigDecimal.valueOf(2); BigDecimal zero = BigDecimal.ZERO; while ( integer.compareTo(zero) > 0 ) { BigDecimal[] result = integer.divideAndRemainder(two); sb.append(result[1]); integer = result[0]; } sb.reverse(); int count = 0; if ( fractional.compareTo(zero) != 0 ) { sb.append("."); } while ( fractional.compareTo(zero) != 0 ) { count++; fractional = fractional.multiply(two); sb.append(fractional.setScale(0, RoundingMode.FLOOR)); if ( fractional.compareTo(BigDecimal.ONE) >= 0 ) { fractional = fractional.subtract(BigDecimal.ONE); } if ( count >= digits ) { break; } } return sb.toString(); } }
hex2bin = dict('{:x} {:04b}'.format(x,x).split() for x in range(16)) bin2hex = dict('{:b} {:x}'.format(x,x).split() for x in range(16)) def float_dec2bin(d): neg = False if d < 0: d = -d neg = True hx = float(d).hex() p = hx.index('p') bn = ''.join(hex2bin.get(char, char) for char in hx[2:p]) return (('-' if neg else '') + bn.strip('0') + hx[p:p+2] + bin(int(hx[p+2:]))[2:]) def float_bin2dec(bn): neg = False if bn[0] == '-': bn = bn[1:] neg = True dp = bn.index('.') extra0 = '0' * (4 - (dp % 4)) bn2 = extra0 + bn dp = bn2.index('.') p = bn2.index('p') hx = ''.join(bin2hex.get(bn2[i:min(i+4, p)].lstrip('0'), bn2[i]) for i in range(0, dp+1, 4)) bn3 = bn2[dp+1:p] extra0 = '0' * (4 - (len(bn3) % 4)) bn4 = bn3 + extra0 hx += ''.join(bin2hex.get(bn4[i:i+4].lstrip('0')) for i in range(0, len(bn4), 4)) hx = (('-' if neg else '') + '0x' + hx + bn2[p:p+2] + str(int('0b' + bn2[p+2:], 2))) return float.fromhex(hx)
Write the same code in Python as shown below in Java.
import java.io.File; import java.lang.reflect.Method; import java.net.URI; import java.util.Arrays; import javax.tools.JavaCompiler; import javax.tools.SimpleJavaFileObject; import javax.tools.ToolProvider; public class Eval { private static final String CLASS_NAME = "TempPleaseDeleteMe"; private static class StringCompiler extends SimpleJavaFileObject { final String m_sourceCode; private StringCompiler( final String sourceCode ) { super( URI.create( "string: m_sourceCode = sourceCode; } @Override public CharSequence getCharContent( final boolean ignoreEncodingErrors ) { return m_sourceCode; } private boolean compile() { final JavaCompiler javac = ToolProvider.getSystemJavaCompiler(); return javac.getTask( null, javac.getStandardFileManager( null, null, null ), null, null, null, Arrays.asList( this ) ).call(); } private double callEval( final double x ) throws Exception { final Class<?> clarse = Class.forName( CLASS_NAME ); final Method eval = clarse.getMethod( "eval", double.class ); return ( Double ) eval.invoke( null, x ); } } public static double evalWithX( final String code, final double x ) throws Exception { final StringCompiler sc = new StringCompiler( "class " + CLASS_NAME + "{public static double eval(double x){return (" + code + ");}}" ); if ( ! sc.compile() ) throw new RuntimeException( "Compiler error" ); return sc.callEval( x ); } public static void main( final String [] args ) throws Exception { final String expression = args [ 0 ]; final double x1 = Double.parseDouble( args [ 1 ] ); final double x2 = Double.parseDouble( args [ 2 ] ); System.out.println( evalWithX( expression, x1 ) - evalWithX( expression, x2 ) ); } }
>>> def eval_with_x(code, a, b): return eval(code, {'x':b}) - eval(code, {'x':a}) >>> eval_with_x('2 ** x', 3, 5) 24
Change the following Java code into Python without altering its purpose.
import java.io.File; import java.lang.reflect.Method; import java.net.URI; import java.util.Arrays; import javax.tools.JavaCompiler; import javax.tools.SimpleJavaFileObject; import javax.tools.ToolProvider; public class Eval { private static final String CLASS_NAME = "TempPleaseDeleteMe"; private static class StringCompiler extends SimpleJavaFileObject { final String m_sourceCode; private StringCompiler( final String sourceCode ) { super( URI.create( "string: m_sourceCode = sourceCode; } @Override public CharSequence getCharContent( final boolean ignoreEncodingErrors ) { return m_sourceCode; } private boolean compile() { final JavaCompiler javac = ToolProvider.getSystemJavaCompiler(); return javac.getTask( null, javac.getStandardFileManager( null, null, null ), null, null, null, Arrays.asList( this ) ).call(); } private double callEval( final double x ) throws Exception { final Class<?> clarse = Class.forName( CLASS_NAME ); final Method eval = clarse.getMethod( "eval", double.class ); return ( Double ) eval.invoke( null, x ); } } public static double evalWithX( final String code, final double x ) throws Exception { final StringCompiler sc = new StringCompiler( "class " + CLASS_NAME + "{public static double eval(double x){return (" + code + ");}}" ); if ( ! sc.compile() ) throw new RuntimeException( "Compiler error" ); return sc.callEval( x ); } public static void main( final String [] args ) throws Exception { final String expression = args [ 0 ]; final double x1 = Double.parseDouble( args [ 1 ] ); final double x2 = Double.parseDouble( args [ 2 ] ); System.out.println( evalWithX( expression, x1 ) - evalWithX( expression, x2 ) ); } }
>>> def eval_with_x(code, a, b): return eval(code, {'x':b}) - eval(code, {'x':a}) >>> eval_with_x('2 ** x', 3, 5) 24
Preserve the algorithm and functionality while converting the code from Java to Python.
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class CheckMachinFormula { private static String FILE_NAME = "MachinFormula.txt"; public static void main(String[] args) { try { runPrivate(); } catch (Exception e) { e.printStackTrace(); } } private static void runPrivate() throws IOException { try (BufferedReader reader = new BufferedReader(new FileReader(new File(FILE_NAME)));) { String inLine = null; while ( (inLine = reader.readLine()) != null ) { String[] split = inLine.split("="); System.out.println(tanLeft(split[0].trim()) + " = " + split[1].trim().replaceAll("\\s+", " ") + " = " + tanRight(split[1].trim())); } } } private static String tanLeft(String formula) { if ( formula.compareTo("pi/4") == 0 ) { return "1"; } throw new RuntimeException("ERROR 104: Unknown left side: " + formula); } private static final Pattern ARCTAN_PATTERN = Pattern.compile("(-{0,1}\\d+)\\*arctan\\((\\d+)/(\\d+)\\)"); private static Fraction tanRight(String formula) { Matcher matcher = ARCTAN_PATTERN.matcher(formula); List<Term> terms = new ArrayList<>(); while ( matcher.find() ) { terms.add(new Term(Integer.parseInt(matcher.group(1)), new Fraction(matcher.group(2), matcher.group(3)))); } return evaluateArctan(terms); } private static Fraction evaluateArctan(List<Term> terms) { if ( terms.size() == 1 ) { Term term = terms.get(0); return evaluateArctan(term.coefficient, term.fraction); } int size = terms.size(); List<Term> left = terms.subList(0, (size+1) / 2); List<Term> right = terms.subList((size+1) / 2, size); return arctanFormula(evaluateArctan(left), evaluateArctan(right)); } private static Fraction evaluateArctan(int coefficient, Fraction fraction) { if ( coefficient == 1 ) { return fraction; } else if ( coefficient < 0 ) { return evaluateArctan(-coefficient, fraction).negate(); } if ( coefficient % 2 == 0 ) { Fraction f = evaluateArctan(coefficient/2, fraction); return arctanFormula(f, f); } Fraction a = evaluateArctan(coefficient/2, fraction); Fraction b = evaluateArctan(coefficient - (coefficient/2), fraction); return arctanFormula(a, b); } private static Fraction arctanFormula(Fraction f1, Fraction f2) { return f1.add(f2).divide(Fraction.ONE.subtract(f1.multiply(f2))); } private static class Fraction { public static final Fraction ONE = new Fraction("1", "1"); private BigInteger numerator; private BigInteger denominator; public Fraction(String num, String den) { numerator = new BigInteger(num); denominator = new BigInteger(den); } public Fraction(BigInteger num, BigInteger den) { numerator = num; denominator = den; } public Fraction negate() { return new Fraction(numerator.negate(), denominator); } public Fraction add(Fraction f) { BigInteger gcd = denominator.gcd(f.denominator); BigInteger first = numerator.multiply(f.denominator.divide(gcd)); BigInteger second = f.numerator.multiply(denominator.divide(gcd)); return new Fraction(first.add(second), denominator.multiply(f.denominator).divide(gcd)); } public Fraction subtract(Fraction f) { return add(f.negate()); } public Fraction multiply(Fraction f) { BigInteger num = numerator.multiply(f.numerator); BigInteger den = denominator.multiply(f.denominator); BigInteger gcd = num.gcd(den); return new Fraction(num.divide(gcd), den.divide(gcd)); } public Fraction divide(Fraction f) { return multiply(new Fraction(f.denominator, f.numerator)); } @Override public String toString() { if ( denominator.compareTo(BigInteger.ONE) == 0 ) { return numerator.toString(); } return numerator + " / " + denominator; } } private static class Term { private int coefficient; private Fraction fraction; public Term(int c, Fraction f) { coefficient = c; fraction = f; } } }
import re from fractions import Fraction from pprint import pprint as pp equationtext = def parse_eqn(equationtext=equationtext): eqn_re = re.compile(r) found = eqn_re.findall(equationtext) machins, part = [], [] for lhs, sign, mult, numer, denom in eqn_re.findall(equationtext): if lhs and part: machins.append(part) part = [] part.append( ( (-1 if sign == '-' else 1) * ( int(mult) if mult else 1), Fraction(int(numer), (int(denom) if denom else 1)) ) ) machins.append(part) return machins def tans(xs): xslen = len(xs) if xslen == 1: return tanEval(*xs[0]) aa, bb = xs[:xslen//2], xs[xslen//2:] a, b = tans(aa), tans(bb) return (a + b) / (1 - a * b) def tanEval(coef, f): if coef == 1: return f if coef < 0: return -tanEval(-coef, f) ca = coef // 2 cb = coef - ca a, b = tanEval(ca, f), tanEval(cb, f) return (a + b) / (1 - a * b) if __name__ == '__main__': machins = parse_eqn() for machin, eqn in zip(machins, equationtext.split('\n')): ans = tans(machin) print('%5s: %s' % ( ('OK' if ans == 1 else 'ERROR'), eqn))
Translate this program into Python but keep the logic exactly as in Java.
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class CheckMachinFormula { private static String FILE_NAME = "MachinFormula.txt"; public static void main(String[] args) { try { runPrivate(); } catch (Exception e) { e.printStackTrace(); } } private static void runPrivate() throws IOException { try (BufferedReader reader = new BufferedReader(new FileReader(new File(FILE_NAME)));) { String inLine = null; while ( (inLine = reader.readLine()) != null ) { String[] split = inLine.split("="); System.out.println(tanLeft(split[0].trim()) + " = " + split[1].trim().replaceAll("\\s+", " ") + " = " + tanRight(split[1].trim())); } } } private static String tanLeft(String formula) { if ( formula.compareTo("pi/4") == 0 ) { return "1"; } throw new RuntimeException("ERROR 104: Unknown left side: " + formula); } private static final Pattern ARCTAN_PATTERN = Pattern.compile("(-{0,1}\\d+)\\*arctan\\((\\d+)/(\\d+)\\)"); private static Fraction tanRight(String formula) { Matcher matcher = ARCTAN_PATTERN.matcher(formula); List<Term> terms = new ArrayList<>(); while ( matcher.find() ) { terms.add(new Term(Integer.parseInt(matcher.group(1)), new Fraction(matcher.group(2), matcher.group(3)))); } return evaluateArctan(terms); } private static Fraction evaluateArctan(List<Term> terms) { if ( terms.size() == 1 ) { Term term = terms.get(0); return evaluateArctan(term.coefficient, term.fraction); } int size = terms.size(); List<Term> left = terms.subList(0, (size+1) / 2); List<Term> right = terms.subList((size+1) / 2, size); return arctanFormula(evaluateArctan(left), evaluateArctan(right)); } private static Fraction evaluateArctan(int coefficient, Fraction fraction) { if ( coefficient == 1 ) { return fraction; } else if ( coefficient < 0 ) { return evaluateArctan(-coefficient, fraction).negate(); } if ( coefficient % 2 == 0 ) { Fraction f = evaluateArctan(coefficient/2, fraction); return arctanFormula(f, f); } Fraction a = evaluateArctan(coefficient/2, fraction); Fraction b = evaluateArctan(coefficient - (coefficient/2), fraction); return arctanFormula(a, b); } private static Fraction arctanFormula(Fraction f1, Fraction f2) { return f1.add(f2).divide(Fraction.ONE.subtract(f1.multiply(f2))); } private static class Fraction { public static final Fraction ONE = new Fraction("1", "1"); private BigInteger numerator; private BigInteger denominator; public Fraction(String num, String den) { numerator = new BigInteger(num); denominator = new BigInteger(den); } public Fraction(BigInteger num, BigInteger den) { numerator = num; denominator = den; } public Fraction negate() { return new Fraction(numerator.negate(), denominator); } public Fraction add(Fraction f) { BigInteger gcd = denominator.gcd(f.denominator); BigInteger first = numerator.multiply(f.denominator.divide(gcd)); BigInteger second = f.numerator.multiply(denominator.divide(gcd)); return new Fraction(first.add(second), denominator.multiply(f.denominator).divide(gcd)); } public Fraction subtract(Fraction f) { return add(f.negate()); } public Fraction multiply(Fraction f) { BigInteger num = numerator.multiply(f.numerator); BigInteger den = denominator.multiply(f.denominator); BigInteger gcd = num.gcd(den); return new Fraction(num.divide(gcd), den.divide(gcd)); } public Fraction divide(Fraction f) { return multiply(new Fraction(f.denominator, f.numerator)); } @Override public String toString() { if ( denominator.compareTo(BigInteger.ONE) == 0 ) { return numerator.toString(); } return numerator + " / " + denominator; } } private static class Term { private int coefficient; private Fraction fraction; public Term(int c, Fraction f) { coefficient = c; fraction = f; } } }
import re from fractions import Fraction from pprint import pprint as pp equationtext = def parse_eqn(equationtext=equationtext): eqn_re = re.compile(r) found = eqn_re.findall(equationtext) machins, part = [], [] for lhs, sign, mult, numer, denom in eqn_re.findall(equationtext): if lhs and part: machins.append(part) part = [] part.append( ( (-1 if sign == '-' else 1) * ( int(mult) if mult else 1), Fraction(int(numer), (int(denom) if denom else 1)) ) ) machins.append(part) return machins def tans(xs): xslen = len(xs) if xslen == 1: return tanEval(*xs[0]) aa, bb = xs[:xslen//2], xs[xslen//2:] a, b = tans(aa), tans(bb) return (a + b) / (1 - a * b) def tanEval(coef, f): if coef == 1: return f if coef < 0: return -tanEval(-coef, f) ca = coef // 2 cb = coef - ca a, b = tanEval(ca, f), tanEval(cb, f) return (a + b) / (1 - a * b) if __name__ == '__main__': machins = parse_eqn() for machin, eqn in zip(machins, equationtext.split('\n')): ans = tans(machin) print('%5s: %s' % ( ('OK' if ans == 1 else 'ERROR'), eqn))