Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Change the programming language of this snippet from C++ to Python without modifying what it does. | #include <stdio.h>
#include <math.h>
int p(int year) {
return (int)((double)year + floor(year/4) - floor(year/100) + floor(year/400)) % 7;
}
int is_long_year(int year) {
return p(year) == 4 || p(year - 1) == 3;
}
void print_long_years(int from, int to) {
for (int year = from; year <= to; ++year) {
if (is_long_year(year)) {
printf("%d ", year);
}
}
}
int main() {
printf("Long (53 week) years between 1800 and 2100\n\n");
print_long_years(1800, 2100);
printf("\n");
return 0;
}
|
from datetime import date
def longYear(y):
return 52 < date(y, 12, 28).isocalendar()[1]
def main():
for year in [
x for x in range(2000, 1 + 2100)
if longYear(x)
]:
print(year)
if __name__ == '__main__':
main()
|
Write the same code in Python as shown below in C++. | #include <iostream">
#include <cmath>
#include <vector>
#include <algorithm>
#include <iomanip>
#include <numeric>
using namespace std;
const uint* binary(uint n, uint length);
uint sum_subset_unrank_bin(const vector<uint>& d, uint r);
vector<uint> factors(uint x);
bool isPrime(uint number);
bool isZum(uint n);
ostream& operator<<(ostream& os, const vector<uint>& zumz) {
for (uint i = 0; i < zumz.size(); i++) {
if (i % 10 == 0)
os << endl;
os << setw(10) << zumz[i] << ' ';
}
return os;
}
int main() {
cout << "First 220 Zumkeller numbers:" << endl;
vector<uint> zumz;
for (uint n = 2; zumz.size() < 220; n++)
if (isZum(n))
zumz.push_back(n);
cout << zumz << endl << endl;
cout << "First 40 odd Zumkeller numbers:" << endl;
vector<uint> zumz2;
for (uint n = 2; zumz2.size() < 40; n++)
if (n % 2 && isZum(n))
zumz2.push_back(n);
cout << zumz2 << endl << endl;
cout << "First 40 odd Zumkeller numbers not ending in 5:" << endl;
vector<uint> zumz3;
for (uint n = 2; zumz3.size() < 40; n++)
if (n % 2 && (n % 10) != 5 && isZum(n))
zumz3.push_back(n);
cout << zumz3 << endl << endl;
return 0;
}
const uint* binary(uint n, uint length) {
uint* bin = new uint[length];
fill(bin, bin + length, 0);
for (uint i = 0; n > 0; i++) {
uint rem = n % 2;
n /= 2;
if (rem)
bin[length - 1 - i] = 1;
}
return bin;
}
uint sum_subset_unrank_bin(const vector<uint>& d, uint r) {
vector<uint> subset;
const uint* bits = binary(r, d.size() - 1);
for (uint i = 0; i < d.size() - 1; i++)
if (bits[i])
subset.push_back(d[i]);
delete[] bits;
return accumulate(subset.begin(), subset.end(), 0u);
}
vector<uint> factors(uint x) {
vector<uint> result;
for (uint i = 1; i * i <= x; i++) {
if (x % i == 0) {
result.push_back(i);
if (x / i != i)
result.push_back(x / i);
}
}
sort(result.begin(), result.end());
return result;
}
bool isPrime(uint number) {
if (number < 2) return false;
if (number == 2) return true;
if (number % 2 == 0) return false;
for (uint i = 3; i * i <= number; i += 2)
if (number % i == 0) return false;
return true;
}
bool isZum(uint n) {
if (isPrime(n))
return false;
const auto d = factors(n);
uint s = accumulate(d.begin(), d.end(), 0u);
if (s % 2 || s < 2 * n)
return false;
if (n % 2 || d.size() >= 24)
return true;
if (!(s % 2) && d[d.size() - 1] <= s / 2)
for (uint x = 2; (uint) log2(x) < (d.size() - 1); x++)
if (sum_subset_unrank_bin(d, x) == s / 2)
return true;
return false;
}
| 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 C++, keeping it the same logically? | #include <iostream>
#include <string>
#include <map>
template<typename map_type>
map_type merge(const map_type& original, const map_type& update) {
map_type result(update);
result.insert(original.begin(), original.end());
return result;
}
int main() {
typedef std::map<std::string, std::string> map;
map original{
{"name", "Rocket Skates"},
{"price", "12.75"},
{"color", "yellow"}
};
map update{
{"price", "15.25"},
{"color", "red"},
{"year", "1974"}
};
map merged(merge(original, update));
for (auto&& i : merged)
std::cout << "key: " << i.first << ", value: " << i.second << '\n';
return 0;
}
| base = {"name":"Rocket Skates", "price":12.75, "color":"yellow"}
update = {"price":15.25, "color":"red", "year":1974}
result = {**base, **update}
print(result)
|
Write a version of this C++ function in Python with identical behavior. | #include <iostream>
#include <string>
#include <map>
template<typename map_type>
map_type merge(const map_type& original, const map_type& update) {
map_type result(update);
result.insert(original.begin(), original.end());
return result;
}
int main() {
typedef std::map<std::string, std::string> map;
map original{
{"name", "Rocket Skates"},
{"price", "12.75"},
{"color", "yellow"}
};
map update{
{"price", "15.25"},
{"color", "red"},
{"year", "1974"}
};
map merged(merge(original, update));
for (auto&& i : merged)
std::cout << "key: " << i.first << ", value: " << i.second << '\n';
return 0;
}
| base = {"name":"Rocket Skates", "price":12.75, "color":"yellow"}
update = {"price":15.25, "color":"red", "year":1974}
result = {**base, **update}
print(result)
|
Convert this C++ snippet to Python and keep its semantics consistent. | #include <boost/multiprecision/cpp_dec_float.hpp>
#include <iostream>
const char* names[] = { "Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminium", "Iron", "Tin", "Lead" };
template<const uint N>
void lucas(ulong b) {
std::cout << "Lucas sequence for " << names[b] << " ratio, where b = " << b << ":\nFirst " << N << " elements: ";
auto x0 = 1L, x1 = 1L;
std::cout << x0 << ", " << x1;
for (auto i = 1u; i <= N - 1 - 1; i++) {
auto x2 = b * x1 + x0;
std::cout << ", " << x2;
x0 = x1;
x1 = x2;
}
std::cout << std::endl;
}
template<const ushort P>
void metallic(ulong b) {
using namespace boost::multiprecision;
using bfloat = number<cpp_dec_float<P+1>>;
bfloat x0(1), x1(1);
auto prev = bfloat(1).str(P+1);
for (auto i = 0u;;) {
i++;
bfloat x2(b * x1 + x0);
auto thiz = bfloat(x2 / x1).str(P+1);
if (prev == thiz) {
std::cout << "Value after " << i << " iteration" << (i == 1 ? ": " : "s: ") << thiz << std::endl << std::endl;
break;
}
prev = thiz;
x0 = x1;
x1 = x2;
}
}
int main() {
for (auto b = 0L; b < 10L; b++) {
lucas<15>(b);
metallic<32>(b);
}
std::cout << "Golden ratio, where b = 1:" << std::endl;
metallic<256>(1);
return 0;
}
| 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)
|
Generate a Python translation of this C++ snippet without changing its computational steps. | #include <boost/multiprecision/cpp_dec_float.hpp>
#include <iostream>
const char* names[] = { "Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminium", "Iron", "Tin", "Lead" };
template<const uint N>
void lucas(ulong b) {
std::cout << "Lucas sequence for " << names[b] << " ratio, where b = " << b << ":\nFirst " << N << " elements: ";
auto x0 = 1L, x1 = 1L;
std::cout << x0 << ", " << x1;
for (auto i = 1u; i <= N - 1 - 1; i++) {
auto x2 = b * x1 + x0;
std::cout << ", " << x2;
x0 = x1;
x1 = x2;
}
std::cout << std::endl;
}
template<const ushort P>
void metallic(ulong b) {
using namespace boost::multiprecision;
using bfloat = number<cpp_dec_float<P+1>>;
bfloat x0(1), x1(1);
auto prev = bfloat(1).str(P+1);
for (auto i = 0u;;) {
i++;
bfloat x2(b * x1 + x0);
auto thiz = bfloat(x2 / x1).str(P+1);
if (prev == thiz) {
std::cout << "Value after " << i << " iteration" << (i == 1 ? ": " : "s: ") << thiz << std::endl << std::endl;
break;
}
prev = thiz;
x0 = x1;
x1 = x2;
}
}
int main() {
for (auto b = 0L; b < 10L; b++) {
lucas<15>(b);
metallic<32>(b);
}
std::cout << "Golden ratio, where b = 1:" << std::endl;
metallic<256>(1);
return 0;
}
| 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)
|
Produce a language-to-language conversion: from C++ to Python, same semantics. | #include <ctime>
#include <iostream>
#include <algorithm>
#include <fstream>
#include <string>
#include <vector>
#include <map>
class markov {
public:
void create( std::string& file, unsigned int keyLen, unsigned int words ) {
std::ifstream f( file.c_str(), std::ios_base::in );
fileBuffer = std::string( ( std::istreambuf_iterator<char>( f ) ), std::istreambuf_iterator<char>() );
f.close();
if( fileBuffer.length() < 1 ) return;
createDictionary( keyLen );
createText( words - keyLen );
}
private:
void createText( int w ) {
std::string key, first, second;
size_t next;
std::map<std::string, std::vector<std::string> >::iterator it = dictionary.begin();
std::advance( it, rand() % dictionary.size() );
key = ( *it ).first;
std::cout << key;
while( true ) {
std::vector<std::string> d = dictionary[key];
if( d.size() < 1 ) break;
second = d[rand() % d.size()];
if( second.length() < 1 ) break;
std::cout << " " << second;
if( --w < 0 ) break;
next = key.find_first_of( 32, 0 );
first = key.substr( next + 1 );
key = first + " " + second;
}
std::cout << "\n";
}
void createDictionary( unsigned int kl ) {
std::string w1, key;
size_t wc = 0, pos, next;
next = fileBuffer.find_first_not_of( 32, 0 );
if( next == std::string::npos ) return;
while( wc < kl ) {
pos = fileBuffer.find_first_of( ' ', next );
w1 = fileBuffer.substr( next, pos - next );
key += w1 + " ";
next = fileBuffer.find_first_not_of( 32, pos + 1 );
if( next == std::string::npos ) return;
wc++;
}
key = key.substr( 0, key.size() - 1 );
while( true ) {
next = fileBuffer.find_first_not_of( 32, pos + 1 );
if( next == std::string::npos ) return;
pos = fileBuffer.find_first_of( 32, next );
w1 = fileBuffer.substr( next, pos - next );
if( w1.size() < 1 ) break;
if( std::find( dictionary[key].begin(), dictionary[key].end(), w1 ) == dictionary[key].end() )
dictionary[key].push_back( w1 );
key = key.substr( key.find_first_of( 32 ) + 1 ) + " " + w1;
}
}
std::string fileBuffer;
std::map<std::string, std::vector<std::string> > dictionary;
};
int main( int argc, char* argv[] ) {
srand( unsigned( time( 0 ) ) );
markov m;
m.create( std::string( "alice_oz.txt" ), 3, 200 );
return 0;
}
| 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)
|
Translate this program into Python but keep the logic exactly as in C++. | #include <iostream>
#include <vector>
#include <string>
#include <list>
#include <limits>
#include <set>
#include <utility>
#include <algorithm>
#include <iterator>
typedef int vertex_t;
typedef double weight_t;
const weight_t max_weight = std::numeric_limits<double>::infinity();
struct neighbor {
vertex_t target;
weight_t weight;
neighbor(vertex_t arg_target, weight_t arg_weight)
: target(arg_target), weight(arg_weight) { }
};
typedef std::vector<std::vector<neighbor> > adjacency_list_t;
void DijkstraComputePaths(vertex_t source,
const adjacency_list_t &adjacency_list,
std::vector<weight_t> &min_distance,
std::vector<vertex_t> &previous)
{
int n = adjacency_list.size();
min_distance.clear();
min_distance.resize(n, max_weight);
min_distance[source] = 0;
previous.clear();
previous.resize(n, -1);
std::set<std::pair<weight_t, vertex_t> > vertex_queue;
vertex_queue.insert(std::make_pair(min_distance[source], source));
while (!vertex_queue.empty())
{
weight_t dist = vertex_queue.begin()->first;
vertex_t u = vertex_queue.begin()->second;
vertex_queue.erase(vertex_queue.begin());
const std::vector<neighbor> &neighbors = adjacency_list[u];
for (std::vector<neighbor>::const_iterator neighbor_iter = neighbors.begin();
neighbor_iter != neighbors.end();
neighbor_iter++)
{
vertex_t v = neighbor_iter->target;
weight_t weight = neighbor_iter->weight;
weight_t distance_through_u = dist + weight;
if (distance_through_u < min_distance[v]) {
vertex_queue.erase(std::make_pair(min_distance[v], v));
min_distance[v] = distance_through_u;
previous[v] = u;
vertex_queue.insert(std::make_pair(min_distance[v], v));
}
}
}
}
std::list<vertex_t> DijkstraGetShortestPathTo(
vertex_t vertex, const std::vector<vertex_t> &previous)
{
std::list<vertex_t> path;
for ( ; vertex != -1; vertex = previous[vertex])
path.push_front(vertex);
return path;
}
int main()
{
adjacency_list_t adjacency_list(6);
adjacency_list[0].push_back(neighbor(1, 7));
adjacency_list[0].push_back(neighbor(2, 9));
adjacency_list[0].push_back(neighbor(5, 14));
adjacency_list[1].push_back(neighbor(0, 7));
adjacency_list[1].push_back(neighbor(2, 10));
adjacency_list[1].push_back(neighbor(3, 15));
adjacency_list[2].push_back(neighbor(0, 9));
adjacency_list[2].push_back(neighbor(1, 10));
adjacency_list[2].push_back(neighbor(3, 11));
adjacency_list[2].push_back(neighbor(5, 2));
adjacency_list[3].push_back(neighbor(1, 15));
adjacency_list[3].push_back(neighbor(2, 11));
adjacency_list[3].push_back(neighbor(4, 6));
adjacency_list[4].push_back(neighbor(3, 6));
adjacency_list[4].push_back(neighbor(5, 9));
adjacency_list[5].push_back(neighbor(0, 14));
adjacency_list[5].push_back(neighbor(2, 2));
adjacency_list[5].push_back(neighbor(4, 9));
std::vector<weight_t> min_distance;
std::vector<vertex_t> previous;
DijkstraComputePaths(0, adjacency_list, min_distance, previous);
std::cout << "Distance from 0 to 4: " << min_distance[4] << std::endl;
std::list<vertex_t> path = DijkstraGetShortestPathTo(4, previous);
std::cout << "Path : ";
std::copy(path.begin(), path.end(), std::ostream_iterator<vertex_t>(std::cout, " "));
std::cout << std::endl;
return 0;
}
| 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"))
|
Convert this C++ block to Python, preserving its control flow and logic. | #include <algorithm>
#include <iostream>
#include <random>
#include <vector>
double uniform01() {
static std::default_random_engine generator;
static std::uniform_real_distribution<double> distribution(0.0, 1.0);
return distribution(generator);
}
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;
}
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;
}
struct MyVector {
public:
MyVector(const std::vector<double> &da) : dims(da) {
}
double &operator[](size_t i) {
return dims[i];
}
const double &operator[](size_t i) const {
return dims[i];
}
MyVector operator+(const MyVector &rhs) const {
std::vector<double> temp(dims);
for (size_t i = 0; i < rhs.dims.size(); ++i) {
temp[i] += rhs[i];
}
return MyVector(temp);
}
MyVector operator*(const MyVector &rhs) const {
std::vector<double> temp(dims.size(), 0.0);
for (size_t i = 0; i < dims.size(); i++) {
if (dims[i] != 0.0) {
for (size_t j = 0; j < dims.size(); j++) {
if (rhs[j] != 0.0) {
auto s = reorderingSign(i, j) * dims[i] * rhs[j];
auto k = i ^ j;
temp[k] += s;
}
}
}
}
return MyVector(temp);
}
MyVector operator*(double scale) const {
std::vector<double> temp(dims);
std::for_each(temp.begin(), temp.end(), [scale](double a) { return a * scale; });
return MyVector(temp);
}
MyVector operator-() const {
return *this * -1.0;
}
MyVector dot(const MyVector &rhs) const {
return (*this * rhs + rhs * *this) * 0.5;
}
friend std::ostream &operator<<(std::ostream &, const MyVector &);
private:
std::vector<double> dims;
};
std::ostream &operator<<(std::ostream &os, const MyVector &v) {
auto it = v.dims.cbegin();
auto end = v.dims.cend();
os << '[';
if (it != end) {
os << *it;
it = std::next(it);
}
while (it != end) {
os << ", " << *it;
it = std::next(it);
}
return os << ']';
}
MyVector e(int n) {
if (n > 4) {
throw new std::runtime_error("n must be less than 5");
}
auto result = MyVector(std::vector<double>(32, 0.0));
result[1 << n] = 1.0;
return result;
}
MyVector randomVector() {
auto result = MyVector(std::vector<double>(32, 0.0));
for (int i = 0; i < 5; i++) {
result = result + MyVector(std::vector<double>(1, uniform01())) * e(i);
}
return result;
}
MyVector randomMultiVector() {
auto result = MyVector(std::vector<double>(32, 0.0));
for (int i = 0; i < 32; i++) {
result[i] = uniform01();
}
return result;
}
int main() {
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (i < j) {
if (e(i).dot(e(j))[0] != 0.0) {
std::cout << "Unexpected non-null scalar product.";
return 1;
} else if (i == j) {
if (e(i).dot(e(j))[0] == 0.0) {
std::cout << "Unexpected null scalar product.";
}
}
}
}
}
auto a = randomMultiVector();
auto b = randomMultiVector();
auto c = randomMultiVector();
auto x = randomVector();
std::cout << ((a * b) * c) << '\n';
std::cout << (a * (b * c)) << "\n\n";
std::cout << (a * (b + c)) << '\n';
std::cout << (a * b + a * c) << "\n\n";
std::cout << ((a + b) * c) << '\n';
std::cout << (a * c + b * c) << "\n\n";
std::cout << (x * x) << '\n';
return 0;
}
| 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()
|
Port the following code from C++ to Python with equivalent syntax and logic. | #include <functional>
#include <iostream>
#include <vector>
struct Node {
std::string sub = "";
std::vector<int> ch;
Node() {
}
Node(const std::string& sub, std::initializer_list<int> children) : sub(sub) {
ch.insert(ch.end(), children);
}
};
struct SuffixTree {
std::vector<Node> nodes;
SuffixTree(const std::string& str) {
nodes.push_back(Node{});
for (size_t i = 0; i < str.length(); i++) {
addSuffix(str.substr(i));
}
}
void visualize() {
if (nodes.size() == 0) {
std::cout << "<empty>\n";
return;
}
std::function<void(int, const std::string&)> f;
f = [&](int n, const std::string & pre) {
auto children = nodes[n].ch;
if (children.size() == 0) {
std::cout << "- " << nodes[n].sub << '\n';
return;
}
std::cout << "+ " << nodes[n].sub << '\n';
auto it = std::begin(children);
if (it != std::end(children)) do {
if (std::next(it) == std::end(children)) break;
std::cout << pre << "+-";
f(*it, pre + "| ");
it = std::next(it);
} while (true);
std::cout << pre << "+-";
f(children[children.size() - 1], pre + " ");
};
f(0, "");
}
private:
void addSuffix(const std::string & suf) {
int n = 0;
size_t i = 0;
while (i < suf.length()) {
char b = suf[i];
int x2 = 0;
int n2;
while (true) {
auto children = nodes[n].ch;
if (x2 == children.size()) {
n2 = nodes.size();
nodes.push_back(Node(suf.substr(i), {}));
nodes[n].ch.push_back(n2);
return;
}
n2 = children[x2];
if (nodes[n2].sub[0] == b) {
break;
}
x2++;
}
auto sub2 = nodes[n2].sub;
size_t j = 0;
while (j < sub2.size()) {
if (suf[i + j] != sub2[j]) {
auto n3 = n2;
n2 = nodes.size();
nodes.push_back(Node(sub2.substr(0, j), { n3 }));
nodes[n3].sub = sub2.substr(j);
nodes[n].ch[x2] = n2;
break;
}
j++;
}
i += j;
n = n2;
}
}
};
int main() {
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()
|
Produce a language-to-language conversion: from C++ to Python, same semantics. | #include <functional>
#include <iostream>
#include <vector>
struct Node {
std::string sub = "";
std::vector<int> ch;
Node() {
}
Node(const std::string& sub, std::initializer_list<int> children) : sub(sub) {
ch.insert(ch.end(), children);
}
};
struct SuffixTree {
std::vector<Node> nodes;
SuffixTree(const std::string& str) {
nodes.push_back(Node{});
for (size_t i = 0; i < str.length(); i++) {
addSuffix(str.substr(i));
}
}
void visualize() {
if (nodes.size() == 0) {
std::cout << "<empty>\n";
return;
}
std::function<void(int, const std::string&)> f;
f = [&](int n, const std::string & pre) {
auto children = nodes[n].ch;
if (children.size() == 0) {
std::cout << "- " << nodes[n].sub << '\n';
return;
}
std::cout << "+ " << nodes[n].sub << '\n';
auto it = std::begin(children);
if (it != std::end(children)) do {
if (std::next(it) == std::end(children)) break;
std::cout << pre << "+-";
f(*it, pre + "| ");
it = std::next(it);
} while (true);
std::cout << pre << "+-";
f(children[children.size() - 1], pre + " ");
};
f(0, "");
}
private:
void addSuffix(const std::string & suf) {
int n = 0;
size_t i = 0;
while (i < suf.length()) {
char b = suf[i];
int x2 = 0;
int n2;
while (true) {
auto children = nodes[n].ch;
if (x2 == children.size()) {
n2 = nodes.size();
nodes.push_back(Node(suf.substr(i), {}));
nodes[n].ch.push_back(n2);
return;
}
n2 = children[x2];
if (nodes[n2].sub[0] == b) {
break;
}
x2++;
}
auto sub2 = nodes[n2].sub;
size_t j = 0;
while (j < sub2.size()) {
if (suf[i + j] != sub2[j]) {
auto n3 = n2;
n2 = nodes.size();
nodes.push_back(Node(sub2.substr(0, j), { n3 }));
nodes[n3].sub = sub2.substr(j);
nodes[n].ch[x2] = n2;
break;
}
j++;
}
i += j;
n = n2;
}
}
};
int main() {
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()
|
Port the provided C++ code into Python while preserving the original functionality. | #include <iostream>
#include <map>
#include <string>
int main() {
std::map<std::string, int> dict {
{"One", 1},
{"Two", 2},
{"Three", 7}
};
dict["Three"] = 3;
std::cout << "One: " << dict["One"] << std::endl;
std::cout << "Key/Value pairs: " << std::endl;
for(auto& kv: dict) {
std::cout << " " << kv.first << ": " << kv.second << std::endl;
}
return 0;
}
| 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)
|
Change the programming language of this snippet from C++ to Python without modifying what it does. | #include <stdexcept>
class tiny_int
{
public:
tiny_int(int i):
value(i)
{
if (value < 1)
throw std::out_of_range("tiny_int: value smaller than 1");
if (value > 10)
throw std::out_of_range("tiny_int: value larger than 10");
}
operator int() const
{
return value;
}
tiny_int& operator+=(int i)
{
*this = value + i;
return *this;
}
tiny_int& operator-=(int i)
{
*this = value - i;
return *this;
}
tiny_int& operator*=(int i)
{
*this = value * i;
return *this;
}
tiny_int& operator/=(int i)
{
*this = value / i;
return *this;
}
tiny_int& operator<<=(int i)
{
*this = value << i;
return *this;
}
tiny_int& operator>>=(int i)
{
*this = value >> i;
return *this;
}
tiny_int& operator&=(int i)
{
*this = value & i;
return *this;
}
tiny_int& operator|=(int i)
{
*this = value | i;
return *this;
}
private:
unsigned char value;
};
| >>> 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 a Python translation of this C++ snippet without changing its computational steps. | #include <iomanip>
#include <iostream>
#include <boost/multiprecision/cpp_int.hpp>
template <typename IntegerType>
IntegerType arithmetic_derivative(IntegerType n) {
bool negative = n < 0;
if (negative)
n = -n;
if (n < 2)
return 0;
IntegerType sum = 0, count = 0, m = n;
while ((m & 1) == 0) {
m >>= 1;
count += n;
}
if (count > 0)
sum += count / 2;
for (IntegerType p = 3, sq = 9; sq <= m; p += 2) {
count = 0;
while (m % p == 0) {
m /= p;
count += n;
}
if (count > 0)
sum += count / p;
sq += (p + 1) << 2;
}
if (m > 1)
sum += n / m;
if (negative)
sum = -sum;
return sum;
}
int main() {
using boost::multiprecision::int128_t;
for (int n = -99, i = 0; n <= 100; ++n, ++i) {
std::cout << std::setw(4) << arithmetic_derivative(n)
<< ((i + 1) % 10 == 0 ? '\n' : ' ');
}
int128_t p = 10;
std::cout << '\n';
for (int i = 0; i < 20; ++i, p *= 10) {
std::cout << "D(10^" << std::setw(2) << i + 1
<< ") / 7 = " << arithmetic_derivative(p) / 7 << '\n';
}
}
| from sympy.ntheory import factorint
def D(n):
if n < 0:
return -D(-n)
elif n < 2:
return 0
else:
fdict = factorint(n)
if len(fdict) == 1 and 1 in fdict:
return 1
return sum([n * e // p for p, e in fdict.items()])
for n in range(-99, 101):
print('{:5}'.format(D(n)), end='\n' if n % 10 == 0 else '')
print()
for m in range(1, 21):
print('(D for 10**{}) divided by 7 is {}'.format(m, D(10 ** m) // 7))
|
Preserve the algorithm and functionality while converting the code from C++ to Python. | #include <algorithm>
#include <iostream>
int main() {
std::string str("AABBBC");
int count = 0;
do {
std::cout << str << (++count % 10 == 0 ? '\n' : ' ');
} while (std::next_permutation(str.begin(), str.end()));
}
|
from itertools import permutations
numList = [2,3,1]
baseList = []
for i in numList:
for j in range(0,i):
baseList.append(i)
stringDict = {'A':2,'B':3,'C':1}
baseString=""
for i in stringDict:
for j in range(0,stringDict[i]):
baseString+=i
print("Permutations for " + str(baseList) + " : ")
[print(i) for i in set(permutations(baseList))]
print("Permutations for " + baseString + " : ")
[print(i) for i in set(permutations(baseString))]
|
Preserve the algorithm and functionality while converting the code from C++ to Python. | #include <cmath>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <tuple>
int main() {
std::ofstream out("penrose_tiling.svg");
if (!out) {
std::cerr << "Cannot open output file.\n";
return EXIT_FAILURE;
}
std::string penrose("[N]++[N]++[N]++[N]++[N]");
for (int i = 1; i <= 4; ++i) {
std::string next;
for (char ch : penrose) {
switch (ch) {
case 'A':
break;
case 'M':
next += "OA++PA----NA[-OA----MA]++";
break;
case 'N':
next += "+OA--PA[---MA--NA]+";
break;
case 'O':
next += "-MA++NA[+++OA++PA]-";
break;
case 'P':
next += "--OA++++MA[+PA++++NA]--NA";
break;
default:
next += ch;
break;
}
}
penrose = std::move(next);
}
const double r = 30;
const double pi5 = 0.628318530717959;
double x = r * 8, y = r * 8, theta = pi5;
std::set<std::string> svg;
std::stack<std::tuple<double, double, double>> stack;
for (char ch : penrose) {
switch (ch) {
case 'A': {
double nx = x + r * std::cos(theta);
double ny = y + r * std::sin(theta);
std::ostringstream line;
line << std::fixed << std::setprecision(3) << "<line x1='" << x
<< "' y1='" << y << "' x2='" << nx << "' y2='" << ny << "'/>";
svg.insert(line.str());
x = nx;
y = ny;
} break;
case '+':
theta += pi5;
break;
case '-':
theta -= pi5;
break;
case '[':
stack.push({x, y, theta});
break;
case ']':
std::tie(x, y, theta) = stack.top();
stack.pop();
break;
}
}
out << "<svg xmlns='http:
<< "' width='" << r * 16 << "'>\n"
<< "<rect height='100%' width='100%' fill='black'/>\n"
<< "<g stroke='rgb(255,165,0)'>\n";
for (const auto& line : svg)
out << line << '\n';
out << "</g>\n</svg>\n";
return EXIT_SUCCESS;
}
| 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)
|
Port the following code from C++ to Python with equivalent syntax and logic. | #include <algorithm>
#include <cassert>
#include <iomanip>
#include <iostream>
#include <vector>
std::vector<bool> prime_sieve(int limit) {
std::vector<bool> sieve(limit, 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;
}
std::vector<int> prime_factors(int n) {
std::vector<int> factors;
if (n > 1 && (n & 1) == 0) {
factors.push_back(2);
while ((n & 1) == 0)
n >>= 1;
}
for (int p = 3; p * p <= n; p += 2) {
if (n % p == 0) {
factors.push_back(p);
while (n % p == 0)
n /= p;
}
}
if (n > 1)
factors.push_back(n);
return factors;
}
int main() {
const int limit = 1000000;
const int imax = limit / 6;
std::vector<bool> sieve = prime_sieve(imax + 1);
std::vector<bool> sphenic(limit + 1, false);
for (int i = 0; i <= imax; ++i) {
if (!sieve[i])
continue;
int jmax = std::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 = std::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;
}
}
}
std::cout << "Sphenic numbers < 1000:\n";
for (int i = 0, n = 0; i < 1000; ++i) {
if (!sphenic[i])
continue;
++n;
std::cout << std::setw(3) << i << (n % 15 == 0 ? '\n' : ' ');
}
std::cout << "\nSphenic triplets < 10,000:\n";
for (int i = 0, n = 0; i < 10000; ++i) {
if (i > 1 && sphenic[i] && sphenic[i - 1] && sphenic[i - 2]) {
++n;
std::cout << "(" << 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;
}
}
std::cout << "\nNumber of sphenic numbers < 1,000,000: " << count << '\n';
std::cout << "Number of sphenic triplets < 1,000,000: " << triplets << '\n';
auto factors = prime_factors(s200000);
assert(factors.size() == 3);
std::cout << "The 200,000th sphenic number: " << s200000 << " = "
<< factors[0] << " * " << factors[1] << " * " << factors[2]
<< '\n';
std::cout << "The 5,000th sphenic triplet: (" << t5000 - 2 << ", "
<< t5000 - 1 << ", " << t5000 << ")\n";
}
|
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}).')
|
Ensure the translated Python code behaves exactly like the original C++ snippet. | #include <any>
#include <iostream>
#include <iterator>
#include <vector>
using namespace std;
vector<any> MakeTree(input_iterator auto first, input_iterator auto last, int depth = 1)
{
vector<any> tree;
while (first < last && depth <= *first)
{
if(*first == depth)
{
tree.push_back(*first);
++first;
}
else
{
tree.push_back(MakeTree(first, last, depth + 1));
first = find(first + 1, last, depth);
}
}
return tree;
}
void PrintTree(input_iterator auto first, input_iterator auto last)
{
cout << "[";
for(auto it = first; it != last; ++it)
{
if(it != first) cout << ", ";
if constexpr (is_integral_v<remove_reference_t<decltype(*first)>>)
{
cout << *it;
}
else
{
if(it->type() == typeid(unsigned int))
{
cout << any_cast<unsigned int>(*it);
}
else
{
const auto& subTree = any_cast<vector<any>>(*it);
PrintTree(subTree.begin(), subTree.end());
}
}
}
cout << "]";
}
int main(void)
{
auto execises = vector<vector<unsigned int>> {
{},
{1, 2, 4},
{3, 1, 3, 1},
{1, 2, 3, 1},
{3, 2, 1, 3},
{3, 3, 3, 1, 1, 3, 3, 3}
};
for(const auto& e : execises)
{
auto tree = MakeTree(e.begin(), e.end());
PrintTree(e.begin(), e.end());
cout << " Nests to:\n";
PrintTree(tree.begin(), tree.end());
cout << "\n\n";
}
}
| def to_tree(x, index=0, depth=1):
so_far = []
while index < len(x):
this = x[index]
if this == depth:
so_far.append(this)
elif this > depth:
index, deeper = to_tree(x, index, depth + 1)
so_far.append(deeper)
else:
index -=1
break
index += 1
return (index, so_far) if depth > 1 else so_far
if __name__ == "__main__":
from pprint import pformat
def pnest(nest:list, width: int=9) -> str:
text = pformat(nest, width=width).replace('\n', '\n ')
print(f" OR {text}\n")
exercises = [
[],
[1, 2, 4],
[3, 1, 3, 1],
[1, 2, 3, 1],
[3, 2, 1, 3],
[3, 3, 3, 1, 1, 3, 3, 3],
]
for flat in exercises:
nest = to_tree(flat)
print(f"{flat} NESTS TO: {nest}")
pnest(nest)
|
Write the same algorithm in Python as shown in this C++ implementation. | #include <any>
#include <iostream>
#include <iterator>
#include <vector>
using namespace std;
vector<any> MakeTree(input_iterator auto first, input_iterator auto last, int depth = 1)
{
vector<any> tree;
while (first < last && depth <= *first)
{
if(*first == depth)
{
tree.push_back(*first);
++first;
}
else
{
tree.push_back(MakeTree(first, last, depth + 1));
first = find(first + 1, last, depth);
}
}
return tree;
}
void PrintTree(input_iterator auto first, input_iterator auto last)
{
cout << "[";
for(auto it = first; it != last; ++it)
{
if(it != first) cout << ", ";
if constexpr (is_integral_v<remove_reference_t<decltype(*first)>>)
{
cout << *it;
}
else
{
if(it->type() == typeid(unsigned int))
{
cout << any_cast<unsigned int>(*it);
}
else
{
const auto& subTree = any_cast<vector<any>>(*it);
PrintTree(subTree.begin(), subTree.end());
}
}
}
cout << "]";
}
int main(void)
{
auto execises = vector<vector<unsigned int>> {
{},
{1, 2, 4},
{3, 1, 3, 1},
{1, 2, 3, 1},
{3, 2, 1, 3},
{3, 3, 3, 1, 1, 3, 3, 3}
};
for(const auto& e : execises)
{
auto tree = MakeTree(e.begin(), e.end());
PrintTree(e.begin(), e.end());
cout << " Nests to:\n";
PrintTree(tree.begin(), tree.end());
cout << "\n\n";
}
}
| def to_tree(x, index=0, depth=1):
so_far = []
while index < len(x):
this = x[index]
if this == depth:
so_far.append(this)
elif this > depth:
index, deeper = to_tree(x, index, depth + 1)
so_far.append(deeper)
else:
index -=1
break
index += 1
return (index, so_far) if depth > 1 else so_far
if __name__ == "__main__":
from pprint import pformat
def pnest(nest:list, width: int=9) -> str:
text = pformat(nest, width=width).replace('\n', '\n ')
print(f" OR {text}\n")
exercises = [
[],
[1, 2, 4],
[3, 1, 3, 1],
[1, 2, 3, 1],
[3, 2, 1, 3],
[3, 3, 3, 1, 1, 3, 3, 3],
]
for flat in exercises:
nest = to_tree(flat)
print(f"{flat} NESTS TO: {nest}")
pnest(nest)
|
Write the same algorithm in Python as shown in this C++ implementation. | #include <any>
#include <iostream>
#include <iterator>
#include <vector>
using namespace std;
vector<any> MakeTree(input_iterator auto first, input_iterator auto last, int depth = 1)
{
vector<any> tree;
while (first < last && depth <= *first)
{
if(*first == depth)
{
tree.push_back(*first);
++first;
}
else
{
tree.push_back(MakeTree(first, last, depth + 1));
first = find(first + 1, last, depth);
}
}
return tree;
}
void PrintTree(input_iterator auto first, input_iterator auto last)
{
cout << "[";
for(auto it = first; it != last; ++it)
{
if(it != first) cout << ", ";
if constexpr (is_integral_v<remove_reference_t<decltype(*first)>>)
{
cout << *it;
}
else
{
if(it->type() == typeid(unsigned int))
{
cout << any_cast<unsigned int>(*it);
}
else
{
const auto& subTree = any_cast<vector<any>>(*it);
PrintTree(subTree.begin(), subTree.end());
}
}
}
cout << "]";
}
int main(void)
{
auto execises = vector<vector<unsigned int>> {
{},
{1, 2, 4},
{3, 1, 3, 1},
{1, 2, 3, 1},
{3, 2, 1, 3},
{3, 3, 3, 1, 1, 3, 3, 3}
};
for(const auto& e : execises)
{
auto tree = MakeTree(e.begin(), e.end());
PrintTree(e.begin(), e.end());
cout << " Nests to:\n";
PrintTree(tree.begin(), tree.end());
cout << "\n\n";
}
}
| def to_tree(x, index=0, depth=1):
so_far = []
while index < len(x):
this = x[index]
if this == depth:
so_far.append(this)
elif this > depth:
index, deeper = to_tree(x, index, depth + 1)
so_far.append(deeper)
else:
index -=1
break
index += 1
return (index, so_far) if depth > 1 else so_far
if __name__ == "__main__":
from pprint import pformat
def pnest(nest:list, width: int=9) -> str:
text = pformat(nest, width=width).replace('\n', '\n ')
print(f" OR {text}\n")
exercises = [
[],
[1, 2, 4],
[3, 1, 3, 1],
[1, 2, 3, 1],
[3, 2, 1, 3],
[3, 3, 3, 1, 1, 3, 3, 3],
]
for flat in exercises:
nest = to_tree(flat)
print(f"{flat} NESTS TO: {nest}")
pnest(nest)
|
Rewrite this program in Python while keeping its functionality equivalent to the C++ version. | #include<iostream>
#include<string>
#include<boost/filesystem.hpp>
#include<boost/format.hpp>
#include<boost/iostreams/device/mapped_file.hpp>
#include<optional>
#include<algorithm>
#include<iterator>
#include<execution>
#include"dependencies/xxhash.hpp"
template<typename T, typename V, typename F>
size_t for_each_adjacent_range(T begin, T end, V getvalue, F callback) {
size_t partitions = 0;
while (begin != end) {
auto const& value = getvalue(*begin);
auto current = begin;
while (++current != end && getvalue(*current) == value);
callback(begin, current, value);
++partitions;
begin = current;
}
return partitions;
}
namespace bi = boost::iostreams;
namespace fs = boost::filesystem;
struct file_entry {
public:
explicit file_entry(fs::directory_entry const & entry)
: path_{entry.path()}, size_{fs::file_size(entry)}
{}
auto size() const { return size_; }
auto const& path() const { return path_; }
auto get_hash() {
if (!hash_)
hash_ = compute_hash();
return *hash_;
}
private:
xxh::hash64_t compute_hash() {
bi::mapped_file_source source;
source.open<fs::wpath>(this->path());
if (!source.is_open()) {
std::cerr << "Cannot open " << path() << std::endl;
throw std::runtime_error("Cannot open file");
}
xxh::hash_state64_t hash_stream;
hash_stream.update(source.data(), size_);
return hash_stream.digest();
}
private:
fs::wpath path_;
uintmax_t size_;
std::optional<xxh::hash64_t> hash_;
};
using vector_type = std::vector<file_entry>;
using iterator_type = vector_type::iterator;
auto find_files_in_dir(fs::wpath const& path, vector_type& file_vector, uintmax_t min_size = 1) {
size_t found = 0, ignored = 0;
if (!fs::is_directory(path)) {
std::cerr << path << " is not a directory!" << std::endl;
}
else {
std::cerr << "Searching " << path << std::endl;
for (auto& e : fs::recursive_directory_iterator(path)) {
++found;
if (fs::is_regular_file(e) && fs::file_size(e) >= min_size)
file_vector.emplace_back(e);
else ++ignored;
}
}
return std::make_tuple(found, ignored);
}
int main(int argn, char* argv[])
{
vector_type files;
for (auto i = 1; i < argn; ++i) {
fs::wpath path(argv[i]);
auto [found, ignored] = find_files_in_dir(path, files);
std::cerr << boost::format{
" %1$6d files found\n"
" %2$6d files ignored\n"
" %3$6d files added\n" } % found % ignored % (found - ignored)
<< std::endl;
}
std::cerr << "Found " << files.size() << " regular files" << std::endl;
std::sort(std::execution::par_unseq, files.begin(), files.end()
, [](auto const& a, auto const& b) { return a.size() > b.size(); }
);
for_each_adjacent_range(
std::begin(files)
, std::end(files)
, [](vector_type::value_type const& f) { return f.size(); }
, [](auto start, auto end, auto file_size) {
size_t nr_of_files = std::distance(start, end);
if (nr_of_files > 1) {
std::sort(start, end, [](auto& a, auto& b) {
auto const& ha = a.get_hash();
auto const& hb = b.get_hash();
auto const& pa = a.path();
auto const& pb = b.path();
return std::tie(ha, pa) < std::tie(hb, pb);
});
for_each_adjacent_range(
start
, end
, [](vector_type::value_type& f) { return f.get_hash(); }
, [file_size](auto hstart, auto hend, auto hash) {
size_t hnr_of_files = std::distance(hstart, hend);
if (hnr_of_files > 1) {
std::cout << boost::format{ "%1$3d files with hash %3$016x and size %2$d\n" }
% hnr_of_files % file_size % hash;
std::for_each(hstart, hend, [hash, file_size](auto& e) {
std::cout << '\t' << e.path() << '\n';
}
);
}
}
);
}
}
);
return 0;
}
| 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 C++. | #include <iomanip>
#include <iostream>
#include <boost/rational.hpp>
#include <boost/multiprecision/cpp_int.hpp>
using integer = boost::multiprecision::cpp_int;
using rational = boost::rational<integer>;
integer sylvester_next(const integer& n) {
return n * n - n + 1;
}
int main() {
std::cout << "First 10 elements in Sylvester's sequence:\n";
integer term = 2;
rational sum = 0;
for (int i = 1; i <= 10; ++i) {
std::cout << std::setw(2) << i << ": " << term << '\n';
sum += rational(1, term);
term = sylvester_next(term);
}
std::cout << "Sum of reciprocals: " << sum << '\n';
}
|
from functools import reduce
from itertools import count, islice
def sylvester():
def go(n):
return 1 + reduce(
lambda a, x: a * go(x),
range(0, n),
1
) if 0 != n else 2
return map(go, count(0))
def main():
print("First 10 terms of OEIS A000058:")
xs = list(islice(sylvester(), 10))
print('\n'.join([
str(x) for x in xs
]))
print("\nSum of the reciprocals of the first 10 terms:")
print(
reduce(lambda a, x: a + 1 / x, xs, 0)
)
if __name__ == '__main__':
main()
|
Please provide an equivalent version of this C++ code in Python. | #include <vector>
#include <sstream>
#include <iostream>
#include <iterator>
#include <stdlib.h>
#include <string.h>
using namespace std;
struct node
{
int val;
unsigned char neighbors;
};
class nSolver
{
public:
nSolver()
{
dx[0] = -1; dy[0] = -2; dx[1] = -1; dy[1] = 2;
dx[2] = 1; dy[2] = -2; dx[3] = 1; dy[3] = 2;
dx[4] = -2; dy[4] = -1; dx[5] = -2; dy[5] = 1;
dx[6] = 2; dy[6] = -1; dx[7] = 2; dy[7] = 1;
}
void solve( vector<string>& puzz, int max_wid )
{
if( puzz.size() < 1 ) return;
wid = max_wid; hei = static_cast<int>( puzz.size() ) / wid;
int len = wid * hei, c = 0; max = len;
arr = new node[len]; memset( arr, 0, len * sizeof( node ) );
for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )
{
if( ( *i ) == "*" ) { max--; arr[c++].val = -1; continue; }
arr[c].val = atoi( ( *i ).c_str() );
c++;
}
solveIt(); c = 0;
for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )
{
if( ( *i ) == "." )
{
ostringstream o; o << arr[c].val;
( *i ) = o.str();
}
c++;
}
delete [] arr;
}
private:
bool search( int x, int y, int w )
{
if( w > max ) return true;
node* n = &arr[x + y * wid];
n->neighbors = getNeighbors( x, y );
for( int d = 0; d < 8; d++ )
{
if( n->neighbors & ( 1 << d ) )
{
int a = x + dx[d], b = y + dy[d];
if( arr[a + b * wid].val == 0 )
{
arr[a + b * wid].val = w;
if( search( a, b, w + 1 ) ) return true;
arr[a + b * wid].val = 0;
}
}
}
return false;
}
unsigned char getNeighbors( int x, int y )
{
unsigned char c = 0; int a, b;
for( int xx = 0; xx < 8; xx++ )
{
a = x + dx[xx], b = y + dy[xx];
if( a < 0 || b < 0 || a >= wid || b >= hei ) continue;
if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx );
}
return c;
}
void solveIt()
{
int x, y, z; findStart( x, y, z );
if( z == 99999 ) { cout << "\nCan't find start point!\n"; return; }
search( x, y, z + 1 );
}
void findStart( int& x, int& y, int& z )
{
z = 99999;
for( int b = 0; b < hei; b++ )
for( int a = 0; a < wid; a++ )
if( arr[a + wid * b].val > 0 && arr[a + wid * b].val < z )
{
x = a; y = b;
z = arr[a + wid * b].val;
}
}
int wid, hei, max, dx[8], dy[8];
node* arr;
};
int main( int argc, char* argv[] )
{
int wid; string p;
p = "* * * * * 1 * . * * * * * * * * * * . * . * * * * * * * * * . . . . . * * * * * * * * * . . . * * * * * * * . * * . * . * * . * * . . . . . * * * . . . . . * * . . * * * * * . . * * . . . . . * * * . . . . . * * . * * . * . * * . * * * * * * * . . . * * * * * * * * * . . . . . * * * * * * * * * . * . * * * * * * * * * * . * . * * * * * "; wid = 13;
istringstream iss( p ); vector<string> puzz;
copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) );
nSolver s; s.solve( puzz, wid );
int c = 0;
for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )
{
if( ( *i ) != "*" && ( *i ) != "." )
{
if( atoi( ( *i ).c_str() ) < 10 ) cout << "0";
cout << ( *i ) << " ";
}
else cout << " ";
if( ++c >= wid ) { cout << endl; c = 0; }
}
cout << endl << endl;
return system( "pause" );
}
| 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)
|
Convert this C++ snippet to Python and keep its semantics consistent. | #include <vector>
#include <sstream>
#include <iostream>
#include <iterator>
#include <stdlib.h>
#include <string.h>
using namespace std;
struct node
{
int val;
unsigned char neighbors;
};
class nSolver
{
public:
nSolver()
{
dx[0] = -1; dy[0] = -2; dx[1] = -1; dy[1] = 2;
dx[2] = 1; dy[2] = -2; dx[3] = 1; dy[3] = 2;
dx[4] = -2; dy[4] = -1; dx[5] = -2; dy[5] = 1;
dx[6] = 2; dy[6] = -1; dx[7] = 2; dy[7] = 1;
}
void solve( vector<string>& puzz, int max_wid )
{
if( puzz.size() < 1 ) return;
wid = max_wid; hei = static_cast<int>( puzz.size() ) / wid;
int len = wid * hei, c = 0; max = len;
arr = new node[len]; memset( arr, 0, len * sizeof( node ) );
for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )
{
if( ( *i ) == "*" ) { max--; arr[c++].val = -1; continue; }
arr[c].val = atoi( ( *i ).c_str() );
c++;
}
solveIt(); c = 0;
for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )
{
if( ( *i ) == "." )
{
ostringstream o; o << arr[c].val;
( *i ) = o.str();
}
c++;
}
delete [] arr;
}
private:
bool search( int x, int y, int w )
{
if( w > max ) return true;
node* n = &arr[x + y * wid];
n->neighbors = getNeighbors( x, y );
for( int d = 0; d < 8; d++ )
{
if( n->neighbors & ( 1 << d ) )
{
int a = x + dx[d], b = y + dy[d];
if( arr[a + b * wid].val == 0 )
{
arr[a + b * wid].val = w;
if( search( a, b, w + 1 ) ) return true;
arr[a + b * wid].val = 0;
}
}
}
return false;
}
unsigned char getNeighbors( int x, int y )
{
unsigned char c = 0; int a, b;
for( int xx = 0; xx < 8; xx++ )
{
a = x + dx[xx], b = y + dy[xx];
if( a < 0 || b < 0 || a >= wid || b >= hei ) continue;
if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx );
}
return c;
}
void solveIt()
{
int x, y, z; findStart( x, y, z );
if( z == 99999 ) { cout << "\nCan't find start point!\n"; return; }
search( x, y, z + 1 );
}
void findStart( int& x, int& y, int& z )
{
z = 99999;
for( int b = 0; b < hei; b++ )
for( int a = 0; a < wid; a++ )
if( arr[a + wid * b].val > 0 && arr[a + wid * b].val < z )
{
x = a; y = b;
z = arr[a + wid * b].val;
}
}
int wid, hei, max, dx[8], dy[8];
node* arr;
};
int main( int argc, char* argv[] )
{
int wid; string p;
p = "* * * * * 1 * . * * * * * * * * * * . * . * * * * * * * * * . . . . . * * * * * * * * * . . . * * * * * * * . * * . * . * * . * * . . . . . * * * . . . . . * * . . * * * * * . . * * . . . . . * * * . . . . . * * . * * . * . * * . * * * * * * * . . . * * * * * * * * * . . . . . * * * * * * * * * . * . * * * * * * * * * * . * . * * * * * "; wid = 13;
istringstream iss( p ); vector<string> puzz;
copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) );
nSolver s; s.solve( puzz, wid );
int c = 0;
for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )
{
if( ( *i ) != "*" && ( *i ) != "." )
{
if( atoi( ( *i ).c_str() ) < 10 ) cout << "0";
cout << ( *i ) << " ";
}
else cout << " ";
if( ++c >= wid ) { cout << endl; c = 0; }
}
cout << endl << endl;
return system( "pause" );
}
| 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)
|
Port the provided C++ code into Python while preserving the original functionality. | #include <vector>
#include <sstream>
#include <iostream>
#include <iterator>
#include <stdlib.h>
#include <string.h>
using namespace std;
struct node
{
int val;
unsigned char neighbors;
};
class nSolver
{
public:
nSolver()
{
dx[0] = -1; dy[0] = -2; dx[1] = -1; dy[1] = 2;
dx[2] = 1; dy[2] = -2; dx[3] = 1; dy[3] = 2;
dx[4] = -2; dy[4] = -1; dx[5] = -2; dy[5] = 1;
dx[6] = 2; dy[6] = -1; dx[7] = 2; dy[7] = 1;
}
void solve( vector<string>& puzz, int max_wid )
{
if( puzz.size() < 1 ) return;
wid = max_wid; hei = static_cast<int>( puzz.size() ) / wid;
int len = wid * hei, c = 0; max = len;
arr = new node[len]; memset( arr, 0, len * sizeof( node ) );
for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )
{
if( ( *i ) == "*" ) { max--; arr[c++].val = -1; continue; }
arr[c].val = atoi( ( *i ).c_str() );
c++;
}
solveIt(); c = 0;
for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )
{
if( ( *i ) == "." )
{
ostringstream o; o << arr[c].val;
( *i ) = o.str();
}
c++;
}
delete [] arr;
}
private:
bool search( int x, int y, int w )
{
if( w > max ) return true;
node* n = &arr[x + y * wid];
n->neighbors = getNeighbors( x, y );
for( int d = 0; d < 8; d++ )
{
if( n->neighbors & ( 1 << d ) )
{
int a = x + dx[d], b = y + dy[d];
if( arr[a + b * wid].val == 0 )
{
arr[a + b * wid].val = w;
if( search( a, b, w + 1 ) ) return true;
arr[a + b * wid].val = 0;
}
}
}
return false;
}
unsigned char getNeighbors( int x, int y )
{
unsigned char c = 0; int a, b;
for( int xx = 0; xx < 8; xx++ )
{
a = x + dx[xx], b = y + dy[xx];
if( a < 0 || b < 0 || a >= wid || b >= hei ) continue;
if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx );
}
return c;
}
void solveIt()
{
int x, y, z; findStart( x, y, z );
if( z == 99999 ) { cout << "\nCan't find start point!\n"; return; }
search( x, y, z + 1 );
}
void findStart( int& x, int& y, int& z )
{
z = 99999;
for( int b = 0; b < hei; b++ )
for( int a = 0; a < wid; a++ )
if( arr[a + wid * b].val > 0 && arr[a + wid * b].val < z )
{
x = a; y = b;
z = arr[a + wid * b].val;
}
}
int wid, hei, max, dx[8], dy[8];
node* arr;
};
int main( int argc, char* argv[] )
{
int wid; string p;
p = "* * * * * 1 * . * * * * * * * * * * . * . * * * * * * * * * . . . . . * * * * * * * * * . . . * * * * * * * . * * . * . * * . * * . . . . . * * * . . . . . * * . . * * * * * . . * * . . . . . * * * . . . . . * * . * * . * . * * . * * * * * * * . . . * * * * * * * * * . . . . . * * * * * * * * * . * . * * * * * * * * * * . * . * * * * * "; wid = 13;
istringstream iss( p ); vector<string> puzz;
copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) );
nSolver s; s.solve( puzz, wid );
int c = 0;
for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )
{
if( ( *i ) != "*" && ( *i ) != "." )
{
if( atoi( ( *i ).c_str() ) < 10 ) cout << "0";
cout << ( *i ) << " ";
}
else cout << " ";
if( ++c >= wid ) { cout << endl; c = 0; }
}
cout << endl << endl;
return system( "pause" );
}
| 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)
|
Generate an equivalent Python version of this C++ code. | #include <iostream>
#include <vector>
#include <algorithm>
#include <string>
template <typename T>
void print(const std::vector<T> v) {
std::cout << "{ ";
for (const auto& e : v) {
std::cout << e << " ";
}
std::cout << "}";
}
template <typename T>
auto orderDisjointArrayItems(std::vector<T> M, std::vector<T> N) {
std::vector<T*> M_p(std::size(M));
for (auto i = 0; i < std::size(M_p); ++i) {
M_p[i] = &M[i];
}
for (auto e : N) {
auto i = std::find_if(std::begin(M_p), std::end(M_p), [e](auto c) -> bool {
if (c != nullptr) {
if (*c == e) return true;
}
return false;
});
if (i != std::end(M_p)) {
*i = nullptr;
}
}
for (auto i = 0; i < std::size(N); ++i) {
auto j = std::find_if(std::begin(M_p), std::end(M_p), [](auto c) -> bool {
return c == nullptr;
});
if (j != std::end(M_p)) {
*j = &M[std::distance(std::begin(M_p), j)];
**j = N[i];
}
}
return M;
}
int main() {
std::vector<std::vector<std::vector<std::string>>> l = {
{ { "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" } }
};
for (const auto& e : l) {
std::cout << "M: ";
print(e[0]);
std::cout << ", N: ";
print(e[1]);
std::cout << ", M': ";
auto res = orderDisjointArrayItems<std::string>(e[0], e[1]);
print(res);
std::cout << std::endl;
}
std::cin.ignore();
std::cin.get();
return 0;
}
| 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))
|
Convert the following code from C++ to Python, ensuring the logic remains intact. | #include <iostream>
int main()
{
std::cout <<
R"EOF( A raw string begins with R, then a double-quote ("), then an optional
identifier (here I've used "EOF"), then an opening parenthesis ('('). If you
use an identifier, it cannot be longer than 16 characters, and it cannot
contain a space, either opening or closing parentheses, a backslash, a tab, a
vertical tab, a form feed, or a newline.
It ends with a closing parenthesis (')'), the identifer (if you used one),
and a double-quote.
All characters are okay in a raw string, no escape sequences are necessary
or recognized, and all whitespace is preserved.
)EOF";
}
| print()
|
Transform the following C++ implementation into Python, maintaining the same output and logic. | #include <iostream>
int main()
{
std::cout <<
R"EOF( A raw string begins with R, then a double-quote ("), then an optional
identifier (here I've used "EOF"), then an opening parenthesis ('('). If you
use an identifier, it cannot be longer than 16 characters, and it cannot
contain a space, either opening or closing parentheses, a backslash, a tab, a
vertical tab, a form feed, or a newline.
It ends with a closing parenthesis (')'), the identifer (if you used one),
and a double-quote.
All characters are okay in a raw string, no escape sequences are necessary
or recognized, and all whitespace is preserved.
)EOF";
}
| print()
|
Produce a functionally identical Python code for the snippet given in C++. | #include <iostream>
int main()
{
std::cout <<
R"EOF( A raw string begins with R, then a double-quote ("), then an optional
identifier (here I've used "EOF"), then an opening parenthesis ('('). If you
use an identifier, it cannot be longer than 16 characters, and it cannot
contain a space, either opening or closing parentheses, a backslash, a tab, a
vertical tab, a form feed, or a newline.
It ends with a closing parenthesis (')'), the identifer (if you used one),
and a double-quote.
All characters are okay in a raw string, no escape sequences are necessary
or recognized, and all whitespace is preserved.
)EOF";
}
| print()
|
Ensure the translated Python code behaves exactly like the original C++ snippet. | #include <iostream>
int main()
{
std::cout <<
R"EOF( A raw string begins with R, then a double-quote ("), then an optional
identifier (here I've used "EOF"), then an opening parenthesis ('('). If you
use an identifier, it cannot be longer than 16 characters, and it cannot
contain a space, either opening or closing parentheses, a backslash, a tab, a
vertical tab, a form feed, or a newline.
It ends with a closing parenthesis (')'), the identifer (if you used one),
and a double-quote.
All characters are okay in a raw string, no escape sequences are necessary
or recognized, and all whitespace is preserved.
)EOF";
}
| print()
|
Port the provided C++ code into Python while preserving the original functionality. | #include <iostream>
#include <string>
#include <vector>
#include <unordered_map>
using tab_t = std::vector<std::vector<std::string>>;
tab_t tab1 {
{"27", "Jonah"}
, {"18", "Alan"}
, {"28", "Glory"}
, {"18", "Popeye"}
, {"28", "Alan"}
};
tab_t tab2 {
{"Jonah", "Whales"}
, {"Jonah", "Spiders"}
, {"Alan", "Ghosts"}
, {"Alan", "Zombies"}
, {"Glory", "Buffy"}
};
std::ostream& operator<<(std::ostream& o, const tab_t& t) {
for(size_t i = 0; i < t.size(); ++i) {
o << i << ":";
for(const auto& e : t[i])
o << '\t' << e;
o << std::endl;
}
return o;
}
tab_t Join(const tab_t& a, size_t columna, const tab_t& b, size_t columnb) {
std::unordered_multimap<std::string, size_t> hashmap;
for(size_t i = 0; i < a.size(); ++i) {
hashmap.insert(std::make_pair(a[i][columna], i));
}
tab_t result;
for(size_t i = 0; i < b.size(); ++i) {
auto range = hashmap.equal_range(b[i][columnb]);
for(auto it = range.first; it != range.second; ++it) {
tab_t::value_type row;
row.insert(row.end() , a[it->second].begin() , a[it->second].end());
row.insert(row.end() , b[i].begin() , b[i].end());
result.push_back(std::move(row));
}
}
return result;
}
int main(int argc, char const *argv[])
{
using namespace std;
int ret = 0;
cout << "Table A: " << endl << tab1 << endl;
cout << "Table B: " << endl << tab2 << endl;
auto tab3 = Join(tab1, 1, tab2, 0);
cout << "Joined tables: " << endl << tab3 << endl;
return ret;
}
| 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)
|
Produce a functionally identical Python code for the snippet given in C++. | #include <iostream>
#include <string>
#include <vector>
#include <unordered_map>
using tab_t = std::vector<std::vector<std::string>>;
tab_t tab1 {
{"27", "Jonah"}
, {"18", "Alan"}
, {"28", "Glory"}
, {"18", "Popeye"}
, {"28", "Alan"}
};
tab_t tab2 {
{"Jonah", "Whales"}
, {"Jonah", "Spiders"}
, {"Alan", "Ghosts"}
, {"Alan", "Zombies"}
, {"Glory", "Buffy"}
};
std::ostream& operator<<(std::ostream& o, const tab_t& t) {
for(size_t i = 0; i < t.size(); ++i) {
o << i << ":";
for(const auto& e : t[i])
o << '\t' << e;
o << std::endl;
}
return o;
}
tab_t Join(const tab_t& a, size_t columna, const tab_t& b, size_t columnb) {
std::unordered_multimap<std::string, size_t> hashmap;
for(size_t i = 0; i < a.size(); ++i) {
hashmap.insert(std::make_pair(a[i][columna], i));
}
tab_t result;
for(size_t i = 0; i < b.size(); ++i) {
auto range = hashmap.equal_range(b[i][columnb]);
for(auto it = range.first; it != range.second; ++it) {
tab_t::value_type row;
row.insert(row.end() , a[it->second].begin() , a[it->second].end());
row.insert(row.end() , b[i].begin() , b[i].end());
result.push_back(std::move(row));
}
}
return result;
}
int main(int argc, char const *argv[])
{
using namespace std;
int ret = 0;
cout << "Table A: " << endl << tab1 << endl;
cout << "Table B: " << endl << tab2 << endl;
auto tab3 = Join(tab1, 1, tab2, 0);
cout << "Joined tables: " << endl << tab3 << endl;
return ret;
}
| 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 C++. | #include <algorithm>
#include <chrono>
#include <cmath>
#include <cstdint>
#include <iomanip>
#include <iostream>
#include <vector>
#include <boost/multiprecision/cpp_int.hpp>
using boost::multiprecision::uint128_t;
template <typename T> void unique_sort(std::vector<T>& vector) {
std::sort(vector.begin(), vector.end());
vector.erase(std::unique(vector.begin(), vector.end()), vector.end());
}
auto perfect_powers(uint128_t n) {
std::vector<uint128_t> result;
for (uint128_t i = 2, s = sqrt(n); i <= s; ++i)
for (uint128_t p = i * i; p < n; p *= i)
result.push_back(p);
unique_sort(result);
return result;
}
auto achilles(uint128_t from, uint128_t to, const std::vector<uint128_t>& pps) {
std::vector<uint128_t> result;
auto c = static_cast<uint128_t>(std::cbrt(static_cast<double>(to / 4)));
auto s = sqrt(to / 8);
for (uint128_t b = 2; b <= c; ++b) {
uint128_t b3 = b * b * b;
for (uint128_t a = 2; a <= s; ++a) {
uint128_t p = b3 * a * a;
if (p >= to)
break;
if (p >= from && !binary_search(pps.begin(), pps.end(), p))
result.push_back(p);
}
}
unique_sort(result);
return result;
}
uint128_t totient(uint128_t n) {
uint128_t tot = n;
if ((n & 1) == 0) {
while ((n & 1) == 0)
n >>= 1;
tot -= tot >> 1;
}
for (uint128_t p = 3; p * p <= n; p += 2) {
if (n % p == 0) {
while (n % p == 0)
n /= p;
tot -= tot / p;
}
}
if (n > 1)
tot -= tot / n;
return tot;
}
int main() {
auto start = std::chrono::high_resolution_clock::now();
const uint128_t limit = 1000000000000000;
auto pps = perfect_powers(limit);
auto ach = achilles(1, 1000000, pps);
std::cout << "First 50 Achilles numbers:\n";
for (size_t i = 0; i < 50 && i < ach.size(); ++i)
std::cout << std::setw(4) << ach[i] << ((i + 1) % 10 == 0 ? '\n' : ' ');
std::cout << "\nFirst 50 strong Achilles numbers:\n";
for (size_t i = 0, count = 0; count < 50 && i < ach.size(); ++i)
if (binary_search(ach.begin(), ach.end(), totient(ach[i])))
std::cout << std::setw(6) << ach[i]
<< (++count % 10 == 0 ? '\n' : ' ');
int digits = 2;
std::cout << "\nNumber of Achilles numbers with:\n";
for (uint128_t from = 1, to = 100; to <= limit; to *= 10, ++digits) {
size_t count = achilles(from, to, pps).size();
std::cout << std::setw(2) << digits << " digits: " << count << '\n';
from = to;
}
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> duration(end - start);
std::cout << "\nElapsed time: " << duration.count() << " seconds\n";
}
| from math import gcd
from sympy import factorint
def is_Achilles(n):
p = factorint(n).values()
return all(i > 1 for i in p) and gcd(*p) == 1
def is_strong_Achilles(n):
return is_Achilles(n) and is_Achilles(totient(n))
def test_strong_Achilles(nachilles, nstrongachilles):
print('First', nachilles, 'Achilles numbers:')
n, found = 0, 0
while found < nachilles:
if is_Achilles(n):
found += 1
print(f'{n: 8,}', end='\n' if found % 10 == 0 else '')
n += 1
print('\nFirst', nstrongachilles, 'strong Achilles numbers:')
n, found = 0, 0
while found < nstrongachilles:
if is_strong_Achilles(n):
found += 1
print(f'{n: 9,}', end='\n' if found % 10 == 0 else '')
n += 1
print('\nCount of Achilles numbers for various intervals:')
intervals = [[10, 99], [100, 999], [1000, 9999], [10000, 99999], [100000, 999999]]
for interval in intervals:
print(f'{interval}:', sum(is_Achilles(i) for i in range(*interval)))
test_strong_Achilles(50, 100)
|
Can you help me rewrite this code in Python instead of C++, keeping it the same logically? | #include <algorithm>
#include <chrono>
#include <cmath>
#include <cstdint>
#include <iomanip>
#include <iostream>
#include <vector>
#include <boost/multiprecision/cpp_int.hpp>
using boost::multiprecision::uint128_t;
template <typename T> void unique_sort(std::vector<T>& vector) {
std::sort(vector.begin(), vector.end());
vector.erase(std::unique(vector.begin(), vector.end()), vector.end());
}
auto perfect_powers(uint128_t n) {
std::vector<uint128_t> result;
for (uint128_t i = 2, s = sqrt(n); i <= s; ++i)
for (uint128_t p = i * i; p < n; p *= i)
result.push_back(p);
unique_sort(result);
return result;
}
auto achilles(uint128_t from, uint128_t to, const std::vector<uint128_t>& pps) {
std::vector<uint128_t> result;
auto c = static_cast<uint128_t>(std::cbrt(static_cast<double>(to / 4)));
auto s = sqrt(to / 8);
for (uint128_t b = 2; b <= c; ++b) {
uint128_t b3 = b * b * b;
for (uint128_t a = 2; a <= s; ++a) {
uint128_t p = b3 * a * a;
if (p >= to)
break;
if (p >= from && !binary_search(pps.begin(), pps.end(), p))
result.push_back(p);
}
}
unique_sort(result);
return result;
}
uint128_t totient(uint128_t n) {
uint128_t tot = n;
if ((n & 1) == 0) {
while ((n & 1) == 0)
n >>= 1;
tot -= tot >> 1;
}
for (uint128_t p = 3; p * p <= n; p += 2) {
if (n % p == 0) {
while (n % p == 0)
n /= p;
tot -= tot / p;
}
}
if (n > 1)
tot -= tot / n;
return tot;
}
int main() {
auto start = std::chrono::high_resolution_clock::now();
const uint128_t limit = 1000000000000000;
auto pps = perfect_powers(limit);
auto ach = achilles(1, 1000000, pps);
std::cout << "First 50 Achilles numbers:\n";
for (size_t i = 0; i < 50 && i < ach.size(); ++i)
std::cout << std::setw(4) << ach[i] << ((i + 1) % 10 == 0 ? '\n' : ' ');
std::cout << "\nFirst 50 strong Achilles numbers:\n";
for (size_t i = 0, count = 0; count < 50 && i < ach.size(); ++i)
if (binary_search(ach.begin(), ach.end(), totient(ach[i])))
std::cout << std::setw(6) << ach[i]
<< (++count % 10 == 0 ? '\n' : ' ');
int digits = 2;
std::cout << "\nNumber of Achilles numbers with:\n";
for (uint128_t from = 1, to = 100; to <= limit; to *= 10, ++digits) {
size_t count = achilles(from, to, pps).size();
std::cout << std::setw(2) << digits << " digits: " << count << '\n';
from = to;
}
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> duration(end - start);
std::cout << "\nElapsed time: " << duration.count() << " seconds\n";
}
| from math import gcd
from sympy import factorint
def is_Achilles(n):
p = factorint(n).values()
return all(i > 1 for i in p) and gcd(*p) == 1
def is_strong_Achilles(n):
return is_Achilles(n) and is_Achilles(totient(n))
def test_strong_Achilles(nachilles, nstrongachilles):
print('First', nachilles, 'Achilles numbers:')
n, found = 0, 0
while found < nachilles:
if is_Achilles(n):
found += 1
print(f'{n: 8,}', end='\n' if found % 10 == 0 else '')
n += 1
print('\nFirst', nstrongachilles, 'strong Achilles numbers:')
n, found = 0, 0
while found < nstrongachilles:
if is_strong_Achilles(n):
found += 1
print(f'{n: 9,}', end='\n' if found % 10 == 0 else '')
n += 1
print('\nCount of Achilles numbers for various intervals:')
intervals = [[10, 99], [100, 999], [1000, 9999], [10000, 99999], [100000, 999999]]
for interval in intervals:
print(f'{interval}:', sum(is_Achilles(i) for i in range(*interval)))
test_strong_Achilles(50, 100)
|
Please provide an equivalent version of this C++ code in Python. | #include <iomanip>
#include <iostream>
bool odd_square_free_semiprime(int n) {
if ((n & 1) == 0)
return false;
int count = 0;
for (int i = 3; i * i <= n; i += 2) {
for (; n % i == 0; n /= i) {
if (++count > 1)
return false;
}
}
return count == 1;
}
int main() {
const int n = 1000;
std::cout << "Odd square-free semiprimes < " << n << ":\n";
int count = 0;
for (int i = 1; i < n; i += 2) {
if (odd_square_free_semiprime(i)) {
++count;
std::cout << std::setw(4) << i;
if (count % 20 == 0)
std::cout << '\n';
}
}
std::cout << "\nCount: " << count << '\n';
return 0;
}
|
def isPrime(n):
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
if __name__ == '__main__':
for p in range(3, 999):
if not isPrime(p):
continue
for q in range(p+1, 1000//p):
if not isPrime(q):
continue
print(p*q, end = " ");
|
Write the same code in Python as shown below in C++. | #include <iomanip>
#include <iostream>
bool odd_square_free_semiprime(int n) {
if ((n & 1) == 0)
return false;
int count = 0;
for (int i = 3; i * i <= n; i += 2) {
for (; n % i == 0; n /= i) {
if (++count > 1)
return false;
}
}
return count == 1;
}
int main() {
const int n = 1000;
std::cout << "Odd square-free semiprimes < " << n << ":\n";
int count = 0;
for (int i = 1; i < n; i += 2) {
if (odd_square_free_semiprime(i)) {
++count;
std::cout << std::setw(4) << i;
if (count % 20 == 0)
std::cout << '\n';
}
}
std::cout << "\nCount: " << count << '\n';
return 0;
}
|
def isPrime(n):
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
if __name__ == '__main__':
for p in range(3, 999):
if not isPrime(p):
continue
for q in range(p+1, 1000//p):
if not isPrime(q):
continue
print(p*q, end = " ");
|
Write the same code in Python as shown below in C++. |
#include <cmath>
#include <fstream>
#include <iostream>
#include <string>
class sierpinski_curve {
public:
void write(std::ostream& out, int size, int length, int order);
private:
static std::string rewrite(const std::string& s);
void line(std::ostream& out);
void execute(std::ostream& out, const std::string& s);
double x_;
double y_;
int angle_;
int length_;
};
void sierpinski_curve::write(std::ostream& out, int size, int length, int order) {
length_ = length;
x_ = length/std::sqrt(2.0);
y_ = 2 * x_;
angle_ = 45;
out << "<svg xmlns='http:
<< size << "' height='" << size << "'>\n";
out << "<rect width='100%' height='100%' fill='white'/>\n";
out << "<path stroke-width='1' stroke='black' fill='none' d='";
std::string s = "F--XF--F--XF";
for (int i = 0; i < order; ++i)
s = rewrite(s);
execute(out, s);
out << "'/>\n</svg>\n";
}
std::string sierpinski_curve::rewrite(const std::string& s) {
std::string t;
for (char c : s) {
if (c == 'X')
t += "XF+G+XF--F--XF+G+X";
else
t += c;
}
return t;
}
void sierpinski_curve::line(std::ostream& out) {
double theta = (3.14159265359 * angle_)/180.0;
x_ += length_ * std::cos(theta);
y_ -= length_ * std::sin(theta);
out << " L" << x_ << ',' << y_;
}
void sierpinski_curve::execute(std::ostream& out, const std::string& s) {
out << 'M' << x_ << ',' << y_;
for (char c : s) {
switch (c) {
case 'F':
case 'G':
line(out);
break;
case '+':
angle_ = (angle_ + 45) % 360;
break;
case '-':
angle_ = (angle_ - 45) % 360;
break;
}
}
}
int main() {
std::ofstream out("sierpinski_curve.svg");
if (!out) {
std::cerr << "Cannot open output file\n";
return 1;
}
sierpinski_curve s;
s.write(out, 545, 7, 5);
return 0;
}
| 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)
|
Write a version of this C++ function in Python with identical behavior. |
#include <cmath>
#include <fstream>
#include <iostream>
#include <string>
class sierpinski_curve {
public:
void write(std::ostream& out, int size, int length, int order);
private:
static std::string rewrite(const std::string& s);
void line(std::ostream& out);
void execute(std::ostream& out, const std::string& s);
double x_;
double y_;
int angle_;
int length_;
};
void sierpinski_curve::write(std::ostream& out, int size, int length, int order) {
length_ = length;
x_ = length/std::sqrt(2.0);
y_ = 2 * x_;
angle_ = 45;
out << "<svg xmlns='http:
<< size << "' height='" << size << "'>\n";
out << "<rect width='100%' height='100%' fill='white'/>\n";
out << "<path stroke-width='1' stroke='black' fill='none' d='";
std::string s = "F--XF--F--XF";
for (int i = 0; i < order; ++i)
s = rewrite(s);
execute(out, s);
out << "'/>\n</svg>\n";
}
std::string sierpinski_curve::rewrite(const std::string& s) {
std::string t;
for (char c : s) {
if (c == 'X')
t += "XF+G+XF--F--XF+G+X";
else
t += c;
}
return t;
}
void sierpinski_curve::line(std::ostream& out) {
double theta = (3.14159265359 * angle_)/180.0;
x_ += length_ * std::cos(theta);
y_ -= length_ * std::sin(theta);
out << " L" << x_ << ',' << y_;
}
void sierpinski_curve::execute(std::ostream& out, const std::string& s) {
out << 'M' << x_ << ',' << y_;
for (char c : s) {
switch (c) {
case 'F':
case 'G':
line(out);
break;
case '+':
angle_ = (angle_ + 45) % 360;
break;
case '-':
angle_ = (angle_ - 45) % 360;
break;
}
}
}
int main() {
std::ofstream out("sierpinski_curve.svg");
if (!out) {
std::cerr << "Cannot open output file\n";
return 1;
}
sierpinski_curve s;
s.write(out, 545, 7, 5);
return 0;
}
| 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)
|
Generate an equivalent Python version of this C++ code. | #include <string>
#include <vector>
#include <map>
#include <iostream>
#include <algorithm>
#include <utility>
#include <sstream>
std::string mostFreqKHashing ( const std::string & input , int k ) {
std::ostringstream oss ;
std::map<char, int> frequencies ;
for ( char c : input ) {
frequencies[ c ] = std::count ( input.begin( ) , input.end( ) , c ) ;
}
std::vector<std::pair<char , int>> letters ( frequencies.begin( ) , frequencies.end( ) ) ;
std::sort ( letters.begin( ) , letters.end( ) , [input] ( std::pair<char, int> a ,
std::pair<char, int> b ) { char fc = std::get<0>( a ) ; char fs = std::get<0>( b ) ;
int o = std::get<1>( a ) ; int p = std::get<1>( b ) ; if ( o != p ) { return o > p ; }
else { return input.find_first_of( fc ) < input.find_first_of ( fs ) ; } } ) ;
for ( int i = 0 ; i < letters.size( ) ; i++ ) {
oss << std::get<0>( letters[ i ] ) ;
oss << std::get<1>( letters[ i ] ) ;
}
std::string output ( oss.str( ).substr( 0 , 2 * k ) ) ;
if ( letters.size( ) >= k ) {
return output ;
}
else {
return output.append( "NULL0" ) ;
}
}
int mostFreqKSimilarity ( const std::string & first , const std::string & second ) {
int i = 0 ;
while ( i < first.length( ) - 1 ) {
auto found = second.find_first_of( first.substr( i , 2 ) ) ;
if ( found != std::string::npos )
return std::stoi ( first.substr( i , 2 )) ;
else
i += 2 ;
}
return 0 ;
}
int mostFreqKSDF ( const std::string & firstSeq , const std::string & secondSeq , int num ) {
return mostFreqKSimilarity ( mostFreqKHashing( firstSeq , num ) , mostFreqKHashing( secondSeq , num ) ) ;
}
int main( ) {
std::string s1("LCLYTHIGRNIYYGSYLYSETWNTGIMLLLITMATAFMGYVLPWGQMSFWGATVITNLFSAIPYIGTNLV" ) ;
std::string s2( "EWIWGGFSVDKATLNRFFAFHFILPFTMVALAGVHLTFLHETGSNNPLGLTSDSDKIPFHPYYTIKDFLG" ) ;
std::cout << "MostFreqKHashing( s1 , 2 ) = " << mostFreqKHashing( s1 , 2 ) << '\n' ;
std::cout << "MostFreqKHashing( s2 , 2 ) = " << mostFreqKHashing( s2 , 2 ) << '\n' ;
return 0 ;
}
| 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))
|
Rewrite the snippet below in Python so it works the same as the original C++ code. | #include <algorithm>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <string>
unsigned int reverse(unsigned int base, unsigned int n) {
unsigned int rev = 0;
for (; n > 0; n /= base)
rev = rev * base + (n % base);
return rev;
}
class palindrome_generator {
public:
explicit palindrome_generator(unsigned int base)
: base_(base), upper_(base) {}
unsigned int next_palindrome();
private:
unsigned int base_;
unsigned int lower_ = 1;
unsigned int upper_;
unsigned int next_ = 0;
bool even_ = false;
};
unsigned int palindrome_generator::next_palindrome() {
++next_;
if (next_ == upper_) {
if (even_) {
lower_ = upper_;
upper_ *= base_;
}
next_ = lower_;
even_ = !even_;
}
return even_ ? next_ * upper_ + reverse(base_, next_)
: next_ * lower_ + reverse(base_, next_ / base_);
}
bool is_prime(unsigned int n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
for (unsigned int p = 5; p * p <= n; p += 4) {
if (n % p == 0)
return false;
p += 2;
if (n % p == 0)
return false;
}
return true;
}
std::string to_string(unsigned int base, unsigned int n) {
assert(base <= 36);
static constexpr char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
std::string str;
for (; n != 0; n /= base)
str += digits[n % base];
std::reverse(str.begin(), str.end());
return str;
}
void print_palindromic_primes(unsigned int base, unsigned int limit) {
auto width =
static_cast<unsigned int>(std::ceil(std::log(limit) / std::log(base)));
unsigned int count = 0;
auto columns = 80 / (width + 1);
std::cout << "Base " << base << " palindromic primes less than " << limit
<< ":\n";
palindrome_generator pgen(base);
unsigned int palindrome;
while ((palindrome = pgen.next_palindrome()) < limit) {
if (is_prime(palindrome)) {
++count;
std::cout << std::setw(width) << to_string(base, palindrome)
<< (count % columns == 0 ? '\n' : ' ');
}
}
if (count % columns != 0)
std::cout << '\n';
std::cout << "Count: " << count << '\n';
}
void count_palindromic_primes(unsigned int base, unsigned int limit) {
unsigned int count = 0;
palindrome_generator pgen(base);
unsigned int palindrome;
while ((palindrome = pgen.next_palindrome()) < limit)
if (is_prime(palindrome))
++count;
std::cout << "Number of base " << base << " palindromic primes less than "
<< limit << ": " << count << '\n';
}
int main() {
print_palindromic_primes(10, 1000);
std::cout << '\n';
print_palindromic_primes(10, 100000);
std::cout << '\n';
count_palindromic_primes(10, 1000000000);
std::cout << '\n';
print_palindromic_primes(16, 500);
}
|
from itertools import takewhile
def palindromicPrimes():
def p(n):
s = str(n)
return s == s[::-1]
return (n for n in primes() if p(n))
def main():
print('\n'.join(
str(x) for x in takewhile(
lambda n: 1000 > n,
palindromicPrimes()
)
))
def primes():
n = 2
dct = {}
while True:
if n in dct:
for p in dct[n]:
dct.setdefault(n + p, []).append(p)
del dct[n]
else:
yield n
dct[n * n] = [n]
n = 1 + n
if __name__ == '__main__':
main()
|
Port the following code from C++ to Python with equivalent syntax and logic. | #include <algorithm>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <string>
unsigned int reverse(unsigned int base, unsigned int n) {
unsigned int rev = 0;
for (; n > 0; n /= base)
rev = rev * base + (n % base);
return rev;
}
class palindrome_generator {
public:
explicit palindrome_generator(unsigned int base)
: base_(base), upper_(base) {}
unsigned int next_palindrome();
private:
unsigned int base_;
unsigned int lower_ = 1;
unsigned int upper_;
unsigned int next_ = 0;
bool even_ = false;
};
unsigned int palindrome_generator::next_palindrome() {
++next_;
if (next_ == upper_) {
if (even_) {
lower_ = upper_;
upper_ *= base_;
}
next_ = lower_;
even_ = !even_;
}
return even_ ? next_ * upper_ + reverse(base_, next_)
: next_ * lower_ + reverse(base_, next_ / base_);
}
bool is_prime(unsigned int n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
for (unsigned int p = 5; p * p <= n; p += 4) {
if (n % p == 0)
return false;
p += 2;
if (n % p == 0)
return false;
}
return true;
}
std::string to_string(unsigned int base, unsigned int n) {
assert(base <= 36);
static constexpr char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
std::string str;
for (; n != 0; n /= base)
str += digits[n % base];
std::reverse(str.begin(), str.end());
return str;
}
void print_palindromic_primes(unsigned int base, unsigned int limit) {
auto width =
static_cast<unsigned int>(std::ceil(std::log(limit) / std::log(base)));
unsigned int count = 0;
auto columns = 80 / (width + 1);
std::cout << "Base " << base << " palindromic primes less than " << limit
<< ":\n";
palindrome_generator pgen(base);
unsigned int palindrome;
while ((palindrome = pgen.next_palindrome()) < limit) {
if (is_prime(palindrome)) {
++count;
std::cout << std::setw(width) << to_string(base, palindrome)
<< (count % columns == 0 ? '\n' : ' ');
}
}
if (count % columns != 0)
std::cout << '\n';
std::cout << "Count: " << count << '\n';
}
void count_palindromic_primes(unsigned int base, unsigned int limit) {
unsigned int count = 0;
palindrome_generator pgen(base);
unsigned int palindrome;
while ((palindrome = pgen.next_palindrome()) < limit)
if (is_prime(palindrome))
++count;
std::cout << "Number of base " << base << " palindromic primes less than "
<< limit << ": " << count << '\n';
}
int main() {
print_palindromic_primes(10, 1000);
std::cout << '\n';
print_palindromic_primes(10, 100000);
std::cout << '\n';
count_palindromic_primes(10, 1000000000);
std::cout << '\n';
print_palindromic_primes(16, 500);
}
|
from itertools import takewhile
def palindromicPrimes():
def p(n):
s = str(n)
return s == s[::-1]
return (n for n in primes() if p(n))
def main():
print('\n'.join(
str(x) for x in takewhile(
lambda n: 1000 > n,
palindromicPrimes()
)
))
def primes():
n = 2
dct = {}
while True:
if n in dct:
for p in dct[n]:
dct.setdefault(n + p, []).append(p)
del dct[n]
else:
yield n
dct[n * n] = [n]
n = 1 + n
if __name__ == '__main__':
main()
|
Transform the following C++ implementation into Python, maintaining the same output and logic. | #include <bitset>
#include <cctype>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
bool contains_all_vowels_once(const std::string& word) {
std::bitset<5> vowels;
for (char ch : word) {
ch = std::tolower(static_cast<unsigned char>(ch));
size_t bit = 0;
switch (ch) {
case 'a': bit = 0; break;
case 'e': bit = 1; break;
case 'i': bit = 2; break;
case 'o': bit = 3; break;
case 'u': bit = 4; break;
default: continue;
}
if (vowels.test(bit))
return false;
vowels.set(bit);
}
return vowels.all();
}
int main(int argc, char** argv) {
const char* filename(argc < 2 ? "unixdict.txt" : argv[1]);
std::ifstream in(filename);
if (!in) {
std::cerr << "Cannot open file '" << filename << "'.\n";
return EXIT_FAILURE;
}
std::string word;
int n = 0;
while (getline(in, word)) {
if (word.size() > 10 && contains_all_vowels_once(word))
std::cout << std::setw(2) << ++n << ": " << word << '\n';
}
return EXIT_SUCCESS;
}
| import urllib.request
from collections import Counter
urllib.request.urlretrieve("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt", "unixdict.txt")
dictionary = open("unixdict.txt","r")
wordList = dictionary.read().split('\n')
dictionary.close()
for word in wordList:
if len(word)>10:
frequency = Counter(word.lower())
if frequency['a']==frequency['e']==frequency['i']==frequency['o']==frequency['u']==1:
print(word)
|
Write the same code in Python as shown below in C++. | #include <iostream>
#include <optional>
using namespace std;
class TropicalAlgebra
{
optional<double> m_value;
public:
friend std::ostream& operator<<(std::ostream&, const TropicalAlgebra&);
friend TropicalAlgebra pow(const TropicalAlgebra& base, unsigned int exponent) noexcept;
TropicalAlgebra() = default;
explicit TropicalAlgebra(double value) noexcept
: m_value{value} {}
TropicalAlgebra& operator+=(const TropicalAlgebra& rhs) noexcept
{
if(!m_value)
{
*this = rhs;
}
else if (!rhs.m_value)
{
}
else
{
*m_value = max(*rhs.m_value, *m_value);
}
return *this;
}
TropicalAlgebra& operator*=(const TropicalAlgebra& rhs) noexcept
{
if(!m_value)
{
}
else if (!rhs.m_value)
{
*this = rhs;
}
else
{
*m_value += *rhs.m_value;
}
return *this;
}
};
inline TropicalAlgebra operator+(TropicalAlgebra lhs, const TropicalAlgebra& rhs) noexcept
{
lhs += rhs;
return lhs;
}
inline TropicalAlgebra operator*(TropicalAlgebra lhs, const TropicalAlgebra& rhs) noexcept
{
lhs *= rhs;
return lhs;
}
inline TropicalAlgebra pow(const TropicalAlgebra& base, unsigned int exponent) noexcept
{
auto result = base;
for(unsigned int i = 1; i < exponent; i++)
{
result *= base;
}
return result;
}
ostream& operator<<(ostream& os, const TropicalAlgebra& pt)
{
if(!pt.m_value) cout << "-Inf\n";
else cout << *pt.m_value << "\n";
return os;
}
int main(void) {
const TropicalAlgebra a(-2);
const TropicalAlgebra b(-1);
const TropicalAlgebra c(-0.5);
const TropicalAlgebra d(-0.001);
const TropicalAlgebra e(0);
const TropicalAlgebra h(1.5);
const TropicalAlgebra i(2);
const TropicalAlgebra j(5);
const TropicalAlgebra k(7);
const TropicalAlgebra l(8);
const TropicalAlgebra m;
cout << "2 * -2 == " << i * a;
cout << "-0.001 + -Inf == " << d + m;
cout << "0 * -Inf == " << e * m;
cout << "1.5 + -1 == " << h + b;
cout << "-0.5 * 0 == " << c * e;
cout << "pow(5, 7) == " << pow(j, 7);
cout << "5 * (8 + 7)) == " << j * (l + k);
cout << "5 * 8 + 5 * 7 == " << j * l + j * k;
}
| from numpy import Inf
class MaxTropical:
def __init__(self, x=0):
self.x = x
def __str__(self):
return str(self.x)
def __add__(self, other):
return MaxTropical(max(self.x, other.x))
def __mul__(self, other):
return MaxTropical(self.x + other.x)
def __pow__(self, other):
assert other.x // 1 == other.x and other.x > 0, "Invalid Operation"
return MaxTropical(self.x * other.x)
def __eq__(self, other):
return self.x == other.x
if __name__ == "__main__":
a = MaxTropical(-2)
b = MaxTropical(-1)
c = MaxTropical(-0.5)
d = MaxTropical(-0.001)
e = MaxTropical(0)
f = MaxTropical(0.5)
g = MaxTropical(1)
h = MaxTropical(1.5)
i = MaxTropical(2)
j = MaxTropical(5)
k = MaxTropical(7)
l = MaxTropical(8)
m = MaxTropical(-Inf)
print("2 * -2 == ", i * a)
print("-0.001 + -Inf == ", d + m)
print("0 * -Inf == ", e * m)
print("1.5 + -1 == ", h + b)
print("-0.5 * 0 == ", c * e)
print("5**7 == ", j**k)
print("5 * (8 + 7)) == ", j * (l + k))
print("5 * 8 + 5 * 7 == ", j * l + j * k)
print("5 * (8 + 7) == 5 * 8 + 5 * 7", j * (l + k) == j * l + j * k)
|
Please provide an equivalent version of this C++ code in Python. | #include <iostream>
#include <optional>
using namespace std;
class TropicalAlgebra
{
optional<double> m_value;
public:
friend std::ostream& operator<<(std::ostream&, const TropicalAlgebra&);
friend TropicalAlgebra pow(const TropicalAlgebra& base, unsigned int exponent) noexcept;
TropicalAlgebra() = default;
explicit TropicalAlgebra(double value) noexcept
: m_value{value} {}
TropicalAlgebra& operator+=(const TropicalAlgebra& rhs) noexcept
{
if(!m_value)
{
*this = rhs;
}
else if (!rhs.m_value)
{
}
else
{
*m_value = max(*rhs.m_value, *m_value);
}
return *this;
}
TropicalAlgebra& operator*=(const TropicalAlgebra& rhs) noexcept
{
if(!m_value)
{
}
else if (!rhs.m_value)
{
*this = rhs;
}
else
{
*m_value += *rhs.m_value;
}
return *this;
}
};
inline TropicalAlgebra operator+(TropicalAlgebra lhs, const TropicalAlgebra& rhs) noexcept
{
lhs += rhs;
return lhs;
}
inline TropicalAlgebra operator*(TropicalAlgebra lhs, const TropicalAlgebra& rhs) noexcept
{
lhs *= rhs;
return lhs;
}
inline TropicalAlgebra pow(const TropicalAlgebra& base, unsigned int exponent) noexcept
{
auto result = base;
for(unsigned int i = 1; i < exponent; i++)
{
result *= base;
}
return result;
}
ostream& operator<<(ostream& os, const TropicalAlgebra& pt)
{
if(!pt.m_value) cout << "-Inf\n";
else cout << *pt.m_value << "\n";
return os;
}
int main(void) {
const TropicalAlgebra a(-2);
const TropicalAlgebra b(-1);
const TropicalAlgebra c(-0.5);
const TropicalAlgebra d(-0.001);
const TropicalAlgebra e(0);
const TropicalAlgebra h(1.5);
const TropicalAlgebra i(2);
const TropicalAlgebra j(5);
const TropicalAlgebra k(7);
const TropicalAlgebra l(8);
const TropicalAlgebra m;
cout << "2 * -2 == " << i * a;
cout << "-0.001 + -Inf == " << d + m;
cout << "0 * -Inf == " << e * m;
cout << "1.5 + -1 == " << h + b;
cout << "-0.5 * 0 == " << c * e;
cout << "pow(5, 7) == " << pow(j, 7);
cout << "5 * (8 + 7)) == " << j * (l + k);
cout << "5 * 8 + 5 * 7 == " << j * l + j * k;
}
| from numpy import Inf
class MaxTropical:
def __init__(self, x=0):
self.x = x
def __str__(self):
return str(self.x)
def __add__(self, other):
return MaxTropical(max(self.x, other.x))
def __mul__(self, other):
return MaxTropical(self.x + other.x)
def __pow__(self, other):
assert other.x // 1 == other.x and other.x > 0, "Invalid Operation"
return MaxTropical(self.x * other.x)
def __eq__(self, other):
return self.x == other.x
if __name__ == "__main__":
a = MaxTropical(-2)
b = MaxTropical(-1)
c = MaxTropical(-0.5)
d = MaxTropical(-0.001)
e = MaxTropical(0)
f = MaxTropical(0.5)
g = MaxTropical(1)
h = MaxTropical(1.5)
i = MaxTropical(2)
j = MaxTropical(5)
k = MaxTropical(7)
l = MaxTropical(8)
m = MaxTropical(-Inf)
print("2 * -2 == ", i * a)
print("-0.001 + -Inf == ", d + m)
print("0 * -Inf == ", e * m)
print("1.5 + -1 == ", h + b)
print("-0.5 * 0 == ", c * e)
print("5**7 == ", j**k)
print("5 * (8 + 7)) == ", j * (l + k))
print("5 * 8 + 5 * 7 == ", j * l + j * k)
print("5 * (8 + 7) == 5 * 8 + 5 * 7", j * (l + k) == j * l + j * k)
|
Keep all operations the same but rewrite the snippet in Python. | #include <windows.h>
#include <iostream>
#include <string>
using namespace std;
const int PLAYERS = 4, MAX_POINTS = 100;
enum Moves { ROLL, HOLD };
class player
{
public:
player() { current_score = round_score = 0; }
void addCurrScore() { current_score += round_score; }
int getCurrScore() { return current_score; }
int getRoundScore() { return round_score; }
void addRoundScore( int rs ) { round_score += rs; }
void zeroRoundScore() { round_score = 0; }
virtual int getMove() = 0;
virtual ~player() {}
protected:
int current_score, round_score;
};
class RAND_Player : public player
{
virtual int getMove()
{
if( round_score + current_score >= MAX_POINTS ) return HOLD;
if( rand() % 10 < 5 ) return ROLL;
if( round_score > 0 ) return HOLD;
return ROLL;
}
};
class Q2WIN_Player : public player
{
virtual int getMove()
{
if( round_score + current_score >= MAX_POINTS ) return HOLD;
int q = MAX_POINTS - current_score;
if( q < 6 ) return ROLL;
q /= 4;
if( round_score < q ) return ROLL;
return HOLD;
}
};
class AL20_Player : public player
{
virtual int getMove()
{
if( round_score + current_score >= MAX_POINTS ) return HOLD;
if( round_score < 20 ) return ROLL;
return HOLD;
}
};
class AL20T_Player : public player
{
virtual int getMove()
{
if( round_score + current_score >= MAX_POINTS ) return HOLD;
int d = ( 100 * round_score ) / 20;
if( round_score < 20 && d < rand() % 100 ) return ROLL;
return HOLD;
}
};
class Auto_pigGame
{
public:
Auto_pigGame()
{
_players[0] = new RAND_Player();
_players[1] = new Q2WIN_Player();
_players[2] = new AL20_Player();
_players[3] = new AL20T_Player();
}
~Auto_pigGame()
{
delete _players[0];
delete _players[1];
delete _players[2];
delete _players[3];
}
void play()
{
int die, p = 0;
bool endGame = false;
while( !endGame )
{
switch( _players[p]->getMove() )
{
case ROLL:
die = rand() % 6 + 1;
if( die == 1 )
{
cout << "Player " << p + 1 << " rolled " << die << " - current score: " << _players[p]->getCurrScore() << endl << endl;
nextTurn( p );
continue;
}
_players[p]->addRoundScore( die );
cout << "Player " << p + 1 << " rolled " << die << " - round score: " << _players[p]->getRoundScore() << endl;
break;
case HOLD:
_players[p]->addCurrScore();
cout << "Player " << p + 1 << " holds - current score: " << _players[p]->getCurrScore() << endl << endl;
if( _players[p]->getCurrScore() >= MAX_POINTS )
endGame = true;
else nextTurn( p );
}
}
showScore();
}
private:
void nextTurn( int& p )
{
_players[p]->zeroRoundScore();
++p %= PLAYERS;
}
void showScore()
{
cout << endl;
cout << "Player I (RAND): " << _players[0]->getCurrScore() << endl;
cout << "Player II (Q2WIN): " << _players[1]->getCurrScore() << endl;
cout << "Player III (AL20): " << _players[2]->getCurrScore() << endl;
cout << "Player IV (AL20T): " << _players[3]->getCurrScore() << endl << endl << endl;
system( "pause" );
}
player* _players[PLAYERS];
};
int main( int argc, char* argv[] )
{
srand( GetTickCount() );
Auto_pigGame pg;
pg.play();
return 0;
}
|
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()))
|
Produce a language-to-language conversion: from C++ to Python, same semantics. | #include <windows.h>
#include <iostream>
#include <string>
using namespace std;
const int PLAYERS = 4, MAX_POINTS = 100;
enum Moves { ROLL, HOLD };
class player
{
public:
player() { current_score = round_score = 0; }
void addCurrScore() { current_score += round_score; }
int getCurrScore() { return current_score; }
int getRoundScore() { return round_score; }
void addRoundScore( int rs ) { round_score += rs; }
void zeroRoundScore() { round_score = 0; }
virtual int getMove() = 0;
virtual ~player() {}
protected:
int current_score, round_score;
};
class RAND_Player : public player
{
virtual int getMove()
{
if( round_score + current_score >= MAX_POINTS ) return HOLD;
if( rand() % 10 < 5 ) return ROLL;
if( round_score > 0 ) return HOLD;
return ROLL;
}
};
class Q2WIN_Player : public player
{
virtual int getMove()
{
if( round_score + current_score >= MAX_POINTS ) return HOLD;
int q = MAX_POINTS - current_score;
if( q < 6 ) return ROLL;
q /= 4;
if( round_score < q ) return ROLL;
return HOLD;
}
};
class AL20_Player : public player
{
virtual int getMove()
{
if( round_score + current_score >= MAX_POINTS ) return HOLD;
if( round_score < 20 ) return ROLL;
return HOLD;
}
};
class AL20T_Player : public player
{
virtual int getMove()
{
if( round_score + current_score >= MAX_POINTS ) return HOLD;
int d = ( 100 * round_score ) / 20;
if( round_score < 20 && d < rand() % 100 ) return ROLL;
return HOLD;
}
};
class Auto_pigGame
{
public:
Auto_pigGame()
{
_players[0] = new RAND_Player();
_players[1] = new Q2WIN_Player();
_players[2] = new AL20_Player();
_players[3] = new AL20T_Player();
}
~Auto_pigGame()
{
delete _players[0];
delete _players[1];
delete _players[2];
delete _players[3];
}
void play()
{
int die, p = 0;
bool endGame = false;
while( !endGame )
{
switch( _players[p]->getMove() )
{
case ROLL:
die = rand() % 6 + 1;
if( die == 1 )
{
cout << "Player " << p + 1 << " rolled " << die << " - current score: " << _players[p]->getCurrScore() << endl << endl;
nextTurn( p );
continue;
}
_players[p]->addRoundScore( die );
cout << "Player " << p + 1 << " rolled " << die << " - round score: " << _players[p]->getRoundScore() << endl;
break;
case HOLD:
_players[p]->addCurrScore();
cout << "Player " << p + 1 << " holds - current score: " << _players[p]->getCurrScore() << endl << endl;
if( _players[p]->getCurrScore() >= MAX_POINTS )
endGame = true;
else nextTurn( p );
}
}
showScore();
}
private:
void nextTurn( int& p )
{
_players[p]->zeroRoundScore();
++p %= PLAYERS;
}
void showScore()
{
cout << endl;
cout << "Player I (RAND): " << _players[0]->getCurrScore() << endl;
cout << "Player II (Q2WIN): " << _players[1]->getCurrScore() << endl;
cout << "Player III (AL20): " << _players[2]->getCurrScore() << endl;
cout << "Player IV (AL20T): " << _players[3]->getCurrScore() << endl << endl << endl;
system( "pause" );
}
player* _players[PLAYERS];
};
int main( int argc, char* argv[] )
{
srand( GetTickCount() );
Auto_pigGame pg;
pg.play();
return 0;
}
|
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()))
|
Change the following C++ code into Python without altering its purpose. | #include <iostream>
#include <map>
#include <vector>
#include <gmpxx.h>
using integer = mpz_class;
integer reverse(integer n) {
integer rev = 0;
while (n > 0) {
rev = rev * 10 + (n % 10);
n /= 10;
}
return rev;
}
void print_vector(const std::vector<integer>& vec) {
if (vec.empty())
return;
auto i = vec.begin();
std::cout << *i++;
for (; i != vec.end(); ++i)
std::cout << ", " << *i;
std::cout << '\n';
}
int main() {
std::map<integer, std::pair<bool, integer>> cache;
std::vector<integer> seeds, related, palindromes;
for (integer n = 1; n <= 10000; ++n) {
std::pair<bool, integer> p(true, n);
std::vector<integer> seen;
integer rev = reverse(n);
integer sum = n;
for (int i = 0; i < 500; ++i) {
sum += rev;
rev = reverse(sum);
if (rev == sum) {
p.first = false;
p.second = 0;
break;
}
auto iter = cache.find(sum);
if (iter != cache.end()) {
p = iter->second;
break;
}
seen.push_back(sum);
}
for (integer s : seen)
cache.emplace(s, p);
if (!p.first)
continue;
if (p.second == n)
seeds.push_back(n);
else
related.push_back(n);
if (n == reverse(n))
palindromes.push_back(n);
}
std::cout << "number of seeds: " << seeds.size() << '\n';
std::cout << "seeds: ";
print_vector(seeds);
std::cout << "number of related: " << related.size() << '\n';
std::cout << "palindromes: ";
print_vector(palindromes);
return 0;
}
| 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))
|
Port the provided C++ code into Python while preserving the original functionality. | #include <iostream>
#include <map>
#include <vector>
#include <gmpxx.h>
using integer = mpz_class;
integer reverse(integer n) {
integer rev = 0;
while (n > 0) {
rev = rev * 10 + (n % 10);
n /= 10;
}
return rev;
}
void print_vector(const std::vector<integer>& vec) {
if (vec.empty())
return;
auto i = vec.begin();
std::cout << *i++;
for (; i != vec.end(); ++i)
std::cout << ", " << *i;
std::cout << '\n';
}
int main() {
std::map<integer, std::pair<bool, integer>> cache;
std::vector<integer> seeds, related, palindromes;
for (integer n = 1; n <= 10000; ++n) {
std::pair<bool, integer> p(true, n);
std::vector<integer> seen;
integer rev = reverse(n);
integer sum = n;
for (int i = 0; i < 500; ++i) {
sum += rev;
rev = reverse(sum);
if (rev == sum) {
p.first = false;
p.second = 0;
break;
}
auto iter = cache.find(sum);
if (iter != cache.end()) {
p = iter->second;
break;
}
seen.push_back(sum);
}
for (integer s : seen)
cache.emplace(s, p);
if (!p.first)
continue;
if (p.second == n)
seeds.push_back(n);
else
related.push_back(n);
if (n == reverse(n))
palindromes.push_back(n);
}
std::cout << "number of seeds: " << seeds.size() << '\n';
std::cout << "seeds: ";
print_vector(seeds);
std::cout << "number of related: " << related.size() << '\n';
std::cout << "palindromes: ";
print_vector(palindromes);
return 0;
}
| 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 C++ code. | #include <iomanip>
#include <iostream>
bool nondecimal(unsigned int n) {
for (; n > 0; n >>= 4) {
if ((n & 0xF) > 9)
return true;
}
return false;
}
int main() {
unsigned int count = 0;
for (unsigned int n = 0; n < 501; ++n) {
if (nondecimal(n)) {
++count;
std::cout << std::setw(3) << n << (count % 15 == 0 ? '\n' : ' ');
}
}
std::cout << "\n\n" << count << " such numbers found.\n";
}
|
def p(n):
return 9 < n and (9 < n % 16 or p(n // 16))
def main():
xs = [
str(n) for n in range(1, 1 + 500)
if p(n)
]
print(f'{len(xs)} matches for the predicate:\n')
print(
table(6)(xs)
)
def chunksOf(n):
def go(xs):
return (
xs[i:n + i] for i in range(0, len(xs), n)
) if 0 < n else None
return go
def table(n):
def go(xs):
w = len(xs[-1])
return '\n'.join(
' '.join(row) for row in chunksOf(n)([
s.rjust(w, ' ') for s in xs
])
)
return go
if __name__ == '__main__':
main()
|
Generate an equivalent Python version of this C++ code. | #include <iomanip>
#include <iostream>
bool nondecimal(unsigned int n) {
for (; n > 0; n >>= 4) {
if ((n & 0xF) > 9)
return true;
}
return false;
}
int main() {
unsigned int count = 0;
for (unsigned int n = 0; n < 501; ++n) {
if (nondecimal(n)) {
++count;
std::cout << std::setw(3) << n << (count % 15 == 0 ? '\n' : ' ');
}
}
std::cout << "\n\n" << count << " such numbers found.\n";
}
|
def p(n):
return 9 < n and (9 < n % 16 or p(n // 16))
def main():
xs = [
str(n) for n in range(1, 1 + 500)
if p(n)
]
print(f'{len(xs)} matches for the predicate:\n')
print(
table(6)(xs)
)
def chunksOf(n):
def go(xs):
return (
xs[i:n + i] for i in range(0, len(xs), n)
) if 0 < n else None
return go
def table(n):
def go(xs):
w = len(xs[-1])
return '\n'.join(
' '.join(row) for row in chunksOf(n)([
s.rjust(w, ' ') for s in xs
])
)
return go
if __name__ == '__main__':
main()
|
Transform the following C++ implementation into Python, maintaining the same output and logic. | #include <iomanip>
#include <iostream>
bool nondecimal(unsigned int n) {
for (; n > 0; n >>= 4) {
if ((n & 0xF) > 9)
return true;
}
return false;
}
int main() {
unsigned int count = 0;
for (unsigned int n = 0; n < 501; ++n) {
if (nondecimal(n)) {
++count;
std::cout << std::setw(3) << n << (count % 15 == 0 ? '\n' : ' ');
}
}
std::cout << "\n\n" << count << " such numbers found.\n";
}
|
def p(n):
return 9 < n and (9 < n % 16 or p(n // 16))
def main():
xs = [
str(n) for n in range(1, 1 + 500)
if p(n)
]
print(f'{len(xs)} matches for the predicate:\n')
print(
table(6)(xs)
)
def chunksOf(n):
def go(xs):
return (
xs[i:n + i] for i in range(0, len(xs), n)
) if 0 < n else None
return go
def table(n):
def go(xs):
w = len(xs[-1])
return '\n'.join(
' '.join(row) for row in chunksOf(n)([
s.rjust(w, ' ') for s in xs
])
)
return go
if __name__ == '__main__':
main()
|
Keep all operations the same but rewrite the snippet in Python. | #include <algorithm>
#include <iomanip>
#include <iostream>
#include <list>
struct range {
range(int lo, int hi) : low(lo), high(hi) {}
int low;
int high;
};
std::ostream& operator<<(std::ostream& out, const range& r) {
return out << r.low << '-' << r.high;
}
class ranges {
public:
ranges() {}
explicit ranges(std::initializer_list<range> init) : ranges_(init) {}
void add(int n);
void remove(int n);
bool empty() const { return ranges_.empty(); }
private:
friend std::ostream& operator<<(std::ostream& out, const ranges& r);
std::list<range> ranges_;
};
void ranges::add(int n) {
for (auto i = ranges_.begin(); i != ranges_.end(); ++i) {
if (n + 1 < i->low) {
ranges_.emplace(i, n, n);
return;
}
if (n > i->high + 1)
continue;
if (n + 1 == i->low)
i->low = n;
else if (n == i->high + 1)
i->high = n;
else
return;
if (i != ranges_.begin()) {
auto prev = std::prev(i);
if (prev->high + 1 == i->low) {
i->low = prev->low;
ranges_.erase(prev);
}
}
auto next = std::next(i);
if (next != ranges_.end() && next->low - 1 == i->high) {
i->high = next->high;
ranges_.erase(next);
}
return;
}
ranges_.emplace_back(n, n);
}
void ranges::remove(int n) {
for (auto i = ranges_.begin(); i != ranges_.end(); ++i) {
if (n < i->low)
return;
if (n == i->low) {
if (++i->low > i->high)
ranges_.erase(i);
return;
}
if (n == i->high) {
if (--i->high < i->low)
ranges_.erase(i);
return;
}
if (n > i->low & n < i->high) {
int low = i->low;
i->low = n + 1;
ranges_.emplace(i, low, n - 1);
return;
}
}
}
std::ostream& operator<<(std::ostream& out, const ranges& r) {
if (!r.empty()) {
auto i = r.ranges_.begin();
out << *i++;
for (; i != r.ranges_.end(); ++i)
out << ',' << *i;
}
return out;
}
void test_add(ranges& r, int n) {
r.add(n);
std::cout << " add " << std::setw(2) << n << " => " << r << '\n';
}
void test_remove(ranges& r, int n) {
r.remove(n);
std::cout << " remove " << std::setw(2) << n << " => " << r << '\n';
}
void test1() {
ranges r;
std::cout << "Start: \"" << r << "\"\n";
test_add(r, 77);
test_add(r, 79);
test_add(r, 78);
test_remove(r, 77);
test_remove(r, 78);
test_remove(r, 79);
}
void test2() {
ranges r{{1,3}, {5,5}};
std::cout << "Start: \"" << r << "\"\n";
test_add(r, 1);
test_remove(r, 4);
test_add(r, 7);
test_add(r, 8);
test_add(r, 6);
test_remove(r, 7);
}
void test3() {
ranges r{{1,5}, {10,25}, {27,30}};
std::cout << "Start: \"" << r << "\"\n";
test_add(r, 26);
test_add(r, 9);
test_add(r, 7);
test_remove(r, 26);
test_remove(r, 9);
test_remove(r, 7);
}
int main() {
test1();
std::cout << '\n';
test2();
std::cout << '\n';
test3();
return 0;
}
| class Sequence():
def __init__(self, sequence_string):
self.ranges = self.to_ranges(sequence_string)
assert self.ranges == sorted(self.ranges), "Sequence order error"
def to_ranges(self, txt):
return [[int(x) for x in r.strip().split('-')]
for r in txt.strip().split(',') if r]
def remove(self, rem):
ranges = self.ranges
for i, r in enumerate(ranges):
if r[0] <= rem <= r[1]:
if r[0] == rem:
if r[1] > rem:
r[0] += 1
else:
del ranges[i]
elif r[1] == rem:
if r[0] < rem:
r[1] -= 1
else:
del ranges[i]
else:
r[1], splitrange = rem - 1, [rem + 1, r[1]]
ranges.insert(i + 1, splitrange)
break
if r[0] > rem:
break
return self
def add(self, add):
ranges = self.ranges
for i, r in enumerate(ranges):
if r[0] <= add <= r[1]:
break
elif r[0] - 1 == add:
r[0] = add
break
elif r[1] + 1 == add:
r[1] = add
break
elif r[0] > add:
ranges.insert(i, [add, add])
break
else:
ranges.append([add, add])
return self
return self.consolidate()
def consolidate(self):
"Combine overlapping ranges"
ranges = self.ranges
for this, that in zip(ranges, ranges[1:]):
if this[1] + 1 >= that[0]:
if this[1] >= that[1]:
this[:], that[:] = [], this
else:
this[:], that[:] = [], [this[0], that[1]]
ranges[:] = [r for r in ranges if r]
return self
def __repr__(self):
rr = self.ranges
return ",".join(f"{r[0]}-{r[1]}" for r in rr)
def demo(opp_txt):
by_line = opp_txt.strip().split('\n')
start = by_line.pop(0)
ex = Sequence(start.strip().split()[-1][1:-1])
lines = [line.strip().split() for line in by_line]
opps = [((ex.add if word[0] == "add" else ex.remove), int(word[1]))
for word in lines]
print(f"Start: \"{ex}\"")
for op, val in opps:
print(f" {op.__name__:>6} {val:2} => {op(val)}")
print()
if __name__ == '__main__':
demo()
demo()
demo()
|
Port the following code from C++ to Python with equivalent syntax and logic. | #include <cassert>
#include <iomanip>
#include <iostream>
#include <string>
#include <gmpxx.h>
using big_int = mpz_class;
auto juggler(int n) {
assert(n >= 1);
int count = 0, max_count = 0;
big_int a = n, max = n;
while (a != 1) {
if (a % 2 == 0)
a = sqrt(a);
else
a = sqrt(big_int(a * a * a));
++count;
if (a > max) {
max = a;
max_count = count;
}
}
return std::make_tuple(count, max_count, max, max.get_str().size());
}
int main() {
std::cout.imbue(std::locale(""));
std::cout << "n l[n] i[n] h[n]\n";
std::cout << "--------------------------------\n";
for (int n = 20; n < 40; ++n) {
auto [count, max_count, max, digits] = juggler(n);
std::cout << std::setw(2) << n << " " << std::setw(2) << count
<< " " << std::setw(2) << max_count << " " << max
<< '\n';
}
std::cout << '\n';
std::cout << " n l[n] i[n] d[n]\n";
std::cout << "----------------------------------------\n";
for (int n : {113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443,
275485, 1267909, 2264915, 5812827, 7110201, 56261531,
92502777, 172376627, 604398963}) {
auto [count, max_count, max, digits] = juggler(n);
std::cout << std::setw(11) << n << " " << std::setw(3) << count
<< " " << std::setw(3) << max_count << " " << digits
<< '\n';
}
}
| from math import isqrt
def juggler(k, countdig=True, maxiters=1000):
m, maxj, maxjpos = k, k, 0
for i in range(1, maxiters):
m = isqrt(m) if m % 2 == 0 else isqrt(m * m * m)
if m >= maxj:
maxj, maxjpos = m, i
if m == 1:
print(f"{k: 9}{i: 6,}{maxjpos: 6}{len(str(maxj)) if countdig else maxj: 20,}{' digits' if countdig else ''}")
return i
print("ERROR: Juggler series starting with $k did not converge in $maxiters iterations")
print(" n l(n) i(n) h(n) or d(n)\n-------------------------------------------")
for k in range(20, 40):
juggler(k, False)
for k in [113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443, 275485, 1267909]:
juggler(k)
|
Change the following C++ code into Python without altering its purpose. | #include <cassert>
#include <iomanip>
#include <iostream>
#include <string>
#include <gmpxx.h>
using big_int = mpz_class;
auto juggler(int n) {
assert(n >= 1);
int count = 0, max_count = 0;
big_int a = n, max = n;
while (a != 1) {
if (a % 2 == 0)
a = sqrt(a);
else
a = sqrt(big_int(a * a * a));
++count;
if (a > max) {
max = a;
max_count = count;
}
}
return std::make_tuple(count, max_count, max, max.get_str().size());
}
int main() {
std::cout.imbue(std::locale(""));
std::cout << "n l[n] i[n] h[n]\n";
std::cout << "--------------------------------\n";
for (int n = 20; n < 40; ++n) {
auto [count, max_count, max, digits] = juggler(n);
std::cout << std::setw(2) << n << " " << std::setw(2) << count
<< " " << std::setw(2) << max_count << " " << max
<< '\n';
}
std::cout << '\n';
std::cout << " n l[n] i[n] d[n]\n";
std::cout << "----------------------------------------\n";
for (int n : {113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443,
275485, 1267909, 2264915, 5812827, 7110201, 56261531,
92502777, 172376627, 604398963}) {
auto [count, max_count, max, digits] = juggler(n);
std::cout << std::setw(11) << n << " " << std::setw(3) << count
<< " " << std::setw(3) << max_count << " " << digits
<< '\n';
}
}
| from math import isqrt
def juggler(k, countdig=True, maxiters=1000):
m, maxj, maxjpos = k, k, 0
for i in range(1, maxiters):
m = isqrt(m) if m % 2 == 0 else isqrt(m * m * m)
if m >= maxj:
maxj, maxjpos = m, i
if m == 1:
print(f"{k: 9}{i: 6,}{maxjpos: 6}{len(str(maxj)) if countdig else maxj: 20,}{' digits' if countdig else ''}")
return i
print("ERROR: Juggler series starting with $k did not converge in $maxiters iterations")
print(" n l(n) i(n) h(n) or d(n)\n-------------------------------------------")
for k in range(20, 40):
juggler(k, False)
for k in [113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443, 275485, 1267909]:
juggler(k)
|
Keep all operations the same but rewrite the snippet in Python. |
#include <cmath>
#include <fstream>
#include <iostream>
#include <string>
class sierpinski_square {
public:
void write(std::ostream& out, int size, int length, int order);
private:
static std::string rewrite(const std::string& s);
void line(std::ostream& out);
void execute(std::ostream& out, const std::string& s);
double x_;
double y_;
int angle_;
int length_;
};
void sierpinski_square::write(std::ostream& out, int size, int length, int order) {
length_ = length;
x_ = (size - length)/2;
y_ = length;
angle_ = 0;
out << "<svg xmlns='http:
<< size << "' height='" << size << "'>\n";
out << "<rect width='100%' height='100%' fill='white'/>\n";
out << "<path stroke-width='1' stroke='black' fill='none' d='";
std::string s = "F+XF+F+XF";
for (int i = 0; i < order; ++i)
s = rewrite(s);
execute(out, s);
out << "'/>\n</svg>\n";
}
std::string sierpinski_square::rewrite(const std::string& s) {
std::string t;
for (char c : s) {
if (c == 'X')
t += "XF-F+F-XF+F+XF-F+F-X";
else
t += c;
}
return t;
}
void sierpinski_square::line(std::ostream& out) {
double theta = (3.14159265359 * angle_)/180.0;
x_ += length_ * std::cos(theta);
y_ += length_ * std::sin(theta);
out << " L" << x_ << ',' << y_;
}
void sierpinski_square::execute(std::ostream& out, const std::string& s) {
out << 'M' << x_ << ',' << y_;
for (char c : s) {
switch (c) {
case 'F':
line(out);
break;
case '+':
angle_ = (angle_ + 90) % 360;
break;
case '-':
angle_ = (angle_ - 90) % 360;
break;
}
}
}
int main() {
std::ofstream out("sierpinski_square.svg");
if (!out) {
std::cerr << "Cannot open output file\n";
return 1;
}
sierpinski_square s;
s.write(out, 635, 5, 5);
return 0;
}
| 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)
|
Port the provided C++ code into Python while preserving the original functionality. | #include <algorithm>
#include <cmath>
#include <cstdint>
#include <iostream>
#include <numeric>
#include <vector>
bool is_square_free(uint64_t n) {
static constexpr uint64_t primes[] {
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,
43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97
};
for (auto p : primes) {
auto p2 = p * p;
if (p2 > n)
break;
if (n % p2 == 0)
return false;
}
return true;
}
uint64_t iroot(uint64_t n, uint64_t r) {
static constexpr double adj = 1e-6;
return static_cast<uint64_t>(std::pow(n, 1.0/r) + adj);
}
uint64_t ipow(uint64_t n, uint64_t p) {
uint64_t prod = 1;
for (; p > 0; p >>= 1) {
if (p & 1)
prod *= n;
n *= n;
}
return prod;
}
std::vector<uint64_t> powerful(uint64_t n, uint64_t k) {
std::vector<uint64_t> result;
std::function<void(uint64_t, uint64_t)> f = [&](uint64_t m, uint64_t r) {
if (r < k) {
result.push_back(m);
return;
}
uint64_t root = iroot(n/m, r);
for (uint64_t v = 1; v <= root; ++v) {
if (r > k && (!is_square_free(v) || std::gcd(m, v) != 1))
continue;
f(m * ipow(v, r), r - 1);
}
};
f(1, 2*k - 1);
std::sort(result.begin(), result.end());
return result;
}
uint64_t powerful_count(uint64_t n, uint64_t k) {
uint64_t count = 0;
std::function<void(uint64_t, uint64_t)> f = [&](uint64_t m, uint64_t r) {
if (r <= k) {
count += iroot(n/m, r);
return;
}
uint64_t root = iroot(n/m, r);
for (uint64_t v = 1; v <= root; ++v) {
if (is_square_free(v) && std::gcd(m, v) == 1)
f(m * ipow(v, r), r - 1);
}
};
f(1, 2*k - 1);
return count;
}
int main() {
const size_t max = 5;
for (uint64_t k = 2, p = 100; k <= 10; ++k, p *= 10) {
auto result = powerful(p, k);
std::cout << result.size() << " " << k
<< "-powerful numbers <= 10^" << k << ":";
for (size_t i = 0; i < result.size(); ++i) {
if (i == max)
std::cout << " ...";
else if (i < max || i + max >= result.size())
std::cout << ' ' << result[i];
}
std::cout << '\n';
}
std::cout << '\n';
for (uint64_t k = 2; k <= 10; ++k) {
std::cout << "Count of " << k << "-powerful numbers <= 10^j for 0 <= j < "
<< k + 10 << ":";
for (uint64_t j = 0, p = 1; j < k + 10; ++j, p *= 10)
std::cout << ' ' << powerful_count(p, k);
std::cout << '\n';
}
}
| 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))
|
Can you help me rewrite this code in Python instead of C++, keeping it the same logically? | #include <algorithm>
#include <cmath>
#include <cstdint>
#include <iostream>
#include <numeric>
#include <vector>
bool is_square_free(uint64_t n) {
static constexpr uint64_t primes[] {
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,
43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97
};
for (auto p : primes) {
auto p2 = p * p;
if (p2 > n)
break;
if (n % p2 == 0)
return false;
}
return true;
}
uint64_t iroot(uint64_t n, uint64_t r) {
static constexpr double adj = 1e-6;
return static_cast<uint64_t>(std::pow(n, 1.0/r) + adj);
}
uint64_t ipow(uint64_t n, uint64_t p) {
uint64_t prod = 1;
for (; p > 0; p >>= 1) {
if (p & 1)
prod *= n;
n *= n;
}
return prod;
}
std::vector<uint64_t> powerful(uint64_t n, uint64_t k) {
std::vector<uint64_t> result;
std::function<void(uint64_t, uint64_t)> f = [&](uint64_t m, uint64_t r) {
if (r < k) {
result.push_back(m);
return;
}
uint64_t root = iroot(n/m, r);
for (uint64_t v = 1; v <= root; ++v) {
if (r > k && (!is_square_free(v) || std::gcd(m, v) != 1))
continue;
f(m * ipow(v, r), r - 1);
}
};
f(1, 2*k - 1);
std::sort(result.begin(), result.end());
return result;
}
uint64_t powerful_count(uint64_t n, uint64_t k) {
uint64_t count = 0;
std::function<void(uint64_t, uint64_t)> f = [&](uint64_t m, uint64_t r) {
if (r <= k) {
count += iroot(n/m, r);
return;
}
uint64_t root = iroot(n/m, r);
for (uint64_t v = 1; v <= root; ++v) {
if (is_square_free(v) && std::gcd(m, v) == 1)
f(m * ipow(v, r), r - 1);
}
};
f(1, 2*k - 1);
return count;
}
int main() {
const size_t max = 5;
for (uint64_t k = 2, p = 100; k <= 10; ++k, p *= 10) {
auto result = powerful(p, k);
std::cout << result.size() << " " << k
<< "-powerful numbers <= 10^" << k << ":";
for (size_t i = 0; i < result.size(); ++i) {
if (i == max)
std::cout << " ...";
else if (i < max || i + max >= result.size())
std::cout << ' ' << result[i];
}
std::cout << '\n';
}
std::cout << '\n';
for (uint64_t k = 2; k <= 10; ++k) {
std::cout << "Count of " << k << "-powerful numbers <= 10^j for 0 <= j < "
<< k + 10 << ":";
for (uint64_t j = 0, p = 1; j < k + 10; ++j, p *= 10)
std::cout << ' ' << powerful_count(p, k);
std::cout << '\n';
}
}
| 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))
|
Convert this C++ snippet to Python and keep its semantics consistent. | #include <algorithm>
#include <cmath>
#include <cstdint>
#include <iostream>
#include <numeric>
#include <vector>
bool is_square_free(uint64_t n) {
static constexpr uint64_t primes[] {
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,
43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97
};
for (auto p : primes) {
auto p2 = p * p;
if (p2 > n)
break;
if (n % p2 == 0)
return false;
}
return true;
}
uint64_t iroot(uint64_t n, uint64_t r) {
static constexpr double adj = 1e-6;
return static_cast<uint64_t>(std::pow(n, 1.0/r) + adj);
}
uint64_t ipow(uint64_t n, uint64_t p) {
uint64_t prod = 1;
for (; p > 0; p >>= 1) {
if (p & 1)
prod *= n;
n *= n;
}
return prod;
}
std::vector<uint64_t> powerful(uint64_t n, uint64_t k) {
std::vector<uint64_t> result;
std::function<void(uint64_t, uint64_t)> f = [&](uint64_t m, uint64_t r) {
if (r < k) {
result.push_back(m);
return;
}
uint64_t root = iroot(n/m, r);
for (uint64_t v = 1; v <= root; ++v) {
if (r > k && (!is_square_free(v) || std::gcd(m, v) != 1))
continue;
f(m * ipow(v, r), r - 1);
}
};
f(1, 2*k - 1);
std::sort(result.begin(), result.end());
return result;
}
uint64_t powerful_count(uint64_t n, uint64_t k) {
uint64_t count = 0;
std::function<void(uint64_t, uint64_t)> f = [&](uint64_t m, uint64_t r) {
if (r <= k) {
count += iroot(n/m, r);
return;
}
uint64_t root = iroot(n/m, r);
for (uint64_t v = 1; v <= root; ++v) {
if (is_square_free(v) && std::gcd(m, v) == 1)
f(m * ipow(v, r), r - 1);
}
};
f(1, 2*k - 1);
return count;
}
int main() {
const size_t max = 5;
for (uint64_t k = 2, p = 100; k <= 10; ++k, p *= 10) {
auto result = powerful(p, k);
std::cout << result.size() << " " << k
<< "-powerful numbers <= 10^" << k << ":";
for (size_t i = 0; i < result.size(); ++i) {
if (i == max)
std::cout << " ...";
else if (i < max || i + max >= result.size())
std::cout << ' ' << result[i];
}
std::cout << '\n';
}
std::cout << '\n';
for (uint64_t k = 2; k <= 10; ++k) {
std::cout << "Count of " << k << "-powerful numbers <= 10^j for 0 <= j < "
<< k + 10 << ":";
for (uint64_t j = 0, p = 1; j < k + 10; ++j, p *= 10)
std::cout << ' ' << powerful_count(p, k);
std::cout << '\n';
}
}
| 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))
|
Transform the following C++ implementation into Python, maintaining the same output and logic. | #include <algorithm>
#include <cstdlib>
#include <fstream>
#include <iostream>
void reverse(std::istream& in, std::ostream& out) {
constexpr size_t record_length = 80;
char record[record_length];
while (in.read(record, record_length)) {
std::reverse(std::begin(record), std::end(record));
out.write(record, record_length);
}
out.flush();
}
int main(int argc, char** argv) {
std::ifstream in("infile.dat", std::ios_base::binary);
if (!in) {
std::cerr << "Cannot open input file\n";
return EXIT_FAILURE;
}
std::ofstream out("outfile.dat", std::ios_base::binary);
if (!out) {
std::cerr << "Cannot open output file\n";
return EXIT_FAILURE;
}
try {
in.exceptions(std::ios_base::badbit);
out.exceptions(std::ios_base::badbit);
reverse(in, out);
} catch (const std::exception& ex) {
std::cerr << "I/O error: " << ex.what() << '\n';
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
| infile = open('infile.dat', 'rb')
outfile = open('outfile.dat', 'wb')
while True:
onerecord = infile.read(80)
if len(onerecord) < 80:
break
onerecordreversed = bytes(reversed(onerecord))
outfile.write(onerecordreversed)
infile.close()
outfile.close()
|
Transform the following C++ implementation into Python, maintaining the same output and logic. | #include <cstdlib>
#include <fstream>
#include <iostream>
int main(int argc, char** argv) {
const char* filename(argc < 2 ? "unixdict.txt" : argv[1]);
std::ifstream in(filename);
if (!in) {
std::cerr << "Cannot open file '" << filename << "'.\n";
return EXIT_FAILURE;
}
std::string word;
int n = 0;
while (getline(in, word)) {
const size_t len = word.size();
if (len > 5 && word.compare(0, 3, word, len - 3) == 0)
std::cout << ++n << ": " << word << '\n';
}
return EXIT_SUCCESS;
}
| 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()
for word in wordList:
if len(word)>5 and word[:3].lower()==word[-3:].lower():
print(word)
|
Maintain the same structure and functionality when rewriting this code in Python. | #include <iostream>
bool is_giuga(unsigned int n) {
unsigned int m = n / 2;
auto test_factor = [&m, n](unsigned int p) -> bool {
if (m % p != 0)
return true;
m /= p;
return m % p != 0 && (n / p - 1) % p == 0;
};
if (!test_factor(3) || !test_factor(5))
return false;
static constexpr unsigned int wheel[] = {4, 2, 4, 2, 4, 6, 2, 6};
for (unsigned int p = 7, i = 0; p * p <= m; ++i) {
if (!test_factor(p))
return false;
p += wheel[i & 7];
}
return m == 1 || (n / m - 1) % m == 0;
}
int main() {
std::cout << "First 5 Giuga numbers:\n";
for (unsigned int i = 0, n = 6; i < 5; n += 4) {
if (is_giuga(n)) {
std::cout << n << '\n';
++i;
}
}
}
|
from math import sqrt
def isGiuga(m):
n = m
f = 2
l = sqrt(n)
while True:
if n % f == 0:
if ((m / f) - 1) % f != 0:
return False
n /= f
if f > n:
return True
else:
f += 1
if f > l:
return False
if __name__ == '__main__':
n = 3
c = 0
print("The first 4 Giuga numbers are: ")
while c < 4:
if isGiuga(n):
c += 1
print(n)
n += 1
|
Generate an equivalent Python version of this C++ code. |
#include <iostream>
#include <vector>
#include <string>
#include <cmath>
std::string frmtPolynomial(std::vector<int> polynomial, bool remainder = false)
{
std::string r = "";
if (remainder)
{
r = " r: " + std::to_string(polynomial.back());
polynomial.pop_back();
}
std::string formatted = "";
int degree = polynomial.size() - 1;
int d = degree;
for (int i : polynomial)
{
if (d < degree)
{
if (i >= 0)
{
formatted += " + ";
}
else
{
formatted += " - ";
}
}
formatted += std::to_string(abs(i));
if (d > 1)
{
formatted += "x^" + std::to_string(d);
}
else if (d == 1)
{
formatted += "x";
}
d--;
}
return formatted;
}
std::vector<int> syntheticDiv(std::vector<int> dividend, std::vector<int> divisor)
{
std::vector<int> quotient;
quotient = dividend;
int normalizer = divisor[0];
for (int i = 0; i < dividend.size() - (divisor.size() - 1); i++)
{
quotient[i] /= normalizer;
int coef = quotient[i];
if (coef != 0)
{
for (int j = 1; j < divisor.size(); j++)
{
quotient[i + j] += -divisor[j] * coef;
}
}
}
return quotient;
}
int main(int argc, char **argv)
{
std::vector<int> dividend{ 1, -12, 0, -42};
std::vector<int> divisor{ 1, -3};
std::cout << frmtPolynomial(dividend) << "\n";
std::cout << frmtPolynomial(divisor) << "\n";
std::vector<int> quotient = syntheticDiv(dividend, divisor);
std::cout << frmtPolynomial(quotient, true) << "\n";
}
| 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))
|
Change the programming language of this snippet from C++ to Python without modifying what it does. |
#include <iostream>
#include <vector>
#include <string>
#include <cmath>
std::string frmtPolynomial(std::vector<int> polynomial, bool remainder = false)
{
std::string r = "";
if (remainder)
{
r = " r: " + std::to_string(polynomial.back());
polynomial.pop_back();
}
std::string formatted = "";
int degree = polynomial.size() - 1;
int d = degree;
for (int i : polynomial)
{
if (d < degree)
{
if (i >= 0)
{
formatted += " + ";
}
else
{
formatted += " - ";
}
}
formatted += std::to_string(abs(i));
if (d > 1)
{
formatted += "x^" + std::to_string(d);
}
else if (d == 1)
{
formatted += "x";
}
d--;
}
return formatted;
}
std::vector<int> syntheticDiv(std::vector<int> dividend, std::vector<int> divisor)
{
std::vector<int> quotient;
quotient = dividend;
int normalizer = divisor[0];
for (int i = 0; i < dividend.size() - (divisor.size() - 1); i++)
{
quotient[i] /= normalizer;
int coef = quotient[i];
if (coef != 0)
{
for (int j = 1; j < divisor.size(); j++)
{
quotient[i + j] += -divisor[j] * coef;
}
}
}
return quotient;
}
int main(int argc, char **argv)
{
std::vector<int> dividend{ 1, -12, 0, -42};
std::vector<int> divisor{ 1, -3};
std::cout << frmtPolynomial(dividend) << "\n";
std::cout << frmtPolynomial(divisor) << "\n";
std::vector<int> quotient = syntheticDiv(dividend, divisor);
std::cout << frmtPolynomial(quotient, true) << "\n";
}
| 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))
|
Convert this C++ snippet to Python and keep its semantics consistent. | #include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <set>
#include <string>
#include <utility>
#include <vector>
using word_list = std::vector<std::pair<std::string, std::string>>;
void print_words(std::ostream& out, const word_list& words) {
int n = 1;
for (const auto& pair : words) {
out << std::right << std::setw(2) << n++ << ": "
<< std::left << std::setw(14) << pair.first
<< pair.second << '\n';
}
}
int main(int argc, char** argv) {
const char* filename(argc < 2 ? "unixdict.txt" : argv[1]);
std::ifstream in(filename);
if (!in) {
std::cerr << "Cannot open file '" << filename << "'.\n";
return EXIT_FAILURE;
}
const int min_length = 5;
std::string line;
std::set<std::string> dictionary;
while (getline(in, line)) {
if (line.size() >= min_length)
dictionary.insert(line);
}
word_list odd_words, even_words;
for (const std::string& word : dictionary) {
if (word.size() < min_length + 2*(min_length/2))
continue;
std::string odd_word, even_word;
for (auto w = word.begin(); w != word.end(); ++w) {
odd_word += *w;
if (++w == word.end())
break;
even_word += *w;
}
if (dictionary.find(odd_word) != dictionary.end())
odd_words.emplace_back(word, odd_word);
if (dictionary.find(even_word) != dictionary.end())
even_words.emplace_back(word, even_word);
}
std::cout << "Odd words:\n";
print_words(std::cout, odd_words);
std::cout << "\nEven words:\n";
print_words(std::cout, even_words);
return EXIT_SUCCESS;
}
|
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)]
|
Produce a language-to-language conversion: from C++ to Python, same semantics. | #include <iomanip>
#include <iostream>
#include <list>
#include <string>
#include <vector>
#include <utility>
#include <vector>
class nest_tree;
bool operator==(const nest_tree&, const nest_tree&);
class nest_tree {
public:
explicit nest_tree(const std::string& name) : name_(name) {}
nest_tree& add_child(const std::string& name) {
children_.emplace_back(name);
return children_.back();
}
void print(std::ostream& out) const {
print(out, 0);
}
const std::string& name() const {
return name_;
}
const std::list<nest_tree>& children() const {
return children_;
}
bool equals(const nest_tree& n) const {
return name_ == n.name_ && children_ == n.children_;
}
private:
void print(std::ostream& out, int level) const {
std::string indent(level * 4, ' ');
out << indent << name_ << '\n';
for (const nest_tree& child : children_)
child.print(out, level + 1);
}
std::string name_;
std::list<nest_tree> children_;
};
bool operator==(const nest_tree& a, const nest_tree& b) {
return a.equals(b);
}
class indent_tree {
public:
explicit indent_tree(const nest_tree& n) {
items_.emplace_back(0, n.name());
from_nest(n, 0);
}
void print(std::ostream& out) const {
for (const auto& item : items_)
std::cout << item.first << ' ' << item.second << '\n';
}
nest_tree to_nest() const {
nest_tree n(items_[0].second);
to_nest_(n, 1, 0);
return n;
}
private:
void from_nest(const nest_tree& n, int level) {
for (const nest_tree& child : n.children()) {
items_.emplace_back(level + 1, child.name());
from_nest(child, level + 1);
}
}
size_t to_nest_(nest_tree& n, size_t pos, int level) const {
while (pos < items_.size() && items_[pos].first == level + 1) {
nest_tree& child = n.add_child(items_[pos].second);
pos = to_nest_(child, pos + 1, level + 1);
}
return pos;
}
std::vector<std::pair<int, std::string>> items_;
};
int main() {
nest_tree n("RosettaCode");
auto& child1 = n.add_child("rocks");
auto& child2 = n.add_child("mocks");
child1.add_child("code");
child1.add_child("comparison");
child1.add_child("wiki");
child2.add_child("trolling");
std::cout << "Initial nest format:\n";
n.print(std::cout);
indent_tree i(n);
std::cout << "\nIndent format:\n";
i.print(std::cout);
nest_tree n2(i.to_nest());
std::cout << "\nFinal nest format:\n";
n2.print(std::cout);
std::cout << "\nAre initial and final nest formats equal? "
<< std::boolalpha << n.equals(n2) << '\n';
return 0;
}
| from pprint import pprint as pp
def to_indent(node, depth=0, flat=None):
if flat is None:
flat = []
if node:
flat.append((depth, node[0]))
for child in node[1]:
to_indent(child, depth + 1, flat)
return flat
def to_nest(lst, depth=0, level=None):
if level is None:
level = []
while lst:
d, name = lst[0]
if d == depth:
children = []
level.append((name, children))
lst.pop(0)
elif d > depth:
to_nest(lst, d, children)
elif d < depth:
return
return level[0] if level else None
if __name__ == '__main__':
print('Start Nest format:')
nest = ('RosettaCode', [('rocks', [('code', []), ('comparison', []), ('wiki', [])]),
('mocks', [('trolling', [])])])
pp(nest, width=25)
print('\n... To Indent format:')
as_ind = to_indent(nest)
pp(as_ind, width=25)
print('\n... To Nest format:')
as_nest = to_nest(as_ind)
pp(as_nest, width=25)
if nest != as_nest:
print("Whoops round-trip issues")
|
Convert this C++ block to Python, preserving its control flow and logic. | #include <map>
#include <iostream>
#include <string>
int main()
{
std::map<char, std::string> rep =
{{'a', "DCaBA"},
{'b', "E"},
{'r', "Fr"}};
std::string magic = "abracadabra";
for(auto it = magic.begin(); it != magic.end(); ++it)
{
if(auto f = rep.find(*it); f != rep.end() && !f->second.empty())
{
*it = f->second.back();
f->second.pop_back();
}
}
std::cout << magic << "\n";
}
| from collections import defaultdict
rep = {'a' : {1 : 'A', 2 : 'B', 4 : 'C', 5 : 'D'}, 'b' : {1 : 'E'}, 'r' : {2 : 'F'}}
def trstring(oldstring, repdict):
seen, newchars = defaultdict(lambda:1, {}), []
for c in oldstring:
i = seen[c]
newchars.append(repdict[c][i] if c in repdict and i in repdict[c] else c)
seen[c] += 1
return ''.join(newchars)
print('abracadabra ->', trstring('abracadabra', rep))
|
Generate a Python translation of this C++ snippet without changing its computational steps. | #include <map>
#include <iostream>
#include <string>
int main()
{
std::map<char, std::string> rep =
{{'a', "DCaBA"},
{'b', "E"},
{'r', "Fr"}};
std::string magic = "abracadabra";
for(auto it = magic.begin(); it != magic.end(); ++it)
{
if(auto f = rep.find(*it); f != rep.end() && !f->second.empty())
{
*it = f->second.back();
f->second.pop_back();
}
}
std::cout << magic << "\n";
}
| from collections import defaultdict
rep = {'a' : {1 : 'A', 2 : 'B', 4 : 'C', 5 : 'D'}, 'b' : {1 : 'E'}, 'r' : {2 : 'F'}}
def trstring(oldstring, repdict):
seen, newchars = defaultdict(lambda:1, {}), []
for c in oldstring:
i = seen[c]
newchars.append(repdict[c][i] if c in repdict and i in repdict[c] else c)
seen[c] += 1
return ''.join(newchars)
print('abracadabra ->', trstring('abracadabra', rep))
|
Preserve the algorithm and functionality while converting the code from C++ to Python. | #include <future>
#include <iomanip>
#include <iostream>
#include <vector>
#include <gmpxx.h>
#include <primesieve.hpp>
std::vector<uint64_t> repunit_primes(uint32_t base,
const std::vector<uint64_t>& primes) {
std::vector<uint64_t> result;
for (uint64_t prime : primes) {
mpz_class repunit(std::string(prime, '1'), base);
if (mpz_probab_prime_p(repunit.get_mpz_t(), 25) != 0)
result.push_back(prime);
}
return result;
}
int main() {
std::vector<uint64_t> primes;
const uint64_t limit = 2700;
primesieve::generate_primes(limit, &primes);
std::vector<std::future<std::vector<uint64_t>>> futures;
for (uint32_t base = 2; base <= 36; ++base) {
futures.push_back(std::async(repunit_primes, base, primes));
}
std::cout << "Repunit prime digits (up to " << limit << ") in:\n";
for (uint32_t base = 2, i = 0; base <= 36; ++base, ++i) {
std::cout << "Base " << std::setw(2) << base << ':';
for (auto digits : futures[i].get())
std::cout << ' ' << digits;
std::cout << '\n';
}
}
| from sympy import isprime
for b in range(2, 17):
print(b, [n for n in range(2, 1001) if isprime(n) and isprime(int('1'*n, base=b))])
|
Produce a functionally identical Python code for the snippet given in C++. | #include <future>
#include <iomanip>
#include <iostream>
#include <vector>
#include <gmpxx.h>
#include <primesieve.hpp>
std::vector<uint64_t> repunit_primes(uint32_t base,
const std::vector<uint64_t>& primes) {
std::vector<uint64_t> result;
for (uint64_t prime : primes) {
mpz_class repunit(std::string(prime, '1'), base);
if (mpz_probab_prime_p(repunit.get_mpz_t(), 25) != 0)
result.push_back(prime);
}
return result;
}
int main() {
std::vector<uint64_t> primes;
const uint64_t limit = 2700;
primesieve::generate_primes(limit, &primes);
std::vector<std::future<std::vector<uint64_t>>> futures;
for (uint32_t base = 2; base <= 36; ++base) {
futures.push_back(std::async(repunit_primes, base, primes));
}
std::cout << "Repunit prime digits (up to " << limit << ") in:\n";
for (uint32_t base = 2, i = 0; base <= 36; ++base, ++i) {
std::cout << "Base " << std::setw(2) << base << ':';
for (auto digits : futures[i].get())
std::cout << ' ' << digits;
std::cout << '\n';
}
}
| from sympy import isprime
for b in range(2, 17):
print(b, [n for n in range(2, 1001) if isprime(n) and isprime(int('1'*n, base=b))])
|
Convert the following code from C++ to Python, ensuring the logic remains intact. | #include <cstdint>
#include <iomanip>
#include <iostream>
#include <vector>
uint64_t modpow(uint64_t base, uint64_t exp, uint64_t mod) {
if (mod == 1)
return 0;
uint64_t result = 1;
base %= mod;
for (; exp > 0; exp >>= 1) {
if ((exp & 1) == 1)
result = (result * base) % mod;
base = (base * base) % mod;
}
return result;
}
bool is_curzon(uint64_t n, uint64_t k) {
const uint64_t r = k * n;
return modpow(k, n, r + 1) == r;
}
int main() {
for (uint64_t k = 2; k <= 10; k += 2) {
std::cout << "Curzon numbers with base " << k << ":\n";
uint64_t count = 0, n = 1;
for (; count < 50; ++n) {
if (is_curzon(n, k)) {
std::cout << std::setw(4) << n
<< (++count % 10 == 0 ? '\n' : ' ');
}
}
for (;;) {
if (is_curzon(n, k))
++count;
if (count == 1000)
break;
++n;
}
std::cout << "1000th Curzon number with base " << k << ": " << n
<< "\n\n";
}
return 0;
}
| def is_Curzon(n, k):
r = k * n
return pow(k, n, r + 1) == r
for k in [2, 4, 6, 8, 10]:
n, curzons = 1, []
while len(curzons) < 1000:
if is_Curzon(n, k):
curzons.append(n)
n += 1
print(f'Curzon numbers with k = {k}:')
for i, c in enumerate(curzons[:50]):
print(f'{c: 5,}', end='\n' if (i + 1) % 25 == 0 else '')
print(f' Thousandth Curzon with k = {k}: {curzons[999]}.\n')
|
Can you help me rewrite this code in Python instead of C++, keeping it the same logically? | #include <cstdint>
#include <iomanip>
#include <iostream>
#include <vector>
uint64_t modpow(uint64_t base, uint64_t exp, uint64_t mod) {
if (mod == 1)
return 0;
uint64_t result = 1;
base %= mod;
for (; exp > 0; exp >>= 1) {
if ((exp & 1) == 1)
result = (result * base) % mod;
base = (base * base) % mod;
}
return result;
}
bool is_curzon(uint64_t n, uint64_t k) {
const uint64_t r = k * n;
return modpow(k, n, r + 1) == r;
}
int main() {
for (uint64_t k = 2; k <= 10; k += 2) {
std::cout << "Curzon numbers with base " << k << ":\n";
uint64_t count = 0, n = 1;
for (; count < 50; ++n) {
if (is_curzon(n, k)) {
std::cout << std::setw(4) << n
<< (++count % 10 == 0 ? '\n' : ' ');
}
}
for (;;) {
if (is_curzon(n, k))
++count;
if (count == 1000)
break;
++n;
}
std::cout << "1000th Curzon number with base " << k << ": " << n
<< "\n\n";
}
return 0;
}
| def is_Curzon(n, k):
r = k * n
return pow(k, n, r + 1) == r
for k in [2, 4, 6, 8, 10]:
n, curzons = 1, []
while len(curzons) < 1000:
if is_Curzon(n, k):
curzons.append(n)
n += 1
print(f'Curzon numbers with k = {k}:')
for i, c in enumerate(curzons[:50]):
print(f'{c: 5,}', end='\n' if (i + 1) % 25 == 0 else '')
print(f' Thousandth Curzon with k = {k}: {curzons[999]}.\n')
|
Convert this C++ block to Python, preserving its control flow and logic. | #include <cstdint>
#include <iomanip>
#include <iostream>
#include <vector>
uint64_t modpow(uint64_t base, uint64_t exp, uint64_t mod) {
if (mod == 1)
return 0;
uint64_t result = 1;
base %= mod;
for (; exp > 0; exp >>= 1) {
if ((exp & 1) == 1)
result = (result * base) % mod;
base = (base * base) % mod;
}
return result;
}
bool is_curzon(uint64_t n, uint64_t k) {
const uint64_t r = k * n;
return modpow(k, n, r + 1) == r;
}
int main() {
for (uint64_t k = 2; k <= 10; k += 2) {
std::cout << "Curzon numbers with base " << k << ":\n";
uint64_t count = 0, n = 1;
for (; count < 50; ++n) {
if (is_curzon(n, k)) {
std::cout << std::setw(4) << n
<< (++count % 10 == 0 ? '\n' : ' ');
}
}
for (;;) {
if (is_curzon(n, k))
++count;
if (count == 1000)
break;
++n;
}
std::cout << "1000th Curzon number with base " << k << ": " << n
<< "\n\n";
}
return 0;
}
| def is_Curzon(n, k):
r = k * n
return pow(k, n, r + 1) == r
for k in [2, 4, 6, 8, 10]:
n, curzons = 1, []
while len(curzons) < 1000:
if is_Curzon(n, k):
curzons.append(n)
n += 1
print(f'Curzon numbers with k = {k}:')
for i, c in enumerate(curzons[:50]):
print(f'{c: 5,}', end='\n' if (i + 1) % 25 == 0 else '')
print(f' Thousandth Curzon with k = {k}: {curzons[999]}.\n')
|
Ensure the translated Python code behaves exactly like the original C++ snippet. | #include <iomanip>
#include <iostream>
#include <boost/math/constants/constants.hpp>
#include <boost/multiprecision/cpp_dec_float.hpp>
using big_float = boost::multiprecision::cpp_dec_float_100;
big_float f(unsigned int n) {
big_float pi(boost::math::constants::pi<big_float>());
return exp(sqrt(big_float(n)) * pi);
}
int main() {
std::cout << "Ramanujan's constant using formula f(N) = exp(pi*sqrt(N)):\n"
<< std::setprecision(80) << f(163) << '\n';
std::cout << "\nResult with last four Heegner numbers:\n";
std::cout << std::setprecision(30);
for (unsigned int n : {19, 43, 67, 163}) {
auto x = f(n);
auto c = ceil(x);
auto pc = 100.0 * (x/c);
std::cout << "f(" << n << ") = " << x << " = "
<< pc << "% of " << c << '\n';
}
return 0;
}
| 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))))
|
Please provide an equivalent version of this C++ code in Python. | #include <iomanip>
#include <iostream>
#include <boost/math/constants/constants.hpp>
#include <boost/multiprecision/cpp_dec_float.hpp>
using big_float = boost::multiprecision::cpp_dec_float_100;
big_float f(unsigned int n) {
big_float pi(boost::math::constants::pi<big_float>());
return exp(sqrt(big_float(n)) * pi);
}
int main() {
std::cout << "Ramanujan's constant using formula f(N) = exp(pi*sqrt(N)):\n"
<< std::setprecision(80) << f(163) << '\n';
std::cout << "\nResult with last four Heegner numbers:\n";
std::cout << std::setprecision(30);
for (unsigned int n : {19, 43, 67, 163}) {
auto x = f(n);
auto c = ceil(x);
auto pc = 100.0 * (x/c);
std::cout << "f(" << n << ") = " << x << " = "
<< pc << "% of " << c << '\n';
}
return 0;
}
| 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 C++ code into Python without altering its purpose. | #include <iomanip>
#include <iostream>
#include <boost/math/constants/constants.hpp>
#include <boost/multiprecision/cpp_dec_float.hpp>
using big_float = boost::multiprecision::cpp_dec_float_100;
big_float f(unsigned int n) {
big_float pi(boost::math::constants::pi<big_float>());
return exp(sqrt(big_float(n)) * pi);
}
int main() {
std::cout << "Ramanujan's constant using formula f(N) = exp(pi*sqrt(N)):\n"
<< std::setprecision(80) << f(163) << '\n';
std::cout << "\nResult with last four Heegner numbers:\n";
std::cout << std::setprecision(30);
for (unsigned int n : {19, 43, 67, 163}) {
auto x = f(n);
auto c = ceil(x);
auto pc = 100.0 * (x/c);
std::cout << "f(" << n << ") = " << x << " = "
<< pc << "% of " << c << '\n';
}
return 0;
}
| 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 programming language of this snippet from C++ to Python without modifying what it does. | class animal {
public:
virtual void bark()
{
throw "implement me: do not know how to bark";
}
};
class elephant : public animal
{
};
int main()
{
elephant e;
e.bark();
}
| class Example(object):
def foo(self):
print("this is foo")
def bar(self):
print("this is bar")
def __getattr__(self, name):
def method(*args):
print("tried to handle unknown method " + name)
if args:
print("it had arguments: " + str(args))
return method
example = Example()
example.foo()
example.bar()
example.grill()
example.ding("dong")
|
Preserve the algorithm and functionality while converting the code from C++ to Python. | #include <algorithm>
#include <iostream>
#include <optional>
#include <set>
#include <string>
#include <string_view>
#include <vector>
struct string_comparator {
using is_transparent = void;
bool operator()(const std::string& lhs, const std::string& rhs) const {
return lhs < rhs;
}
bool operator()(const std::string& lhs, const std::string_view& rhs) const {
return lhs < rhs;
}
bool operator()(const std::string_view& lhs, const std::string& rhs) const {
return lhs < rhs;
}
};
using dictionary = std::set<std::string, string_comparator>;
template <typename iterator, typename separator>
std::string join(iterator begin, iterator end, separator sep) {
std::string result;
if (begin != end) {
result += *begin++;
for (; begin != end; ++begin) {
result += sep;
result += *begin;
}
}
return result;
}
auto create_string(const std::string_view& s,
const std::vector<std::optional<size_t>>& v) {
auto idx = s.size();
std::vector<std::string_view> sv;
while (v[idx].has_value()) {
size_t prev = v[idx].value();
sv.push_back(s.substr(prev, idx - prev));
idx = prev;
}
std::reverse(sv.begin(), sv.end());
return join(sv.begin(), sv.end(), ' ');
}
std::optional<std::string> word_break(const std::string_view& str,
const dictionary& dict) {
auto size = str.size() + 1;
std::vector<std::optional<size_t>> possible(size);
auto check_word = [&dict, &str](size_t i, size_t j)
-> std::optional<size_t> {
if (dict.find(str.substr(i, j - i)) != dict.end())
return i;
return std::nullopt;
};
for (size_t i = 1; i < size; ++i) {
if (!possible[i].has_value())
possible[i] = check_word(0, i);
if (possible[i].has_value()) {
for (size_t j = i + 1; j < size; ++j) {
if (!possible[j].has_value())
possible[j] = check_word(i, j);
}
if (possible[str.size()].has_value())
return create_string(str, possible);
}
}
return std::nullopt;
}
int main(int argc, char** argv) {
dictionary dict;
dict.insert("a");
dict.insert("bc");
dict.insert("abc");
dict.insert("cd");
dict.insert("b");
auto result = word_break("abcd", dict);
if (result.has_value())
std::cout << result.value() << '\n';
return 0;
}
|
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()
|
Please provide an equivalent version of this C++ code in Python. | #include <algorithm>
#include <chrono>
#include <iomanip>
#include <iostream>
#include <locale>
#include <vector>
#include <primesieve.hpp>
auto get_primes_by_digits(uint64_t limit) {
primesieve::iterator pi;
std::vector<std::vector<uint64_t>> primes_by_digits;
std::vector<uint64_t> primes;
for (uint64_t p = 10; p <= limit;) {
uint64_t prime = pi.next_prime();
if (prime > p) {
primes_by_digits.push_back(std::move(primes));
p *= 10;
}
primes.push_back(prime);
}
return primes_by_digits;
}
int main() {
std::cout.imbue(std::locale(""));
auto start = std::chrono::high_resolution_clock::now();
auto primes_by_digits = get_primes_by_digits(1000000000);
std::cout << "First 100 brilliant numbers:\n";
std::vector<uint64_t> brilliant_numbers;
for (const auto& primes : primes_by_digits) {
for (auto i = primes.begin(); i != primes.end(); ++i)
for (auto j = i; j != primes.end(); ++j)
brilliant_numbers.push_back(*i * *j);
if (brilliant_numbers.size() >= 100)
break;
}
std::sort(brilliant_numbers.begin(), brilliant_numbers.end());
for (size_t i = 0; i < 100; ++i) {
std::cout << std::setw(5) << brilliant_numbers[i]
<< ((i + 1) % 10 == 0 ? '\n' : ' ');
}
std::cout << '\n';
uint64_t power = 10;
size_t count = 0;
for (size_t p = 1; p < 2 * primes_by_digits.size(); ++p) {
const auto& primes = primes_by_digits[p / 2];
size_t position = count + 1;
uint64_t min_product = 0;
for (auto i = primes.begin(); i != primes.end(); ++i) {
uint64_t p1 = *i;
auto j = std::lower_bound(i, primes.end(), (power + p1 - 1) / p1);
if (j != primes.end()) {
uint64_t p2 = *j;
uint64_t product = p1 * p2;
if (min_product == 0 || product < min_product)
min_product = product;
position += std::distance(i, j);
if (p1 >= p2)
break;
}
}
std::cout << "First brilliant number >= 10^" << p << " is "
<< min_product << " at position " << position << '\n';
power *= 10;
if (p % 2 == 1) {
size_t size = primes.size();
count += size * (size + 1) / 2;
}
}
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> duration(end - start);
std::cout << "\nElapsed time: " << duration.count() << " seconds\n";
}
| 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
|
Rewrite the snippet below in Python so it works the same as the original C++ code. | #include <algorithm>
#include <chrono>
#include <iomanip>
#include <iostream>
#include <locale>
#include <vector>
#include <primesieve.hpp>
auto get_primes_by_digits(uint64_t limit) {
primesieve::iterator pi;
std::vector<std::vector<uint64_t>> primes_by_digits;
std::vector<uint64_t> primes;
for (uint64_t p = 10; p <= limit;) {
uint64_t prime = pi.next_prime();
if (prime > p) {
primes_by_digits.push_back(std::move(primes));
p *= 10;
}
primes.push_back(prime);
}
return primes_by_digits;
}
int main() {
std::cout.imbue(std::locale(""));
auto start = std::chrono::high_resolution_clock::now();
auto primes_by_digits = get_primes_by_digits(1000000000);
std::cout << "First 100 brilliant numbers:\n";
std::vector<uint64_t> brilliant_numbers;
for (const auto& primes : primes_by_digits) {
for (auto i = primes.begin(); i != primes.end(); ++i)
for (auto j = i; j != primes.end(); ++j)
brilliant_numbers.push_back(*i * *j);
if (brilliant_numbers.size() >= 100)
break;
}
std::sort(brilliant_numbers.begin(), brilliant_numbers.end());
for (size_t i = 0; i < 100; ++i) {
std::cout << std::setw(5) << brilliant_numbers[i]
<< ((i + 1) % 10 == 0 ? '\n' : ' ');
}
std::cout << '\n';
uint64_t power = 10;
size_t count = 0;
for (size_t p = 1; p < 2 * primes_by_digits.size(); ++p) {
const auto& primes = primes_by_digits[p / 2];
size_t position = count + 1;
uint64_t min_product = 0;
for (auto i = primes.begin(); i != primes.end(); ++i) {
uint64_t p1 = *i;
auto j = std::lower_bound(i, primes.end(), (power + p1 - 1) / p1);
if (j != primes.end()) {
uint64_t p2 = *j;
uint64_t product = p1 * p2;
if (min_product == 0 || product < min_product)
min_product = product;
position += std::distance(i, j);
if (p1 >= p2)
break;
}
}
std::cout << "First brilliant number >= 10^" << p << " is "
<< min_product << " at position " << position << '\n';
power *= 10;
if (p % 2 == 1) {
size_t size = primes.size();
count += size * (size + 1) / 2;
}
}
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> duration(end - start);
std::cout << "\nElapsed time: " << duration.count() << " seconds\n";
}
| 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 C++ to Python without modifying what it does. | #include <algorithm>
#include <fstream>
#include <iostream>
#include <map>
#include <string>
#include <vector>
using word_map = std::map<size_t, std::vector<std::string>>;
bool one_away(const std::string& s1, const std::string& s2) {
if (s1.size() != s2.size())
return false;
bool result = false;
for (size_t i = 0, n = s1.size(); i != n; ++i) {
if (s1[i] != s2[i]) {
if (result)
return false;
result = true;
}
}
return result;
}
template <typename iterator_type, typename separator_type>
std::string join(iterator_type begin, iterator_type end,
separator_type separator) {
std::string result;
if (begin != end) {
result += *begin++;
for (; begin != end; ++begin) {
result += separator;
result += *begin;
}
}
return result;
}
bool word_ladder(const word_map& words, const std::string& from,
const std::string& to) {
auto w = words.find(from.size());
if (w != words.end()) {
auto poss = w->second;
std::vector<std::vector<std::string>> queue{{from}};
while (!queue.empty()) {
auto curr = queue.front();
queue.erase(queue.begin());
for (auto i = poss.begin(); i != poss.end();) {
if (!one_away(*i, curr.back())) {
++i;
continue;
}
if (to == *i) {
curr.push_back(to);
std::cout << join(curr.begin(), curr.end(), " -> ") << '\n';
return true;
}
std::vector<std::string> temp(curr);
temp.push_back(*i);
queue.push_back(std::move(temp));
i = poss.erase(i);
}
}
}
std::cout << from << " into " << to << " cannot be done.\n";
return false;
}
int main() {
word_map words;
std::ifstream in("unixdict.txt");
if (!in) {
std::cerr << "Cannot open file unixdict.txt.\n";
return EXIT_FAILURE;
}
std::string word;
while (getline(in, word))
words[word.size()].push_back(word);
word_ladder(words, "boy", "man");
word_ladder(words, "girl", "lady");
word_ladder(words, "john", "jane");
word_ladder(words, "child", "adult");
word_ladder(words, "cat", "dog");
word_ladder(words, "lead", "gold");
word_ladder(words, "white", "black");
word_ladder(words, "bubble", "tickle");
return EXIT_SUCCESS;
}
| 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()))
|
Rewrite the snippet below in Python so it works the same as the original C++ code. | #include <stdio.h>
#include <stdlib.h>
void clear() {
for(int n = 0;n < 10; n++) {
printf("\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\r\n\r\n\r\n");
}
}
#define UP "00^00\r\n00|00\r\n00000\r\n"
#define DOWN "00000\r\n00|00\r\n00v00\r\n"
#define LEFT "00000\r\n<--00\r\n00000\r\n"
#define RIGHT "00000\r\n00-->\r\n00000\r\n"
#define HOME "00000\r\n00+00\r\n00000\r\n"
int main() {
clear();
system("stty raw");
printf(HOME);
printf("space to exit; wasd to move\r\n");
char c = 1;
while(c) {
c = getc(stdin);
clear();
switch (c)
{
case 'a':
printf(LEFT);
break;
case 'd':
printf(RIGHT);
break;
case 'w':
printf(UP);
break;
case 's':
printf(DOWN);
break;
case ' ':
c = 0;
break;
default:
printf(HOME);
};
printf("space to exit; wasd key to move\r\n");
}
system("stty cooked");
system("clear");
return 1;
}
| import sys
import pygame
pygame.init()
clk = pygame.time.Clock()
if pygame.joystick.get_count() == 0:
raise IOError("No joystick detected")
joy = pygame.joystick.Joystick(0)
joy.init()
size = width, height = 600, 600
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Joystick Tester")
frameRect = pygame.Rect((45, 45), (510, 510))
crosshair = pygame.surface.Surface((10, 10))
crosshair.fill(pygame.Color("magenta"))
pygame.draw.circle(crosshair, pygame.Color("blue"), (5,5), 5, 0)
crosshair.set_colorkey(pygame.Color("magenta"), pygame.RLEACCEL)
crosshair = crosshair.convert()
writer = pygame.font.Font(pygame.font.get_default_font(), 15)
buttons = {}
for b in range(joy.get_numbuttons()):
buttons[b] = [
writer.render(
hex(b)[2:].upper(),
1,
pygame.Color("red"),
pygame.Color("black")
).convert(),
((15*b)+45, 560)
]
while True:
pygame.event.pump()
for events in pygame.event.get():
if events.type == pygame.QUIT:
pygame.quit()
sys.exit()
screen.fill(pygame.Color("black"))
x = joy.get_axis(0)
y = joy.get_axis(1)
screen.blit(crosshair, ((x*250)+300-5, (y*250)+300-5))
pygame.draw.rect(screen, pygame.Color("red"), frameRect, 1)
for b in range(joy.get_numbuttons()):
if joy.get_button(b):
screen.blit(buttons[b][0], buttons[b][1])
pygame.display.flip()
clk.tick(40)
|
Write the same code in Python as shown below in C++. | #include <iostream>
#include <locale>
#include <unordered_map>
#include <primesieve.hpp>
class prime_gaps {
public:
prime_gaps() { last_prime_ = iterator_.next_prime(); }
uint64_t find_gap_start(uint64_t gap);
private:
primesieve::iterator iterator_;
uint64_t last_prime_;
std::unordered_map<uint64_t, uint64_t> gap_starts_;
};
uint64_t prime_gaps::find_gap_start(uint64_t gap) {
auto i = gap_starts_.find(gap);
if (i != gap_starts_.end())
return i->second;
for (;;) {
uint64_t prev = last_prime_;
last_prime_ = iterator_.next_prime();
uint64_t diff = last_prime_ - prev;
gap_starts_.emplace(diff, prev);
if (gap == diff)
return prev;
}
}
int main() {
std::cout.imbue(std::locale(""));
const uint64_t limit = 100000000000;
prime_gaps pg;
for (uint64_t pm = 10, gap1 = 2;;) {
uint64_t start1 = pg.find_gap_start(gap1);
uint64_t gap2 = gap1 + 2;
uint64_t start2 = pg.find_gap_start(gap2);
uint64_t diff = start2 > start1 ? start2 - start1 : start1 - start2;
if (diff > pm) {
std::cout << "Earliest difference > " << pm
<< " between adjacent prime gap starting primes:\n"
<< "Gap " << gap1 << " starts at " << start1 << ", gap "
<< gap2 << " starts at " << start2 << ", difference is "
<< diff << ".\n\n";
if (pm == limit)
break;
pm *= 10;
} else {
gap1 = gap2;
}
}
}
|
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
|
Can you help me rewrite this code in Python instead of C++, keeping it the same logically? | #include <algorithm>
#include <functional>
#include <iostream>
#include <numeric>
#include <vector>
typedef std::vector<std::vector<int>> matrix;
matrix dList(int n, int start) {
start--;
std::vector<int> a(n);
std::iota(a.begin(), a.end(), 0);
a[start] = a[0];
a[0] = start;
std::sort(a.begin() + 1, a.end());
auto first = a[1];
matrix r;
std::function<void(int)> recurse;
recurse = [&](int last) {
if (last == first) {
for (size_t j = 1; j < a.size(); j++) {
auto v = a[j];
if (j == v) {
return;
}
}
std::vector<int> b;
std::transform(a.cbegin(), a.cend(), std::back_inserter(b), [](int v) { return v + 1; });
r.push_back(b);
return;
}
for (int i = last; i >= 1; i--) {
std::swap(a[i], a[last]);
recurse(last - 1);
std::swap(a[i], a[last]);
}
};
recurse(n - 1);
return r;
}
void printSquare(const matrix &latin, int n) {
for (auto &row : latin) {
auto it = row.cbegin();
auto end = row.cend();
std::cout << '[';
if (it != end) {
std::cout << *it;
it = std::next(it);
}
while (it != end) {
std::cout << ", " << *it;
it = std::next(it);
}
std::cout << "]\n";
}
std::cout << '\n';
}
unsigned long reducedLatinSquares(int n, bool echo) {
if (n <= 0) {
if (echo) {
std::cout << "[]\n";
}
return 0;
} else if (n == 1) {
if (echo) {
std::cout << "[1]\n";
}
return 1;
}
matrix rlatin;
for (int i = 0; i < n; i++) {
rlatin.push_back({});
for (int j = 0; j < n; j++) {
rlatin[i].push_back(j);
}
}
for (int j = 0; j < n; j++) {
rlatin[0][j] = j + 1;
}
unsigned long count = 0;
std::function<void(int)> recurse;
recurse = [&](int i) {
auto rows = dList(n, i);
for (size_t r = 0; r < rows.size(); r++) {
rlatin[i - 1] = rows[r];
for (int k = 0; k < i - 1; k++) {
for (int j = 1; j < n; j++) {
if (rlatin[k][j] == rlatin[i - 1][j]) {
if (r < rows.size() - 1) {
goto outer;
}
if (i > 2) {
return;
}
}
}
}
if (i < n) {
recurse(i + 1);
} else {
count++;
if (echo) {
printSquare(rlatin, n);
}
}
outer: {}
}
};
recurse(2);
return count;
}
unsigned long factorial(unsigned long n) {
if (n <= 0) return 1;
unsigned long prod = 1;
for (unsigned long i = 2; i <= n; i++) {
prod *= i;
}
return prod;
}
int main() {
std::cout << "The four reduced lating squares of order 4 are:\n";
reducedLatinSquares(4, true);
std::cout << "The size of the set of reduced latin squares for the following orders\n";
std::cout << "and hence the total number of latin squares of these orders are:\n\n";
for (int n = 1; n < 7; n++) {
auto size = reducedLatinSquares(n, false);
auto f = factorial(n - 1);
f *= f * n * size;
std::cout << "Order " << n << ": Size " << size << " x " << n << "! x " << (n - 1) << "! => Total " << f << '\n';
}
return 0;
}
| 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)
|
Write the same algorithm in Python as shown in this C++ implementation. | #include <array>
#include <iomanip>
#include <iostream>
#include <utility>
#include <primesieve.hpp>
class ormiston_pair_generator {
public:
ormiston_pair_generator() { prime_ = pi_.next_prime(); }
std::pair<uint64_t, uint64_t> next_pair() {
for (;;) {
uint64_t prime = prime_;
auto digits = digits_;
prime_ = pi_.next_prime();
digits_ = get_digits(prime_);
if (digits_ == digits)
return std::make_pair(prime, prime_);
}
}
private:
static std::array<int, 10> get_digits(uint64_t n) {
std::array<int, 10> result = {};
for (; n > 0; n /= 10)
++result[n % 10];
return result;
}
primesieve::iterator pi_;
uint64_t prime_;
std::array<int, 10> digits_;
};
int main() {
ormiston_pair_generator generator;
int count = 0;
std::cout << "First 30 Ormiston pairs:\n";
for (; count < 30; ++count) {
auto [p1, p2] = generator.next_pair();
std::cout << '(' << std::setw(5) << p1 << ", " << std::setw(5) << p2
<< ')' << ((count + 1) % 3 == 0 ? '\n' : ' ');
}
std::cout << '\n';
for (uint64_t limit = 1000000; limit <= 1000000000; ++count) {
auto [p1, p2] = generator.next_pair();
if (p1 > limit) {
std::cout << "Number of Ormiston pairs < " << limit << ": " << count
<< '\n';
limit *= 10;
}
}
}
|
from sympy import primerange
PRIMES1M = list(primerange(1, 1_000_000))
ASBASE10SORT = [str(sorted(list(str(i)))) for i in PRIMES1M]
ORMISTONS = [(PRIMES1M[i - 1], PRIMES1M[i]) for i in range(1, len(PRIMES1M))
if ASBASE10SORT[i - 1] == ASBASE10SORT[i]]
print('First 30 Ormiston pairs:')
for (i, o) in enumerate(ORMISTONS):
if i < 30:
print(f'({o[0] : 6} {o[1] : 6} )',
end='\n' if (i + 1) % 5 == 0 else ' ')
else:
break
print(len(ORMISTONS), 'is the count of Ormiston pairs up to one million.')
|
Produce a language-to-language conversion: from C++ to Python, same semantics. | #include <iostream>
#include <locale>
#include <map>
#include <vector>
std::string trim(const std::string &str) {
auto s = str;
auto it1 = std::find_if(s.rbegin(), s.rend(), [](char ch) { return !std::isspace<char>(ch, std::locale::classic()); });
s.erase(it1.base(), s.end());
auto it2 = std::find_if(s.begin(), s.end(), [](char ch) { return !std::isspace<char>(ch, std::locale::classic()); });
s.erase(s.begin(), it2);
return s;
}
template <typename T>
std::ostream &operator<<(std::ostream &os, const std::vector<T> &v) {
auto it = v.cbegin();
auto end = v.cend();
os << '[';
if (it != end) {
os << *it;
it = std::next(it);
}
while (it != end) {
os << ", " << *it;
it = std::next(it);
}
return os << ']';
}
const std::map<std::string, int> LEFT_DIGITS = {
{" ## #", 0},
{" ## #", 1},
{" # ##", 2},
{" #### #", 3},
{" # ##", 4},
{" ## #", 5},
{" # ####", 6},
{" ### ##", 7},
{" ## ###", 8},
{" # ##", 9}
};
const std::map<std::string, int> RIGHT_DIGITS = {
{"### # ", 0},
{"## ## ", 1},
{"## ## ", 2},
{"# # ", 3},
{"# ### ", 4},
{"# ### ", 5},
{"# # ", 6},
{"# # ", 7},
{"# # ", 8},
{"### # ", 9}
};
const std::string END_SENTINEL = "# #";
const std::string MID_SENTINEL = " # # ";
void decodeUPC(const std::string &input) {
auto decode = [](const std::string &candidate) {
using OT = std::vector<int>;
OT output;
size_t pos = 0;
auto part = candidate.substr(pos, END_SENTINEL.length());
if (part == END_SENTINEL) {
pos += END_SENTINEL.length();
} else {
return std::make_pair(false, OT{});
}
for (size_t i = 0; i < 6; i++) {
part = candidate.substr(pos, 7);
pos += 7;
auto e = LEFT_DIGITS.find(part);
if (e != LEFT_DIGITS.end()) {
output.push_back(e->second);
} else {
return std::make_pair(false, output);
}
}
part = candidate.substr(pos, MID_SENTINEL.length());
if (part == MID_SENTINEL) {
pos += MID_SENTINEL.length();
} else {
return std::make_pair(false, OT{});
}
for (size_t i = 0; i < 6; i++) {
part = candidate.substr(pos, 7);
pos += 7;
auto e = RIGHT_DIGITS.find(part);
if (e != RIGHT_DIGITS.end()) {
output.push_back(e->second);
} else {
return std::make_pair(false, output);
}
}
part = candidate.substr(pos, END_SENTINEL.length());
if (part == END_SENTINEL) {
pos += END_SENTINEL.length();
} else {
return std::make_pair(false, OT{});
}
int sum = 0;
for (size_t i = 0; i < output.size(); i++) {
if (i % 2 == 0) {
sum += 3 * output[i];
} else {
sum += output[i];
}
}
return std::make_pair(sum % 10 == 0, output);
};
auto candidate = trim(input);
auto out = decode(candidate);
if (out.first) {
std::cout << out.second << '\n';
} else {
std::reverse(candidate.begin(), candidate.end());
out = decode(candidate);
if (out.first) {
std::cout << out.second << " Upside down\n";
} else if (out.second.size()) {
std::cout << "Invalid checksum\n";
} else {
std::cout << "Invalid digit(s)\n";
}
}
}
int main() {
std::vector<std::string> barcodes = {
" # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # ",
" # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # ",
" # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # ",
" # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # ",
" # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # ",
" # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # ",
" # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # ",
" # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # ",
" # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # ",
" # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # ",
};
for (auto &barcode : barcodes) {
decodeUPC(barcode);
}
return 0;
}
|
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 C++ code. | #include <iostream>
#include <string>
using namespace std;
class playfair
{
public:
void doIt( string k, string t, bool ij, bool e )
{
createGrid( k, ij ); getTextReady( t, ij, e );
if( e ) doIt( 1 ); else doIt( -1 );
display();
}
private:
void doIt( int dir )
{
int a, b, c, d; string ntxt;
for( string::const_iterator ti = _txt.begin(); ti != _txt.end(); ti++ )
{
if( getCharPos( *ti++, a, b ) )
if( getCharPos( *ti, c, d ) )
{
if( a == c ) { ntxt += getChar( a, b + dir ); ntxt += getChar( c, d + dir ); }
else if( b == d ){ ntxt += getChar( a + dir, b ); ntxt += getChar( c + dir, d ); }
else { ntxt += getChar( c, b ); ntxt += getChar( a, d ); }
}
}
_txt = ntxt;
}
void display()
{
cout << "\n\n OUTPUT:\n=========" << endl;
string::iterator si = _txt.begin(); int cnt = 0;
while( si != _txt.end() )
{
cout << *si; si++; cout << *si << " "; si++;
if( ++cnt >= 26 ) cout << endl, cnt = 0;
}
cout << endl << endl;
}
char getChar( int a, int b )
{
return _m[ (b + 5) % 5 ][ (a + 5) % 5 ];
}
bool getCharPos( char l, int &a, int &b )
{
for( int y = 0; y < 5; y++ )
for( int x = 0; x < 5; x++ )
if( _m[y][x] == l )
{ a = x; b = y; return true; }
return false;
}
void getTextReady( string t, bool ij, bool e )
{
for( string::iterator si = t.begin(); si != t.end(); si++ )
{
*si = toupper( *si ); if( *si < 65 || *si > 90 ) continue;
if( *si == 'J' && ij ) *si = 'I';
else if( *si == 'Q' && !ij ) continue;
_txt += *si;
}
if( e )
{
string ntxt = ""; size_t len = _txt.length();
for( size_t x = 0; x < len; x += 2 )
{
ntxt += _txt[x];
if( x + 1 < len )
{
if( _txt[x] == _txt[x + 1] ) ntxt += 'X';
ntxt += _txt[x + 1];
}
}
_txt = ntxt;
}
if( _txt.length() & 1 ) _txt += 'X';
}
void createGrid( string k, bool ij )
{
if( k.length() < 1 ) k = "KEYWORD";
k += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; string nk = "";
for( string::iterator si = k.begin(); si != k.end(); si++ )
{
*si = toupper( *si ); if( *si < 65 || *si > 90 ) continue;
if( ( *si == 'J' && ij ) || ( *si == 'Q' && !ij ) )continue;
if( nk.find( *si ) == -1 ) nk += *si;
}
copy( nk.begin(), nk.end(), &_m[0][0] );
}
string _txt; char _m[5][5];
};
int main( int argc, char* argv[] )
{
string key, i, txt; bool ij, e;
cout << "(E)ncode or (D)ecode? "; getline( cin, i ); e = ( i[0] == 'e' || i[0] == 'E' );
cout << "Enter a en/decryption key: "; getline( cin, key );
cout << "I <-> J (Y/N): "; getline( cin, i ); ij = ( i[0] == 'y' || i[0] == 'Y' );
cout << "Enter the text: "; getline( cin, txt );
playfair pf; pf.doIt( key, txt, ij, e ); return system( "pause" );
}
| 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)
|
Port the following code from C++ to Python with equivalent syntax and logic. | #include <iostream>
#include <string>
using namespace std;
class playfair
{
public:
void doIt( string k, string t, bool ij, bool e )
{
createGrid( k, ij ); getTextReady( t, ij, e );
if( e ) doIt( 1 ); else doIt( -1 );
display();
}
private:
void doIt( int dir )
{
int a, b, c, d; string ntxt;
for( string::const_iterator ti = _txt.begin(); ti != _txt.end(); ti++ )
{
if( getCharPos( *ti++, a, b ) )
if( getCharPos( *ti, c, d ) )
{
if( a == c ) { ntxt += getChar( a, b + dir ); ntxt += getChar( c, d + dir ); }
else if( b == d ){ ntxt += getChar( a + dir, b ); ntxt += getChar( c + dir, d ); }
else { ntxt += getChar( c, b ); ntxt += getChar( a, d ); }
}
}
_txt = ntxt;
}
void display()
{
cout << "\n\n OUTPUT:\n=========" << endl;
string::iterator si = _txt.begin(); int cnt = 0;
while( si != _txt.end() )
{
cout << *si; si++; cout << *si << " "; si++;
if( ++cnt >= 26 ) cout << endl, cnt = 0;
}
cout << endl << endl;
}
char getChar( int a, int b )
{
return _m[ (b + 5) % 5 ][ (a + 5) % 5 ];
}
bool getCharPos( char l, int &a, int &b )
{
for( int y = 0; y < 5; y++ )
for( int x = 0; x < 5; x++ )
if( _m[y][x] == l )
{ a = x; b = y; return true; }
return false;
}
void getTextReady( string t, bool ij, bool e )
{
for( string::iterator si = t.begin(); si != t.end(); si++ )
{
*si = toupper( *si ); if( *si < 65 || *si > 90 ) continue;
if( *si == 'J' && ij ) *si = 'I';
else if( *si == 'Q' && !ij ) continue;
_txt += *si;
}
if( e )
{
string ntxt = ""; size_t len = _txt.length();
for( size_t x = 0; x < len; x += 2 )
{
ntxt += _txt[x];
if( x + 1 < len )
{
if( _txt[x] == _txt[x + 1] ) ntxt += 'X';
ntxt += _txt[x + 1];
}
}
_txt = ntxt;
}
if( _txt.length() & 1 ) _txt += 'X';
}
void createGrid( string k, bool ij )
{
if( k.length() < 1 ) k = "KEYWORD";
k += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; string nk = "";
for( string::iterator si = k.begin(); si != k.end(); si++ )
{
*si = toupper( *si ); if( *si < 65 || *si > 90 ) continue;
if( ( *si == 'J' && ij ) || ( *si == 'Q' && !ij ) )continue;
if( nk.find( *si ) == -1 ) nk += *si;
}
copy( nk.begin(), nk.end(), &_m[0][0] );
}
string _txt; char _m[5][5];
};
int main( int argc, char* argv[] )
{
string key, i, txt; bool ij, e;
cout << "(E)ncode or (D)ecode? "; getline( cin, i ); e = ( i[0] == 'e' || i[0] == 'E' );
cout << "Enter a en/decryption key: "; getline( cin, key );
cout << "I <-> J (Y/N): "; getline( cin, i ); ij = ( i[0] == 'y' || i[0] == 'Y' );
cout << "Enter the text: "; getline( cin, txt );
playfair pf; pf.doIt( key, txt, ij, e ); return system( "pause" );
}
| 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)
|
Transform the following C++ implementation into Python, maintaining the same output and logic. | #include <iomanip>
#include <iostream>
#include <boost/rational.hpp>
#include <boost/multiprecision/gmp.hpp>
using integer = boost::multiprecision::mpz_int;
using rational = boost::rational<integer>;
class harmonic_generator {
public:
rational next() {
rational result = term_;
term_ += rational(1, ++n_);
return result;
}
void reset() {
n_ = 1;
term_ = 1;
}
private:
integer n_ = 1;
rational term_ = 1;
};
int main() {
std::cout << "First 20 harmonic numbers:\n";
harmonic_generator hgen;
for (int i = 1; i <= 20; ++i)
std::cout << std::setw(2) << i << ". " << hgen.next() << '\n';
rational h;
for (int i = 1; i <= 80; ++i)
h = hgen.next();
std::cout << "\n100th harmonic number: " << h << "\n\n";
int n = 1;
hgen.reset();
for (int i = 1; n <= 10; ++i) {
if (hgen.next() > n)
std::cout << "Position of first term > " << std::setw(2) << n++ << ": " << i << '\n';
}
}
| from fractions import Fraction
def harmonic_series():
n, h = Fraction(1), Fraction(1)
while True:
yield h
h += 1 / (n + 1)
n += 1
if __name__ == '__main__':
from itertools import islice
for n, d in (h.as_integer_ratio() for h in islice(harmonic_series(), 20)):
print(n, '/', d)
|
Preserve the algorithm and functionality while converting the code from C++ to Python. |
#include <iostream>
#include <fstream>
#include <queue>
#include <string>
#include <algorithm>
#include <cstdio>
int main(int argc, char* argv[]);
void write_vals(int* const, const size_t, const size_t);
std::string mergeFiles(size_t);
struct Compare
{
bool operator() ( std::pair<int, int>& p1, std::pair<int, int>& p2 )
{
return p1.first >= p2.first;
}
};
using ipair = std::pair<int,int>;
using pairvector = std::vector<ipair>;
using MinHeap = std::priority_queue< ipair, pairvector, Compare >;
const size_t memsize = 32;
const size_t chunksize = memsize / sizeof(int);
const std::string tmp_prefix{"tmp_out_"};
const std::string tmp_suffix{".txt"};
const std::string merged_file{"merged.txt"};
void write_vals( int* const values, const size_t size, const size_t chunk )
{
std::string output_file = (tmp_prefix + std::to_string(chunk) + tmp_suffix);
std::ofstream ofs(output_file.c_str());
for (int i=0; i<size; i++)
ofs << values[i] << '\t';
ofs << '\n';
ofs.close();
}
std::string mergeFiles(size_t chunks, const std::string& merge_file )
{
std::ofstream ofs( merge_file.c_str() );
MinHeap minHeap;
std::ifstream* ifs_tempfiles = new std::ifstream[chunks];
for (size_t i = 1; i<=chunks; i++)
{
int topval = 0;
std::string sorted_file = (tmp_prefix + std::to_string(i) + tmp_suffix);
ifs_tempfiles[i-1].open( sorted_file.c_str() );
if (ifs_tempfiles[i-1].is_open())
{
ifs_tempfiles[i-1] >> topval;
ipair top(topval, (i-1));
minHeap.push( top );
}
}
while (minHeap.size() > 0)
{
int next_val = 0;
ipair min_pair = minHeap.top();
minHeap.pop();
ofs << min_pair.first << ' ';
std::flush(ofs);
if ( ifs_tempfiles[min_pair.second] >> next_val)
{
ipair np( next_val, min_pair.second );
minHeap.push( np );
}
}
for (int i = 1; i <= chunks; i++)
{
ifs_tempfiles[i-1].close();
}
ofs << '\n';
ofs.close();
delete[] ifs_tempfiles;
return merged_file;
}
int main(int argc, char* argv[] )
{
if (argc < 2)
{
std::cerr << "usage: ExternalSort <filename> \n";
return 1;
}
std::ifstream ifs( argv[1] );
if ( ifs.fail() )
{
std::cerr << "error opening " << argv[1] << "\n";
return 2;
}
int* inputValues = new int[chunksize];
int chunk = 1;
int val = 0;
int count = 0;
bool done = false;
std::cout << "internal buffer is " << memsize << " bytes" << "\n";
while (ifs >> val)
{
done = false;
inputValues[count] = val;
count++;
if (count == chunksize)
{
std::sort(inputValues, inputValues + count);
write_vals(inputValues, count, chunk);
chunk ++;
count = 0;
done = true;
}
}
if (! done)
{
std::sort(inputValues, inputValues + count);
write_vals(inputValues, count, chunk);
}
else
{
chunk --;
}
ifs.close();
delete[] inputValues;
if ( chunk == 0 )
std::cout << "no data found\n";
else
std::cout << "Sorted output is in file: " << mergeFiles(chunk, merged_file ) << "\n";
return EXIT_SUCCESS;
}
|
import io
def sort_large_file(n: int, source: open, sink: open, file_opener = open)->None:
mergers = []
while True:
text = list(source.read(n))
if not len(text):
break;
text.sort()
merge_me = file_opener()
merge_me.write(''.join(text))
mergers.append(merge_me)
merge_me.seek(0)
stack_tops = [f.read(1) for f in mergers]
while stack_tops:
c = min(stack_tops)
sink.write(c)
i = stack_tops.index(c)
t = mergers[i].read(1)
if t:
stack_tops[i] = t
else:
del stack_tops[i]
mergers[i].close()
del mergers[i]
def main():
input_file_too_large_for_memory = io.StringIO('678925341')
t = list(input_file_too_large_for_memory.read())
t.sort()
expect = ''.join(t)
print('expect', expect)
for memory_size in range(1,12):
input_file_too_large_for_memory.seek(0)
output_file_too_large_for_memory = io.StringIO()
sort_large_file(memory_size, input_file_too_large_for_memory, output_file_too_large_for_memory, io.StringIO)
output_file_too_large_for_memory.seek(0)
assert(output_file_too_large_for_memory.read() == expect)
print('memory size {} passed'.format(memory_size))
if __name__ == '__main__':
example = main
example()
|
Translate this program into Python but keep the logic exactly as in C++. |
#include <iostream>
#include <fstream>
#include <queue>
#include <string>
#include <algorithm>
#include <cstdio>
int main(int argc, char* argv[]);
void write_vals(int* const, const size_t, const size_t);
std::string mergeFiles(size_t);
struct Compare
{
bool operator() ( std::pair<int, int>& p1, std::pair<int, int>& p2 )
{
return p1.first >= p2.first;
}
};
using ipair = std::pair<int,int>;
using pairvector = std::vector<ipair>;
using MinHeap = std::priority_queue< ipair, pairvector, Compare >;
const size_t memsize = 32;
const size_t chunksize = memsize / sizeof(int);
const std::string tmp_prefix{"tmp_out_"};
const std::string tmp_suffix{".txt"};
const std::string merged_file{"merged.txt"};
void write_vals( int* const values, const size_t size, const size_t chunk )
{
std::string output_file = (tmp_prefix + std::to_string(chunk) + tmp_suffix);
std::ofstream ofs(output_file.c_str());
for (int i=0; i<size; i++)
ofs << values[i] << '\t';
ofs << '\n';
ofs.close();
}
std::string mergeFiles(size_t chunks, const std::string& merge_file )
{
std::ofstream ofs( merge_file.c_str() );
MinHeap minHeap;
std::ifstream* ifs_tempfiles = new std::ifstream[chunks];
for (size_t i = 1; i<=chunks; i++)
{
int topval = 0;
std::string sorted_file = (tmp_prefix + std::to_string(i) + tmp_suffix);
ifs_tempfiles[i-1].open( sorted_file.c_str() );
if (ifs_tempfiles[i-1].is_open())
{
ifs_tempfiles[i-1] >> topval;
ipair top(topval, (i-1));
minHeap.push( top );
}
}
while (minHeap.size() > 0)
{
int next_val = 0;
ipair min_pair = minHeap.top();
minHeap.pop();
ofs << min_pair.first << ' ';
std::flush(ofs);
if ( ifs_tempfiles[min_pair.second] >> next_val)
{
ipair np( next_val, min_pair.second );
minHeap.push( np );
}
}
for (int i = 1; i <= chunks; i++)
{
ifs_tempfiles[i-1].close();
}
ofs << '\n';
ofs.close();
delete[] ifs_tempfiles;
return merged_file;
}
int main(int argc, char* argv[] )
{
if (argc < 2)
{
std::cerr << "usage: ExternalSort <filename> \n";
return 1;
}
std::ifstream ifs( argv[1] );
if ( ifs.fail() )
{
std::cerr << "error opening " << argv[1] << "\n";
return 2;
}
int* inputValues = new int[chunksize];
int chunk = 1;
int val = 0;
int count = 0;
bool done = false;
std::cout << "internal buffer is " << memsize << " bytes" << "\n";
while (ifs >> val)
{
done = false;
inputValues[count] = val;
count++;
if (count == chunksize)
{
std::sort(inputValues, inputValues + count);
write_vals(inputValues, count, chunk);
chunk ++;
count = 0;
done = true;
}
}
if (! done)
{
std::sort(inputValues, inputValues + count);
write_vals(inputValues, count, chunk);
}
else
{
chunk --;
}
ifs.close();
delete[] inputValues;
if ( chunk == 0 )
std::cout << "no data found\n";
else
std::cout << "Sorted output is in file: " << mergeFiles(chunk, merged_file ) << "\n";
return EXIT_SUCCESS;
}
|
import io
def sort_large_file(n: int, source: open, sink: open, file_opener = open)->None:
mergers = []
while True:
text = list(source.read(n))
if not len(text):
break;
text.sort()
merge_me = file_opener()
merge_me.write(''.join(text))
mergers.append(merge_me)
merge_me.seek(0)
stack_tops = [f.read(1) for f in mergers]
while stack_tops:
c = min(stack_tops)
sink.write(c)
i = stack_tops.index(c)
t = mergers[i].read(1)
if t:
stack_tops[i] = t
else:
del stack_tops[i]
mergers[i].close()
del mergers[i]
def main():
input_file_too_large_for_memory = io.StringIO('678925341')
t = list(input_file_too_large_for_memory.read())
t.sort()
expect = ''.join(t)
print('expect', expect)
for memory_size in range(1,12):
input_file_too_large_for_memory.seek(0)
output_file_too_large_for_memory = io.StringIO()
sort_large_file(memory_size, input_file_too_large_for_memory, output_file_too_large_for_memory, io.StringIO)
output_file_too_large_for_memory.seek(0)
assert(output_file_too_large_for_memory.read() == expect)
print('memory size {} passed'.format(memory_size))
if __name__ == '__main__':
example = main
example()
|
Transform the following C++ implementation into Python, maintaining the same output and logic. |
class matrixNG {
private:
virtual void consumeTerm(){}
virtual void consumeTerm(int n){}
virtual const bool needTerm(){}
protected: int cfn = 0, thisTerm;
bool haveTerm = false;
friend class NG;
};
class NG_4 : public matrixNG {
private: int a1, a, b1, b, t;
const bool needTerm() {
if (b1==0 and b==0) return false;
if (b1==0 or b==0) return true; else thisTerm = a/b;
if (thisTerm==(int)(a1/b1)){
t=a; a=b; b=t-b*thisTerm; t=a1; a1=b1; b1=t-b1*thisTerm;
haveTerm=true; return false;
}
return true;
}
void consumeTerm(){a=a1; b=b1;}
void consumeTerm(int n){t=a; a=a1; a1=t+a1*n; t=b; b=b1; b1=t+b1*n;}
public:
NG_4(int a1, int a, int b1, int b): a1(a1), a(a), b1(b1), b(b){}
};
class NG : public ContinuedFraction {
private:
matrixNG* ng;
ContinuedFraction* n[2];
public:
NG(NG_4* ng, ContinuedFraction* n1): ng(ng){n[0] = n1;}
NG(NG_8* ng, ContinuedFraction* n1, ContinuedFraction* n2): ng(ng){n[0] = n1; n[1] = n2;}
const int nextTerm() {ng->haveTerm = false; return ng->thisTerm;}
const bool moreTerms(){
while(ng->needTerm()) if(n[ng->cfn]->moreTerms()) ng->consumeTerm(n[ng->cfn]->nextTerm()); else ng->consumeTerm();
return ng->haveTerm;
}
};
| class NG:
def __init__(self, a1, a, b1, b):
self.a1, self.a, self.b1, self.b = a1, a, b1, b
def ingress(self, n):
self.a, self.a1 = self.a1, self.a + self.a1 * n
self.b, self.b1 = self.b1, self.b + self.b1 * n
@property
def needterm(self):
return (self.b == 0 or self.b1 == 0) or not self.a//self.b == self.a1//self.b1
@property
def egress(self):
n = self.a // self.b
self.a, self.b = self.b, self.a - self.b * n
self.a1, self.b1 = self.b1, self.a1 - self.b1 * n
return n
@property
def egress_done(self):
if self.needterm: self.a, self.b = self.a1, self.b1
return self.egress
@property
def done(self):
return self.b == 0 and self.b1 == 0
|
Change the programming language of this snippet from C++ to Python without modifying what it does. | #include <iostream>
#include <vector>
#include <boost/rational.hpp>
using rational = boost::rational<unsigned long>;
unsigned long floor(const rational& r) {
return r.numerator()/r.denominator();
}
rational calkin_wilf_next(const rational& term) {
return 1UL/(2UL * floor(term) + 1UL - term);
}
std::vector<unsigned long> continued_fraction(const rational& r) {
unsigned long a = r.numerator();
unsigned long b = r.denominator();
std::vector<unsigned long> result;
do {
result.push_back(a/b);
unsigned long c = a;
a = b;
b = c % b;
} while (a != 1);
if (result.size() > 0 && result.size() % 2 == 0) {
--result.back();
result.push_back(1);
}
return result;
}
unsigned long term_number(const rational& r) {
unsigned long result = 0;
unsigned long d = 1;
unsigned long p = 0;
for (unsigned long n : continued_fraction(r)) {
for (unsigned long i = 0; i < n; ++i, ++p)
result |= (d << p);
d = !d;
}
return result;
}
int main() {
rational term = 1;
std::cout << "First 20 terms of the Calkin-Wilf sequence are:\n";
for (int i = 1; i <= 20; ++i) {
std::cout << std::setw(2) << i << ": " << term << '\n';
term = calkin_wilf_next(term);
}
rational r(83116, 51639);
std::cout << r << " is the " << term_number(r) << "th term of the sequence.\n";
}
| from fractions import Fraction
from math import floor
from itertools import islice, groupby
def cw():
a = Fraction(1)
while True:
yield a
a = 1 / (2 * floor(a) + 1 - a)
def r2cf(rational):
num, den = rational.numerator, rational.denominator
while den:
num, (digit, den) = den, divmod(num, den)
yield digit
def get_term_num(rational):
ans, dig, pwr = 0, 1, 0
for n in r2cf(rational):
for _ in range(n):
ans |= dig << pwr
pwr += 1
dig ^= 1
return ans
if __name__ == '__main__':
print('TERMS 1..20: ', ', '.join(str(x) for x in islice(cw(), 20)))
x = Fraction(83116, 51639)
print(f"\n{x} is the {get_term_num(x):_}'th term.")
|
Write the same algorithm in Python as shown in this C++ implementation. | #include <iostream>
#include <vector>
#include <boost/rational.hpp>
using rational = boost::rational<unsigned long>;
unsigned long floor(const rational& r) {
return r.numerator()/r.denominator();
}
rational calkin_wilf_next(const rational& term) {
return 1UL/(2UL * floor(term) + 1UL - term);
}
std::vector<unsigned long> continued_fraction(const rational& r) {
unsigned long a = r.numerator();
unsigned long b = r.denominator();
std::vector<unsigned long> result;
do {
result.push_back(a/b);
unsigned long c = a;
a = b;
b = c % b;
} while (a != 1);
if (result.size() > 0 && result.size() % 2 == 0) {
--result.back();
result.push_back(1);
}
return result;
}
unsigned long term_number(const rational& r) {
unsigned long result = 0;
unsigned long d = 1;
unsigned long p = 0;
for (unsigned long n : continued_fraction(r)) {
for (unsigned long i = 0; i < n; ++i, ++p)
result |= (d << p);
d = !d;
}
return result;
}
int main() {
rational term = 1;
std::cout << "First 20 terms of the Calkin-Wilf sequence are:\n";
for (int i = 1; i <= 20; ++i) {
std::cout << std::setw(2) << i << ": " << term << '\n';
term = calkin_wilf_next(term);
}
rational r(83116, 51639);
std::cout << r << " is the " << term_number(r) << "th term of the sequence.\n";
}
| from fractions import Fraction
from math import floor
from itertools import islice, groupby
def cw():
a = Fraction(1)
while True:
yield a
a = 1 / (2 * floor(a) + 1 - a)
def r2cf(rational):
num, den = rational.numerator, rational.denominator
while den:
num, (digit, den) = den, divmod(num, den)
yield digit
def get_term_num(rational):
ans, dig, pwr = 0, 1, 0
for n in r2cf(rational):
for _ in range(n):
ans |= dig << pwr
pwr += 1
dig ^= 1
return ans
if __name__ == '__main__':
print('TERMS 1..20: ', ', '.join(str(x) for x in islice(cw(), 20)))
x = Fraction(83116, 51639)
print(f"\n{x} is the {get_term_num(x):_}'th term.")
|
Change the programming language of this snippet from C++ to Python without modifying what it does. | #include <array>
#include <chrono>
#include <iomanip>
#include <iostream>
#include <vector>
auto init_zc() {
std::array<int, 1000> zc;
zc.fill(0);
zc[0] = 3;
for (int x = 1; x <= 9; ++x) {
zc[x] = 2;
zc[10 * x] = 2;
zc[100 * x] = 2;
for (int y = 10; y <= 90; y += 10) {
zc[y + x] = 1;
zc[10 * y + x] = 1;
zc[10 * (y + x)] = 1;
}
}
return zc;
}
template <typename clock_type>
auto elapsed(const std::chrono::time_point<clock_type>& t0) {
auto t1 = clock_type::now();
auto duration =
std::chrono::duration_cast<std::chrono::milliseconds>(t1 - t0);
return duration.count();
}
int main() {
auto zc = init_zc();
auto t0 = std::chrono::high_resolution_clock::now();
int trail = 1, first = 0;
double total = 0;
std::vector<int> rfs{1};
std::cout << std::fixed << std::setprecision(10);
for (int f = 2; f <= 50000; ++f) {
int carry = 0, d999, zeroes = (trail - 1) * 3, len = rfs.size();
for (int j = trail - 1; j < len || carry != 0; ++j) {
if (j < len)
carry += rfs[j] * f;
d999 = carry % 1000;
if (j < len)
rfs[j] = d999;
else
rfs.push_back(d999);
zeroes += zc[d999];
carry /= 1000;
}
while (rfs[trail - 1] == 0)
++trail;
d999 = rfs.back();
d999 = d999 < 100 ? (d999 < 10 ? 2 : 1) : 0;
zeroes -= d999;
int digits = rfs.size() * 3 - d999;
total += double(zeroes) / digits;
double ratio = total / f;
if (ratio >= 0.16)
first = 0;
else if (first == 0)
first = f;
if (f == 100 || f == 1000 || f == 10000) {
std::cout << "Mean proportion of zero digits in factorials to " << f
<< " is " << ratio << ". (" << elapsed(t0) << "ms)\n";
}
}
std::cout << "The mean proportion dips permanently below 0.16 at " << first
<< ". (" << elapsed(t0) << "ms)\n";
}
| def facpropzeros(N, verbose = True):
proportions = [0.0] * N
fac, psum = 1, 0.0
for i in range(N):
fac *= i + 1
d = list(str(fac))
psum += sum(map(lambda x: x == '0', d)) / len(d)
proportions[i] = psum / (i + 1)
if verbose:
print("The mean proportion of 0 in factorials from 1 to {} is {}.".format(N, psum / N))
return proportions
for n in [100, 1000, 10000]:
facpropzeros(n)
props = facpropzeros(47500, False)
n = (next(i for i in reversed(range(len(props))) if props[i] > 0.16))
print("The mean proportion dips permanently below 0.16 at {}.".format(n + 2))
|
Change the programming language of this snippet from C++ to Python without modifying what it does. |
#include <iostream>
#include <vector>
#include <utility>
#include <cmath>
#include <random>
#include <chrono>
#include <algorithm>
#include <iterator>
typedef std::pair<double, double> point_t;
typedef std::pair<point_t, point_t> points_t;
double distance_between(const point_t& a, const point_t& b) {
return std::sqrt(std::pow(b.first - a.first, 2)
+ std::pow(b.second - a.second, 2));
}
std::pair<double, points_t> find_closest_brute(const std::vector<point_t>& points) {
if (points.size() < 2) {
return { -1, { { 0, 0 }, { 0, 0 } } };
}
auto minDistance = std::abs(distance_between(points.at(0), points.at(1)));
points_t minPoints = { points.at(0), points.at(1) };
for (auto i = std::begin(points); i != (std::end(points) - 1); ++i) {
for (auto j = i + 1; j < std::end(points); ++j) {
auto newDistance = std::abs(distance_between(*i, *j));
if (newDistance < minDistance) {
minDistance = newDistance;
minPoints.first = *i;
minPoints.second = *j;
}
}
}
return { minDistance, minPoints };
}
std::pair<double, points_t> find_closest_optimized(const std::vector<point_t>& xP,
const std::vector<point_t>& yP) {
if (xP.size() <= 3) {
return find_closest_brute(xP);
}
auto N = xP.size();
auto xL = std::vector<point_t>();
auto xR = std::vector<point_t>();
std::copy(std::begin(xP), std::begin(xP) + (N / 2), std::back_inserter(xL));
std::copy(std::begin(xP) + (N / 2), std::end(xP), std::back_inserter(xR));
auto xM = xP.at((N-1) / 2).first;
auto yL = std::vector<point_t>();
auto yR = std::vector<point_t>();
std::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yL), [&xM](const point_t& p) {
return p.first <= xM;
});
std::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yR), [&xM](const point_t& p) {
return p.first > xM;
});
auto p1 = find_closest_optimized(xL, yL);
auto p2 = find_closest_optimized(xR, yR);
auto minPair = (p1.first <= p2.first) ? p1 : p2;
auto yS = std::vector<point_t>();
std::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yS), [&minPair, &xM](const point_t& p) {
return std::abs(xM - p.first) < minPair.first;
});
auto result = minPair;
for (auto i = std::begin(yS); i != (std::end(yS) - 1); ++i) {
for (auto k = i + 1; k != std::end(yS) &&
((k->second - i->second) < minPair.first); ++k) {
auto newDistance = std::abs(distance_between(*k, *i));
if (newDistance < result.first) {
result = { newDistance, { *k, *i } };
}
}
}
return result;
}
void print_point(const point_t& point) {
std::cout << "(" << point.first
<< ", " << point.second
<< ")";
}
int main(int argc, char * argv[]) {
std::default_random_engine re(std::chrono::system_clock::to_time_t(
std::chrono::system_clock::now()));
std::uniform_real_distribution<double> urd(-500.0, 500.0);
std::vector<point_t> points(100);
std::generate(std::begin(points), std::end(points), [&urd, &re]() {
return point_t { 1000 + urd(re), 1000 + urd(re) };
});
auto answer = find_closest_brute(points);
std::sort(std::begin(points), std::end(points), [](const point_t& a, const point_t& b) {
return a.first < b.first;
});
auto xP = points;
std::sort(std::begin(points), std::end(points), [](const point_t& a, const point_t& b) {
return a.second < b.second;
});
auto yP = points;
std::cout << "Min distance (brute): " << answer.first << " ";
print_point(answer.second.first);
std::cout << ", ";
print_point(answer.second.second);
answer = find_closest_optimized(xP, yP);
std::cout << "\nMin distance (optimized): " << answer.first << " ";
print_point(answer.second.first);
std::cout << ", ";
print_point(answer.second.second);
return 0;
}
|
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()
|
Translate this program into Python but keep the logic exactly as in C++. |
#include <iostream>
#include <vector>
#include <utility>
#include <cmath>
#include <random>
#include <chrono>
#include <algorithm>
#include <iterator>
typedef std::pair<double, double> point_t;
typedef std::pair<point_t, point_t> points_t;
double distance_between(const point_t& a, const point_t& b) {
return std::sqrt(std::pow(b.first - a.first, 2)
+ std::pow(b.second - a.second, 2));
}
std::pair<double, points_t> find_closest_brute(const std::vector<point_t>& points) {
if (points.size() < 2) {
return { -1, { { 0, 0 }, { 0, 0 } } };
}
auto minDistance = std::abs(distance_between(points.at(0), points.at(1)));
points_t minPoints = { points.at(0), points.at(1) };
for (auto i = std::begin(points); i != (std::end(points) - 1); ++i) {
for (auto j = i + 1; j < std::end(points); ++j) {
auto newDistance = std::abs(distance_between(*i, *j));
if (newDistance < minDistance) {
minDistance = newDistance;
minPoints.first = *i;
minPoints.second = *j;
}
}
}
return { minDistance, minPoints };
}
std::pair<double, points_t> find_closest_optimized(const std::vector<point_t>& xP,
const std::vector<point_t>& yP) {
if (xP.size() <= 3) {
return find_closest_brute(xP);
}
auto N = xP.size();
auto xL = std::vector<point_t>();
auto xR = std::vector<point_t>();
std::copy(std::begin(xP), std::begin(xP) + (N / 2), std::back_inserter(xL));
std::copy(std::begin(xP) + (N / 2), std::end(xP), std::back_inserter(xR));
auto xM = xP.at((N-1) / 2).first;
auto yL = std::vector<point_t>();
auto yR = std::vector<point_t>();
std::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yL), [&xM](const point_t& p) {
return p.first <= xM;
});
std::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yR), [&xM](const point_t& p) {
return p.first > xM;
});
auto p1 = find_closest_optimized(xL, yL);
auto p2 = find_closest_optimized(xR, yR);
auto minPair = (p1.first <= p2.first) ? p1 : p2;
auto yS = std::vector<point_t>();
std::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yS), [&minPair, &xM](const point_t& p) {
return std::abs(xM - p.first) < minPair.first;
});
auto result = minPair;
for (auto i = std::begin(yS); i != (std::end(yS) - 1); ++i) {
for (auto k = i + 1; k != std::end(yS) &&
((k->second - i->second) < minPair.first); ++k) {
auto newDistance = std::abs(distance_between(*k, *i));
if (newDistance < result.first) {
result = { newDistance, { *k, *i } };
}
}
}
return result;
}
void print_point(const point_t& point) {
std::cout << "(" << point.first
<< ", " << point.second
<< ")";
}
int main(int argc, char * argv[]) {
std::default_random_engine re(std::chrono::system_clock::to_time_t(
std::chrono::system_clock::now()));
std::uniform_real_distribution<double> urd(-500.0, 500.0);
std::vector<point_t> points(100);
std::generate(std::begin(points), std::end(points), [&urd, &re]() {
return point_t { 1000 + urd(re), 1000 + urd(re) };
});
auto answer = find_closest_brute(points);
std::sort(std::begin(points), std::end(points), [](const point_t& a, const point_t& b) {
return a.first < b.first;
});
auto xP = points;
std::sort(std::begin(points), std::end(points), [](const point_t& a, const point_t& b) {
return a.second < b.second;
});
auto yP = points;
std::cout << "Min distance (brute): " << answer.first << " ";
print_point(answer.second.first);
std::cout << ", ";
print_point(answer.second.second);
answer = find_closest_optimized(xP, yP);
std::cout << "\nMin distance (optimized): " << answer.first << " ";
print_point(answer.second.first);
std::cout << ", ";
print_point(answer.second.second);
return 0;
}
|
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()
|
Change the following C++ code into Python without altering its purpose. | int i;
void* address_of_i = &i;
| var num = 12
var pointer = ptr(num)
print pointer
@unsafe
pointer.addr = 0xFFFE
|
Generate a Python translation of this C++ snippet without changing its computational steps. | class Animal
{
};
class Dog: public Animal
{
};
class Lab: public Dog
{
};
class Collie: public Dog
{
};
class Cat: public Animal
{
};
| class Animal:
pass
class Dog(Animal):
pass
class Cat(Animal):
pass
class Lab(Dog):
pass
class Collie(Dog):
pass
|
Change the following C++ code into Python without altering its purpose. | #include <map>
| hash = dict()
hash = dict(red="FF0000", green="00FF00", blue="0000FF")
hash = { 'key1':1, 'key2':2, }
value = hash[key]
|
Port the following code from C++ to Python with equivalent syntax and logic. |
#include "colorwheelwidget.h"
#include <QPainter>
#include <QPaintEvent>
#include <cmath>
namespace {
QColor hsvToRgb(int h, double s, double v) {
double hp = h/60.0;
double c = s * v;
double x = c * (1 - std::abs(std::fmod(hp, 2) - 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 QColor(r * 255, g * 255, b * 255);
}
}
ColorWheelWidget::ColorWheelWidget(QWidget *parent)
: QWidget(parent) {
setWindowTitle(tr("Color Wheel"));
resize(400, 400);
}
void ColorWheelWidget::paintEvent(QPaintEvent *event) {
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
const QColor backgroundColor(0, 0, 0);
const QColor white(255, 255, 255);
painter.fillRect(event->rect(), backgroundColor);
const int margin = 10;
const double diameter = std::min(width(), height()) - 2*margin;
QPointF center(width()/2.0, height()/2.0);
QRectF rect(center.x() - diameter/2.0, center.y() - diameter/2.0,
diameter, diameter);
for (int angle = 0; angle < 360; ++angle) {
QColor color(hsvToRgb(angle, 1.0, 1.0));
QRadialGradient gradient(center, diameter/2.0);
gradient.setColorAt(0, white);
gradient.setColorAt(1, color);
QBrush brush(gradient);
QPen pen(brush, 1.0);
painter.setPen(pen);
painter.setBrush(brush);
painter.drawPie(rect, angle * 16, 16);
}
}
| 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)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.