Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Write the same algorithm in REXX as shown in this Python implementation.
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)) ...
u = .unknown~new u~foo(1, 2, 3) ::class unknown ::method unknown use arg name, args say "Unknown method" name "invoked with arguments:" args~tostring('l',', ')
Keep all operations the same but rewrite the snippet in REXX.
assert 1.008 == molar_mass('H') assert 2.016 == molar_mass('H2') assert 18.015 == molar_mass('H2O') assert 34.014 == molar_mass('H2O2') assert 34.014 == molar_mass('(HO)2') assert 142.036 == molar_mass('Na2SO4') assert ...
numeric digits 30 @.= ; @.Co= 58.933195 ; @.H = 1.00794 ; @.Np=237 ; @.Se= 78.96 @.Cr= 51.9961 ; @.In=114.818 ; @.N = 14.0067 ; @.Sg=266 @.Ac=227 ; @.Cs=132.9054519; @.Ir=192.217 ; @.Og=294 ; @.Si= 28.0855 @.Ag=...
Write the same algorithm in REXX as shown in this Python implementation.
import operator class AstNode(object): def __init__( self, opr, left, right ): self.opr = opr self.l = left self.r = right def eval(self): return self.opr(self.l.eval(), self.r.eval()) class LeafNode(object): def __init__( self, valStrg ): self.v = int(valStrg) def eval(sel...
expressions = .array~of("2+3", "2+3/4", "2*3-4", "2*(3+4)+5/6", "2 * (3 + (4 * 5 + (6 * 7) * 8) - 9) * 10", "2*-3--4+-.25") loop input over expressions expression = createExpression(input) if expression \= .nil then say 'Expression "'input'" parses to "'expression~string'" and evaluates to "'expression~...
Rewrite the snippet below in REXX so it works the same as the original Python code.
import operator class AstNode(object): def __init__( self, opr, left, right ): self.opr = opr self.l = left self.r = right def eval(self): return self.opr(self.l.eval(), self.r.eval()) class LeafNode(object): def __init__( self, valStrg ): self.v = int(valStrg) def eval(sel...
expressions = .array~of("2+3", "2+3/4", "2*3-4", "2*(3+4)+5/6", "2 * (3 + (4 * 5 + (6 * 7) * 8) - 9) * 10", "2*-3--4+-.25") loop input over expressions expression = createExpression(input) if expression \= .nil then say 'Expression "'input'" parses to "'expression~string'" and evaluates to "'expression~...
Keep all operations the same but rewrite the snippet in REXX.
from pprint import pprint as pp class Template(): def __init__(self, structure): self.structure = structure self.used_payloads, self.missed_payloads = [], [] def inject_payload(self, id2data): def _inject_payload(substruct, i2d, used, missed): used.extend(i2d[x...
tok.='' Do i=0 To 6 tok.i="'Payload#"i"'" End t1='[[[1,2],[3,4,1],5]]' t2='[[[1,6],[3,4,7,0],5]]' Call transform t1 Call transform t2 Exit transform: Parse Arg t 1 tt [[['Payload#1', 'Payload#2'], ['Payload#3', 'Payload#4', 'Payload#1'], 'Payload#5']] */ lvl=0 n.=0 o='' w='' used.=0 Do While t<>'' Parse V...
Convert the following code from Python to REXX, ensuring the logic remains intact.
import os targetfile = "pycon-china" os.rename(os.path.realpath(targetfile), os.path.realpath(targetfile)+".bak") f = open(os.path.realpath(targetfile), "w") f.write("this task was solved during a talk about rosettacode at the PyCon China in 2011") f.close()
parse arg oFID . if oFID=='' then do say '***error*** no fileID was specified.' exit 13 end tFID= oFID'.$$$' call lineout oFID call lineo...
Port the following code from Python to REXX with equivalent syntax and logic.
import os targetfile = "pycon-china" os.rename(os.path.realpath(targetfile), os.path.realpath(targetfile)+".bak") f = open(os.path.realpath(targetfile), "w") f.write("this task was solved during a talk about rosettacode at the PyCon China in 2011") f.close()
parse arg oFID . if oFID=='' then do say '***error*** no fileID was specified.' exit 13 end tFID= oFID'.$$$' call lineout oFID call lineo...
Maintain the same structure and functionality when rewriting this code in REXX.
from re import sub testtexts = [ , , ] for txt in testtexts: text2 = sub(r'<lang\s+\"?([\w\d\s]+)\"?\s?>', r'<syntaxhighlight lang=\1>', txt) text2 = sub(r'<lang\s*>', r'<syntaxhighlight lang=text>', text2) text2 = sub(r'</lang\s*>', r'
@="<"; old.=; old.1 = @'%s>' ; new.1 = @"lang %s>" old.2 = @'/%s>' ; new.2 = @"/lang>" old.3 = @'code %s>' ; new.3 = @"lang %s>" old.4 = @'/code>' ; new.4 = @"/lang>" iFID = 'Wikisource.txt' ...
Port the following code from Python to REXX with equivalent syntax and logic.
from itertools import count def firstGap(xs): return next(x for x in count(1) if x not in xs) def main(): print('\n'.join([ f'{repr(xs)} -> {firstGap(xs)}' for xs in [ [1, 2, 0], [3, 4, -1, 1], [7, 8, 9, 11, 12] ] ])) if __name__ == '...
parse arg a if a='' | a="," then a= '[1,2,0] [3,4,-1,1] [7,8,9,11,12] [1,2,3,4,5]' , "[-6,-5,-2,-1] [5,-5] [-2] [1] []" say 'the smallest missing positive integer for the following sets is:' say do j=1 for words(a) ...
Produce a functionally identical REXX code for the snippet given in Python.
import random import sys snl = { 4: 14, 9: 31, 17: 7, 20: 38, 28: 84, 40: 59, 51: 67, 54: 34, 62: 19, 63: 81, 64: 60, 71: 91, 87: 24, 93: 73, 95: 75, 99: 78 } sixesRollAgain = True def turn(player, square): while True: roll = random.randint(1...
parse arg np seed . if np=='' | np=="," then np= 3 if datatype(seed, 'W') then call random ,,seed pad= left('',7) do k=1 for 100; @.k= k end ...
Generate an equivalent REXX version of this Python code.
import random import sys snl = { 4: 14, 9: 31, 17: 7, 20: 38, 28: 84, 40: 59, 51: 67, 54: 34, 62: 19, 63: 81, 64: 60, 71: 91, 87: 24, 93: 73, 95: 75, 99: 78 } sixesRollAgain = True def turn(player, square): while True: roll = random.randint(1...
parse arg np seed . if np=='' | np=="," then np= 3 if datatype(seed, 'W') then call random ,,seed pad= left('',7) do k=1 for 100; @.k= k end ...
Port the following code from Python to REXX with equivalent syntax and logic.
from fractions import Fraction class Fr(Fraction): def __repr__(self): return '(%s/%s)' % (self.numerator, self.denominator) def farey(n, length=False): if not length: return [Fr(0, 1)] + sorted({Fr(m, k) for k in range(1, n+1) for m in range(1, k+1)}) else: return (n*(...
parse arg LO HI INC . if LO=='' | LO=="," then LO= 1 if HI=='' | HI=="," then HI= LO if INC=='' | INC=="," then INC= 1 sw= linesize() - 1 oLO= LO do j=abs(LO)...
Produce a language-to-language conversion: from Python to REXX, same semantics.
from fractions import Fraction class Fr(Fraction): def __repr__(self): return '(%s/%s)' % (self.numerator, self.denominator) def farey(n, length=False): if not length: return [Fr(0, 1)] + sorted({Fr(m, k) for k in range(1, n+1) for m in range(1, k+1)}) else: return (n*(...
parse arg LO HI INC . if LO=='' | LO=="," then LO= 1 if HI=='' | HI=="," then HI= LO if INC=='' | INC=="," then INC= 1 sw= linesize() - 1 oLO= LO do j=abs(LO)...
Change the following Python code into REXX without altering its purpose.
from proper_divisors import proper_divs from functools import lru_cache @lru_cache() def pdsum(n): return sum(proper_divs(n)) def aliquot(n, maxlen=16, maxterm=2**47): if n == 0: return 'terminating', [0] s, slen, new = [n], 1, n while slen <= maxlen and new < maxterm: new =...
parse arg low high $L high= word(high low 10,1); low= word(low 1,1) if $L='' then $L=11 12 28 496 220 1184 12496 1264460 790 909 562 1064 1488 15355717786080 numeric digits 100 big= 2**47; NTlimit= 16 + 1 numeric digits max(9, length...
Maintain the same structure and functionality when rewriting this code in REXX.
from proper_divisors import proper_divs from functools import lru_cache @lru_cache() def pdsum(n): return sum(proper_divs(n)) def aliquot(n, maxlen=16, maxterm=2**47): if n == 0: return 'terminating', [0] s, slen, new = [n], 1, n while slen <= maxlen and new < maxterm: new =...
parse arg low high $L high= word(high low 10,1); low= word(low 1,1) if $L='' then $L=11 12 28 496 220 1184 12496 1264460 790 909 562 1064 1488 15355717786080 numeric digits 100 big= 2**47; NTlimit= 16 + 1 numeric digits max(9, length...
Rewrite this program in REXX while keeping its functionality equivalent to the Python version.
from fractions import Fraction from decimal import Decimal, getcontext getcontext().prec = 60 from itertools import product casting_functions = [int, float, complex, Fraction, Decimal, hex, oct, bin, bool, ...
digs=digits() ; say digs a=.1.2...$ ; say a a=+7 ; say a a='+66' ; say a a='- 66.' ; ...
Ensure the translated REXX code behaves exactly like the original Python snippet.
from fractions import Fraction from decimal import Decimal, getcontext getcontext().prec = 60 from itertools import product casting_functions = [int, float, complex, Fraction, Decimal, hex, oct, bin, bool, ...
digs=digits() ; say digs a=.1.2...$ ; say a a=+7 ; say a a='+66' ; say a a='- 66.' ; ...
Change the programming language of this snippet from Python to REXX without modifying what it does.
import random def MillerRabinPrimalityTest(number): if number == 2: return True elif number == 1 or number % 2 == 0: return False oddPartOfNumber = number - 1 timesTwoDividNumber = 0 while oddPartOfNumber % 2 == 0: oddPartOfNumbe...
do j=1; if \isPrime(j) then iterate r= testMer(j) if r==0 then say right('M'j, 10) "──────── is a Mersenne prime." else say right('M'j, 50) "is composite, a factor:" r end ex...
Generate a REXX translation of this Python snippet without changing its computational steps.
import random def MillerRabinPrimalityTest(number): if number == 2: return True elif number == 1 or number % 2 == 0: return False oddPartOfNumber = number - 1 timesTwoDividNumber = 0 while oddPartOfNumber % 2 == 0: oddPartOfNumbe...
do j=1; if \isPrime(j) then iterate r= testMer(j) if r==0 then say right('M'j, 10) "──────── is a Mersenne prime." else say right('M'j, 50) "is composite, a factor:" r end ex...
Convert this Python snippet to REXX and keep its semantics consistent.
def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True if __name__ == '__main__': p = 2 n = 1 print("2",end = " ") while True: if isPrime(p + n**3): p += n**3 n = 1 print(p,end = " ")...
parse arg hi cols . if hi=='' | hi=="," then hi= 15000 if cols=='' | cols=="," then cols= 10 call genP w= 10 title= 'the smallest primes < ' commas(hi) ...
Keep all operations the same but rewrite the snippet in REXX.
def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True if __name__ == '__main__': p = 2 n = 1 print("2",end = " ") while True: if isPrime(p + n**3): p += n**3 n = 1 print(p,end = " ")...
parse arg hi cols . if hi=='' | hi=="," then hi= 15000 if cols=='' | cols=="," then cols= 10 call genP w= 10 title= 'the smallest primes < ' commas(hi) ...
Write the same algorithm in REXX as shown in this Python implementation.
LIMIT = 1_000_035 def primes2(limit=LIMIT): if limit < 2: return [] if limit < 3: return [2] lmtbf = (limit - 3) // 2 buf = [True] * (lmtbf + 1) for i in range((int(limit ** 0.5) - 3) // 2 + 1): if buf[i]: p = i + i + 3 s = p * (i + 1) + i buf[s::p] = [Fal...
parse arg N endU end2 end3 end4 end5 . if N=='' | N=="," then N= 1000035 - 1 if endU=='' | endU=="," then endU= 10 if end2=='' | end2=="," then end2= 5 if end3=='' | end3=="," then end3= 5 if end4=='' | end4=="," then end4= 5 if end5=='' | end5...
Rewrite the snippet below in REXX so it works the same as the original Python code.
from collections import defaultdict from itertools import product from pprint import pprint as pp cube2n = {x**3:x for x in range(1, 1201)} sum2cubes = defaultdict(set) for c1, c2 in product(cube2n, cube2n): if c1 >= c2: sum2cubes[c1 + c2].add((cube2n[c1], cube2n[c2])) taxied = sorted((k, v) for k,v in sum2cubes.it...
parse arg L.1 H.1 L.2 H.2 L.3 H.3 . if L.1=='' | L.1=="," then L.1= 1 if H.1=='' | H.1=="," then H.1= 25 if L.2=='' | L.2=="," then L.2= 454 if H.2=='' | H.2=="," then H.2= 456 if L.3=='' | L.3=="," then L.3=2000 if H.3=='' | H.3...
Port the following code from Python to REXX with equivalent syntax and logic.
import numpy as np def primesfrom2to(n): sieve = np.ones(n//3 + (n%6==2), dtype=np.bool) sieve[0] = False for i in range(int(n**0.5)//3+1): if sieve[i]: k=3*i+1|1 sieve[ ((k*k)//3) ::2*k] = False sieve[(k*k+4*k-2*k*(i&1))//3::2*k] = False ...
parse arg N kind _ . 1 . okind; upper kind if N=='' | N=="," then N= 36 if kind=='' | kind=="," then kind= 'STRONG' if _\=='' then call ser 'too many arguments specified.' if kind\=='WEAK' & kind\=='STRONG' then call ser 'invalid 2nd argument: ' okind ...
Preserve the algorithm and functionality while converting the code from Python to REXX.
from itertools import islice def lfact(): yield 0 fact, summ, n = 1, 0, 1 while 1: fact, summ, n = fact*n, summ + fact, n + 1 yield summ print('first 11:\n %r' % [lf for i, lf in zip(range(11), lfact())]) print('20 through 110 (inclusive) by tens:') for lf in islice(lfact(), 20, 111, 10)...
parse arg bot top inc . if bot=='' | bot=="," then bot= 1 if top=='' | top=="," then top= bot if inc='' | inc=="," then inc= 1 tell= bot<0 bot= abs(bot) w= length(top) ...
Rewrite this program in REXX while keeping its functionality equivalent to the Python version.
from itertools import islice def lfact(): yield 0 fact, summ, n = 1, 0, 1 while 1: fact, summ, n = fact*n, summ + fact, n + 1 yield summ print('first 11:\n %r' % [lf for i, lf in zip(range(11), lfact())]) print('20 through 110 (inclusive) by tens:') for lf in islice(lfact(), 20, 111, 10)...
parse arg bot top inc . if bot=='' | bot=="," then bot= 1 if top=='' | top=="," then top= bot if inc='' | inc=="," then inc= 1 tell= bot<0 bot= abs(bot) w= length(top) ...
Can you help me rewrite this code in REXX instead of Python, keeping it the same logically?
from sympy import primerange def strange_triplets(mx: int = 30) -> None: primes = list(primerange(0, mx)) primes3 = set(primerange(0, 3 * mx)) for i, n in enumerate(primes): for j, m in enumerate(primes[i + 1:], i + 1): for p in primes[j + 1:]: if n + m + p in primes3: ...
parse arg hi . if hi=='' | hi=="," then hi= 30 tell= hi>0; hi= abs(hi); hi= hi - 1 if tell>0 then say 'list of unique triplet strange primes whose sum is a prime.:' call genP finds= 0 ...
Produce a language-to-language conversion: from Python to REXX, same semantics.
from sympy import primerange def strange_triplets(mx: int = 30) -> None: primes = list(primerange(0, mx)) primes3 = set(primerange(0, 3 * mx)) for i, n in enumerate(primes): for j, m in enumerate(primes[i + 1:], i + 1): for p in primes[j + 1:]: if n + m + p in primes3: ...
parse arg hi . if hi=='' | hi=="," then hi= 30 tell= hi>0; hi= abs(hi); hi= hi - 1 if tell>0 then say 'list of unique triplet strange primes whose sum is a prime.:' call genP finds= 0 ...
Convert the following code from Python to REXX, ensuring the logic remains intact.
from sympy import isprime def motzkin(num_wanted): mot = [1] * (num_wanted + 1) for i in range(2, num_wanted + 1): mot[i] = (mot[i-1]*(2*i+1) + mot[i-2]*(3*i-3)) // (i + 2) return mot def print_motzkin_table(N=41): print( " n M[n] Prime?\n------------...
numeric digits 92 parse arg n . if n=='' | n=="," then n= 42 w= length(n) + 1; wm= digits()%4 say center('n', w ) center("Motzkin[n]", wm) center(' primality', 11) say center('' , w, "─") center('' ...
Write the same code in REXX as shown below in Python.
def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True def nextPrime(n): if n == 0: return 2 if n < 3: return n + 1 q = n + 2 while not isPrime(q): q += 2 return q if __name__ == "__main__": ...
parse arg hi cols . if hi=='' | hi=="," then hi= 100 if cols=='' | cols=="," then cols= 5 call genP hi do p=1 while @.p<hi end #m= # - 1 call genP @.# + @.#m - 1 w= 20 ...
Port the provided Python code into REXX while preserving the original functionality.
def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True def nextPrime(n): if n == 0: return 2 if n < 3: return n + 1 q = n + 2 while not isPrime(q): q += 2 return q if __name__ == "__main__": ...
parse arg hi cols . if hi=='' | hi=="," then hi= 100 if cols=='' | cols=="," then cols= 5 call genP hi do p=1 while @.p<hi end #m= # - 1 call genP @.# + @.#m - 1 w= 20 ...
Maintain the same structure and functionality when rewriting this code in REXX.
Python 3.8.5 (default, Sep 3 2020, 21:29:08) [MSC v.1916 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> from sympy import isprime >>> [x for x in range(101,500) if isprime(sum(int(c) for c in str(x)[:2])) and isprime(sum(int(c) for c in str(x)[1:]))] [111, ...
parse arg LO HI . if LO=='' | LO=="," then LO= 101 if HI=='' | HI=="," then HI= 499 !.= 0; !.2= 1; !.3= 1; !.5= 1; !.7= 1 !.11= 1; !.13= 1; !.17= 1 $= #= 0 ...
Convert this Python snippet to REXX and keep its semantics consistent.
Python 3.8.5 (default, Sep 3 2020, 21:29:08) [MSC v.1916 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> from sympy import isprime >>> [x for x in range(101,500) if isprime(sum(int(c) for c in str(x)[:2])) and isprime(sum(int(c) for c in str(x)[1:]))] [111, ...
parse arg LO HI . if LO=='' | LO=="," then LO= 101 if HI=='' | HI=="," then HI= 499 !.= 0; !.2= 1; !.3= 1; !.5= 1; !.7= 1 !.11= 1; !.13= 1; !.17= 1 $= #= 0 ...
Ensure the translated REXX code behaves exactly like the original Python snippet.
def divisors(n): divs = [1] for ii in range(2, int(n ** 0.5) + 3): if n % ii == 0: divs.append(ii) divs.append(int(n / ii)) divs.append(n) return list(set(divs)) def is_prime(n): return len(divisors(n)) == 2 def digit_check(n): if len(str(n))<2: return...
parse arg n q if n=='' | n=="," then n= 25 if q='' then q= 100 1000 say '═══listing the first' n "SPDS primes═══" call spds n do i=1 for words(q)+1; y=word(q, i); if y=='' | y=="," then iterate ...
Produce a functionally identical REXX code for the snippet given in Python.
def MagicSquareDoublyEven(order): sq = [range(1+n*order,order + (n*order)+1) for n in range(order) ] n1 = order/4 for r in range(n1): r1 = sq[r][n1:-n1] r2 = sq[order -r - 1][n1:-n1] r1.reverse() r2.reverse() sq[r][n1:-n1] = r2 sq[order -r - 1][n1:-n1] = r1 ...
n= 8; s= n%4; L= n%2-s+1; w= length(n**2) @.= 0; H= n%2+s call gen call diag call corn call midd call swap ...
Convert the following code from Python to REXX, ensuring the logic remains intact.
import math def SquareFree ( _number ) : max = (int) (math.sqrt ( _number )) for root in range ( 2, max+1 ): if 0 == _number % ( root * root ): return False return True def ListSquareFrees( _start, _end ): count = 0 for i in range ( _start, _end+1 ): if True == SquareFree( i ): print ( "{}\t".fo...
numeric digits 20 parse arg LO HI . if LO=='' | LO=="," then LO= 1 if HI=='' | HI=="," then HI= 145 sw= linesize() - 1 # = 0 $= ...
Please provide an equivalent version of this Python code in REXX.
class DigitSumer : def __init__(self): sumdigit = lambda n : sum( map( int,str( n ))) self.t = [sumdigit( i ) for i in xrange( 10000 )] def __call__ ( self,n ): r = 0 while n >= 10000 : n,q = divmod( n,10000 ) r += self.t[q] return r + self.t[n] ...
parse arg n . if n=='' | n=="," then n= 50 tell = n>0; n= abs(n) @.= . do j=1 for n*10 $= j do...
Rewrite this program in REXX while keeping its functionality equivalent to the Python version.
def digit_sum(n, sum): sum += 1 while n > 0 and n % 10 == 0: sum -= 9 n /= 10 return sum previous = 1 gap = 0 sum = 0 niven_index = 0 gap_index = 1 print("Gap index Gap Niven index Niven number") niven = 1 while gap_index <= 22: sum = digit_sum(niven, sum) ...
parse arg lim . if lim=='' | lim==',' then lim= 10000000 numeric digits 2 + max(8, length(lim) ) gap= 0; old= 0 @gsa= 'gap starts at Niven #' call tell center('gap size', 12) cent...
Produce a functionally identical REXX code for the snippet given in Python.
from sys import argv unit2mult = {"arshin": 0.7112, "centimeter": 0.01, "diuym": 0.0254, "fut": 0.3048, "kilometer": 1000.0, "liniya": 0.00254, "meter": 1.0, "milia": 7467.6, "piad": 0.1778, "sazhen": 2.1336, "tochka": 0.000254, "vershok": 0.04445,...
numeric digits 200 KM= 1000; CM=100 sw= linesize() -1 parse arg N what _ __ if N=='' then call err 'no arguments specified.'...
Transform the following Python implementation into REXX, maintaining the same output and logic.
import time from collections import deque from operator import itemgetter from typing import Tuple Pancakes = Tuple[int, ...] def flip(pancakes: Pancakes, position: int) -> Pancakes: return tuple([*reversed(pancakes[:position]), *pancakes[position:]]) def pancake(n: int) -> Tuple[Pancakes, int]: ...
pad= center('' , 10) say pad center('pancakes', 10 ) center('pancake flips', 15 ) say pad center('' , 10, "─") center('', 15, "─") do #=1 for 20; say pad center(#, 10) center( pancake(#), 15) end exit 0...
Generate a REXX translation of this Python snippet without changing its computational steps.
def quad(top=2200): r = [False] * top ab = [False] * (top * 2)**2 for a in range(1, top): for b in range(a, top): ab[a * a + b * b] = True s = 3 for c in range(1, top): s1, s, s2 = s, s + 2, s + 2 for d in range(c + 1, top): if ab[s1]: ...
parse arg hi . if hi=='' | hi=="," then hi=2200; high= 3 * hi @.=. !.=. do j=1 for high _= j*j; !._= j; if j<=hi then @.j= _ end d.=. ...
Can you help me rewrite this code in REXX instead of Python, keeping it the same logically?
from collections import Counter def decompose_sum(s): return [(a,s-a) for a in range(2,int(s/2+1))] all_pairs = set((a,b) for a in range(2,100) for b in range(a+1,100) if a+b<100) product_counts = Counter(c*d for c,d in all_pairs) unique_products = set((a,b) for a,b in all_pairs if product_counts[a*b]==1) s_...
all =.set~new Call time 'R' cnt.=0 do a=2 to 100 do b=a+1 to 100-2 p=a b if a+b>100 then leave b all~put(p) prd=a*b cnt.prd+=1 End End Say "There are" all~items "pairs where X+Y <=" max "(and X<Y)" spairs=.set~new Do Until all~items=0 do p over all d=decompositions(p) If take...
Write the same code in REXX as shown below in Python.
"Generate a short Superpermutation of n characters A... as a string using various algorithms." from __future__ import print_function, division from itertools import permutations from math import factorial import string import datetime import gc MAXN = 7 def s_perm0(n): allchars = string.ascii_uppercase...
parse arg cycles . if cycles=='' | cycles=="," then cycles= 7 do n=0 to cycles #= 0; $.= do pop=1 for n; @.pop= d2x(pop); $.0= $.0 || @.pop end do while aPerm(n, 0) ...
Write the same algorithm in REXX as shown in this Python implementation.
>>> def isint(f): return complex(f).imag == 0 and complex(f).real.is_integer() >>> [isint(f) for f in (1.0, 2, (3.0+0.0j), 4.1, (3+4j), (5.6+0j))] [True, True, True, False, False, False] >>> ... >>> isint(25.000000) True >>> isint(24.999999) False >>> isint(25.000100) False >>> isint(-2.1e120) True >>> isint(-5...
* 22.06.2014 Walter Pachl using a complex data class * ooRexx Distribution contains an elaborate complex class * parts of which are used here * see REXX for Extra Credit implementation *--------------------------------------------------------------------*/ Numeric Digits 1000 Call test_integer .complex~new(1e+12,0e-3)...
Generate a REXX translation of this Python snippet without changing its computational steps.
from __future__ import print_function from time import sleep last_idle = last_total = 0 while True: with open('/proc/stat') as f: fields = [float(column) for column in f.readline().strip().split()[1:]] idle, total = fields[3], sum(fields) idle_delta, total_delta = idle - last_idle, total - last_to...
signal on halt numeric digits 20 parse arg n wait iFID . if n=='' | n="," then n= 10 if wait=='' | wait="," then wait= 1 if iFID=='' | iFID="," then iFID= '/proc/stat' prevTot = 0; ...
Rewrite this program in REXX while keeping its functionality equivalent to the Python version.
import time def ulam(n): if n <= 2: return n mx = 1352000 lst = [1, 2] + [0] * mx sums = [0] * (mx * 2 + 1) sums[3] = 1 size = 2 while size < n: query = lst[size-1] + 1 while True: if sums[query] == 1: for i in range(size): ...
parse arg $ if $='' | $="," then $= 10 100 1000 10000 do k=1 for words($) x= Ulam( word($, k) ) say 'the ' commas(#)th(#) ' Ulam number is: ' commas(x) end exit 0 ...
Rewrite this program in REXX while keeping its functionality equivalent to the Python version.
range17 = range(17) a = [['0'] * 17 for i in range17] idx = [0] * 4 def find_group(mark, min_n, max_n, depth=1): if (depth == 4): prefix = "" if (mark == '1') else "un" print("Fail, found totally {}connected group:".format(prefix)) for i in range(4): print(idx[i]) retur...
@.=0; #=17 do d=0 for #; @.d.d= 2 end do k=1 by 0 while k<=8 do i=0 for #; j= (i+k) // # @.i.j= 1; @.j.i= 1 end k= k + k ...
Convert this Python block to REXX, preserving its control flow and logic.
def smallest_six(n): p = 1 while str(n) not in str(p): p *= 6 return p for n in range(22): print("{:2}: {}".format(n, smallest_six(n)))
numeric digits 100 parse arg hi . if hi=='' | hi=="," then hi= 22 w= 50 @smp6= ' smallest power of six (expressed in decimal) which contains N' say ' N β”‚ power β”‚'center(@...
Translate this program into REXX but keep the logic exactly as in Python.
print("working...") print("Steady squares under 10.000 are:") limit = 10000 for n in range(1,limit): nstr = str(n) nlen = len(nstr) square = str(pow(n,2)) rn = square[-nlen:] if nstr == rn: print(str(n) + " " + str(square)) print("done...")
Numeric Digits 50 Call time 'R' n=1000000000 Say 'Steady squares below' n Do i=1 To n c=right(i,1) If pos(c,'156')>0 Then Do i2=i*i If right(i2,length(i))=i Then Say right(i,length(n)) i2 End End Say time('E')
Preserve the algorithm and functionality while converting the code from Python to REXX.
primes =[] sp =[] usp=[] n = 10000000 if 2<n: primes.append(2) for i in range(3,n+1,2): for j in primes: if(j>i/2) or (j==primes[-1]): primes.append(i) if((i-1)/2) in primes: sp.append(i) break else: usp.append(i) ...
parse arg N kind _ . 1 . okind; upper kind if N=='' | N=="," then N= 35 if kind=='' | kind=="," then kind= 'SAFE' if _\=='' then call ser 'too many arguments specified.' if kind\=='SAFE' & kind\=='UNSAFE' then call ser 'invalid 2nd argument: ' okind ...
Produce a language-to-language conversion: from Python to REXX, same semantics.
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, "...
S. = ; R. = S.1 = 27 'Jonah' ; R.1 = "Jonah Whales" S.2 = 18 'Alan' ; R.2 = "Jonah Spiders" S.3 = 28 'Glory' ; R.3 = "Alan Ghosts" S.4 = 18 ...
Preserve the algorithm and functionality while converting the code from Python to REXX.
from itertools import product def replicateM(n): def rep(m): def go(x): return [[]] if 1 > x else ( liftA2List(lambda a, b: [a] + b)(m)(go(x - 1)) ) return go(n) return lambda m: rep(m) def main(): print( fTable(main.__doc__ ...
parse arg things bunch inbetweenChars names call permSets things, bunch, inBetweenChars, names exit p: return word( arg(1), 1) permSets: procedure; parse arg x,y,between,uSy...
Ensure the translated REXX code behaves exactly like the original Python snippet.
from itertools import product def replicateM(n): def rep(m): def go(x): return [[]] if 1 > x else ( liftA2List(lambda a, b: [a] + b)(m)(go(x - 1)) ) return go(n) return lambda m: rep(m) def main(): print( fTable(main.__doc__ ...
parse arg things bunch inbetweenChars names call permSets things, bunch, inBetweenChars, names exit p: return word( arg(1), 1) permSets: procedure; parse arg x,y,between,uSy...
Can you help me rewrite this code in REXX instead of Python, keeping it the same logically?
import time import os seconds = input("Enter a number of seconds: ") sound = input("Enter an mp3 filename: ") time.sleep(float(seconds)) os.startfile(sound + ".mp3")
say '──────── Please enter a number of seconds to wait:' parse pull waitTime . say '──────── Please enter a name of an MP3 file to play:' parse pull MP3FILE call sleep waitTime MP3FILE'.MP3'
Convert the following code from Python to REXX, ensuring the logic remains intact.
def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True if __name__ == '__main__': p = 2 j = 1 print(2, end = " "); while True: while True: if isPrime(p + j*j): break j += 1 ...
parse arg hi cols . if hi=='' | hi=="," then hi= 16000 if cols=='' | cols=="," then cols= 10 call genP w= 10 title= 'the smallest primes < ' commas(hi) ...
Convert the following code from Python to REXX, ensuring the logic remains intact.
def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True if __name__ == '__main__': p = 2 j = 1 print(2, end = " "); while True: while True: if isPrime(p + j*j): break j += 1 ...
parse arg hi cols . if hi=='' | hi=="," then hi= 16000 if cols=='' | cols=="," then cols= 10 call genP w= 10 title= 'the smallest primes < ' commas(hi) ...
Port the provided Python code into REXX while preserving the original functionality.
def hourglass_puzzle(): t4 = 0 while t4 < 10_000: t7_left = 7 - t4 % 7 if t7_left == 9 - 4: break t4 += 4 else: print('Not found') return print(f) hourglass_puzzle()
t4= 0 mx= 10000 do t4=0 by 4 to mx t7_left= 7 - t4 % 7 if t7_left==9-4 then leave end say if t4>mx then do say 'Not found.' exit 4 end say "Turn over both sandglasses (at the same time) and continue" say "flipping t...
Convert this Python snippet to REXX and keep its semantics consistent.
def hourglass_puzzle(): t4 = 0 while t4 < 10_000: t7_left = 7 - t4 % 7 if t7_left == 9 - 4: break t4 += 4 else: print('Not found') return print(f) hourglass_puzzle()
t4= 0 mx= 10000 do t4=0 by 4 to mx t7_left= 7 - t4 % 7 if t7_left==9-4 then leave end say if t4>mx then do say 'Not found.' exit 4 end say "Turn over both sandglasses (at the same time) and continue" say "flipping t...
Convert the following code from Python to REXX, ensuring the logic remains intact.
from math import prod def maxproduct(mat, length): nrow, ncol = len(mat), len(mat[0]) maxprod, maxrow, maxcol, arr = 0, [0, 0], [0, 0], [0] for row in range(nrow): for col in range(ncol): row2, col2 = row + length, col + length if row < nrow - length: ...
a.1=.array~of(08,02,22,97,38,15,00,40,00,75,04,05,07,78,52,12,50,77,91,08) a.2=.array~of(49,49,99,40,17,81,18,57,60,87,17,40,98,43,69,48,04,56,62,00) a.3=.array~of(81,49,31,73,55,79,14,29,93,71,40,67,53,88,30,03,49,13,36,65) a.4=.array~of(52,70,95,23,04,60,11,42,69,24,68,56,01,32,56,71,37,02,36,91) a.5=.array~of(22,31...
Change the following Python code into REXX without altering its purpose.
import time print "\033[?1049h\033[H" print "Alternate buffer!" for i in xrange(5, 0, -1): print "Going back in:", i time.sleep(1) print "\033[?1049l"
parse value scrsize() with sd sw . parse value cursor(1,1) with curRow curCol . do original=1 for sd @line.original=scrRead(original,1, sw) end 'CLS' do sd % 2 ...
Write the same algorithm in REXX as shown in this Python implementation.
import pyttsx engine = pyttsx.init() engine.say("It was all a dream.") engine.runAndWait()
parse arg t if t='' then exit dquote= '"' rate= 1 'NIRCMD' "speak text" dquote t dquote rate
Produce a functionally identical REXX code for the snippet given in Python.
k8 = [ 14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7 ] k7 = [ 15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10 ] k6 = [ 10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8 ] k5 = [ 7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15 ] k4 = [ 2, 12, 4, 1, 7, 10, ...
numeric digits 12 @.0 = 4 10 9 2 13 8 0 14 6 11 1 12 7 15 5 3 @.1 = 14 11 4 12 6 13 15 10 2 3 8 1 0 7 5 9 @.2 = 5 8 1 13 10 3 4 ...
Transform the following Python implementation into REXX, maintaining the same output and logic.
environments = [{'cnt':0, 'seq':i+1} for i in range(12)] code = while any(env['seq'] > 1 for env in environments): for env in environments: exec(code, globals(), env) print() print('Counts') for env in environments: print('% 4d' % env['cnt'], end='') print()
parse arg n . if n=='' | n=="," then n= 12 @.= do i=1 for n; @.i= i end w= length(n) do forever until @.0; @.0= 1 ...
Change the programming language of this snippet from Python to REXX without modifying what it does.
import win32api import win32con import pywintypes devmode=pywintypes.DEVMODEType() devmode.PelsWidth=640 devmode.PelsHeight=480 devmode.Fields=win32con.DM_PELSWIDTH | win32con.DM_PELSHEIGHT win32api.ChangeDisplaySettings(devmode,0)
parse arg cols lines . 'MODE' "CON: COLS="cols 'LINES='lines
Write the same algorithm in REXX as shown in this Python implementation.
import win32api import win32con import pywintypes devmode=pywintypes.DEVMODEType() devmode.PelsWidth=640 devmode.PelsHeight=480 devmode.Fields=win32con.DM_PELSWIDTH | win32con.DM_PELSHEIGHT win32api.ChangeDisplaySettings(devmode,0)
parse arg cols lines . 'MODE' "CON: COLS="cols 'LINES='lines
Produce a language-to-language conversion: from Python to REXX, same semantics.
import curses from random import randint stdscr = curses.initscr() for rows in range(10): line = ''.join([chr(randint(41, 90)) for i in range(10)]) stdscr.addstr(line + '\n') icol = 3 - 1 irow = 6 - 1 ch = stdscr.instr(irow, icol, 1).decode(encoding="utf-8") stdscr.move(irow, icol + 10) stdscr.addstr('Ch...
row = 6 col = 3 howMany = 1 stuff = scrRead(row, col, howMany) other = scrRead(40, 3, 1)
Change the programming language of this snippet from Python to REXX without modifying what it does.
def legendre(a, p): return pow(a, (p - 1) // 2, p) def tonelli(n, p): assert legendre(n, p) == 1, "not a square (mod p)" q = p - 1 s = 0 while q % 2 == 0: q //= 2 s += 1 if s == 1: return pow(n, (p + 1) // 4, p) for z in range(2, p): if p - 1 == legendre(z, p...
Numeric Digits 1000000 ttest ='[(10, 13), (56, 101), (1030, 10009), (44402, 100049)]' Do While pos('(',ttest)>0 Parse Var ttest '(' n ',' p ')' ttest r = tonelli(n, p) Say "n =" n "p =" p Say " rootsΒ :" r (p - r) End Exit legendre: Procedure Parse Arg a, p return pow(a, (p - 1) % 2, p) tonelli...
Translate the given Python code snippet into REXX without altering its behavior.
def legendre(a, p): return pow(a, (p - 1) // 2, p) def tonelli(n, p): assert legendre(n, p) == 1, "not a square (mod p)" q = p - 1 s = 0 while q % 2 == 0: q //= 2 s += 1 if s == 1: return pow(n, (p + 1) // 4, p) for z in range(2, p): if p - 1 == legendre(z, p...
Numeric Digits 1000000 ttest ='[(10, 13), (56, 101), (1030, 10009), (44402, 100049)]' Do While pos('(',ttest)>0 Parse Var ttest '(' n ',' p ')' ttest r = tonelli(n, p) Say "n =" n "p =" p Say " rootsΒ :" r (p - r) End Exit legendre: Procedure Parse Arg a, p return pow(a, (p - 1) % 2, p) tonelli...
Change the programming language of this snippet from Python to REXX without modifying what it does.
class Setr(): def __init__(self, lo, hi, includelo=True, includehi=False): self.eqn = "(%i<%sX<%s%i)" % (lo, '=' if includelo else '', '=' if includehi else '', hi) def __contains__(self, X...
call quertySet 1, 3, '[1,2)' call quertySet , , '[0,2) union (1,3)' call quertySet , , '[0,1) union (2,3]' call quertySet , , '[0,2] inter (1,3)' call quertySet , , '(1,2) ∩ (2,3]' call quertySet , , '[0,2) \ (1,3)' say; say center(' star...
Generate an equivalent REXX version of this Python code.
class Setr(): def __init__(self, lo, hi, includelo=True, includehi=False): self.eqn = "(%i<%sX<%s%i)" % (lo, '=' if includelo else '', '=' if includehi else '', hi) def __contains__(self, X...
call quertySet 1, 3, '[1,2)' call quertySet , , '[0,2) union (1,3)' call quertySet , , '[0,1) union (2,3]' call quertySet , , '[0,2] inter (1,3)' call quertySet , , '(1,2) ∩ (2,3]' call quertySet , , '[0,2) \ (1,3)' say; say center(' star...
Can you help me rewrite this code in REXX instead of Python, keeping it the same logically?
from collections import defaultdict states = ["Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Missi...
!='Alabama, Alaska, Arizona, Arkansas, California, Colorado, Connecticut, Delaware, Florida, Georgia,', 'Hawaii, Idaho, Illinois, Indiana, Iowa, Kansas, Kentucky, Louisiana, Maine, Maryland, Massachusetts, ', 'Michigan, Minnesota, Mississippi, Missouri, Montana, Nebraska, Nevada, New Hampshire, ...
Convert the following code from Python to REXX, ensuring the logic remains intact.
from itertools import islice, count def superd(d): if d != int(d) or not 2 <= d <= 9: raise ValueError("argument must be integer from 2 to 9 inclusive") tofind = str(d) * d for n in count(2): if tofind in str(d * n ** d): yield n if __name__ == '__main__': for d in range(2,...
numeric digits 100 parse arg n LO HI . if n=='' | n=="," then n= 10 if LO=='' | LO=="," then LO= 2 if HI=='' | HI=="," then HI= 9 do d=LO to HI...
Change the following Python code into REXX without altering its purpose.
from itertools import islice, count def superd(d): if d != int(d) or not 2 <= d <= 9: raise ValueError("argument must be integer from 2 to 9 inclusive") tofind = str(d) * d for n in count(2): if tofind in str(d * n ** d): yield n if __name__ == '__main__': for d in range(2,...
numeric digits 100 parse arg n LO HI . if n=='' | n=="," then n= 10 if LO=='' | LO=="," then LO= 2 if HI=='' | HI=="," then HI= 9 do d=LO to HI...
Translate the given Python code snippet into REXX without altering its behavior.
from math import floor from collections import deque from typing import Dict, Generator def padovan_r() -> Generator[int, None, None]: last = deque([1, 1, 1], 4) while True: last.append(last[-2] + last[-3]) yield last.popleft() _p, _s = 1.324717957244746025960908854, 1.0453567932525329623 de...
numeric digits 40 parse arg n nF Ln cL . if n=='' | n=="," then n= 20 if nF=='' | nF=="," then nF= 64 if Ln=='' | Ln=="," then Ln= 10 if cL=='' | cL=="," then cL= 32 PR= 1.3247179572447...
Change the programming language of this snippet from Python to REXX without modifying what it does.
from __future__ import annotations from typing import Any from typing import Callable from typing import Generic from typing import Optional from typing import TypeVar from typing import Union T = TypeVar("T") class Maybe(Generic[T]): def __init__(self, value: Union[Optional[T], Maybe[T]] = None): if ...
call add 1, 2 call add 1, 2.0 call add 1, 2.0, -6 call add self, 2 exit 0 add: void= 'VOID'; f= do j=1 for arg() call bind( arg(j) ); f= f arg(j) end say ...
Write the same algorithm in REXX as shown in this Python implementation.
from collections import defaultdict import urllib.request CH2NUM = {ch: str(num) for num, chars in enumerate('abc def ghi jkl mno pqrs tuv wxyz'.split(), 2) for ch in chars} URL = 'http://www.puzzlers.org/pub/wordlists/unixdict.txt' def getwords(url): return urllib.request.urlopen(url).read().decode("utf-8").lower(...
parse arg iFID . if iFID=='' | iFID=="," then iFID='UNIXDICT.TXT' @.= 0 !.=; $.= alphabet= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' digitKey= 22233344455566677778889999 digKey= 0; ...
Generate a REXX translation of this Python snippet without changing its computational steps.
names = sorted((set(globals().keys()) | set(__builtins__.__dict__.keys())) - set('_ names i'.split())) print( '\n'.join(' '.join(names[i:i+8]) for i in range(0, len(names), 8)) )
options replace format comments java crossref savelog symbols binary class RCSpecialVariables method RCSpecialVariables() x = super.toString y = this.toString say '<super>'x'</super>' say '<this>'y'</this>' say '<class>'RCSpecialVariables.class'</class>' say '<digits>'digits'</digits>' say '<form>'form...
Generate an equivalent REXX version of this Python code.
>>> 3 3 >>> _*_, _**0.5 (9, 1.7320508075688772) >>>
parse arg N call squareIt N say result ' ◄───' exit 0 squareIt: return arg(1) ** 2
Rewrite this program in REXX while keeping its functionality equivalent to the Python version.
>>> 3 3 >>> _*_, _**0.5 (9, 1.7320508075688772) >>>
parse arg N call squareIt N say result ' ◄───' exit 0 squareIt: return arg(1) ** 2
Change the following Python code into REXX without altering its purpose.
import sys from socket import inet_aton, inet_ntoa from struct import pack, unpack args = sys.argv[1:] if len(args) == 0: args = sys.stdin.readlines() for cidr in args: dotted, size_str = cidr.split('/') size = int(size_str) numeric = unpack('!I', inet_aton(dotted))[0] binary = f'{numeric: ...
parse arg a . if a=='' | a=="," then a= '87.70.141.1/22' , '36.18.154.103/12' , '62.62.197.11/29' , '67.137.119.181/4' , '161.214.74.21/24' , ...
Produce a language-to-language conversion: from Python to REXX, same semantics.
import sys from socket import inet_aton, inet_ntoa from struct import pack, unpack args = sys.argv[1:] if len(args) == 0: args = sys.stdin.readlines() for cidr in args: dotted, size_str = cidr.split('/') size = int(size_str) numeric = unpack('!I', inet_aton(dotted))[0] binary = f'{numeric: ...
parse arg a . if a=='' | a=="," then a= '87.70.141.1/22' , '36.18.154.103/12' , '62.62.197.11/29' , '67.137.119.181/4' , '161.214.74.21/24' , ...
Convert the following code from Python to REXX, ensuring the logic remains intact.
from __future__ import print_function from scipy.misc import factorial as fact from scipy.misc import comb def perm(N, k, exact=0): return comb(N, k, exact) * fact(k, exact) exact=True print('Sample Perms 1..12') for N in range(1, 13): k = max(N-2, 1) print('%iP%i =' % (N, k), perm(N, k, exact), end=', '...
numeric digits 100 do j=1 for 12; _= do k=1 for j _=_ 'P('j","k')='perm(j,k)" " end say strip(_) end say ...
Please provide an equivalent version of this Python code in REXX.
from decimal import * D = Decimal getcontext().prec = 100 a = n = D(1) g, z, half = 1 / D(2).sqrt(), D(0.25), D(0.5) for i in range(18): x = [(a + g) * half, (a * g).sqrt()] var = x[0] - a z -= var * var * n n += n a, g = x print(a * a / z)
parse arg d .; if d=='' | d=="," then d= 500 numeric digits d+5 z= 1/4; a= 1; g= sqrt(1/2) n= 1 do j=1 until a==old; old= a x= (a+g) * .5; g= sqrt(a*g) z= z - n*(x-a)**2; n= n+n; a= x end ...
Convert this Python block to REXX, preserving its control flow and logic.
from decimal import * D = Decimal getcontext().prec = 100 a = n = D(1) g, z, half = 1 / D(2).sqrt(), D(0.25), D(0.5) for i in range(18): x = [(a + g) * half, (a * g).sqrt()] var = x[0] - a z -= var * var * n n += n a, g = x print(a * a / z)
parse arg d .; if d=='' | d=="," then d= 500 numeric digits d+5 z= 1/4; a= 1; g= sqrt(1/2) n= 1 do j=1 until a==old; old= a x= (a+g) * .5; g= sqrt(a*g) z= z - n*(x-a)**2; n= n+n; a= x end ...
Generate a REXX translation of this Python snippet without changing its computational steps.
def sieve(limit): primes = [] c = [False] * (limit + 1) p = 3 while True: p2 = p * p if p2 > limit: break for i in range(p2, limit, 2 * p): c[i] = True while True: p += 2 if not c[p]: break for i in range(3, limit, 2): if not c[i...
parse arg a if a='' | a="," then a= '500 -500 -1000 -2000 -4000 -8000 -16000' , '-32000 -64000 -128000 -512000 -1024000' do k=1 for words(a); H=word(a, k) neg= H<1 H= abs(H) ...
Preserve the algorithm and functionality while converting the code from Python to REXX.
from pyprimes import nprimes from functools import reduce primelist = list(nprimes(1000001)) def primorial(n): return reduce(int.__mul__, primelist[:n], 1) if __name__ == '__main__': print('First ten primorals:', [primorial(n) for n in range(10)]) for e in range(7): n = 10**e print('...
parse arg N H . if N=='' | N==',' then N= 10 if H=='' | H==',' then H= 100000 numeric digits 600000 w= length( commas( digits() ) ) @.=.; @.0= 1; @.1= 2; @.2= 3; @.3= 5; @.4= 7; @.5= 11; @.6= 13...
Convert this Python block to REXX, preserving its control flow and logic.
from fractions import Fraction from math import ceil class Fr(Fraction): def __repr__(self): return '%s/%s' % (self.numerator, self.denominator) def ef(fr): ans = [] if fr >= 1: if fr.denominator == 1: return [[int(fr)], Fr(0, 1)] intfr = int(fr) ans, fr = [[int...
parse arg fract '' -1 t; z=$egyptF(fract) if t\==. then say fract ' ───► ' z return z $egyptF: parse arg z 1 zn '/' zd,,$; if zd=='' then zd=1 if z='' then call erx "no fraction was specified." if zd==0 then call erx "denominator can'...
Port the following code from Python to REXX with equivalent syntax and logic.
from fractions import Fraction from math import ceil class Fr(Fraction): def __repr__(self): return '%s/%s' % (self.numerator, self.denominator) def ef(fr): ans = [] if fr >= 1: if fr.denominator == 1: return [[int(fr)], Fr(0, 1)] intfr = int(fr) ans, fr = [[int...
parse arg fract '' -1 t; z=$egyptF(fract) if t\==. then say fract ' ───► ' z return z $egyptF: parse arg z 1 zn '/' zd,,$; if zd=='' then zd=1 if z='' then call erx "no fraction was specified." if zd==0 then call erx "denominator can'...
Rewrite the snippet below in REXX so it works the same as the original Python code.
from numpy import * def Legendre(n,x): x=array(x) if (n==0): return x*0+1.0 elif (n==1): return x else: return ((2.0*n-1.0)*x*Legendre(n-1,x)-(n-1)*Legendre(n-2,x))/n def DLegendre(n,x): x=array(x) if (n==0): return x*0 elif (n==1): return x*0+1.0 else: return (n/(x**2-1.0))*(x*Legendre(n,x)...
* 31.10.2013 Walter Pachl Translation from REXX (from PL/I) * using ooRexx' rxmath package * which limits the precision to 16 digits *--------------------------------------------------------------------*/ prec=60 Numeric Digits prec epsilon=1/10**prec pi=3.14159265358...
Generate a REXX translation of this Python snippet without changing its computational steps.
def cut_it(h, w): dirs = ((1, 0), (-1, 0), (0, -1), (0, 1)) if h % 2: h, w = w, h if h % 2: return 0 if w == 1: return 1 count = 0 next = [w + 1, -w - 1, -1, 1] blen = (h + 1) * (w + 1) - 1 grid = [False] * (blen + 1) def walk(y, x, count): if not y or y == h or not x or x ...
numeric digits 20 parse arg N .; if N=='' | N=="," then N= 10 dir.= 0; dir.0.1= -1; dir.1.0= -1; dir.2.1= 1; dir.3.0= 1 do y=2 to N; say do x=1 for y; if x//2 & y//2 then iterate z= solve(y,x,1); _= comm...
Change the following Python code into REXX without altering its purpose.
def cut_it(h, w): dirs = ((1, 0), (-1, 0), (0, -1), (0, 1)) if h % 2: h, w = w, h if h % 2: return 0 if w == 1: return 1 count = 0 next = [w + 1, -w - 1, -1, 1] blen = (h + 1) * (w + 1) - 1 grid = [False] * (blen + 1) def walk(y, x, count): if not y or y == h or not x or x ...
numeric digits 20 parse arg N .; if N=='' | N=="," then N= 10 dir.= 0; dir.0.1= -1; dir.1.0= -1; dir.2.1= 1; dir.3.0= 1 do y=2 to N; say do x=1 for y; if x//2 & y//2 then iterate z= solve(y,x,1); _= comm...
Transform the following Python implementation into REXX, maintaining the same output and logic.
import datetime import math primes = [ 3, 5 ] cutOff = 200 bigUn = 100_000 chunks = 50 little = bigUn / chunks tn = " cuban prime" print ("The first {:,}{}s:".format(cutOff, tn)) c = 0 showEach = True u = 0 v = 1 st = datetime.datetime.now() for i in range(1, int(math.pow(2,20))): found = False u += 6 v += u ...
numeric digits 20 parse arg N . if N=='' | N=="," then N= 200 Nth= N<0; N= abs(N) @.=0; @.0=1; @.2=1; @.3=1; @.4=1; @.5=1; @.6=1; @.8=1 sw= linesize() - 1; if sw<1 then sw= 79 w=12; ...
Rewrite this program in REXX while keeping its functionality equivalent to the Python version.
from __future__ import division size(300, 260) background(255) x = floor(random(width)) y = floor(random(height)) for _ in range(30000): v = floor(random(3)) if v == 0: x = x / 2 y = y / 2 colour = color(0, 255, 0) elif v == 1: x = width / 2 + (width / 2 - x) / 2 ...
parse value scrsize() with sd sw . sw= sw - 2 sd= sd - 4 parse arg pts chr seed . if pts=='' | pts=="," then pts= 1000000 if chr=='' | chr=="," then chr= 'βˆ™' if datatype(seed,'W...
Preserve the algorithm and functionality while converting the code from Python to REXX.
from __future__ import division size(300, 260) background(255) x = floor(random(width)) y = floor(random(height)) for _ in range(30000): v = floor(random(3)) if v == 0: x = x / 2 y = y / 2 colour = color(0, 255, 0) elif v == 1: x = width / 2 + (width / 2 - x) / 2 ...
parse value scrsize() with sd sw . sw= sw - 2 sd= sd - 4 parse arg pts chr seed . if pts=='' | pts=="," then pts= 1000000 if chr=='' | chr=="," then chr= 'βˆ™' if datatype(seed,'W...
Translate this program into REXX but keep the logic exactly as in Python.
from itertools import product, combinations, izip scoring = [0, 1, 3] histo = [[0] * 10 for _ in xrange(4)] for results in product(range(3), repeat=6): s = [0] * 4 for r, g in izip(results, combinations(range(4), 2)): s[g[0]] += scoring[r] s[g[1]] += scoring[2 - r] for h, v in izip(histo,...
results = '000000' games = '12 13 14 23 24 34' points.=0 records.=0 Do Until nextResult(results)=0 records.=0 Do i=1 To 6 r=substr(results,i,1) g=word(games,i); Parse Var g g1 +1 g2 Select When r='2' Then records.g1=records.g1+3 When r='1' Th...
Rewrite this program in REXX while keeping its functionality equivalent to the Python version.
from collections import namedtuple from pprint import pprint as pp OpInfo = namedtuple('OpInfo', 'prec assoc') L, R = 'Left Right'.split() ops = { '^': OpInfo(prec=4, assoc=R), '*': OpInfo(prec=3, assoc=L), '/': OpInfo(prec=3, assoc=L), '+': OpInfo(prec=2, assoc=L), '-': OpInfo(prec=2, assoc=L), '(': OpInfo(pre...
parse arg x if x='' then x= '3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3' ox=x x='(' space(x) ") " #=words(x) do i=1 for #; @.i=word(x, i) end tell=1 ...
Please provide an equivalent version of this Python code in REXX.
import math def perlin_noise(x, y, z): X = math.floor(x) & 255 Y = math.floor(y) & 255 Z = math.floor(z) & 255 x -= math.floor(x) y -= math.floor(y) z -= math.floor(z) u = fade(x) ...
_= 97a0895b5a0f830dc95f6035c2e907e18c24671e458e086325f0150a17be0694f778ea4b001ac53e5efcdbcb75230b2039b12158ed953857ae147d88aba844af, ||4aa547868b301ba64d929ee7536fe57a3cd385e6dc695c29372ef528f4668f3641193fa101d85049d14c84bbd05912a9c8c4878274bc9f56a4646dc6adba0340, ||34d9e2fa7c7b05ca2693767eff5255d4cfce3be32f103a11b6...
Change the following Python code into REXX without altering its purpose.
import os from math import pi, sin au_header = bytearray( [46, 115, 110, 100, 0, 0, 0, 24, 255, 255, 255, 255, 0, 0, 0, 3, 0, 0, 172, 68, 0, 0, 0, 1]) def f(x, freq): "Compute sine wave as 16-bi...
parse arg freq time . if freq=='' | freq=="," then freq= 880 if time=='' | time=="," then time= 5 call sound freq, time exit 0
Keep all operations the same but rewrite the snippet in REXX.
from __future__ import print_function import matplotlib.pyplot as plt class AStarGraph(object): def __init__(self): self.barriers = [] self.barriers.append([(2,4),(2,5),(2,6),(3,6),(4,6),(5,6),(5,5),(5,4),(5,3),(5,2),(4,2),(3,2)]) def heuristic(self, start, goal): D = 1 D2 = 1 dx = abs(start[0] -...
parse arg N sCol sRow . if N=='' | N=="," then N=8 if sCol=='' | sCol=="," then sCol=1 if sRow=='' | sRow=="," then sRow=1 beg= '─0─' o.=.; p.=0 times=0 ...
Ensure the translated REXX code behaves exactly like the original Python snippet.
from __future__ import print_function import matplotlib.pyplot as plt class AStarGraph(object): def __init__(self): self.barriers = [] self.barriers.append([(2,4),(2,5),(2,6),(3,6),(4,6),(5,6),(5,5),(5,4),(5,3),(5,2),(4,2),(3,2)]) def heuristic(self, start, goal): D = 1 D2 = 1 dx = abs(start[0] -...
parse arg N sCol sRow . if N=='' | N=="," then N=8 if sCol=='' | sCol=="," then sCol=1 if sRow=='' | sRow=="," then sRow=1 beg= '─0─' o.=.; p.=0 times=0 ...