Skip to content

Instantly share code, notes, and snippets.

@naitoh
Created February 1, 2019 12:32
Show Gist options
  • Save naitoh/90713db966916ccbe4851f21f8b736ab to your computer and use it in GitHub Desktop.
Save naitoh/90713db966916ccbe4851f21f8b736ab to your computer and use it in GitHub Desktop.
py2rb master 0d2fbc5a86b82707a1d83241a21af6b2cc22c0b8
-- [python] ---------
* tests/algorithms/sqrt.py
def abs(x):
if x > 0:
return x
else:
return -x
def sqrt(x):
eps = 1e-10
x = float(x)
r = x/2
residual = r**2 - x
while abs(residual) > eps:
r_d = -residual/(2*r)
r += r_d
residual = r**2 - x
return r
def p(x):
prec = 11
l = list(iter(str(x)))[:prec]
if not "." in l:
l.append(".")
l.append("0")
while len(l) < prec:
l.append("0")
s = ""
for c in l:
s += c
return s
print((p(sqrt(1))))
print((p(sqrt(2))))
print((p(sqrt(3))))
print((p(sqrt(4))))
print((p(sqrt(5))))
print((p(sqrt(6))))
print((p(sqrt(7000))))
-- [ruby] -----------
$ py2rb tests/algorithms/sqrt.py
def abs(x)
if x > 0
return x
else
return -x
end
end
def sqrt(x)
eps = 1e-10
x = x.to_f
r = x / 2.to_f
residual = (r ** 2) - x
while residual.abs > eps
r_d = (-residual) / (2 * r).to_f
r += r_d
residual = (r ** 2) - x
end
return r
end
def p(x)
prec = 11
l = x.to_s.each.to_a[0...prec]
if is_bool(!l.include?("."))
l.push(".")
l.push("0")
end
while l.size < prec
l.push("0")
end
s = ""
for c in l
s += c
end
return s
end
print(p(sqrt(1)))
print(p(sqrt(2)))
print(p(sqrt(3)))
print(p(sqrt(4)))
print(p(sqrt(5)))
print(p(sqrt(6)))
print(p(sqrt(7000)))
-- [python] ---------
* tests/algorithms/triangulation.py
def abs(x):
if x > 0:
return x
else:
return -x
def sqrt(x):
eps = 1e-10
x = float(x)
r = x/2
residual = r**2 - x
while abs(residual) > eps:
r_d = -residual/(2*r)
r += r_d
residual = r**2 - x
return r
def is_on_the_left(c, a, b, pts_list):
ax, ay = pts_list[a]
bx, by = pts_list[b]
cx, cy = pts_list[c]
ux = float(bx - ax)
uy = float(by - ay)
vx = float(cx - ax)
vy = float(cy - ay)
return (ux*vy - uy*vx > 0)
def criterion(a, b, c, pts_list):
ax, ay = pts_list[a]
bx, by = pts_list[b]
cx, cy = pts_list[c]
ux = float(ax - cx)
uy = float(ay - cy)
vx = float(bx - cx)
vy = float(by - cy)
len_u = sqrt(ux*ux + uy*uy)
len_v = sqrt(vx*vx + vy*vy)
return (ux*vx + uy*vy)/(len_u*len_v)
def find_third_point(a, b, pts_list, edges):
"""
Take a boundary edge (a,b), and in the list of points
find a point 'c' that lies on the left of ab and maximizes
the angle acb
"""
found = 0
minimum = 10**8 #this is dirty
c_index = -1
pt_index = -1
for c_point in pts_list:
c_index += 1
if c_index != a and c_index != b and is_on_the_left(c_index, a, b, pts_list):
edge_intersects = \
edge_intersects_edges((a, c_index), pts_list, edges) or \
edge_intersects_edges((b, c_index), pts_list, edges)
if not edge_intersects:
crit = criterion(a, b, c_index, pts_list)
if crit < minimum:
minimum = crit
pt_index = c_index
found = 1
if found == 0:
raise TriangulationError("ERROR: Optimal point not found in find_third_point().")
return pt_index
def lies_inside(c, bdy_edges):
for edge in bdy_edges:
a,b = edge
if c == a or c == b: return False
return True
def is_boundary_edge(a, b, bdy_edges):
"""
Checks whether edge (a, b) is in the list of boundary edges
"""
for edge in bdy_edges:
a0, b0 = edge
if a == a0 and b == b0:
return True
return False
def triangulate_af(pts_list, bdy_edges):
"""
Create a triangulation using the advancing front method.
"""
# create empty list of elements
elems = []
bdy_edges = bdy_edges[:]
# main loop
while bdy_edges != []:
# take the last item from the list of bdy edges (and remove it)
a,b = bdy_edges.pop()
c = find_third_point(a, b, pts_list, bdy_edges)
elems.append((a,b,c))
if is_boundary_edge(c, a, bdy_edges):
bdy_edges.remove((c,a))
else:
bdy_edges.append((a,c))
if is_boundary_edge(b, c, bdy_edges):
bdy_edges.remove((b,c))
else:
bdy_edges.append((c,b))
return elems
def ccw(a, b, c):
return (c[1]-a[1])*(b[0]-a[0]) > (b[1]-a[1])*(c[0]-a[0])
def intersect(a, b, c, d):
return ccw(a, c, d) != ccw(b, c, d) and ccw(a, b, c) != ccw(a, b, d)
def two_edges_intersect(nodes, e1, e2):
"""
Checks whether the two edges intersect.
It assumes that e1 and e2 are tuples of (a_id, b_id) of ids into the nodes.
"""
a = nodes[e1[0]]
b = nodes[e1[1]]
c = nodes[e2[0]]
d = nodes[e2[1]]
return intersect(a, b, c, d)
def any_edges_intersect(nodes, edges):
"""
Returns True if any two edges intersect.
"""
for i in range(len(edges)):
for j in range(i+1, len(edges)):
e1 = edges[i]
e2 = edges[j]
if e1[1] == e2[0] or e1[0] == e2[1]:
continue
if two_edges_intersect(nodes, e1, e2):
return True
return False
def edge_intersects_edges(e1, nodes, edges):
"""
Returns True if "e1" intersects any edge from "edges".
"""
for i in range(len(edges)):
e2 = edges[i]
if e1[1] == e2[0] or e1[0] == e2[1]:
continue
if two_edges_intersect(nodes, e1, e2):
return True
return False
def example1():
nodes = [
(0, 0),
(1, 0),
(1, 1),
(0, 1),
]
edges = [(0, 1), (1, 2), (2, 3), (3, 0)]
elems = triangulate_af(nodes, edges)
return nodes, edges, elems
def example2():
nodes = [
(0, 0),
(1, 0),
(2, 1),
(2, 2),
(1, 2),
(0.5, 1.5),
(0, 1),
]
edges = [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 0)]
elems = triangulate_af(nodes, edges)
return nodes, edges, elems
nodes, edges, elems = example1()
print("nodes", nodes)
print("edges", edges)
print("elems", elems)
if not any_edges_intersect(nodes, edges):
print("ok")
print()
nodes, edges, elems = example2()
print("nodes", nodes)
print("edges", edges)
print("elems", elems)
if not any_edges_intersect(nodes, edges):
print("ok")
-- [ruby] -----------
$ py2rb tests/algorithms/triangulation.py
def abs(x)
if x > 0
return x
else
return -x
end
end
def sqrt(x)
eps = 1e-10
x = x.to_f
r = x / 2.to_f
residual = (r ** 2) - x
while residual.abs > eps
r_d = (-residual) / (2 * r).to_f
r += r_d
residual = (r ** 2) - x
end
return r
end
def is_on_the_left(c, a, b, pts_list)
ax,ay = pts_list[a]
bx,by = pts_list[b]
cx,cy = pts_list[c]
ux = (bx - ax).to_f
uy = (by - ay).to_f
vx = (cx - ax).to_f
vy = (cy - ay).to_f
return (ux * vy) - (uy * vx) > 0
end
def criterion(a, b, c, pts_list)
ax,ay = pts_list[a]
bx,by = pts_list[b]
cx,cy = pts_list[c]
ux = (ax - cx).to_f
uy = (ay - cy).to_f
vx = (bx - cx).to_f
vy = (by - cy).to_f
len_u = sqrt((ux * ux) + (uy * uy))
len_v = sqrt((vx * vx) + (vy * vy))
return ((ux * vx) + (uy * vy)) / (len_u * len_v).to_f
end
def find_third_point(a, b, pts_list, edges)
#
# Take a boundary edge (a,b), and in the list of points
# find a point 'c' that lies on the left of ab and maximizes
# the angle acb
#
found = 0
minimum = 10 ** 8
c_index = -1
pt_index = -1
for c_point in pts_list
c_index += 1
if is_bool(c_index != a && c_index != b && is_on_the_left(c_index, a, b, pts_list))
edge_intersects = edge_intersects_edges([a, c_index], pts_list, edges) || edge_intersects_edges([b, c_index], pts_list, edges)
if is_bool(!edge_intersects)
crit = criterion(a, b, c_index, pts_list)
if crit < minimum
minimum = crit
pt_index = c_index
found = 1
end
end
end
end
if found == 0
raise TriangulationError, "ERROR: Optimal point not found in find_third_point()."
end
return pt_index
end
def lies_inside(c, bdy_edges)
for edge in bdy_edges
a,b = edge
if is_bool(c == a || c == b)
return false
end
end
return true
end
def is_boundary_edge(a, b, bdy_edges)
#
# Checks whether edge (a, b) is in the list of boundary edges
#
for edge in bdy_edges
a0,b0 = edge
if is_bool(a == a0 && b == b0)
return true
end
end
return false
end
def triangulate_af(pts_list, bdy_edges)
#
# Create a triangulation using the advancing front method.
#
elems = []
bdy_edges = bdy_edges[0..-1]
while bdy_edges != []
a,b = bdy_edges.pop()
c = find_third_point(a, b, pts_list, bdy_edges)
elems.push([a, b, c])
if is_bool(is_boundary_edge(c, a, bdy_edges))
bdy_edges.remove([c, a])
else
bdy_edges.push([a, c])
end
if is_bool(is_boundary_edge(b, c, bdy_edges))
bdy_edges.remove([b, c])
else
bdy_edges.push([c, b])
end
end
return elems
end
def ccw(a, b, c)
return (c[1] - a[1]) * (b[0] - a[0]) > (b[1] - a[1]) * (c[0] - a[0])
end
def intersect(a, b, c, d)
return ccw(a, c, d) != ccw(b, c, d) && ccw(a, b, c) != ccw(a, b, d)
end
def two_edges_intersect(nodes, e1, e2)
#
# Checks whether the two edges intersect.
#
# It assumes that e1 and e2 are tuples of (a_id, b_id) of ids into the nodes.
#
a = nodes[e1[0]]
b = nodes[e1[1]]
c = nodes[e2[0]]
d = nodes[e2[1]]
return intersect(a, b, c, d)
end
def any_edges_intersect(nodes, edges)
#
# Returns True if any two edges intersect.
#
for i in edges.size.times
for j in (i + 1).upto(edges.size-1)
e1 = edges[i]
e2 = edges[j]
if is_bool(e1[1] == e2[0] || e1[0] == e2[1])
next
end
if is_bool(two_edges_intersect(nodes, e1, e2))
return true
end
end
end
return false
end
def edge_intersects_edges(e1, nodes, edges)
#
# Returns True if \"e1\" intersects any edge from \"edges\".
#
for i in edges.size.times
e2 = edges[i]
if is_bool(e1[1] == e2[0] || e1[0] == e2[1])
next
end
if is_bool(two_edges_intersect(nodes, e1, e2))
return true
end
end
return false
end
def example1()
nodes = [[0, 0], [1, 0], [1, 1], [0, 1]]
edges = [[0, 1], [1, 2], [2, 3], [3, 0]]
elems = triangulate_af(nodes, edges)
return [nodes, edges, elems]
end
def example2()
nodes = [[0, 0], [1, 0], [2, 1], [2, 2], [1, 2], [0.5, 1.5], [0, 1]]
edges = [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 0]]
elems = triangulate_af(nodes, edges)
return [nodes, edges, elems]
end
nodes,edges,elems = example1()
print("nodes", nodes)
print("edges", edges)
print("elems", elems)
if is_bool(!any_edges_intersect(nodes, edges))
print("ok")
end
print()
nodes,edges,elems = example2()
print("nodes", nodes)
print("edges", edges)
print("elems", elems)
if is_bool(!any_edges_intersect(nodes, edges))
print("ok")
end
-- [python] ---------
* tests/basic/assert.py
try:
assert True, "no message"
except AssertionError as err:
print('AssertionError :', err)
except:
print('Error :')
try:
assert False, "error message"
except AssertionError as err:
print('AssertionError :', err)
except:
print('Error :')
-- [ruby] -----------
$ py2rb tests/basic/assert.py
begin
raise "no message" unless true
rescue RuntimeError => err
print("AssertionError :", err)
rescue
print("Error :")
end
begin
raise "error message" unless false
rescue RuntimeError => err
print("AssertionError :", err)
rescue
print("Error :")
end
-- [python] ---------
* tests/basic/assign.py
x = y = 1
print(x)
print(y)
y += 3
print(x)
print(y)
x, y = 1, 2
print(x)
print(y)
x = [3]
print(x)
x,y = [3,2]
print(x)
print(y)
x, = [3]
print(x)
-- [ruby] -----------
$ py2rb tests/basic/assign.py
x = y = 1
print(x)
print(y)
y += 3
print(x)
print(y)
x,y = [1, 2]
print(x)
print(y)
x = [3]
print(x)
x,y = [3, 2]
print(x)
print(y)
x, = [3]
print(x)
-- [python] ---------
* tests/basic/assign_slice.py
a = [1,2,3,4,5,6,7]
a[4:6] = ['a','b']
#def show(x):
def show(a):
print("----")
for x in a:
print(x)
show(a)
a[2:4] = ['z']
show(a)
a[0:2] = ['abc','def','abc','def']
show(a)
-- [ruby] -----------
$ py2rb tests/basic/assign_slice.py
a = [1, 2, 3, 4, 5, 6, 7]
a[4...6] = ["a", "b"]
def show(a)
print("----")
for x in a
print(x)
end
end
show(a)
a[2...4] = ["z"]
show(a)
a[0...2] = ["abc", "def", "abc", "def"]
show(a)
-- [python] ---------
* tests/basic/augassign.py
a = 1
a += 1
print(a)
a += 3
print(a)
a -= 2
print(a)
-- [ruby] -----------
$ py2rb tests/basic/augassign.py
a = 1
a += 1
print(a)
a += 3
print(a)
a -= 2
print(a)
-- [python] ---------
* tests/basic/augassign2.py
def f1(x):
return x
def f2(x):
return x + 5
def f3(x):
a = x + 1
return a - 5
def f3b(x):
a = x + 1
a -= 5
return a
def f3c(x):
a = float(x) + 1
a /= 5
return a
def f3d(x):
a = x + 1
a *= 5
return a
def f3e(x):
a = x + 1
a += 5
return a
def f4(x):
if x:
return 5
else:
return 6
def f5(x):
a = 1
if x:
a = a + 1
else:
a = a - 1
return a
print(f1(3))
print(f2(3))
print(f3(3))
print(f3b(3))
print(f3c(3))
print(f3d(3))
print(f3e(3))
print(f4(True))
print(f4(False))
print(f5(True))
print(f5(False))
-- [ruby] -----------
$ py2rb tests/basic/augassign2.py
def f1(x)
return x
end
def f2(x)
return x + 5
end
def f3(x)
a = x + 1
return a - 5
end
def f3b(x)
a = x + 1
a -= 5
return a
end
def f3c(x)
a = x.to_f + 1
a = a / 5.to_f
return a
end
def f3d(x)
a = x + 1
a *= 5
return a
end
def f3e(x)
a = x + 1
a += 5
return a
end
def f4(x)
if is_bool(x)
return 5
else
return 6
end
end
def f5(x)
a = 1
if is_bool(x)
a = a + 1
else
a = a - 1
end
return a
end
print(f1(3))
print(f2(3))
print(f3(3))
print(f3b(3))
print(f3c(3))
print(f3d(3))
print(f3e(3))
print(f4(true))
print(f4(false))
print(f5(true))
print(f5(false))
-- [python] ---------
* tests/basic/binaryops.py
x = 1
y = 2
z = 3
print(10 % z)
print(y*x)
print(y-z)
print(y+x+z)
print((5 + 4) / 2)
print(9 / 2)
print(9 // 2)
print(10 ** 2)
-- [ruby] -----------
$ py2rb tests/basic/binaryops.py
x = 1
y = 2
z = 3
print(10 % z)
print(y * x)
print(y - z)
print((y + x) + z)
print((5 + 4) / 2.to_f)
print(9 / 2.to_f)
print(9 / 2)
print(10 ** 2)
-- [python] ---------
* tests/basic/break.py
x = 0
while True:
x = x + 1
print(x)
if x > 10:
break
-- [ruby] -----------
$ py2rb tests/basic/break.py
x = 0
while true
x = x + 1
print(x)
if x > 10
break
end
end
-- [python] ---------
* tests/basic/class.py
class foobar(object):
x = 1
def __init__(self):
self.foovar = 1
def foo(self,x):
self.foovar = self.foovar + x
def bar(self):
print(self.foovar)
f = foobar()
f.bar()
f.foo(1)
f.foo(2)
f.bar()
f.bar()
f.foo(-1)
f.bar()
f.foo(7)
f.bar()
-- [ruby] -----------
$ py2rb tests/basic/class.py
class Foobar
@@x = 1
def initialize()
@foovar = 1
end
def foo(x)
@foovar = @foovar + x
end
def bar()
print(@foovar)
end
def self.x; @@x; end
def self.x=(val); @@x=val; end
def x; @x = @@x if @x.nil?; @x; end
def x=(val); @x=val; end
end
f = Foobar.new()
f.bar()
f.foo(1)
f.foo(2)
f.bar()
f.bar()
f.foo(-1)
f.bar()
f.foo(7)
f.bar()
-- [python] ---------
* tests/basic/class2.py
class Class1(object):
def __init__(self):
pass
def test1(self):
return 5
class Class2(object):
def test1(self):
return 6
class Class3(object):
def test1(self, x):
return self.test2(x)-1
def test2(self, x):
return 2*x
a = Class1()
print(a.test1())
a = Class2()
print(a.test1())
a = Class3()
print(a.test1(3))
print(a.test2(3))
-- [ruby] -----------
$ py2rb tests/basic/class2.py
class Class1
def initialize()
# pass
end
def test1()
return 5
end
end
class Class2
def test1()
return 6
end
end
class Class3
def test1(x)
return test2(x) - 1
end
def test2(x)
return 2 * x
end
end
a = Class1.new()
print(a.test1())
a = Class2.new()
print(a.test1())
a = Class3.new()
print(a.test1(3))
print(a.test2(3))
-- [python] ---------
* tests/basic/class3.py
class A(object):
v = 1
a = A()
XX = A
x = XX()
print(x.v)
-- [ruby] -----------
$ py2rb tests/basic/class3.py
class A
@@v = 1
def self.v; @@v; end
def self.v=(val); @@v=val; end
def v; @v = @@v if @v.nil?; @v; end
def v=(val); @v=val; end
end
a = A.new()
XX = A
x = XX.()
print(x.v)
-- [python] ---------
* tests/basic/class4.py
def create(cls):
return cls()
class A(object):
def m(self):
print("A.m()")
a = A()
a.m()
b = create(A)
b.m()
-- [ruby] -----------
$ py2rb tests/basic/class4.py
def create(cls)
return cls.()
end
class A
def m()
print("A.m()")
end
end
a = A.new()
a.m()
b = create(A)
b.m()
-- [python] ---------
* tests/basic/class5.py
def create(cls):
return cls()
class A:
def m(self):
print("A.m()")
a = A()
a.m()
b = create(A)
b.m()
-- [ruby] -----------
$ py2rb tests/basic/class5.py
def create(cls)
return cls.()
end
class A
def m()
print("A.m()")
end
end
a = A.new()
a.m()
b = create(A)
b.m()
-- [python] ---------
* tests/basic/class6.py
def create(cls):
return cls()
class A:
def __init__(self):
self.msg = "A.m()"
def m(self):
print(self.msg)
a = A()
a.m()
b = create(A)
b.m()
-- [ruby] -----------
$ py2rb tests/basic/class6.py
def create(cls)
return cls.()
end
class A
def initialize()
@msg = "A.m()"
end
def m()
print(@msg)
end
end
a = A.new()
a.m()
b = create(A)
b.m()
-- [python] ---------
* tests/basic/closure.py
def factory(x):
def fn():
return x
return fn
a1 = factory("foo")
a2 = factory("bar")
print(a1())
print(a2())
-- [ruby] -----------
$ py2rb tests/basic/closure.py
def factory(x)
fn = lambda do
return x
end
return fn
end
a1 = factory("foo")
a2 = factory("bar")
print(a1.())
print(a2.())
-- [python] ---------
* tests/basic/closure_in_class.py
class foo(object):
def factory(self, x):
def fn():
return x
return fn
f = foo()
a1 = f.factory("foo")
a2 = f.factory("bar")
print(a1())
print(a2())
-- [ruby] -----------
$ py2rb tests/basic/closure_in_class.py
class Foo
def factory(x)
fn = lambda do
return x
end
return fn
end
end
f = Foo.new()
a1 = f.factory("foo")
a2 = f.factory("bar")
print(a1.())
print(a2.())
-- [python] ---------
* tests/basic/continue.py
for x in range(0,20):
if x > 10 and x < 17:
continue
print(x)
-- [ruby] -----------
$ py2rb tests/basic/continue.py
for x in 0.upto(20-1)
if is_bool(x > 10 && x < 17)
next
end
print(x)
end
-- [python] ---------
* tests/basic/del_array.py
mylist = [1,2,3,4,5]
del mylist[3]
for x in range(0,len(mylist)):
print(mylist[x])
-- [ruby] -----------
$ py2rb tests/basic/del_array.py
mylist = [1, 2, 3, 4, 5]
mylist.delete_at(3)
for x in 0.upto(mylist.size-1)
print(mylist[x])
end
-- [python] ---------
* tests/basic/del_attr.py
class spam:
def __init__(self):
self.eggs = 0
def addegg(self):
try:
if self.eggs:
self.eggs += 1
else:
self.eggs = 1
except:
self.eggs = 1
def printit(self):
try:
if self.eggs:
print(self.eggs)
else:
print("no eggs")
except:
print("no eggs")
s = spam()
s.addegg()
s.addegg()
s.printit()
s.addegg()
s.printit()
del s.eggs
s.printit()
s.addegg()
s.addegg()
s.printit()
-- [ruby] -----------
$ py2rb tests/basic/del_attr.py
class Spam
def initialize()
@eggs = 0
end
def addegg()
begin
if is_bool(@eggs)
@eggs += 1
else
@eggs = 1
end
rescue
@eggs = 1
end
end
def printit()
begin
if is_bool(@eggs)
print(@eggs)
else
print("no eggs")
end
rescue
print("no eggs")
end
end
end
s = Spam.new()
s.addegg()
s.addegg()
s.printit()
s.addegg()
s.printit()
s.instance_eval { remove_instance_variable(:@eggs) }
s.printit()
s.addegg()
s.addegg()
s.printit()
-- [python] ---------
* tests/basic/del_dict.py
mydict = {}
mydict["abc"] = "def"
mydict["def"] = "abc"
mydict["xyz"] = "rst"
print(mydict["abc"])
print(mydict["def"])
print(mydict["xyz"])
del mydict["def"]
if "abc" in mydict:
print("abc in mydict")
else:
print("abc not in mydict")
if "def" in mydict:
print("def in mydict")
else:
print("def not in mydict")
if "xyz" in mydict:
print("xyz in mydict")
else:
print("xyz not in mydict")
-- [ruby] -----------
$ py2rb tests/basic/del_dict.py
mydict = {}
mydict["abc"] = "def"
mydict["def"] = "abc"
mydict["xyz"] = "rst"
print(mydict["abc"])
print(mydict["def"])
print(mydict["xyz"])
mydict.delete("def")
if mydict.include?("abc")
print("abc in mydict")
else
print("abc not in mydict")
end
if mydict.include?("def")
print("def in mydict")
else
print("def not in mydict")
end
if mydict.include?("xyz")
print("xyz in mydict")
else
print("xyz not in mydict")
end
-- [python] ---------
* tests/basic/del_slice.py
mylist = [1,2,3,4,5]
del mylist[1:3]
for x in range(0,len(mylist)):
print(mylist[x])
-- [ruby] -----------
$ py2rb tests/basic/del_slice.py
mylist = [1, 2, 3, 4, 5]
mylist.slice!(1...3)
for x in 0.upto(mylist.size-1)
print(mylist[x])
end
-- [python] ---------
* tests/basic/dictcomp1.py
foo = {key.upper(): data * 2 for key, data in {'a': 7, 'b': 5}.items()}
print(foo['A'])
print(foo['B'])
-- [ruby] -----------
$ py2rb tests/basic/dictcomp1.py
foo = {"a" => 7, "b" => 5}.to_a().map{|key, data|[key.upcase(), data * 2]}.to_h
print(foo["A"])
print(foo["B"])
-- [python] ---------
* tests/basic/dictcomp2.py
foo = {key.upper(): data * 2 for key, data in {'a': 7, 'b': 5}.items() if data > 6}
print(len(foo))
print(foo['A'])
-- [ruby] -----------
$ py2rb tests/basic/dictcomp2.py
foo = {"a" => 7, "b" => 5}.to_a().select{|key, data| data > 6}.map{|key, data|[key.upcase(), data * 2]}.to_h
print(foo.size)
print(foo["A"])
-- [python] ---------
* tests/basic/dictionary.py
foo = { 'a':'b', 'c':'d' }
print(foo['a'])
print(foo['c'])
if 'a' in foo:
print("a in foo")
-- [ruby] -----------
$ py2rb tests/basic/dictionary.py
foo = {"a" => "b", "c" => "d"}
print(foo["a"])
print(foo["c"])
if foo.include?("a")
print("a in foo")
end
-- [python] ---------
* tests/basic/dictionary2.py
def dict1():
a = {1: 3, "s": 4}
return len(a)
def dict2():
a = {1: 3, "s": 4}
b = a[1] + a["s"]
return b
def dict3():
a = {}
a[1] = 3
a["s"] = 4
b = a[1] + a["s"]
return b
print(dict1())
print(dict2())
print(dict3())
-- [ruby] -----------
$ py2rb tests/basic/dictionary2.py
def dict1()
a = {1 => 3, "s" => 4}
return a.size
end
def dict2()
a = {1 => 3, "s" => 4}
b = a[1] + a["s"]
return b
end
def dict3()
a = {}
a[1] = 3
a["s"] = 4
b = a[1] + a["s"]
return b
end
print(dict1())
print(dict2())
print(dict3())
-- [python] ---------
* tests/basic/dictionary3.py
foo = dict()
foo['a'] = 'b'
foo['c'] = 'd'
print(foo['a'])
print(foo['c'])
bar = dict([('a', 1), ('b', 2), ('c', 3)])
if 'a' in bar:
print("a in bar")
-- [ruby] -----------
$ py2rb tests/basic/dictionary3.py
foo = {}
foo["a"] = "b"
foo["c"] = "d"
print(foo["a"])
print(foo["c"])
bar = {"a" => 1, "b" => 2, "c" => 3}
if bar.include?("a")
print("a in bar")
end
-- [python] ---------
* tests/basic/docstring.py
class myclass(object):
"""This is a class that really says something"""
def __init__(self,msg):
self.msg = msg
def saysomething(self):
print(self.msg)
m = myclass("hello")
m.saysomething()
-- [ruby] -----------
$ py2rb tests/basic/docstring.py
class Myclass
# This is a class that really says something
def initialize(msg)
@msg = msg
end
def saysomething()
print(@msg)
end
end
m = Myclass.new("hello")
m.saysomething()
-- [python] ---------
* tests/basic/embedding.py
"""py2rb-verbatim:
function foo(x) {
print(x);
}
"""
"""py2rb-skip-begin"""
def foo(x):
print(x)
"""py2rb-skip-end"""
foo('bar')
-- [ruby] -----------
$ py2rb tests/basic/embedding.py
# py2rb-verbatim:
# function foo(x) {
# print(x);
# }
#
# py2rb-skip-begin
def foo(x)
print(x)
end
# py2rb-skip-end
foo("bar")
-- [python] ---------
* tests/basic/fib.py
def fib(x):
if x == 1:
return x
else:
return x*fib(x-1)
print(fib(4))
-- [ruby] -----------
$ py2rb tests/basic/fib.py
def fib(x)
if x == 1
return x
else
return x * (fib(x - 1))
end
end
print(fib(4))
-- [python] ---------
* tests/basic/float2int.py
for f in [123.456,1.1,-0.00045,-1.45,1.5,1022423.22]:
i = int(f)
print(i)
-- [ruby] -----------
$ py2rb tests/basic/float2int.py
for f in [123.456, 1.1, -0.00045, -1.45, 1.5, 1022423.22]
i = f.to_i
print(i)
end
-- [python] ---------
* tests/basic/for_in.py
# iterating over a list
print('-- list --')
a = [1,2,3,4,5]
for x in a:
print(x)
# iterating over a tuple
print('-- tuple else case --')
a = ('cats','dogs','squirrels')
for x in a:
print(x)
else:
print('ok')
print('-- tuple else break case --')
for x in a:
print(x)
if x == 'squirrels':
break
else:
print('ok')
# iterating over a dictionary
# sort order in python is undefined, so need to sort the results
# explictly before comparing output
print('-- dict keys --')
a = {'a':1,'b':2,'c':3 }
keys = []
for x in a.keys():
keys.append(x)
keys.sort()
for k in keys:
print(k)
print('-- dict values --')
values = list()
for v in a.values():
values.append(v)
values.sort()
for v in values:
print(v)
items = dict()
for k, v in a.items():
items[k] = v
print('-- dict item --')
print(items['a'])
print(items['b'])
print(items['c'])
# iterating over a string
print('-- string --')
a = 'defabc'
for x in a:
print(x)
-- [ruby] -----------
$ py2rb tests/basic/for_in.py
print("-- list --")
a = [1, 2, 3, 4, 5]
for x in a
print(x)
end
print("-- tuple else case --")
a = ["cats", "dogs", "squirrels"]
__dummy0__ = false
for x in a
print(x)
if x == a[-1]
__dummy0__ = true
end
end
if __dummy0__
print("ok")
end
print("-- tuple else break case --")
__dummy1__ = false
for x in a
print(x)
if x == "squirrels"
break
end
if x == a[-1]
__dummy1__ = true
end
end
if __dummy1__
print("ok")
end
print("-- dict keys --")
a = {"a" => 1, "b" => 2, "c" => 3}
keys = []
for x in a.keys()
keys.push(x)
end
keys.sort!()
for k in keys
print(k)
end
print("-- dict values --")
values = []
for v in a.values()
values.push(v)
end
values.sort!()
for v in values
print(v)
end
items = {}
for (k, v) in a.to_a()
items[k] = v
end
print("-- dict item --")
print(items["a"])
print(items["b"])
print(items["c"])
print("-- string --")
a = "defabc"
for x in a
print(x)
end
-- [python] ---------
* tests/basic/for_range1.py
for x in range(1,10):
print(x)
-- [ruby] -----------
$ py2rb tests/basic/for_range1.py
for x in 1.upto(10-1)
print(x)
end
-- [python] ---------
* tests/basic/for_range2.py
for i in range(5):
for j in range(i+1, 5):
print("i:%s, j:%s" % (i,j))
-- [ruby] -----------
$ py2rb tests/basic/for_range2.py
for i in 5.times
for j in (i + 1).upto(5-1)
print("i:%s, j:%s" % [i, j])
end
end
-- [python] ---------
* tests/basic/for_step.py
for x in range(19,342,13):
print(x)
-- [ruby] -----------
$ py2rb tests/basic/for_step.py
for x in 19.step(342, 13)
print(x)
end
-- [python] ---------
* tests/basic/getattr.py
class foobar(object):
x = 1
def __init__(self):
self.foovar = 1
def bar(self, y=0):
print(self.foovar + y)
f = foobar()
a = 'bar'
getattr(f, 'bar')(y=1)
getattr(f, a)()
print(getattr(f, 'x'))
print(getattr(f, 'z', 'Nothing'))
-- [ruby] -----------
$ py2rb tests/basic/getattr.py
class Foobar
@@x = 1
def initialize()
@foovar = 1
end
def bar(y: 0)
print(@foovar + y)
end
def self.x; @@x; end
def self.x=(val); @@x=val; end
def x; @x = @@x if @x.nil?; @x; end
def x=(val); @x=val; end
end
f = Foobar.new()
a = "bar"
f.getattr("bar").(y: 1)
f.getattr(a).()
print(f.getattr("x"))
print(f.getattr("z", "Nothing"))
-- [python] ---------
* tests/basic/globalvar.py
a = "spam"
b = "eggs"
print(a)
print(b)
-- [ruby] -----------
$ py2rb tests/basic/globalvar.py
a = "spam"
b = "eggs"
print(a)
print(b)
-- [python] ---------
* tests/basic/hasattr1.py
class AttrTest():
def __init__(self):
self.base = -1
def __call__(self):
if hasattr(self, 'base'):
print("Class :base is True")
else:
print("Class :base is False")
attr_test = AttrTest()
if hasattr(attr_test, 'base'):
print("base is True")
else:
print("base is False")
if hasattr(attr_test, 'foo'):
print("foo is True")
else:
print("foo is False")
if hasattr(attr_test, 'bar'):
print("bar is True")
else:
print("bar is False")
attr_test()
#base = 'base'
#if hasattr(attr_test, base):
# print("base is True")
#else:
# print("base is False")
-- [ruby] -----------
$ py2rb tests/basic/hasattr1.py
class AttrTest
def initialize()
@base = -1
end
def call()
if is_bool(self.instance_variable_defined? :@base)
print("Class :base is True")
else
print("Class :base is False")
end
end
end
attr_test = AttrTest.new()
if is_bool(attr_test.instance_variable_defined? :@base)
print("base is True")
else
print("base is False")
end
if is_bool(attr_test.instance_variable_defined? :@foo)
print("foo is True")
else
print("foo is False")
end
if is_bool(attr_test.instance_variable_defined? :@bar)
print("bar is True")
else
print("bar is False")
end
attr_test.()
-- [python] ---------
* tests/basic/helloworld.py
print('hello')
print('hello world')
-- [ruby] -----------
$ py2rb tests/basic/helloworld.py
print("hello")
print("hello world")
-- [python] ---------
* tests/basic/ifelse.py
print("OK") if True else print("NG")
-- [ruby] -----------
$ py2rb tests/basic/ifelse.py
(true) ? print("OK") : print("NG")
-- [python] ---------
* tests/basic/ifs.py
def ifs1(x):
a = 1
if x:
a = a + 1
a *= 2
else:
a = a - 1
a *= 4
return a
def ifs2(x):
a = 1
if x > 0:
a = a + 1
a *= 2
else:
a = a - 1
a *= 4
return a
def ifs3(x):
a = 1
if x > 0:
if x > 10:
a = 3
else:
a = 4
a = 5
return a
def ifs4(x):
a = 1
if x > 0:
if x > 10:
a = 3
else:
a = 4
else:
a = 5
return a
print(ifs1(True))
print(ifs1(False))
print(ifs2(1))
print(ifs2(-1))
print(ifs3(1))
print(ifs3(20))
print(ifs3(-1))
print(ifs4(1))
print(ifs4(20))
print(ifs4(-1))
-- [ruby] -----------
$ py2rb tests/basic/ifs.py
def ifs1(x)
a = 1
if is_bool(x)
a = a + 1
a *= 2
else
a = a - 1
a *= 4
end
return a
end
def ifs2(x)
a = 1
if x > 0
a = a + 1
a *= 2
else
a = a - 1
a *= 4
end
return a
end
def ifs3(x)
a = 1
if x > 0
if x > 10
a = 3
else
a = 4
end
end
a = 5
return a
end
def ifs4(x)
a = 1
if x > 0
if x > 10
a = 3
else
a = 4
end
else
a = 5
end
return a
end
print(ifs1(true))
print(ifs1(false))
print(ifs2(1))
print(ifs2(-1))
print(ifs3(1))
print(ifs3(20))
print(ifs3(-1))
print(ifs4(1))
print(ifs4(20))
print(ifs4(-1))
-- [python] ---------
* tests/basic/ifs2.py
def ifs1(x):
a = 1
if 0 < x < 10:
a = 2
else:
a = 3
return a
def ifs2(x):
a = 1
if 0 == x != 10:
a = 2
else:
a = 3
return a
def ifs3(x):
a = 1
if 0 in x in [[0]]:
a = 2
else:
a = 3
return a
print('ifs1')
print(ifs1(-1))
print(ifs1(1))
print(ifs1(11))
print('ifs2')
print(ifs2(0))
print(ifs2(10))
print('ifs3')
print(ifs3([0]))
print(ifs3([1]))
-- [ruby] -----------
$ py2rb tests/basic/ifs2.py
def ifs1(x)
a = 1
if (0 < x) and (x < 10)
a = 2
else
a = 3
end
return a
end
def ifs2(x)
a = 1
if (0 == x) and (x != 10)
a = 2
else
a = 3
end
return a
end
def ifs3(x)
a = 1
if (x.include?(0)) and ([[0]].include?(x))
a = 2
else
a = 3
end
return a
end
print("ifs1")
print(ifs1(-1))
print(ifs1(1))
print(ifs1(11))
print("ifs2")
print(ifs2(0))
print(ifs2(10))
print("ifs3")
print(ifs3([0]))
print(ifs3([1]))
-- [python] ---------
* tests/basic/keys.py
x = { 'foo':'bar','aaa':'bbb','xyz':'zyx','spam':'eggs' }
s = list(x.keys())
s.sort()
for k in s:
print(k + " -> " + x[k])
-- [ruby] -----------
$ py2rb tests/basic/keys.py
x = {"foo" => "bar", "aaa" => "bbb", "xyz" => "zyx", "spam" => "eggs"}
s = x.keys().to_a
s.sort!()
for k in s
print((k + (" -> ")) + x[k])
end
-- [python] ---------
* tests/basic/kwargs.py
def myfunc(a, b, *c, **d):
print(a)
print(b)
for i in c:
print(i)
keys = list(d.keys())
keys.sort()
for i in keys:
print(i)
print(d[i])
myfunc(1, 2, bar='a', foo='c')
print()
myfunc(1, 2, 3, 4, bar='a', foo='c')
-- [ruby] -----------
$ py2rb tests/basic/kwargs.py
def myfunc(a, b, *c, **d)
print(a)
print(b)
for i in c
print(i)
end
keys = d.keys().to_a
keys.sort!()
for i in keys
print(i)
print(d[i])
end
end
myfunc(1, 2, bar: "a", foo: "c")
print()
myfunc(1, 2, 3, 4, bar: "a", foo: "c")
-- [python] ---------
* tests/basic/kwargs2.py
def myfunc(a, b, *c, fuga='hoge', **d):
print(a)
print(b)
for i in c:
print(i)
print(fuga)
keys = list(d.keys())
keys.sort()
for i in keys:
print(i)
print(d[i])
myfunc(1, 2, bar='a', foo='c')
print()
myfunc(1, 2, 3, 4, bar='a', foo='c')
myfunc(1, 2, 3, 4, bar='a', fuga='hogehoge', foo='c')
-- [ruby] -----------
$ py2rb tests/basic/kwargs2.py
def myfunc(a, b, *c, fuga: "hoge", **d)
print(a)
print(b)
for i in c
print(i)
end
print(fuga)
keys = d.keys().to_a
keys.sort!()
for i in keys
print(i)
print(d[i])
end
end
myfunc(1, 2, bar: "a", foo: "c")
print()
myfunc(1, 2, 3, 4, bar: "a", foo: "c")
myfunc(1, 2, 3, 4, bar: "a", fuga: "hogehoge", foo: "c")
-- [python] ---------
* tests/basic/kwargs3.py
def myfunc(a, b=3, c=4):
print(a)
print(b)
print(c)
print()
myfunc(1)
myfunc(1, 2)
myfunc(1, 2, 3)
myfunc(1, c=3, b=4)
myfunc(1, b=4)
-- [ruby] -----------
$ py2rb tests/basic/kwargs3.py
def myfunc(a, b: 3, c: 4)
print(a)
print(b)
print(c)
print()
end
myfunc(1)
myfunc(1, b: 2)
myfunc(1, b: 2, c: 3)
myfunc(1, c: 3, b: 4)
myfunc(1, b: 4)
-- [python] ---------
* tests/basic/lambda.py
y = lambda x:x*x
print(y(4))
print((lambda x,y:x*y)(4,2))
-- [ruby] -----------
$ py2rb tests/basic/lambda.py
y = lambda{|x| x * x}
print(y.call(4))
print(lambda{|x, y| x * y}.call(4, 2))
-- [python] ---------
* tests/basic/lambda2.py
l = lambda *x: print("%s %s %s" % x)
l(1,2,3)
-- [ruby] -----------
$ py2rb tests/basic/lambda2.py
l = lambda{|*x| print("%s %s %s" % x)}
l.call(1, 2, 3)
-- [python] ---------
* tests/basic/lambda3.py
a = 5
def foo(x, y):
x(y)
foo(lambda x: print(a), a)
-- [ruby] -----------
$ py2rb tests/basic/lambda3.py
a = 5
def foo(x, y)
x.(y)
end
foo(lambda{|x| print(a)}, a)
-- [python] ---------
* tests/basic/lambda_map.py
ary =[1, 2]
print([x**2 for x in ary])
print([x**2 for x in [1,2]])
print(list(map(lambda x: x ** 2, ary)))
print(list(map(lambda x: x ** 2, [1,2])))
-- [ruby] -----------
$ py2rb tests/basic/lambda_map.py
ary = [1, 2]
print(ary.map{|x| x ** 2})
print([1, 2].map{|x| x ** 2})
print(ary.map{|x| x ** 2}.to_a)
print([1, 2].map{|x| x ** 2}.to_a)
-- [python] ---------
* tests/basic/list.py
x = [1,2,3,'a','b','c']
y = x[2:4]
print((x[0]))
print((x[3]))
print((y[0]))
print((y[1]))
-- [ruby] -----------
$ py2rb tests/basic/list.py
x = [1, 2, 3, "a", "b", "c"]
y = x[2...4]
print(x[0])
print(x[3])
print(y[0])
print(y[1])
-- [python] ---------
* tests/basic/list2.py
def list1(n):
a = []
a.append(1)
a.append(2)
a.append(3)
a.append(n)
return a[0] + a[1] + a[2] + a[3]
def list2():
a = list(range(5))
return str(a)
def list3():
a = list(range(5))
a[0] = 5
a[4] = 0
return str(a)
def list4():
a = [8, 9, 10, 11, 12, 13, 14]
return a[2:4]
def list5():
a = [8, 9, 10, 11, 12, 13, 14]
return a[:4]
def list6():
a = [8, 9, 10, 11, 12, 13, 14]
return a[1:6:2]
def list7():
a = [8, 9, 10, 11, 12, 13, 14]
return a[:]
def list8():
a = [8, 9, 10, 11, 12, 13, 14]
return a[::]
def list9():
a = [8, 9, 10, 11, 12, 13, 14]
return a[4:]
def list10():
a = [8, 9, 10, 11, 12, 13, 14]
return a[::2]
def list11():
a = [8, 9, 10, 11, 12, 13, 14]
return a[1::2]
def list12():
a = [8, 9, 10, 11, 12, 13, 14]
return a[:4:2]
print(list1(4))
print(list1(5))
print(list2())
print(list3())
print(list4())
print(list5())
print(list6())
print(list7())
print(list8())
print(list9())
print(list10())
print(list11())
print(list12())
-- [ruby] -----------
$ py2rb tests/basic/list2.py
def list1(n)
a = []
a.push(1)
a.push(2)
a.push(3)
a.push(n)
return ((a[0] + a[1]) + a[2]) + a[3]
end
def list2()
a = 5.times.to_a
return a.to_s
end
def list3()
a = 5.times.to_a
a[0] = 5
a[4] = 0
return a.to_s
end
def list4()
a = [8, 9, 10, 11, 12, 13, 14]
return a[2...4]
end
def list5()
a = [8, 9, 10, 11, 12, 13, 14]
return a[0...4]
end
def list6()
a = [8, 9, 10, 11, 12, 13, 14]
return a[1...6].each_slice(2).map(&:first)
end
def list7()
a = [8, 9, 10, 11, 12, 13, 14]
return a[0..-1]
end
def list8()
a = [8, 9, 10, 11, 12, 13, 14]
return a[0..-1]
end
def list9()
a = [8, 9, 10, 11, 12, 13, 14]
return a[4..-1]
end
def list10()
a = [8, 9, 10, 11, 12, 13, 14]
return a[0..-1].each_slice(2).map(&:first)
end
def list11()
a = [8, 9, 10, 11, 12, 13, 14]
return a[1..-1].each_slice(2).map(&:first)
end
def list12()
a = [8, 9, 10, 11, 12, 13, 14]
return a[0...4].each_slice(2).map(&:first)
end
print(list1(4))
print(list1(5))
print(list2())
print(list3())
print(list4())
print(list5())
print(list6())
print(list7())
print(list8())
print(list9())
print(list10())
print(list11())
print(list12())
-- [python] ---------
* tests/basic/list3.py
x = list()
x.append('foo')
print(len(x))
print(x[0])
y = list('foo')
y.append('bar')
print(len(y))
print(y[0])
print(y[1])
z = [0, 1, 2]
print(z)
z = list(z)
print(z)
-- [ruby] -----------
$ py2rb tests/basic/list3.py
x = []
x.push("foo")
print(x.size)
print(x[0])
y = "foo".split('')
y.push("bar")
print(y.size)
print(y[0])
print(y[1])
z = [0, 1, 2]
print(z)
z = z.to_a
print(z)
-- [python] ---------
* tests/basic/listcomp1.py
a = [1,2]
[print("b:%s" % b) for b in a]
a = [(1,2) ,(2,4)]
[print("b:%s c:%s" % (b,c)) for b, c in a]
a = [(1,2,3) ,(2,4,6)]
[print("b:%s c:%s d:%s" % (b,c,d)) for b, c, d in a]
-- [ruby] -----------
$ py2rb tests/basic/listcomp1.py
a = [1, 2]
a.map{|b| print("b:%s" % b)}
a = [[1, 2], [2, 4]]
a.map{|b, c| print("b:%s c:%s" % [b, c])}
a = [[1, 2, 3], [2, 4, 6]]
a.map{|b, c, d| print("b:%s c:%s d:%s" % [b, c, d])}
-- [python] ---------
* tests/basic/literals.py
a = 1.234
b = 3
c = 3.45
d = 'cats'
print(a)
print(b)
print(c)
print(d)
-- [ruby] -----------
$ py2rb tests/basic/literals.py
a = 1.234
b = 3
c = 3.45
d = "cats"
print(a)
print(b)
print(c)
print(d)
-- [python] ---------
* tests/basic/logicalops.py
x = True
y = False
z = not y
if x:
print('x')
if y:
print('y')
if z:
print('z')
-- [ruby] -----------
$ py2rb tests/basic/logicalops.py
x = true
y = false
z = !y
if is_bool(x)
print("x")
end
if is_bool(y)
print("y")
end
if is_bool(z)
print("z")
end
-- [python] ---------
* tests/basic/loops.py
def loop1(x):
a = 0
for i in range(x):
x
a += i
return a
print(loop1(1))
print(loop1(2))
print(loop1(3))
print(loop1(4))
print(loop1(5))
print(loop1(6))
print(loop1(7))
-- [ruby] -----------
$ py2rb tests/basic/loops.py
def loop1(x)
a = 0
for i in x.times
x
a += i
end
return a
end
print(loop1(1))
print(loop1(2))
print(loop1(3))
print(loop1(4))
print(loop1(5))
print(loop1(6))
print(loop1(7))
-- [python] ---------
* tests/basic/multiassign.py
x,y,z = (1,2,3)
print(x,y,z)
-- [ruby] -----------
$ py2rb tests/basic/multiassign.py
x,y,z = [1, 2, 3]
print(x, y, z)
-- [python] ---------
* tests/basic/none.py
x = None
if x == None:
print("x is None/null")
else:
print("x is not None/null")
-- [ruby] -----------
$ py2rb tests/basic/none.py
x = nil
if x == nil
print("x is None/null")
else
print("x is not None/null")
end
-- [python] ---------
* tests/basic/numeric.py
print(int(2.0))
print(float(2))
print(abs(-2.0))
print(abs(-2))
print(bin(254).replace('0b', ''))
print(oct(254).replace('0o', ''))
print(hex(254).replace('0x', ''))
print(hex(-36).replace('0x', ''))
-- [ruby] -----------
$ py2rb tests/basic/numeric.py
print(2.0.to_i)
print(2.to_f)
print((-2.0).abs)
print((-2).abs)
print(254.to_s(2).gsub("0b", ""))
print(254.to_s(8).gsub("0o", ""))
print(254.to_s(16).gsub("0x", ""))
print(((-36).to_s(16)).gsub("0x", ""))
-- [python] ---------
* tests/basic/oo.py
class foo(object):
registered = []
def __init__(self,val):
self.fval = val
self.register(self)
def inc(self):
self.fval += 1
def msg(self):
return "foo says:"+str(self.fval)
@staticmethod
def register(f):
foo.registered.append(f)
@staticmethod
def printregistered():
for r in foo.registered:
print(r.msg())
a = foo(10)
b = foo(20)
c = foo(30)
a.inc()
a.inc()
c.inc()
print(a.msg())
print(b.msg())
print(c.msg())
print("---")
foo.printregistered()
-- [ruby] -----------
$ py2rb tests/basic/oo.py
class Foo
def method_missing(method, *args)
self.class.__send__ method, *args
end
@@registered = []
def initialize(val)
@fval = val
Foo.register(self)
end
def inc()
@fval += 1
end
def msg()
return "foo says:" + @fval.to_s
end
def self.register(f)
@@registered.push(f)
end
def self.printregistered()
for r in @@registered
print(r.msg())
end
end
def self.registered; @@registered; end
def self.registered=(val); @@registered=val; end
def registered; @registered = @@registered if @registered.nil?; @registered; end
def registered=(val); @registered=val; end
end
a = Foo.new(10)
b = Foo.new(20)
c = Foo.new(30)
a.inc()
a.inc()
c.inc()
print(a.msg())
print(b.msg())
print(c.msg())
print("---")
Foo.printregistered()
-- [python] ---------
* tests/basic/oo_attributes.py
class Foobar(object):
foo = 1
bar = [1, 2, 3]
my_foobar = Foobar()
print(my_foobar.foo)
print(my_foobar.bar)
print(Foobar.foo)
print(Foobar.bar)
my_foobar.foo = 2
my_foobar.bar.append(5)
print(my_foobar.foo)
print(my_foobar.bar)
print(Foobar.foo)
print(Foobar.bar)
Foobar.foo = 3
Foobar.bar.append(6)
print(my_foobar.foo)
print(my_foobar.bar)
print(Foobar.foo)
print(Foobar.bar)
-- [ruby] -----------
$ py2rb tests/basic/oo_attributes.py
class Foobar
@@foo = 1
@@bar = [1, 2, 3]
def self.foo; @@foo; end
def self.foo=(val); @@foo=val; end
def foo; @foo = @@foo if @foo.nil?; @foo; end
def foo=(val); @foo=val; end
def self.bar; @@bar; end
def self.bar=(val); @@bar=val; end
def bar; @bar = @@bar if @bar.nil?; @bar; end
def bar=(val); @bar=val; end
end
my_foobar = Foobar.new()
print(my_foobar.foo)
print(my_foobar.bar)
print(Foobar.foo)
print(Foobar.bar)
my_foobar.foo = 2
my_foobar.bar.push(5)
print(my_foobar.foo)
print(my_foobar.bar)
print(Foobar.foo)
print(Foobar.bar)
Foobar.foo = 3
Foobar.bar.push(6)
print(my_foobar.foo)
print(my_foobar.bar)
print(Foobar.foo)
print(Foobar.bar)
-- [python] ---------
* tests/basic/oo_inherit.py
class bar(object):
def __init__(self,name):
self.name = name
def setname(self,name):
self.name = name
class foo(bar):
registered = []
def __init__(self,val,name):
self.fval = val
self.register(self)
bar.__init__(self,name)
def inc(self):
self.fval += 1
def msg(self,*varargs):
txt = ''
for arg in varargs:
txt += str(arg)
txt += ","
return txt + self.name + " says:"+str(self.fval)
@staticmethod
def register(f):
foo.registered.append(f)
@staticmethod
def printregistered():
for r in foo.registered:
print(r.msg())
a = foo(10,'a')
a.setname('aaa')
b = foo(20,'b')
c = foo(30,'c')
a.inc()
a.inc()
c.inc()
print(a.msg())
print(b.msg())
print(c.msg(2,3,4))
print("---")
foo.printregistered()
-- [ruby] -----------
$ py2rb tests/basic/oo_inherit.py
class Bar
def initialize(name)
@name = name
end
def setname(name)
@name = name
end
end
class Foo < Bar
def method_missing(method, *args)
self.class.__send__ method, *args
end
@@registered = []
def initialize(val, name)
@fval = val
Foo.register(self)
super(name)
end
def inc()
@fval += 1
end
def msg(*varargs)
txt = ""
for arg in varargs
txt += arg.to_s
txt += ","
end
return ((txt + @name) + " says:") + @fval.to_s
end
def self.register(f)
@@registered.push(f)
end
def self.printregistered()
for r in @@registered
print(r.msg())
end
end
def self.registered; @@registered; end
def self.registered=(val); @@registered=val; end
def registered; @registered = @@registered if @registered.nil?; @registered; end
def registered=(val); @registered=val; end
end
a = Foo.new(10, "a")
a.setname("aaa")
b = Foo.new(20, "b")
c = Foo.new(30, "c")
a.inc()
a.inc()
c.inc()
print(a.msg())
print(b.msg())
print(c.msg(2, 3, 4))
print("---")
Foo.printregistered()
-- [python] ---------
* tests/basic/oo_inherit2.py
def show(o):
"""
This tests that the proper method is called.
"""
o.msg()
def show2(o):
"""
This tests oo inheritance.
"""
o.print_msg()
class A(object):
def msg(self):
print("A.msg()")
def print_msg(self):
self.msg()
class B(A):
def msg(self):
print("B.msg()")
a = A()
show(a)
show2(a)
b = B()
show(b)
show2(b)
-- [ruby] -----------
$ py2rb tests/basic/oo_inherit2.py
def show(o)
#
# This tests that the proper method is called.
#
o.msg()
end
def show2(o)
#
# This tests oo inheritance.
#
o.print_msg()
end
class A
def msg()
print("A.msg()")
end
def print_msg()
msg()
end
end
class B < A
def msg()
print("B.msg()")
end
end
a = A.new()
show(a)
show2(a)
b = B.new()
show(b)
show2(b)
-- [python] ---------
* tests/basic/oo_inherit3.py
def show(o):
"""
This tests that the proper method is called.
"""
o.msg()
def show2(o):
"""
This tests oo inheritance.
"""
o.print_msg()
class A(object):
def __init__(self):
self._a = 5
def msg(self):
print("A.msg()")
def print_msg(self):
self.msg()
print(self._a)
class B(A):
def msg(self):
print("B.msg()")
a = A()
show(a)
show2(a)
b = B()
show(b)
show2(b)
-- [ruby] -----------
$ py2rb tests/basic/oo_inherit3.py
def show(o)
#
# This tests that the proper method is called.
#
o.msg()
end
def show2(o)
#
# This tests oo inheritance.
#
o.print_msg()
end
class A
def initialize()
@_a = 5
end
def msg()
print("A.msg()")
end
def print_msg()
msg()
print(@_a)
end
end
class B < A
def msg()
print("B.msg()")
end
end
a = A.new()
show(a)
show2(a)
b = B.new()
show(b)
show2(b)
-- [python] ---------
* tests/basic/oo_inherit_simple.py
class bar(object):
def __init__(self,name):
self.name = name
def setname(self,name):
self.name = name
class foo(bar):
registered = []
def __init__(self,val,name):
self.fval = val
self.register(self)
self.name = name
def inc(self):
self.fval += 1
def msg(self, a=None, b=None, c=None):
txt = ''
varargs = a, b, c
for arg in varargs:
if arg is None:
continue
txt += str(arg)
txt += ","
return txt + self.name + " says:"+str(self.fval)
@staticmethod
def register(f):
foo.registered.append(f)
@staticmethod
def printregistered():
for r in foo.registered:
print(r.msg())
a = foo(10,'a')
a.setname('aaa')
b = foo(20,'b')
c = foo(30,'c')
a.inc()
a.inc()
c.inc()
print(a.msg())
print(b.msg())
print(c.msg(2,3,4))
print("---")
foo.printregistered()
-- [ruby] -----------
$ py2rb tests/basic/oo_inherit_simple.py
class Bar
def initialize(name)
@name = name
end
def setname(name)
@name = name
end
end
class Foo < Bar
def method_missing(method, *args)
self.class.__send__ method, *args
end
@@registered = []
def initialize(val, name)
@fval = val
Foo.register(self)
@name = name
end
def inc()
@fval += 1
end
def msg(a: nil, b: nil, c: nil)
txt = ""
varargs = [a, b, c]
for arg in varargs
if arg === nil
next
end
txt += arg.to_s
txt += ","
end
return ((txt + @name) + " says:") + @fval.to_s
end
def self.register(f)
@@registered.push(f)
end
def self.printregistered()
for r in @@registered
print(r.msg())
end
end
def self.registered; @@registered; end
def self.registered=(val); @@registered=val; end
def registered; @registered = @@registered if @registered.nil?; @registered; end
def registered=(val); @registered=val; end
end
a = Foo.new(10, "a")
a.setname("aaa")
b = Foo.new(20, "b")
c = Foo.new(30, "c")
a.inc()
a.inc()
c.inc()
print(a.msg())
print(b.msg())
print(c.msg(a: 2, b: 3, c: 4))
print("---")
Foo.printregistered()
-- [python] ---------
* tests/basic/oo_inherit_simple_super1.py
class bar(object):
def __init__(self,name):
self.name = name
def setname(self,name):
self.name = name
class foo(bar):
registered = []
def __init__(self,val,name):
self.fval = val
self.register(self)
bar.__init__(self,name)
def inc(self):
self.fval += 1
def msg(self, a=None, b=None, c=None):
txt = ''
varargs = a, b, c
for arg in varargs:
if arg is None:
continue
txt += str(arg)
txt += ","
return txt + self.name + " says:"+str(self.fval)
@staticmethod
def register(f):
foo.registered.append(f)
@staticmethod
def printregistered():
for r in foo.registered:
print(r.msg())
a = foo(10,'a')
a.setname('aaa')
b = foo(20,'b')
c = foo(30,'c')
a.inc()
a.inc()
c.inc()
print(a.msg())
print(b.msg())
print(c.msg(2,3,4))
print("---")
foo.printregistered()
-- [ruby] -----------
$ py2rb tests/basic/oo_inherit_simple_super1.py
class Bar
def initialize(name)
@name = name
end
def setname(name)
@name = name
end
end
class Foo < Bar
def method_missing(method, *args)
self.class.__send__ method, *args
end
@@registered = []
def initialize(val, name)
@fval = val
Foo.register(self)
super(name)
end
def inc()
@fval += 1
end
def msg(a: nil, b: nil, c: nil)
txt = ""
varargs = [a, b, c]
for arg in varargs
if arg === nil
next
end
txt += arg.to_s
txt += ","
end
return ((txt + @name) + " says:") + @fval.to_s
end
def self.register(f)
@@registered.push(f)
end
def self.printregistered()
for r in @@registered
print(r.msg())
end
end
def self.registered; @@registered; end
def self.registered=(val); @@registered=val; end
def registered; @registered = @@registered if @registered.nil?; @registered; end
def registered=(val); @registered=val; end
end
a = Foo.new(10, "a")
a.setname("aaa")
b = Foo.new(20, "b")
c = Foo.new(30, "c")
a.inc()
a.inc()
c.inc()
print(a.msg())
print(b.msg())
print(c.msg(a: 2, b: 3, c: 4))
print("---")
Foo.printregistered()
-- [python] ---------
* tests/basic/oo_inherit_simple_super2.py
class bar(object):
def __init__(self,name):
self.name = name
def setname(self,name):
self.name = name
class foo(bar):
registered = []
def __init__(self,val,name):
self.fval = val
self.register(self)
super(foo, self).__init__(name)
def inc(self):
self.fval += 1
def msg(self, a=None, b=None, c=None):
txt = ''
varargs = a, b, c
for arg in varargs:
if arg is None:
continue
txt += str(arg)
txt += ","
return txt + self.name + " says:"+str(self.fval)
@staticmethod
def register(f):
foo.registered.append(f)
@staticmethod
def printregistered():
for r in foo.registered:
print(r.msg())
a = foo(10,'a')
a.setname('aaa')
b = foo(20,'b')
c = foo(30,'c')
a.inc()
a.inc()
c.inc()
print(a.msg())
print(b.msg())
print(c.msg(2,3,4))
print("---")
foo.printregistered()
-- [ruby] -----------
$ py2rb tests/basic/oo_inherit_simple_super2.py
class Bar
def initialize(name)
@name = name
end
def setname(name)
@name = name
end
end
class Foo < Bar
def method_missing(method, *args)
self.class.__send__ method, *args
end
@@registered = []
def initialize(val, name)
@fval = val
Foo.register(self)
super(name)
end
def inc()
@fval += 1
end
def msg(a: nil, b: nil, c: nil)
txt = ""
varargs = [a, b, c]
for arg in varargs
if arg === nil
next
end
txt += arg.to_s
txt += ","
end
return ((txt + @name) + " says:") + @fval.to_s
end
def self.register(f)
@@registered.push(f)
end
def self.printregistered()
for r in @@registered
print(r.msg())
end
end
def self.registered; @@registered; end
def self.registered=(val); @@registered=val; end
def registered; @registered = @@registered if @registered.nil?; @registered; end
def registered=(val); @registered=val; end
end
a = Foo.new(10, "a")
a.setname("aaa")
b = Foo.new(20, "b")
c = Foo.new(30, "c")
a.inc()
a.inc()
c.inc()
print(a.msg())
print(b.msg())
print(c.msg(a: 2, b: 3, c: 4))
print("---")
Foo.printregistered()
-- [python] ---------
* tests/basic/oo_inherit_simple_super3.py
class bar(object):
def __init__(self,name):
self.name = name
def setname(self,name):
self.name = name
class foo(bar):
registered = []
def __init__(self,val,name):
self.fval = val
self.register(self)
super().__init__(name)
def inc(self):
self.fval += 1
def msg(self, a=None, b=None, c=None):
txt = ''
varargs = a, b, c
for arg in varargs:
if arg is None:
continue
txt += str(arg)
txt += ","
return txt + self.name + " says:"+str(self.fval)
@staticmethod
def register(f):
foo.registered.append(f)
@staticmethod
def printregistered():
for r in foo.registered:
print(r.msg())
a = foo(10,'a')
a.setname('aaa')
b = foo(20,'b')
c = foo(30,'c')
a.inc()
a.inc()
c.inc()
print(a.msg())
print(b.msg())
print(c.msg(2,3,4))
print("---")
foo.printregistered()
-- [ruby] -----------
$ py2rb tests/basic/oo_inherit_simple_super3.py
class Bar
def initialize(name)
@name = name
end
def setname(name)
@name = name
end
end
class Foo < Bar
def method_missing(method, *args)
self.class.__send__ method, *args
end
@@registered = []
def initialize(val, name)
@fval = val
Foo.register(self)
super(name)
end
def inc()
@fval += 1
end
def msg(a: nil, b: nil, c: nil)
txt = ""
varargs = [a, b, c]
for arg in varargs
if arg === nil
next
end
txt += arg.to_s
txt += ","
end
return ((txt + @name) + " says:") + @fval.to_s
end
def self.register(f)
@@registered.push(f)
end
def self.printregistered()
for r in @@registered
print(r.msg())
end
end
def self.registered; @@registered; end
def self.registered=(val); @@registered=val; end
def registered; @registered = @@registered if @registered.nil?; @registered; end
def registered=(val); @registered=val; end
end
a = Foo.new(10, "a")
a.setname("aaa")
b = Foo.new(20, "b")
c = Foo.new(30, "c")
a.inc()
a.inc()
c.inc()
print(a.msg())
print(b.msg())
print(c.msg(a: 2, b: 3, c: 4))
print("---")
Foo.printregistered()
-- [python] ---------
* tests/basic/oo_static_inherit.py
class A1(object):
@staticmethod
def msg(val):
print("A1 static method msg says:"+str(val))
class A2(A1):
pass
a = A2()
a.msg("hello")
A2.msg("world")
-- [ruby] -----------
$ py2rb tests/basic/oo_static_inherit.py
class A1
def method_missing(method, *args)
self.class.__send__ method, *args
end
def self.msg(val)
print("A1 static method msg says:" + val.to_s)
end
end
class A2 < A1
# pass
end
a = A2.new()
a.msg("hello")
A2.msg("world")
-- [python] ---------
* tests/basic/pass.py
x = 'hello'
if x != 'hello':
print("1")
pass
print("2")
else:
print("3")
pass
print("4")
-- [ruby] -----------
$ py2rb tests/basic/pass.py
x = "hello"
if x != "hello"
print("1")
# pass
print("2")
else
print("3")
# pass
print("4")
end
-- [python] ---------
* tests/basic/print.py
print(1.23, "foobar", -1, 'x')
-- [ruby] -----------
$ py2rb tests/basic/print.py
print(1.23, "foobar", -1, "x")
-- [python] ---------
* tests/basic/raise.py
a = "hello"
try:
try:
print("Trying illegal access")
x = "abc"
x.abc()
except:
print("Exception raised, re-raising")
raise
except:
print("Exception raised")
pass
-- [ruby] -----------
$ py2rb tests/basic/raise.py
a = "hello"
begin
begin
print("Trying illegal access")
x = "abc"
x.abc()
rescue
print("Exception raised, re-raising")
raise
end
rescue
print("Exception raised")
# pass
end
-- [python] ---------
* tests/basic/raise2.py
try:
raise
except:
pass
try:
foo
except NameError:
print('NameError :')
except:
print('Error :')
try:
raise NameError
except NameError:
print('NameError :')
except:
print('Error :')
try:
raise NameError('User Defined Error Message.')
except NameError as err:
print('NameError :', err)
except:
print('Error :')
try:
raise NotImplementedError('User Defined Error Message.')
except NotImplementedError as err:
print('NotImplementedError :', err)
except:
print('Error :')
-- [ruby] -----------
$ py2rb tests/basic/raise2.py
begin
raise
rescue
# pass
end
begin
foo
rescue NameError
print("NameError :")
rescue
print("Error :")
end
begin
raise NameError
rescue NameError
print("NameError :")
rescue
print("Error :")
end
begin
raise NameError, "User Defined Error Message."
rescue NameError => err
print("NameError :", err)
rescue
print("Error :")
end
begin
raise NotImplementedError, "User Defined Error Message."
rescue NotImplementedError => err
print("NotImplementedError :", err)
rescue
print("Error :")
end
-- [python] ---------
* tests/basic/scope.py
x = 12
def loopy():
for x in range(0,8):
print(x)
loopy()
print(x)
-- [ruby] -----------
$ py2rb tests/basic/scope.py
x = 12
def loopy()
for x in 0.upto(8-1)
print(x)
end
end
loopy()
print(x)
-- [python] ---------
* tests/basic/set.py
# iterating over a list
print('-- set --')
a = set([1,2,3,4,5])
a.remove(3)
for x in a:
print(x)
print('-- set add --')
a = set()
a.add(1)
a.add(2)
a.add(1)
for x in a:
print(x)
print('-- set clear --')
a.clear()
for x in a:
print(x)
-- [ruby] -----------
$ py2rb tests/basic/set.py
print("-- set --")
a = Set.new([1, 2, 3, 4, 5])
a.remove(3)
for x in a
print(x)
end
print("-- set add --")
a = Set.new()
a.add(1)
a.add(2)
a.add(1)
for x in a
print(x)
end
print("-- set clear --")
a.clear()
for x in a
print(x)
end
-- [python] ---------
* tests/basic/str1.py
s1 = "some string"
s2 = "some 'x' string"
s3 = 'some "x" string'
s4 = "some \"x\" string"
s5 = """some "x" string"""
s6 = """some "x" string
and some other string too...
"""
if s2 == s3:
print("ok1")
if s3 == s4:
print("ok2")
if s3 == s5:
print("ok3")
if s3 != s6:
print("ok4")
"""some "x" string
and some other string too...
"""
if True:
"""some "x" string
and some other string too...
"""
-- [ruby] -----------
$ py2rb tests/basic/str1.py
s1 = "some string"
s2 = "some 'x' string"
s3 = "some \"x\" string"
s4 = "some \"x\" string"
s5 = "some \"x\" string"
s6 = "some \"x\" string
and some other string too...
"
if s2 == s3
print("ok1")
end
if s3 == s4
print("ok2")
end
if s3 == s5
print("ok3")
end
if s3 != s6
print("ok4")
end
# some \"x\" string
# and some other string too...
#
if true
# some \"x\" string
# and some other string too...
#
end
-- [python] ---------
* tests/basic/str_endswith.py
if 'hoge.txt'.endswith('.txt'):
print('OK')
else:
print('NG')
-- [ruby] -----------
$ py2rb tests/basic/str_endswith.py
if is_bool("hoge.txt".end_with?(".txt"))
print("OK")
else
print("NG")
end
-- [python] ---------
* tests/basic/sumcomp.py
x = sum(x*x for x in [2,3,4,5,6,7])
print(x)
-- [ruby] -----------
$ py2rb tests/basic/sumcomp.py
x = ([2, 3, 4, 5, 6, 7].map{|x| x * x}).sum
print(x)
-- [python] ---------
* tests/basic/super1.py
class baseklass(object):
def __init__(self,bval):
self.bval = bval
def describe(self,arg):
print("baseklass.describe:"+self.bval+":"+str(arg))
def describe2(self,**kwargs):
print("baseklass.describe2:"+self.bval+":"+kwargs['string'])
class klass(baseklass):
def __init__(self,val,bval):
baseklass.__init__(self,bval)
self.val = val
def describe(self):
super(klass,self).describe(10)
super(klass,self).describe2(string='somestring')
self.describe2(string='somestring')
print("klass.describe:"+self.val)
k = klass("world","hello")
k.describe()
-- [ruby] -----------
$ py2rb tests/basic/super1.py
class Baseklass
def initialize(bval)
@bval = bval
end
def describe(arg)
print((("baseklass.describe:" + @bval) + ":") + arg.to_s)
end
def describe2(**kwargs)
print((("baseklass.describe2:" + @bval) + ":") + kwargs[:string])
end
end
class Klass < Baseklass
def initialize(val, bval)
super(bval)
@val = val
end
def describe()
super(10)
describe2(string: "somestring")
describe2(string: "somestring")
print("klass.describe:" + @val)
end
end
k = Klass.new("world", "hello")
k.describe()
-- [python] ---------
* tests/basic/super2.py
class baseklass(object):
def __init__(self,bval):
self.bval = bval
def describe(self,arg):
print("baseklass.describe:"+self.bval+":"+str(arg))
def describe2(self,**kwargs):
print("baseklass.describe2:"+self.bval+":"+kwargs['string'])
print("baseklass.describe2:"+self.bval+":"+kwargs['string2'])
kwargs['string2'] = kwargs['string3']
print("baseklass.describe2:"+self.bval+":"+kwargs['string2'])
class klass(baseklass):
def __init__(self,val,bval):
baseklass.__init__(self,bval)
self.val = val
def describe(self):
super(klass,self).describe(10)
super(klass,self).describe2(string='somestring', string2='anystring', string3='changestring')
print("klass.describe:"+self.val)
def describe2(self,**kwargs):
print("klass.describe2:"+self.bval+":"+kwargs['string'])
k = klass("world","hello")
k.describe()
-- [ruby] -----------
$ py2rb tests/basic/super2.py
class Baseklass
def initialize(bval)
@bval = bval
end
def describe(arg)
print((("baseklass.describe:" + @bval) + ":") + arg.to_s)
end
def describe2(**kwargs)
print((("baseklass.describe2:" + @bval) + ":") + kwargs[:string])
print((("baseklass.describe2:" + @bval) + ":") + kwargs[:string2])
kwargs[:string2] = kwargs[:string3]
print((("baseklass.describe2:" + @bval) + ":") + kwargs[:string2])
end
end
class Klass < Baseklass
def initialize(val, bval)
super(bval)
@val = val
end
def describe()
super(10)
public_method(:describe2).super_method.call(string: "somestring", string2: "anystring", string3: "changestring")
print("klass.describe:" + @val)
end
def describe2(**kwargs)
print((("klass.describe2:" + @bval) + ":") + kwargs[:string])
end
end
k = Klass.new("world", "hello")
k.describe()
-- [python] ---------
* tests/basic/trueorfalse.py
literals = ['a','',0,None,1,0.0,1.0,-1,-1.0,-0]
for l in literals:
if l:
print("True")
else:
print("False")
-- [ruby] -----------
$ py2rb tests/basic/trueorfalse.py
literals = ["a", "", 0, nil, 1, 0.0, 1.0, -1, -1.0, -0]
for l in literals
if is_bool(l)
print("True")
else
print("False")
end
end
-- [python] ---------
* tests/basic/try.py
class MyException(Exception):
def __init__(self,msg):
self.msg = msg
def message(self):
return self.msg
class MyOtherException(Exception):
def __init__(self,msg):
self.msg = msg
def message(self):
return self.msg
for index in [1,2]:
try:
print('raising exception...')
if index==1:
raise MyException('bar')
elif index==2:
raise MyOtherException('foo')
except MyOtherException as ex2:
print('caught other exception:' + ex2.message())
except MyException as ex:
print('caught exception:' + ex.message())
finally:
print('and finally...')
-- [ruby] -----------
$ py2rb tests/basic/try.py
class MyException < Exception
def initialize(msg)
@msg = msg
end
def message()
return @msg
end
end
class MyOtherException < Exception
def initialize(msg)
@msg = msg
end
def message()
return @msg
end
end
for index in [1, 2]
begin
print("raising exception...")
if index == 1
raise MyException, "bar"
else
if index == 2
raise MyOtherException, "foo"
end
end
rescue MyOtherException => ex2
print("caught other exception:" + ex2.message())
rescue MyException => ex
print("caught exception:" + ex.message())
ensure
print("and finally...")
end
end
-- [python] ---------
* tests/basic/tuple.py
tup = ('a','b',1,2,3)
print(len(tup))
print(tup[0])
print(tup[1])
print(tup[2])
print(tup[3])
print(tup[4])
tup = tuple()
print(len(tup))
tup = tuple(('a','b',1,2,3))
print(len(tup))
print(tup[0])
print(tup[1])
print(tup[2])
print(tup[3])
tup = tuple("ABC")
print(len(tup))
print(tup[0])
print(tup[1])
print(tup[2])
tup = tuple([10, 20])
print(len(tup))
print(tup[0])
print(tup[1])
-- [ruby] -----------
$ py2rb tests/basic/tuple.py
tup = ["a", "b", 1, 2, 3]
print(tup.size)
print(tup[0])
print(tup[1])
print(tup[2])
print(tup[3])
print(tup[4])
tup = []
print(tup.size)
tup = ["a", "b", 1, 2, 3].to_a
print(tup.size)
print(tup[0])
print(tup[1])
print(tup[2])
print(tup[3])
tup = "ABC".split('')
print(tup.size)
print(tup[0])
print(tup[1])
print(tup[2])
tup = [10, 20].to_a
print(tup.size)
print(tup[0])
print(tup[1])
-- [python] ---------
* tests/basic/tuple2.py
def tuple1(x):
t = (x, x+1, x+2)
a, b, c = t
return a+b+c
def tuple2(n):
a = 0
for i in (1, 2, n):
a += i
return a
def tuple3():
a = (1, 3, 5, 4, 9, 1, 2, 3)
return len(a)
def tuple4(n):
a = (1, 3, 3, 4, 9, 1, 2, 3)
return a.count(n)
def tuple5(n):
a = (1, 3, 3, 4, 9, 1, 2, 3)
return a.index(n)
def tuple6():
a = (8, 9, 10, 11, 12, 13, 14)
return a[2:4]
def tuple7():
a = (8, 9, 10, 11, 12, 13, 14)
return a[:4]
def tuple8():
a = (8, 9, 10, 11, 12, 13, 14)
return a[1:6:2]
def tuple9():
a = (8, 9, 10, 11, 12, 13, 14)
return a[:]
def tuple10():
a = (8, 9, 10, 11, 12, 13, 14)
return a[4:]
print(tuple1(3))
print(tuple2(3))
print(tuple2(4))
print(tuple3())
print(tuple4(1))
print(tuple4(3))
print(tuple4(4))
print(tuple4(5))
print(tuple5(1))
print(tuple5(4))
print(tuple6())
print(tuple7())
print(tuple8())
print(tuple9())
print(tuple10())
-- [ruby] -----------
$ py2rb tests/basic/tuple2.py
def tuple1(x)
t = [x, x + 1, x + 2]
a,b,c = t
return (a + b) + c
end
def tuple2(n)
a = 0
for i in [1, 2, n]
a += i
end
return a
end
def tuple3()
a = [1, 3, 5, 4, 9, 1, 2, 3]
return a.size
end
def tuple4(n)
a = [1, 3, 3, 4, 9, 1, 2, 3]
return a.count(n)
end
def tuple5(n)
a = [1, 3, 3, 4, 9, 1, 2, 3]
return a.index(n)
end
def tuple6()
a = [8, 9, 10, 11, 12, 13, 14]
return a[2...4]
end
def tuple7()
a = [8, 9, 10, 11, 12, 13, 14]
return a[0...4]
end
def tuple8()
a = [8, 9, 10, 11, 12, 13, 14]
return a[1...6].each_slice(2).map(&:first)
end
def tuple9()
a = [8, 9, 10, 11, 12, 13, 14]
return a[0..-1]
end
def tuple10()
a = [8, 9, 10, 11, 12, 13, 14]
return a[4..-1]
end
print(tuple1(3))
print(tuple2(3))
print(tuple2(4))
print(tuple3())
print(tuple4(1))
print(tuple4(3))
print(tuple4(4))
print(tuple4(5))
print(tuple5(1))
print(tuple5(4))
print(tuple6())
print(tuple7())
print(tuple8())
print(tuple9())
print(tuple10())
-- [python] ---------
* tests/basic/vargs.py
def myfunc(a,b,*c):
print(a)
print(b)
for i in c:
print(i)
myfunc(1,2)
myfunc('a','b','c','d')
myfunc(3,4,5,6,'hello')
-- [ruby] -----------
$ py2rb tests/basic/vargs.py
def myfunc(a, b, *c)
print(a)
print(b)
for i in c
print(i)
end
end
myfunc(1, 2)
myfunc("a", "b", "c", "d")
myfunc(3, 4, 5, 6, "hello")
-- [python] ---------
* tests/basic/while.py
""" while case """
x = 1
while x<10:
print(x)
x = x + 1
""" while and else case """
x = 1
while x<10:
print(x)
x = x + 1
else:
print("ok")
""" while and else break case """
x = 1
while x<10:
print(x)
x = x + 1
break
else:
print("ok")
-- [ruby] -----------
$ py2rb tests/basic/while.py
# while case
x = 1
while x < 10
print(x)
x = x + 1
end
# while and else case
x = 1
__dummy0__ = false
while true
unless x < 10
__dummy0__ = true
break
end
print(x)
x = x + 1
end
if __dummy0__
print("ok")
end
# while and else break case
x = 1
__dummy1__ = false
while true
unless x < 10
__dummy1__ = true
break
end
print(x)
x = x + 1
break
end
if __dummy1__
print("ok")
end
-- [python] ---------
* tests/basic/with.py
with open("hello.txt", 'w') as f:
f.write("Hello, world!")
with open("hello.txt", 'r') as f:
print(f.read())
with open("hello.txt", 'r'):
print('ok')
-- [ruby] -----------
$ py2rb tests/basic/with.py
open("hello.txt", "w") {|f|
f.write("Hello, world!")
}
open("hello.txt", "r") {|f|
print(f.read())
}
open("hello.txt", "r") {
print("ok")
}
-- [python] ---------
* tests/collections/ordered_dict.py
import collections
d = collections.OrderedDict({'one': 1, 'two':2, 'three':3})
print(d['one'])
print(d['two'])
print(d['three'])
e = collections.OrderedDict(d)
print(e['one'])
print(e['two'])
print(e['three'])
#d = collections.OrderedDict(one=1, two=2, three=3)
#print(d['one'])
#print(d['two'])
#print(d['three'])
-- [ruby] -----------
$ py2rb tests/collections/ordered_dict.py
d = {"one" => 1, "two" => 2, "three" => 3}
print(d["one"])
print(d["two"])
print(d["three"])
e = d.dup
print(e["one"])
print(e["two"])
print(e["three"])
-- [python] ---------
* tests/decorator/function1.py
class wrapper:
def __init__(self,fn):
self.fn = fn
def __call__(self,*args):
return "(" + self.fn(*args) + ")"
def mydecorator(x):
print("decorating " + str(x))
return wrapper(x)
def describe():
return "world"
describe = mydecorator(describe)
print(describe())
-- [ruby] -----------
$ py2rb tests/decorator/function1.py
class Wrapper
def initialize(fn)
@fn = fn
end
def call(*args)
return ("(" + (@fn.(*args))) + ")"
end
end
def mydecorator(x)
print("decorating " + x.to_s)
return Wrapper.new(x)
end
def describe()
return "world"
end
describe = mydecorator(method(:describe))
print(describe.())
-- [python] ---------
* tests/decorator/function2.py
class wrapper:
def __init__(self,fn):
self.fn = fn
def __call__(self,*args):
return "(" + self.fn(*args) + ")"
def mydecorator(x):
print("decorating " + str(x))
return wrapper(x)
@mydecorator
def describe():
return "world"
print(describe())
-- [ruby] -----------
$ py2rb tests/decorator/function2.py
class Wrapper
def initialize(fn)
@fn = fn
end
def call(*args)
return ("(" + (@fn.(*args))) + ")"
end
end
def mydecorator(x)
print("decorating " + x.to_s)
return Wrapper.new(x)
end
def describe()
return "world"
end
describe = mydecorator(method(:describe))
print(describe.())
-- [python] ---------
* tests/decorator/function3.py
class wrapper:
def __init__(self,fn):
self.fn = fn
def __call__(self,*args):
return "(" + self.fn(*args) + ")"
def mydecorator(x):
print("decorating " + str(x))
return wrapper(x)
@mydecorator
def describe():
return "world"
describe = mydecorator(describe)
print(describe())
-- [ruby] -----------
$ py2rb tests/decorator/function3.py
class Wrapper
def initialize(fn)
@fn = fn
end
def call(*args)
return ("(" + (@fn.(*args))) + ")"
end
end
def mydecorator(x)
print("decorating " + x.to_s)
return Wrapper.new(x)
end
def describe()
return "world"
end
describe = mydecorator(method(:describe))
describe = mydecorator(describe)
print(describe.())
-- [python] ---------
* tests/decorator/property.py
class propertyDecorator(object):
def __init__(self, x):
self._x = x
@property
def x(self):
return self._x
pd = propertyDecorator(100)
print(pd.x)
-- [ruby] -----------
$ py2rb tests/decorator/property.py
class PropertyDecorator
def initialize(x)
@_x = x
end
def x()
return @_x
end
end
pd = PropertyDecorator.new(100)
print(pd.x)
-- [python] ---------
* tests/decorator/setter.py
class propertyDecorator(object):
def __init__(self, x):
self._x = x
@property
def x(self):
return self._x
@x.setter
def x(self, value):
self._x = value
pd = propertyDecorator(100)
print(pd.x)
pd.x = 10
print(pd.x)
-- [ruby] -----------
$ py2rb tests/decorator/setter.py
class PropertyDecorator
def initialize(x)
@_x = x
end
def x()
return @_x
end
def x=(value)
@_x = value
end
end
pd = PropertyDecorator.new(100)
print(pd.x)
pd.x = 10
print(pd.x)
-- [python] ---------
* tests/deep-learning-from-scratch/and_gate.py
# coding: utf-8
import numpy as np
def AND(x1, x2):
x = np.array([x1, x2])
w = np.array([0.5, 0.5])
b = -0.7
tmp = np.sum(w*x) + b
if tmp <= 0:
return 0
else:
return 1
if __name__ == '__main__':
for xs in [(0, 0), (1, 0), (0, 1), (1, 1)]:
y = AND(xs[0], xs[1])
print(str(xs) + " -> " + str(y))
-- [ruby] -----------
$ py2rb tests/deep-learning-from-scratch/and_gate.py
require 'numo/narray'
def AND(x1, x2)
x = Numo::NArray.cast([x1, x2])
w = Numo::NArray.cast([0.5, 0.5])
b = -0.7
tmp = ((w * x).sum()) + b
if tmp <= 0
return 0
else
return 1
end
end
if __FILE__ == $0
for xs in [[0, 0], [1, 0], [0, 1], [1, 1]]
y = AND(xs[0], xs[1])
print((xs.to_s + (" -> ")) + y.to_s)
end
end
-- [python] ---------
* tests/deep-learning-from-scratch/relu.py
# coding: utf-8
import numpy as np
def relu(x):
return np.maximum(0, x)
x = np.arange(-5.0, 5.0, 0.1)
y = relu(x)
def print_array(data):
datas = []
for i in data:
if float("%.3f" % abs(i)) == 0:
datas.append(float("%.3f" % abs(i)))
else:
datas.append(float("%.3f" % i))
print(datas)
print(len(x))
print_array(list(x))
print(len(y))
print_array(list(y))
-- [ruby] -----------
$ py2rb tests/deep-learning-from-scratch/relu.py
require 'numo/narray'
def relu(x)
return Numo::DFloat.maximum(0, x)
end
x = Numo::DFloat.new(((5.0-(-5.0))/(0.1).to_f).ceil).seq(-5.0, 0.1)
y = relu(x)
def print_array(data)
datas = []
for i in data
if ("%.3f" % i.abs).to_f == 0
datas.push(("%.3f" % i.abs).to_f)
else
datas.push(("%.3f" % i).to_f)
end
end
print(datas)
end
print(x.size)
print_array(x.to_a)
print(y.size)
print_array(y.to_a)
-- [python] ---------
* tests/deep-learning-from-scratch/sigmoid.py
import numpy as np
def sigmoid(x):
return 1 / (1 + np.exp(-x))
x = np.arange(-5.0, 5.0, 0.1)
y = sigmoid(x)
def print_array(data):
datas = []
for i in data:
if float("%.3f" % abs(i)) == 0:
datas.append(float("%.3f" % abs(i)))
else:
datas.append(float("%.3f" % i))
print(datas)
print(len(x))
print_array(list(x))
print(len(y))
print_array(list(y))
-- [ruby] -----------
$ py2rb tests/deep-learning-from-scratch/sigmoid.py
require 'numo/narray'
def sigmoid(x)
return 1 / (1 + (Numo::NMath.exp(-x)))
end
x = Numo::DFloat.new(((5.0-(-5.0))/(0.1).to_f).ceil).seq(-5.0, 0.1)
y = sigmoid(x)
def print_array(data)
datas = []
for i in data
if ("%.3f" % i.abs).to_f == 0
datas.push(("%.3f" % i.abs).to_f)
else
datas.push(("%.3f" % i).to_f)
end
end
print(datas)
end
print(x.size)
print_array(x.to_a)
print(y.size)
print_array(y.to_a)
-- [python] ---------
* tests/deep-learning-from-scratch/step_function.py
# coding: utf-8
import numpy as np
def step_function(x):
return np.array(x > 0, dtype=np.int)
X = np.arange(-5.0, 5.0, 0.1)
Y = step_function(X)
def print_array(data):
datas = []
for i in data:
if float("%.3f" % abs(i)) == 0:
datas.append(float("%.3f" % abs(i)))
else:
datas.append(float("%.3f" % i))
print(datas)
print(len(X))
print_array(list(X))
print(len(Y))
print_array(list(Y))
-- [ruby] -----------
$ py2rb tests/deep-learning-from-scratch/step_function.py
require 'numo/narray'
def step_function(x)
return Numo::Int64.cast(x > 0)
end
X = Numo::DFloat.new(((5.0-(-5.0))/(0.1).to_f).ceil).seq(-5.0, 0.1)
Y = step_function(X)
def print_array(data)
datas = []
for i in data
if ("%.3f" % i.abs).to_f == 0
datas.push(("%.3f" % i.abs).to_f)
else
datas.push(("%.3f" % i).to_f)
end
end
print(datas)
end
print(X.size)
print_array(X.to_a)
print(Y.size)
print_array(Y.to_a)
-- [python] ---------
* tests/errors/py_collision.py
a = 1
if a == 1:
print("ok")
else:
print("no")
py_builtins = 1
if py_builtins == 1:
print("ok")
else:
print("no")
for py_builtins in range(5):
a += py_builtins
print(a)
-- [ruby] -----------
$ py2rb tests/errors/py_collision.py
a = 1
if a == 1
print("ok")
else
print("no")
end
py_builtins = 1
if py_builtins == 1
print("ok")
else
print("no")
end
for py_builtins in 5.times
a += py_builtins
end
print(a)
-- [python] ---------
* tests/functions/and.py
tests = [(False,False),(False,True),(True,False),(True,True),(True,None),(False,None),(None,True),(None,False)]
def pp(v):
if v == False:
return "F"
if v == True:
return "T"
return "?"
for t in tests:
(b1,b2) = t
print(pp(b1) + " AND " + pp(b2) + "=" + pp(b1 and b2))
-- [ruby] -----------
$ py2rb tests/functions/and.py
tests = [[false, false], [false, true], [true, false], [true, true], [true, nil], [false, nil], [nil, true], [nil, false]]
def pp(v)
if v == false
return "F"
end
if v == true
return "T"
end
return "?"
end
for t in tests
b1,b2 = t
print((((pp(b1) + " AND ") + pp(b2)) + "=") + pp(b1 && b2))
end
-- [python] ---------
* tests/functions/append.py
mylist = []
mylist.append('a')
mylist.append('b')
mylist.append('c')
print(mylist[0])
print(mylist[1])
print(mylist[2])
-- [ruby] -----------
$ py2rb tests/functions/append.py
mylist = []
mylist.push("a")
mylist.push("b")
mylist.push("c")
print(mylist[0])
print(mylist[1])
print(mylist[2])
-- [python] ---------
* tests/functions/aug.py
a = 244
b = 23
print(a)
a += 4
print(a)
a -= 2
print(a)
a <<= 4
print(a)
a >>= 2
print(a)
a |= 234324
print(a)
a &= 213213
print(a)
a ^= 2312
print(a)
a //= 324
print(a)
a += 1
print(a)
a /= 2
print(a)
print(b)
b **= 3
print(b)
-- [ruby] -----------
$ py2rb tests/functions/aug.py
a = 244
b = 23
print(a)
a += 4
print(a)
a -= 2
print(a)
a <<= 4
print(a)
a >>= 2
print(a)
a |= 234324
print(a)
a &= 213213
print(a)
a ^= 2312
print(a)
a /= 324
print(a)
a += 1
print(a)
a = a / 2.to_f
print(a)
print(b)
b = b ** 3
print(b)
-- [python] ---------
* tests/functions/bitand.py
x = 32424
y = 1437
z = x & y
print(z)
-- [ruby] -----------
$ py2rb tests/functions/bitand.py
x = 32424
y = 1437
z = x & y
print(z)
-- [python] ---------
* tests/functions/bitor.py
x = 123215
y = 3423
z = x | y
print(z)
-- [ruby] -----------
$ py2rb tests/functions/bitor.py
x = 123215
y = 3423
z = x | y
print(z)
-- [python] ---------
* tests/functions/bitxor.py
x = 32213
y = 98743
z = x ^ y
print(z)
-- [ruby] -----------
$ py2rb tests/functions/bitxor.py
x = 32213
y = 98743
z = x ^ y
print(z)
-- [python] ---------
* tests/functions/divfloor.py
x = 23423
y = 213
z = x // y
print(z)
-- [ruby] -----------
$ py2rb tests/functions/divfloor.py
x = 23423
y = 213
z = x / y
print(z)
-- [python] ---------
* tests/functions/float.py
a = '123.456'
b = float(a)
print(b)
-- [ruby] -----------
$ py2rb tests/functions/float.py
a = "123.456"
b = a.to_f
print(b)
-- [python] ---------
* tests/functions/floatdiv.py
a = 3
b = 2
c = a / b
print(c)
-- [ruby] -----------
$ py2rb tests/functions/floatdiv.py
a = 3
b = 2
c = a / b.to_f
print(c)
-- [python] ---------
* tests/functions/gtge.py
x = 123
y = 233
y2 = 233
z = 892
if x > y:
print("x > y - incorrect")
else:
print("not x > y - correct")
if y >= y2:
print("y >= y2 - correct")
else:
print("not y >= y2 - incorrect")
if z > x:
print("z > x - correct")
else:
print("not z > x - incorrect")
if y >= z:
print("y >= z - incorrect")
else:
print("not y >= x - correct")
-- [ruby] -----------
$ py2rb tests/functions/gtge.py
x = 123
y = 233
y2 = 233
z = 892
if x > y
print("x > y - incorrect")
else
print("not x > y - correct")
end
if y >= y2
print("y >= y2 - correct")
else
print("not y >= y2 - incorrect")
end
if z > x
print("z > x - correct")
else
print("not z > x - incorrect")
end
if y >= z
print("y >= z - incorrect")
else
print("not y >= x - correct")
end
-- [python] ---------
* tests/functions/in.py
a = { 1:'aaa', 'b':2 }
if 2 in a:
print("2 in a - incorrect")
if 'b' in a:
print("b in a - correct")
if 1 in a:
print("1 in a - correct")
if 3 not in a:
print("3 not in a - correct")
if 'x' not in a:
print("x not in a - correct")
-- [ruby] -----------
$ py2rb tests/functions/in.py
a = {1 => "aaa", "b" => 2}
if a.include?(2)
print("2 in a - incorrect")
end
if a.include?("b")
print("b in a - correct")
end
if a.include?(1)
print("1 in a - correct")
end
if !a.include?(3)
print("3 not in a - correct")
end
if !a.include?("x")
print("x not in a - correct")
end
-- [python] ---------
* tests/functions/int.py
x = '123'
y = int(x)
print(y)
-- [ruby] -----------
$ py2rb tests/functions/int.py
x = "123"
y = x.to_i
print(y)
-- [python] ---------
* tests/functions/isinstance.py
class Spam(object):
def __init__(self,value):
self.value = value
class Eggs(object):
def __init__(self,value):
self.value = value
s = Spam(1)
e = Eggs(2)
if isinstance(s,Spam):
print("s is Spam - correct")
if isinstance(s,Eggs):
print("s is Eggs - incorrect")
if isinstance(e,Spam):
print("e is Spam - incorrect")
if isinstance(e,Eggs):
print("e is Eggs - correct")
if isinstance(1, int):
print("int - correct")
if isinstance(0.1, float):
print("float - correct")
if isinstance('str', str):
print("str - correct")
if isinstance([0], list):
print("list - correct")
if isinstance((0, 1), tuple):
print("tuple - correct")
if isinstance({'a': 1}, dict):
print("dict - correct")
-- [ruby] -----------
$ py2rb tests/functions/isinstance.py
class Spam
def initialize(value)
@value = value
end
end
class Eggs
def initialize(value)
@value = value
end
end
s = Spam.new(1)
e = Eggs.new(2)
if is_bool(s.is_a? Spam)
print("s is Spam - correct")
end
if is_bool(s.is_a? Eggs)
print("s is Eggs - incorrect")
end
if is_bool(e.is_a? Spam)
print("e is Spam - incorrect")
end
if is_bool(e.is_a? Eggs)
print("e is Eggs - correct")
end
if is_bool(1.is_a? Integer)
print("int - correct")
end
if is_bool(0.1.is_a? Float)
print("float - correct")
end
if is_bool("str".is_a? String)
print("str - correct")
end
if is_bool([0].is_a? Array)
print("list - correct")
end
if is_bool([0, 1].is_a? Array)
print("tuple - correct")
end
if is_bool({"a" => 1}.is_a? Hash)
print("dict - correct")
end
-- [python] ---------
* tests/functions/len.py
mylist = [1,2,3]
print(len(mylist))
-- [ruby] -----------
$ py2rb tests/functions/len.py
mylist = [1, 2, 3]
print(mylist.size)
-- [python] ---------
* tests/functions/lshift.py
x = 10
y = x << 3
x <<= 3
print(x,y)
-- [ruby] -----------
$ py2rb tests/functions/lshift.py
x = 10
y = x << 3
x <<= 3
print(x, y)
-- [python] ---------
* tests/functions/ltle.py
x = 123
y = 233
y2 = 233
z = 892
if x < y:
print("x < y - correct")
else:
print("not x < y - incorrect")
if y <= y2:
print("y <= y2 - correct")
else:
print("not y <= y2 - incorrect")
if z < x:
print("z < x - incorrect")
else:
print("not z < x - correct")
if y <= z:
print("y <= z - correct")
else:
print("not y <= x - incorrect")
-- [ruby] -----------
$ py2rb tests/functions/ltle.py
x = 123
y = 233
y2 = 233
z = 892
if x < y
print("x < y - correct")
else
print("not x < y - incorrect")
end
if y <= y2
print("y <= y2 - correct")
else
print("not y <= y2 - incorrect")
end
if z < x
print("z < x - incorrect")
else
print("not z < x - correct")
end
if y <= z
print("y <= z - correct")
else
print("not y <= x - incorrect")
end
-- [python] ---------
* tests/functions/ne.py
#for x in [1,2]:
# pass
for (x,y) in [(1,2),('aaa','bbb'),(4,4),('a','a')]:
if x != y:
print(str(x)+" <> "+str(y))
else:
print("not: " + str(x)+" <> "+str(y))
-- [ruby] -----------
$ py2rb tests/functions/ne.py
for (x, y) in [[1, 2], ["aaa", "bbb"], [4, 4], ["a", "a"]]
if x != y
print((x.to_s + " <> ") + y.to_s)
else
print((("not: " + x.to_s) + " <> ") + y.to_s)
end
end
-- [python] ---------
* tests/functions/or.py
tests = [(False,False),(False,True),(True,False),(True,True),(True,None),(False,None),(None,True),(None,False)]
def pp(v):
if v == False:
return "F"
if v == True:
return "T"
return "?"
for t in tests:
(b1,b2) = t
print(pp(b1) + " OR " + pp(b2) + "=" + pp(b1 or b2))
-- [ruby] -----------
$ py2rb tests/functions/or.py
tests = [[false, false], [false, true], [true, false], [true, true], [true, nil], [false, nil], [nil, true], [nil, false]]
def pp(v)
if v == false
return "F"
end
if v == true
return "T"
end
return "?"
end
for t in tests
b1,b2 = t
print((((pp(b1) + " OR ") + pp(b2)) + "=") + pp(b1 || b2))
end
-- [python] ---------
* tests/functions/pop.py
a = [1,2,3,4]
print(a.pop())
-- [ruby] -----------
$ py2rb tests/functions/pop.py
a = [1, 2, 3, 4]
print(a.pop())
-- [python] ---------
* tests/functions/rshift.py
x = 345
y = x >> 7
x >>= 7
print(x,y)
-- [ruby] -----------
$ py2rb tests/functions/rshift.py
x = 345
y = x >> 7
x >>= 7
print(x, y)
-- [python] ---------
* tests/functions/sort.py
l = [3,2,1]
l.sort()
print(l[0])
print(l[1])
print(l[2])
-- [ruby] -----------
$ py2rb tests/functions/sort.py
l = [3, 2, 1]
l.sort!()
print(l[0])
print(l[1])
print(l[2])
-- [python] ---------
* tests/functions/str.py
a = 1
b = str(a)
c = 'x: ' + b
print(a)
print(b)
print(c)
-- [ruby] -----------
$ py2rb tests/functions/str.py
a = 1
b = a.to_s
c = "x: " + b
print(a)
print(b)
print(c)
-- [python] ---------
* tests/functions/ubitcomp.py
b = (~1 & 0xFFFF)
print(b)
-- [ruby] -----------
$ py2rb tests/functions/ubitcomp.py
b = ~1 & 65535
print(b)
-- [python] ---------
* tests/functions/uminus.py
x = -7623
print(x)
-- [ruby] -----------
$ py2rb tests/functions/uminus.py
x = -7623
print(x)
-- [python] ---------
* tests/functions/uplus.py
x = +7623
print(x)
-- [ruby] -----------
$ py2rb tests/functions/uplus.py
x = +7623
print(x)
-- [python] ---------
* tests/lists/all.py
l = [4,7,3,4,2,1]
v = all(l)
print(str(v).upper())
print(str(all([])).upper())
print(str(all({})).upper())
print(str(all(())).upper())
print(str(all([False])).upper())
print(str(all([None])).upper())
print(str(all([0])).upper())
print(str(all([''])).upper())
print(str(all([[]])).upper())
print(str(all([{}])).upper())
l = [0,{}]
v = all(l)
print(str(v).upper())
-- [ruby] -----------
$ py2rb tests/lists/all.py
l = [4, 7, 3, 4, 2, 1]
v = l.is_all?
print(v.to_s.upcase())
print([].is_all?.to_s.upcase())
print({}.is_all?.to_s.upcase())
print([].is_all?.to_s.upcase())
print([false].is_all?.to_s.upcase())
print([nil].is_all?.to_s.upcase())
print([0].is_all?.to_s.upcase())
print([""].is_all?.to_s.upcase())
print([[]].is_all?.to_s.upcase())
print([{}].is_all?.to_s.upcase())
l = [0, {}]
v = l.is_all?
print(v.to_s.upcase())
-- [python] ---------
* tests/lists/any.py
l = [4,7,3,4,2,1]
v = any(l)
print(str(v).upper())
print(str(any([])).upper())
print(str(any({})).upper())
print(str(any(())).upper())
print(str(any([False])).upper())
print(str(any([None])).upper())
print(str(any([0])).upper())
print(str(any([''])).upper())
print(str(any([[]])).upper())
print(str(any([{}])).upper())
l = [0,{}]
v = any(l)
print(str(v).upper())
-- [ruby] -----------
$ py2rb tests/lists/any.py
l = [4, 7, 3, 4, 2, 1]
v = l.is_any?
print(v.to_s.upcase())
print([].is_any?.to_s.upcase())
print({}.is_any?.to_s.upcase())
print([].is_any?.to_s.upcase())
print([false].is_any?.to_s.upcase())
print([nil].is_any?.to_s.upcase())
print([0].is_any?.to_s.upcase())
print([""].is_any?.to_s.upcase())
print([[]].is_any?.to_s.upcase())
print([{}].is_any?.to_s.upcase())
l = [0, {}]
v = l.is_any?
print(v.to_s.upcase())
-- [python] ---------
* tests/lists/extend.py
list1 = [1,2,'f',44]
list2 = ['a',99,77]
list3 = list1[:]
list3.extend(list2)
for item in list3:
print(item)
-- [ruby] -----------
$ py2rb tests/lists/extend.py
list1 = [1, 2, "f", 44]
list2 = ["a", 99, 77]
list3 = list1[0..-1]
list3.concat(list2)
for item in list3
print(item)
end
-- [python] ---------
* tests/lists/filter.py
l = [1,2,3,4,5,6,7,8,8]
l2 = [x for x in l if x>4]
for v in l2:
print(v)
-- [ruby] -----------
$ py2rb tests/lists/filter.py
l = [1, 2, 3, 4, 5, 6, 7, 8, 8]
l2 = l.select{|x| x > 4}.map{|x| x}
for v in l2
print(v)
end
-- [python] ---------
* tests/lists/in.py
l = ['a','b','c']
def intest(item,ll):
if item in ll:
print(str(item) + ' is in list')
else:
print(str(item) + ' is not in list')
intest('a',l)
intest('b',l)
intest(99,l)
intest(0,l)
intest('z',l)
intest('c',l)
-- [ruby] -----------
$ py2rb tests/lists/in.py
l = ["a", "b", "c"]
def intest(item, ll)
if ll.include?(item)
print(item.to_s + " is in list")
else
print(item.to_s + " is not in list")
end
end
intest("a", l)
intest("b", l)
intest(99, l)
intest(0, l)
intest("z", l)
intest("c", l)
-- [python] ---------
* tests/lists/insert.py
a = []
a.insert(0, 1)
print(a)
a.insert(0, 2)
print(a)
a.insert(0, 3)
print(a)
a.insert(1, 4)
print(a)
a.insert(2, 5)
print(a)
a.insert(5, 6)
print(a)
-- [ruby] -----------
$ py2rb tests/lists/insert.py
a = []
a.insert(0, 1)
print(a)
a.insert(0, 2)
print(a)
a.insert(0, 3)
print(a)
a.insert(1, 4)
print(a)
a.insert(2, 5)
print(a)
a.insert(5, 6)
print(a)
-- [python] ---------
* tests/lists/map.py
def foo(x):
return x*x
y = [1,2,3,4,5]
z = list(map(foo,y))
for val in z:
print(val)
-- [ruby] -----------
$ py2rb tests/lists/map.py
def foo(x)
return x * x
end
y = [1, 2, 3, 4, 5]
z = y.map{|_| foo(_)}.to_a
for val in z
print(val)
end
-- [python] ---------
* tests/lists/max.py
l = [4,7,3,4,2,1]
v = max(l)
print(v)
-- [ruby] -----------
$ py2rb tests/lists/max.py
l = [4, 7, 3, 4, 2, 1]
v = l.max
print(v)
-- [python] ---------
* tests/lists/min.py
l = [4,7,3,4,2,1]
v = min(l)
print(v)
-- [ruby] -----------
$ py2rb tests/lists/min.py
l = [4, 7, 3, 4, 2, 1]
v = l.min
print(v)
-- [python] ---------
* tests/lists/reverse.py
a = [1, 2, 3, 4]
a.reverse()
print(a)
-- [ruby] -----------
$ py2rb tests/lists/reverse.py
a = [1, 2, 3, 4]
a.reverse!()
print(a)
-- [python] ---------
* tests/lists/subclass.py
class A(list):
def my_append(self, a):
self.append(a)
a = A()
print(a)
a.append(5)
print(a)
a.append(6)
print(a)
a.remove(5)
print(a)
-- [ruby] -----------
$ py2rb tests/lists/subclass.py
class A < Array
def my_append(a)
@append.(a)
end
end
a = A.new()
print(a)
a.push(5)
print(a)
a.push(6)
print(a)
a.remove(5)
print(a)
-- [python] ---------
* tests/lists/subclass2.py
class List(object):
def __init__(self, l=[]):
self._list = list(l)
def append(self, x):
self._list.append(x)
def remove(self, x):
self._list.remove(x)
def __str__(self):
return str(self._list)
class A(List):
def my_append(self, a):
self.append(a)
a = A()
print(a)
a.append(5)
print(a)
a.append(6)
print(a)
a.remove(5)
print(a)
-- [ruby] -----------
$ py2rb tests/lists/subclass2.py
class List
def initialize(l: [])
@_list = l.to_a
end
def append(x)
@_list.push(x)
end
def remove(x)
@_list.remove(x)
end
def to_s()
return @_list.to_s
end
alias :push :append
end
class A < List
def my_append(a)
append(a)
end
end
a = A.new()
print(a)
a.push(5)
print(a)
a.push(6)
print(a)
a.remove(5)
print(a)
-- [python] ---------
* tests/lists/subclass3.py
class List(object):
def __init__(self, l=[]):
self._list = list(l)
def append(self, x):
self._list.append(x)
def remove(self, x):
self._list.remove(x)
def __str__(self):
return str(self._list)
class Layer(List):
pass
l1 = Layer()
l1.append(1)
l1.append(2)
l2 = list()
l2.append(3)
l2.append(4)
print(l1)
print(l2)
-- [ruby] -----------
$ py2rb tests/lists/subclass3.py
class List
def initialize(l: [])
@_list = l.to_a
end
def append(x)
@_list.push(x)
end
def remove(x)
@_list.remove(x)
end
def to_s()
return @_list.to_s
end
alias :push :append
end
class Layer < List
# pass
end
l1 = Layer.new()
l1.push(1)
l1.push(2)
l2 = []
l2.push(3)
l2.push(4)
print(l1)
print(l2)
-- [python] ---------
* tests/lists/sum.py
s = [1,2,3,4,5]
t = sum(s)
u = sum([x*x for x in s])
print(t,u)
-- [ruby] -----------
$ py2rb tests/lists/sum.py
s = [1, 2, 3, 4, 5]
t = s.sum
u = (s.map{|x| x * x}).sum
print(t, u)
-- [python] ---------
* tests/lists/sum2.py
s = [1,2,3,4,5]
print(sum(s))
print(sum([1, 8, 11]))
print(sum((1, 8, 11)))
-- [ruby] -----------
$ py2rb tests/lists/sum2.py
s = [1, 2, 3, 4, 5]
print(s.sum)
print([1, 8, 11].sum)
print([1, 8, 11].sum)
-- [python] ---------
* tests/lists/xrange.py
xr = range(20,40)
for x in xr:
print(x)
-- [ruby] -----------
$ py2rb tests/lists/xrange.py
xr = 20.upto(40-1)
for x in xr
print(x)
end
-- [python] ---------
* tests/lists/zip.py
l1 = [1,2,3,4,5]
l2 = [5,4,3,2,1]
l3 = [4,4,4,4]
l4 = list(zip(l1,l2,l3))
for item in l4:
print("---")
for val in item:
print(val)
-- [ruby] -----------
$ py2rb tests/lists/zip.py
l1 = [1, 2, 3, 4, 5]
l2 = [5, 4, 3, 2, 1]
l3 = [4, 4, 4, 4]
l4 = zip_p(l1, l2, l3).to_a
for item in l4
print("---")
for val in item
print(val)
end
end
-- [python] ---------
* tests/modules/classname.py
from modules.moda import ModA
m = ModA('hello')
m.describe()
mc = m.clone()
mc.describe()
-- [ruby] -----------
$ py2rb tests/modules/classname.py
require_relative 'modules/moda'
include Modules::Moda
m = ModA.new("hello")
m.describe()
mc = m.clone()
mc.describe()
-- [python] ---------
* tests/modules/from_import.py
from imported.modulea import modulea_fn
from imported.moduleb import moduleb_fn as modb_fn
from imported.modulec import *
from imported.modulee import *
modulea_fn()
modb_fn()
foo()
bar()
-- [ruby] -----------
$ py2rb tests/modules/from_import.py
require_relative 'imported/modulea'
include Imported::Modulea
require_relative 'imported/moduleb'
include Imported::Moduleb
alias modb_fn moduleb_fn
require_relative 'imported/modulec'
include Imported::Modulec
require_relative 'imported/modulee'
include Imported::Modulee
modulea_fn()
modb_fn()
foo()
bar()
-- [python] ---------
* tests/modules/from_import_as_module.py
from imported.modulea import *
from imported import moduleb as foo
modulea_fn()
foo.moduleb_fn()
ma = modulea_class()
print(ma.msg(1))
mb = foo.moduleb_class()
print(mb.msg(2))
-- [ruby] -----------
$ py2rb tests/modules/from_import_as_module.py
require_relative 'imported/modulea'
include Imported::Modulea
require_relative 'imported/moduleb'
include Imported
Foo = Moduleb
modulea_fn()
Foo::moduleb_fn()
ma = Modulea_class.new()
print(ma.msg(1))
mb = Foo::Moduleb_class.new()
print(mb.msg(2))
-- [python] ---------
* tests/modules/import.py
from imported.modulea import *
import imported.moduleb
modulea_fn()
imported.moduleb.moduleb_fn()
ma = modulea_class()
print(ma.msg(1))
mb = imported.moduleb.moduleb_class()
print(mb.msg(2))
-- [ruby] -----------
$ py2rb tests/modules/import.py
require_relative 'imported/modulea'
include Imported::Modulea
require_relative 'imported/moduleb'
modulea_fn()
Imported::Moduleb::moduleb_fn()
ma = Modulea_class.new()
print(ma.msg(1))
mb = Imported::Moduleb::Moduleb_class.new()
print(mb.msg(2))
-- [python] ---------
* tests/modules/import_alias.py
from imported.alias_fns import foo as bar
from imported.alias_classes import spam as eggs
# call imported function
bar()
# call imported class
e = eggs()
e.msg()
-- [ruby] -----------
$ py2rb tests/modules/import_alias.py
require_relative 'imported/alias_fns'
include Imported::Alias_fns
alias bar foo
require_relative 'imported/alias_classes'
include Imported::Alias_classes
Eggs = Spam
bar()
e = Eggs.new()
e.msg()
-- [python] ---------
* tests/modules/import_as_module.py
from imported.modulea import *
import imported.moduleb as foo
modulea_fn()
foo.moduleb_fn()
ma = modulea_class()
print(ma.msg(1))
mb = foo.moduleb_class()
print(mb.msg(2))
-- [ruby] -----------
$ py2rb tests/modules/import_as_module.py
require_relative 'imported/modulea'
include Imported::Modulea
require_relative 'imported/moduleb'
Foo = Imported::Moduleb
modulea_fn()
Foo::moduleb_fn()
ma = Modulea_class.new()
print(ma.msg(1))
mb = Foo::Moduleb_class.new()
print(mb.msg(2))
-- [python] ---------
* tests/modules/import_class.py
import modules.klasses
k = modules.klasses.Klass()
k.sayhello()
modules.klasses.Klass.sayhello()
-- [ruby] -----------
$ py2rb tests/modules/import_class.py
require_relative 'modules/klasses'
k = Modules::Klasses::Klass.new()
k.sayhello()
Modules::Klasses::Klass.sayhello()
-- [python] ---------
* tests/modules/import_global.py
import imported.moduleb
import imported.moduled
imported.moduleb.moduleb_fn()
imported.moduled.moduled_fn()
-- [ruby] -----------
$ py2rb tests/modules/import_global.py
require_relative 'imported/moduleb'
require_relative 'imported/moduled'
Imported::Moduleb::moduleb_fn()
Imported::Moduled::moduled_fn()
-- [python] ---------
* tests/modules/import_init.py
import children
children.fuga.hi()
children.hoge.hi()
b = children.bar.bar_class()
b.hi()
children.grandchildren.foo.hi()
-- [ruby] -----------
$ py2rb tests/modules/import_init.py
require_relative 'children/__init__'
require_relative 'children/grandchildren/foo'
require_relative 'children/hoge'
require_relative 'children/fuga'
require_relative 'children/bar'
Children::Fuga::hi()
Children::Hoge::hi()
b = Children::Bar::Bar_class.new()
b.hi()
Children::Grandchildren::Foo::hi()
-- [python] ---------
* tests/modules/import_multi.py
import imported.modulec
def foo():
print("foo")
imported.modulec.foo()
foo()
-- [ruby] -----------
$ py2rb tests/modules/import_multi.py
require_relative 'imported/modulec'
def foo()
print("foo")
Imported::Modulec::foo()
end
foo()
-- [python] ---------
* tests/numpy/abs.py
# coding: utf-8
import numpy as np
def print_matrix(data):
data_i = []
for i in list(data):
data_j = []
for j in i:
data_j.append(j)
data_i.append(data_j)
print(data_i)
def print_array(data):
datas = []
for i in data:
datas.append(i)
print(datas)
"""
1-dim
"""
x = np.array([2,-3,4])
print_array(x)
y = np.abs(x)
print_array(y)
y = np.absolute(x)
print_array(y)
"""
2-dim
"""
z = np.array([[-2,3,-6],[3,-4,5]])
print_matrix(z)
y = np.abs(z)
print_matrix(y)
-- [ruby] -----------
$ py2rb tests/numpy/abs.py
require 'numo/narray'
def print_matrix(data)
data_i = []
for i in data.to_a
data_j = []
for j in i
data_j.push(j)
end
data_i.push(data_j)
end
print(data_i)
end
def print_array(data)
datas = []
for i in data
datas.push(i)
end
print(datas)
end
#
# 1-dim
#
x = Numo::NArray.cast([2, -3, 4])
print_array(x)
y = Numo::NArray.cast(x).abs()
print_array(y)
y = Numo::NArray.cast(x).abs()
print_array(y)
#
# 2-dim
#
z = Numo::NArray.cast([[-2, 3, -6], [3, -4, 5]])
print_matrix(z)
y = Numo::NArray.cast(z).abs()
print_matrix(y)
-- [python] ---------
* tests/numpy/all.py
# coding: utf-8
import numpy as np
v = np.all([[True, False], [True, True]])
print(str(v).upper())
""" [True, False] => [1, 0] """
v = np.all([[True, False], [True, True]], axis=0)
for a in v:
if a in (True, 1):
print('TRUE')
else:
print('FALSE')
v = np.all([-1, 0, 4])
print(str(v).upper())
v = np.all([1.0 ,np.nan])
print(str(v).upper())
-- [ruby] -----------
$ py2rb tests/numpy/all.py
require 'numo/narray'
v = Numo::Bit.cast([[true, false], [true, true]]).all?()
print(v.to_s.upcase())
# [True, False] => [1, 0]
v = Numo::Bit.cast([[true, false], [true, true]]).all?(axis: 0)
for a in v
if [true, 1].include?(a)
print("TRUE")
else
print("FALSE")
end
end
v = Numo::Bit.cast([-1, 0, 4]).all?()
print(v.to_s.upcase())
v = Numo::Bit.cast([1.0, Float::NAN]).all?()
print(v.to_s.upcase())
-- [python] ---------
* tests/numpy/any.py
# coding: utf-8
import numpy as np
v = np.any([[True, False], [True, True]])
print(str(v).upper())
""" [False, True] => [0, 1] """
v = np.any([[True, False], [True, True]], axis=0)
for a in v:
if a in (True, 1):
print('TRUE')
else:
print('FALSE')
v = np.any([-1, 0, 4])
print(str(v).upper())
v = np.any(np.nan)
print(str(v).upper())
-- [ruby] -----------
$ py2rb tests/numpy/any.py
require 'numo/narray'
v = Numo::Bit.cast([[true, false], [true, true]]).any?()
print(v.to_s.upcase())
# [False, True] => [0, 1]
v = Numo::Bit.cast([[true, false], [true, true]]).any?(axis: 0)
for a in v
if [true, 1].include?(a)
print("TRUE")
else
print("FALSE")
end
end
v = Numo::Bit.cast([-1, 0, 4]).any?()
print(v.to_s.upcase())
v = Numo::Bit.cast(Float::NAN).any?()
print(v.to_s.upcase())
-- [python] ---------
* tests/numpy/arange.py
import numpy as np
def print_array(data):
datas = []
for i in data:
if float("%.3f" % abs(i)) == 0:
datas.append(float("%.3f" % abs(i)))
else:
datas.append(float("%.3f" % i))
print(datas)
x = np.arange(-1.0, 1.0, 0.1)
print_array(x)
x = np.arange(6)
print_array(x)
x = np.arange(1,6)
print_array(x)
x = np.arange(1,6,2)
print_array(x)
-- [ruby] -----------
$ py2rb tests/numpy/arange.py
require 'numo/narray'
def print_array(data)
datas = []
for i in data
if ("%.3f" % i.abs).to_f == 0
datas.push(("%.3f" % i.abs).to_f)
else
datas.push(("%.3f" % i).to_f)
end
end
print(datas)
end
x = Numo::DFloat.new(((1.0-(-1.0))/(0.1).to_f).ceil).seq(-1.0, 0.1)
print_array(x)
x = Numo::DFloat.new(6).seq(0)
print_array(x)
x = Numo::DFloat.new(6-(1)).seq(1)
print_array(x)
x = Numo::DFloat.new(((6-(1))/(2).to_f).ceil).seq(1, 2)
print_array(x)
-- [python] ---------
* tests/numpy/array2string.py
import numpy as np
x = np.array([1,2,3,4,5,6,7,8,9,10], dtype='int8')
print(list(x))
print(np.array2string(x))
print(np.array2string(x, None))
print(np.array2string(x, None, None, None, ' '))
print(np.array2string(x, precision=2, separator=',', suppress_small=True))
print(np.array2string(x, precision=3, separator=',', suppress_small=True))
print('hoge : ' +np.array2string(x, precision=4, separator=',', suppress_small=True, prefix='hoge : '))
print(np.array2string(x, precision=4))
print(np.array2string(x))
-- [ruby] -----------
$ py2rb tests/numpy/array2string.py
require 'numo/narray'
x = Numo::NArray.cast([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print(x.to_a)
print((x).format_to_a.join())
print((x).format_to_a.join())
print((x).format_to_a.join(" "))
print((x).format_to_a.join(","))
print((x).format_to_a.join(","))
print("hoge : " + (x).format_to_a.join(","))
print((x).format_to_a.join())
print((x).format_to_a.join())
-- [python] ---------
* tests/numpy/asarray.py
import numpy as np
def print_matrix(data):
data_i = []
for i in list(data):
data_j = []
for j in i:
data_j.append(int("%d" % j))
data_i.append(data_j)
print(data_i)
def print_array(data):
datas = []
for i in data:
datas.append(float("%.3f" % i))
print(datas)
x = np.asarray([[1.,2.],[3.,4.]])
print_matrix(x)
x = np.asarray([1.,2.])
print_array(x)
y = np.asarray([3.,4.])
print_array(y)
z = (x + y)[0]
print(z)
-- [ruby] -----------
$ py2rb tests/numpy/asarray.py
require 'numo/narray'
def print_matrix(data)
data_i = []
for i in data.to_a
data_j = []
for j in i
data_j.push(("%d" % j).to_i)
end
data_i.push(data_j)
end
print(data_i)
end
def print_array(data)
datas = []
for i in data
datas.push(("%.3f" % i).to_f)
end
print(datas)
end
x = Numo::NArray.cast([[1.0, 2.0], [3.0, 4.0]])
print_matrix(x)
x = Numo::NArray.cast([1.0, 2.0])
print_array(x)
y = Numo::NArray.cast([3.0, 4.0])
print_array(y)
z = (x + y)[0]
print(z)
-- [python] ---------
* tests/numpy/ellipsis.py
import numpy as np
x = np.array([1, 1, 1])
x[...] = 1
-- [ruby] -----------
$ py2rb tests/numpy/ellipsis.py
require 'numo/narray'
x = Numo::NArray.cast([1, 1, 1])
x[false] = 1
-- [python] ---------
* tests/numpy/empty.py
# coding: utf-8
import numpy as np
def print_array(data):
datas = []
for i in data:
datas.append(i)
print(datas)
x = np.empty(())
print_array(x.shape)
x = np.empty((0))
print_array(x.shape)
x = np.empty((0,0))
print_array(x.shape)
x = np.empty(3, dtype=np.float32)
print_array(x.shape)
x = np.empty((2,3))
print_array(x.shape)
-- [ruby] -----------
$ py2rb tests/numpy/empty.py
require 'numo/narray'
def print_array(data)
datas = []
for i in data
datas.push(i)
end
print(datas)
end
x = Numo::DFloat.new([])
print_array(x.shape)
x = Numo::DFloat.new(0)
print_array(x.shape)
x = Numo::DFloat.new([0, 0])
print_array(x.shape)
x = Numo::SFloat.new(3)
print_array(x.shape)
x = Numo::DFloat.new([2, 3])
print_array(x.shape)
-- [python] ---------
* tests/numpy/ext_slice.py
import numpy as np
def print_matrix(data):
data_i = []
for i in list(data):
data_j = []
for j in i:
data_j.append(int("%d" % j))
data_i.append(data_j)
print(data_i)
def print_array(data):
datas = []
for i in data:
datas.append(int("%d" % i))
print(datas)
x = np.asarray([[1,2,3],[4,5,6]])
print_matrix(x)
"""
x[0,:]
"""
print_array(x[0,:])
"""
x[1,1:]
"""
y = x[1,1:]
print_array(y)
"""
x[1,:2]
"""
x[1,:2] = 5
print_array(y)
print_matrix(x)
x = np.asarray([[1,2,3],[4,5,6]])
print_matrix(x)
"""
x[:,0]
"""
print_array(x[:,0])
"""
x[:,1]
"""
print_array(x[:,1])
x = np.asarray([[[1,2,3],[4,5,6]],[[11,12,13],[14,15,16]]])
#print_matrix(x)
"""
x[0,:] Not Support
It is not supportable if the number of arguments and the number of dimensions are different.
print_matrix(x[0,:])
"""
"""
x[0,1,:]
"""
print_array(x[0,1,:])
-- [ruby] -----------
$ py2rb tests/numpy/ext_slice.py
require 'numo/narray'
def print_matrix(data)
data_i = []
for i in data.to_a
data_j = []
for j in i
data_j.push(("%d" % j).to_i)
end
data_i.push(data_j)
end
print(data_i)
end
def print_array(data)
datas = []
for i in data
datas.push(("%d" % i).to_i)
end
print(datas)
end
x = Numo::NArray.cast([[1, 2, 3], [4, 5, 6]])
print_matrix(x)
#
# x[0,:]
#
print_array(x[0, 0..-1])
#
# x[1,1:]
#
y = x[1, 1..-1]
print_array(y)
#
# x[1,:2]
#
x[1, 0...2] = 5
print_array(y)
print_matrix(x)
x = Numo::NArray.cast([[1, 2, 3], [4, 5, 6]])
print_matrix(x)
#
# x[:,0]
#
print_array(x[0..-1, 0])
#
# x[:,1]
#
print_array(x[0..-1, 1])
x = Numo::NArray.cast([[[1, 2, 3], [4, 5, 6]], [[11, 12, 13], [14, 15, 16]]])
#
# x[0,:] Not Support
#
# It is not supportable if the number of arguments and the number of dimensions are different.
#
# print_matrix(x[0,:])
#
#
# x[0,1,:]
#
print_array(x[0, 1, 0..-1])
-- [python] ---------
* tests/numpy/full.py
# coding: utf-8
import numpy as np
def print_matrix(data):
data_i = []
for i in list(data):
data_j = []
for j in i:
data_j.append(int("%d" % j))
data_i.append(data_j)
print(data_i)
x = np.full((2, 2), 5, dtype=np.int64)
print_matrix(x)
-- [ruby] -----------
$ py2rb tests/numpy/full.py
require 'numo/narray'
def print_matrix(data)
data_i = []
for i in data.to_a
data_j = []
for j in i
data_j.push(("%d" % j).to_i)
end
data_i.push(data_j)
end
print(data_i)
end
x = Numo::Int64.new([2, 2]).fill(5)
print_matrix(x)
-- [python] ---------
* tests/numpy/insert.py
import numpy as np
def print_array(data):
datas = []
for i in data:
datas.append(i)
print(datas)
def print_matrix(data):
data_i = []
for i in list(data):
data_j = []
for j in i:
data_j.append(j)
data_i.append(data_j)
print(data_i)
x = np.array([[1, 1], [2, 2], [3, 3]], dtype=np.int8)
"""[[1, 1], [2, 2], [3, 3]] => [1, 5, 1, 2, 2, 3, 3]"""
x = np.insert(x, 1, 5)
print_array(x)
x = np.array([[1, 1], [2, 2], [3, 3]])
"""[[1, 1], [2, 2], [3, 3]] => [[1, 5, 1], [2, 5, 2], [3, 5, 3]]"""
x = np.insert(x, 1, 5, axis=1)
print_matrix(x)
-- [ruby] -----------
$ py2rb tests/numpy/insert.py
require 'numo/narray'
def print_array(data)
datas = []
for i in data
datas.push(i)
end
print(datas)
end
def print_matrix(data)
data_i = []
for i in data.to_a
data_j = []
for j in i
data_j.push(j)
end
data_i.push(data_j)
end
print(data_i)
end
x = Numo::Int8.cast([[1, 1], [2, 2], [3, 3]])
# [[1, 1], [2, 2], [3, 3]] => [1, 5, 1, 2, 2, 3, 3]
x = (x).insert(1, 5)
print_array(x)
x = Numo::NArray.cast([[1, 1], [2, 2], [3, 3]])
# [[1, 1], [2, 2], [3, 3]] => [[1, 5, 1], [2, 5, 2], [3, 5, 3]]
x = (x).insert(1, 5, axis: 1)
print_matrix(x)
-- [python] ---------
* tests/numpy/like.py
# coding: utf-8
import numpy as np
def print_matrix(data):
data_i = []
for i in list(data):
data_j = []
for j in i:
data_j.append(int("%d" % j))
data_i.append(data_j)
print(data_i)
x = np.arange(6)
x = x.reshape(2, 3)
print_matrix(x)
x = np.ones_like(x)
print_matrix(x)
x = np.zeros_like(x)
print_matrix(x)
x = np.full_like(x, 1)
print_matrix(x)
a = ([1,2,3], [4,5,6])
x = np.empty_like(a)
print(list(x.shape))
a = np.array([[1., 2., 3.],[4.,5.,6.]])
x = np.empty_like(a)
print(list(x.shape))
-- [ruby] -----------
$ py2rb tests/numpy/like.py
require 'numo/narray'
def print_matrix(data)
data_i = []
for i in data.to_a
data_j = []
for j in i
data_j.push(("%d" % j).to_i)
end
data_i.push(data_j)
end
print(data_i)
end
x = Numo::DFloat.new(6).seq(0)
x = x.reshape(2, 3)
print_matrix(x)
x = (x).new_ones()
print_matrix(x)
x = (x).new_zeros()
print_matrix(x)
x = (x).new_fill(1)
print_matrix(x)
a = [[1, 2, 3], [4, 5, 6]]
x = Numo::NArray.new_like(a)
print(x.shape.to_a)
a = Numo::NArray.cast([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
x = Numo::NArray.new_like(a)
print(x.shape.to_a)
-- [python] ---------
* tests/numpy/linspace.py
import numpy as np
x = np.linspace(2.0, 3.0, num=5)
for a in x:
print(a)
-- [ruby] -----------
$ py2rb tests/numpy/linspace.py
require 'numo/narray'
x = Numo::DFloat.linspace(2.0, 3.0, 5)
for a in x
print(a)
end
-- [python] ---------
* tests/numpy/max_min.py
# coding: utf-8
import numpy as np
def print_matrix(data):
data_i = []
for i in list(data):
data_j = []
for j in i:
data_j.append(j)
data_i.append(data_j)
print(data_i)
def print_array(data):
datas = []
for i in data:
datas.append(i)
print(datas)
x = np.array([2,3,4])
print_array(x)
z = np.array([[2,3,6],[3,4,5]])
print_matrix(z)
"""
max
"""
y = x.max()
print(y)
y = np.max([2, 3, 4])
print(y)
"""
amax
"""
y = np.amax([2, 3, 4])
print(y)
"""
max axis=0
"""
y = z.max(axis=0)
print_array(y)
"""
max axis=1
"""
y = np.max([[2,3,6],[3,4,5]], axis=1)
print_array(y)
"""
min
"""
y = x.min()
print(y)
y = np.min([2, 3, 4])
print(y)
"""
amin
"""
y = np.amin([2, 3, 4])
print(y)
"""
min axis=0
"""
y = z.min(axis=0)
print_array(y)
"""
min axis=1
"""
y = np.min([[2,3,6],[3,4,5]], axis=1)
print_array(y)
"""
max axis=0 keepdims
"""
y = np.max([[2,3,6],[3,4,5]], axis=0, keepdims=True)
print_matrix(y)
"""
min keepdims
"""
y = np.min([[2,3,6],[3,4,5]], keepdims=True)
print_matrix(y)
-- [ruby] -----------
$ py2rb tests/numpy/max_min.py
require 'numo/narray'
def print_matrix(data)
data_i = []
for i in data.to_a
data_j = []
for j in i
data_j.push(j)
end
data_i.push(data_j)
end
print(data_i)
end
def print_array(data)
datas = []
for i in data
datas.push(i)
end
print(datas)
end
x = Numo::NArray.cast([2, 3, 4])
print_array(x)
z = Numo::NArray.cast([[2, 3, 6], [3, 4, 5]])
print_matrix(z)
#
# max
#
y = x.max()
print(y)
y = Numo::NArray.cast([2, 3, 4]).max()
print(y)
#
# amax
#
y = Numo::NArray.cast([2, 3, 4]).max()
print(y)
#
# max axis=0
#
y = z.max(axis: 0)
print_array(y)
#
# max axis=1
#
y = Numo::NArray.cast([[2, 3, 6], [3, 4, 5]]).max(axis: 1)
print_array(y)
#
# min
#
y = x.min()
print(y)
y = Numo::NArray.cast([2, 3, 4]).min()
print(y)
#
# amin
#
y = Numo::NArray.cast([2, 3, 4]).min()
print(y)
#
# min axis=0
#
y = z.min(axis: 0)
print_array(y)
#
# min axis=1
#
y = Numo::NArray.cast([[2, 3, 6], [3, 4, 5]]).min(axis: 1)
print_array(y)
#
# max axis=0 keepdims
#
y = Numo::NArray.cast([[2, 3, 6], [3, 4, 5]]).max(axis: 0, keepdims: true)
print_matrix(y)
#
# min keepdims
#
y = Numo::NArray.cast([[2, 3, 6], [3, 4, 5]]).min(keepdims: true)
print_matrix(y)
-- [python] ---------
* tests/numpy/maximum_minimum.py
# coding: utf-8
import numpy as np
def print_array(data):
datas = []
for i in data:
if float("%.3f" % abs(i)) == 0:
datas.append(float("%.3f" % abs(i)))
else:
datas.append(float("%.3f" % i))
print(datas)
x = np.arange(-5.0, 5.0, 0.1)
print(len(x))
print_array(list(x))
"""
maximum
"""
y = np.maximum(0, x)
print(len(y))
print_array(list(y))
"""
minimum
"""
y = np.minimum(0, x)
print(len(y))
print_array(list(y))
-- [ruby] -----------
$ py2rb tests/numpy/maximum_minimum.py
require 'numo/narray'
def print_array(data)
datas = []
for i in data
if ("%.3f" % i.abs).to_f == 0
datas.push(("%.3f" % i.abs).to_f)
else
datas.push(("%.3f" % i).to_f)
end
end
print(datas)
end
x = Numo::DFloat.new(((5.0-(-5.0))/(0.1).to_f).ceil).seq(-5.0, 0.1)
print(x.size)
print_array(x.to_a)
#
# maximum
#
y = Numo::DFloat.maximum(0, x)
print(y.size)
print_array(y.to_a)
#
# minimum
#
y = Numo::DFloat.minimum(0, x)
print(y.size)
print_array(y.to_a)
-- [python] ---------
* tests/numpy/ndarray.py
import numpy as np
a = np.array([1,2,3,4,5], dtype='int8')
if isinstance(a, np.ndarray):
print('OK')
else:
print('NG')
-- [ruby] -----------
$ py2rb tests/numpy/ndarray.py
require 'numo/narray'
a = Numo::NArray.cast([1, 2, 3, 4, 5])
if is_bool(a.is_a? Numo::NArray)
print("OK")
else
print("NG")
end
-- [python] ---------
* tests/numpy/ndarray2.py
import numpy
from numpy import ndarray
a = numpy.array([1,2,3,4,5], dtype='int8')
if isinstance(a, ndarray):
print('OK')
else:
print('NG')
-- [ruby] -----------
$ py2rb tests/numpy/ndarray2.py
require 'numo/narray'
include Numo
a = Numo::NArray.cast([1, 2, 3, 4, 5])
if is_bool(a.is_a? NArray)
print("OK")
else
print("NG")
end
-- [python] ---------
* tests/numpy/ndarray3.py
from numpy import *
a = array([1,2,3,4,5], dtype='int8')
if isinstance(a, ndarray):
print('OK')
else:
print('NG')
-- [ruby] -----------
$ py2rb tests/numpy/ndarray3.py
require 'numo/narray'
include Numo
a = NArray.cast([1, 2, 3, 4, 5])
if is_bool(a.is_a? NArray)
print("OK")
else
print("NG")
end
-- [python] ---------
* tests/numpy/not_like.py
# coding: utf-8
import numpy as np
def print_matrix(data):
data_i = []
for i in list(data):
data_j = []
for j in i:
data_j.append(int("%d" % j))
data_i.append(data_j)
print(data_i)
def print_array(data):
datas = []
for i in data:
if float("%.3f" % abs(i)) == 0:
datas.append(float("%.3f" % abs(i)))
else:
datas.append(float("%.3f" % i))
print(datas)
x = np.ones(5)
print_array(x)
x = np.zeros(5)
print_array(x)
x = np.full((2, 2), 1)
print_matrix(x)
#x = np.empty([2, 2])
#print(list(x.shape))
-- [ruby] -----------
$ py2rb tests/numpy/not_like.py
require 'numo/narray'
def print_matrix(data)
data_i = []
for i in data.to_a
data_j = []
for j in i
data_j.push(("%d" % j).to_i)
end
data_i.push(data_j)
end
print(data_i)
end
def print_array(data)
datas = []
for i in data
if ("%.3f" % i.abs).to_f == 0
datas.push(("%.3f" % i.abs).to_f)
else
datas.push(("%.3f" % i).to_f)
end
end
print(datas)
end
x = Numo::DFloat.ones(5)
print_array(x)
x = Numo::DFloat.zeros(5)
print_array(x)
x = Numo::DFloat.new([2, 2]).fill(1)
print_matrix(x)
-- [python] ---------
* tests/numpy/np_copy.py
import numpy as np
def print_array(data):
datas = []
for i in data:
datas.append(i)
print(datas)
x = np.array([1, 2, 3])
print_array(x)
y = np.copy(x)
print_array(y)
x[0] = 10
print_array(x)
print_array(y)
-- [ruby] -----------
$ py2rb tests/numpy/np_copy.py
require 'numo/narray'
def print_array(data)
datas = []
for i in data
datas.push(i)
end
print(datas)
end
x = Numo::NArray.cast([1, 2, 3])
print_array(x)
y = (x).dup()
print_array(y)
x[0] = 10
print_array(x)
print_array(y)
-- [python] ---------
* tests/numpy/product.py
import numpy as np
x = np.prod([1.,2.])
print(x)
x = np.prod([[1.,2.],[3.,4.]])
print(x)
x = np.prod([1.,2.], dtype= np.int32)
print(int(x))
x = np.prod([1.,2.], None, np.int32)
print(int(x))
x = np.prod([1.,2.], None, dtype= np.int32)
print(int(x))
x = np.prod(dtype= np.int32, a=[1.,2.])
print(int(x))
x = np.prod([[1.,2.],[3.,4.]], axis=0)
print(list(x))
x = np.prod([[1.,2.],[3.,4.]], axis=1)
print(list(x))
x = np.prod([3.,4.], keepdims=True)
print(list(x))
a = [3.,4.]
x = np.prod(a, dtype= np.int32)
print(int(x))
-- [ruby] -----------
$ py2rb tests/numpy/product.py
require 'numo/narray'
x = Numo::NArray.cast([1.0, 2.0]).prod()
print(x)
x = Numo::NArray.cast([[1.0, 2.0], [3.0, 4.0]]).prod()
print(x)
x = Numo::Int32.cast([1.0, 2.0]).prod()
print(x.to_i)
x = Numo::NArray.cast([1.0, 2.0]).prod(axis: nil)
print(x.to_i)
x = Numo::Int32.cast([1.0, 2.0]).prod(axis: nil)
print(x.to_i)
x = Numo::Int32.cast([1.0, 2.0]).prod()
print(x.to_i)
x = Numo::NArray.cast([[1.0, 2.0], [3.0, 4.0]]).prod(axis: 0)
print(x.to_a)
x = Numo::NArray.cast([[1.0, 2.0], [3.0, 4.0]]).prod(axis: 1)
print(x.to_a)
x = Numo::NArray.cast([3.0, 4.0]).prod(keepdims: true)
print(x.to_a)
a = [3.0, 4.0]
x = Numo::Int32.cast(a).prod()
print(x.to_i)
-- [python] ---------
* tests/numpy/random_rand.py
import numpy as np
x = np.random.rand(3,3,3)
print(x.ndim)
-- [ruby] -----------
$ py2rb tests/numpy/random_rand.py
require 'numo/narray'
x = Numo::DFloat.new(3, 3, 3).rand()
print(x.ndim)
-- [python] ---------
* tests/numpy/random_randint.py
import numpy as np
def print_array(data):
datas = []
for i in data:
datas.append(i)
print(datas)
x = np.random.randint(3)
if 0 <= x <= 3:
print('OK')
else:
print('NG')
x = np.random.randint(1,3)
if 1 <= x <= 3:
print('OK')
else:
print('NG')
x = np.random.randint(1,3,(3,3))
print(x.ndim)
print_array(x.shape)
x = np.random.randint(1,3,(3,3), dtype=np.int64)
print(x.ndim)
print_array(x.shape)
-- [ruby] -----------
$ py2rb tests/numpy/random_randint.py
require 'numo/narray'
def print_array(data)
datas = []
for i in data
datas.push(i)
end
print(datas)
end
x = Numo::Int32.new([]).rand(3)
if (0 <= x) and (x <= 3)
print("OK")
else
print("NG")
end
x = Numo::Int32.new([]).rand(3-(1)) + 1
if (1 <= x) and (x <= 3)
print("OK")
else
print("NG")
end
x = Numo::Int32.new([3, 3]).rand(3-(1)) + (1)
print(x.ndim)
print_array(x.shape)
x = Numo::Int64.new([3, 3]).rand(3-(1)) + (1)
print(x.ndim)
print_array(x.shape)
-- [python] ---------
* tests/numpy/random_random.py
import numpy as np
x = np.random.random((3,3,3))
print(x.ndim)
-- [ruby] -----------
$ py2rb tests/numpy/random_random.py
require 'numo/narray'
x = Numo::DFloat.new([3, 3, 3]).rand()
print(x.ndim)
-- [python] ---------
* tests/numpy/random_uniform.py
import numpy as np
def print_matrix(data):
data_i = []
for i in list(data):
data_j = []
for j in i:
data_j.append(j)
data_i.append(data_j)
print(data_i)
x = np.random.uniform(-1, 1, (3,2))
y = np.array(x < 1, dtype=np.int)
print_matrix(y)
y = np.array(x > -1, dtype=np.int)
print_matrix(y)
x = np.random.uniform(-1, 1)
x = np.asarray(x)
print(x.ndim)
-- [ruby] -----------
$ py2rb tests/numpy/random_uniform.py
require 'numo/narray'
def print_matrix(data)
data_i = []
for i in data.to_a
data_j = []
for j in i
data_j.push(j)
end
data_i.push(data_j)
end
print(data_i)
end
x = Numo::DFloat.new([3, 2]).rand(1-(-1)) + (-1)
y = Numo::Int64.cast(x < 1)
print_matrix(y)
y = Numo::Int64.cast(x > -1)
print_matrix(y)
x = Numo::DFloat.new().rand(1-(-1)) + -1
x = Numo::NArray.cast(x)
print(x.ndim)
-- [python] ---------
* tests/numpy/special_values.py
import numpy as np
print(str(0 * np.nan).lower())
if np.nan == np.nan: # False
print("True")
else:
print("False")
if np.inf > np.nan: # False
print("True")
else:
print("False")
print(str(np.nan - np.nan).lower())
-- [ruby] -----------
$ py2rb tests/numpy/special_values.py
require 'numo/narray'
print(((0 * Float::NAN).to_s).downcase())
if Float::NAN == Float::NAN
print("True")
else
print("False")
end
if Float::INFINITY > Float::NAN
print("True")
else
print("False")
end
print(((Float::NAN - Float::NAN).to_s).downcase())
-- [python] ---------
* tests/numpy/sqrt.py
# coding: utf-8
import numpy as np
def print_array(data):
datas = []
for i in data:
if float("%.3f" % abs(i)) == 0:
datas.append(float("%.3f" % abs(i)))
else:
datas.append(float("%.3f" % i))
print(datas)
""" Math functions """
x1 = np.arange(0, 6, 0.1)
y1 = np.sqrt(x1)
for y in [x1]:
print(len(y))
print_array(list(y))
-- [ruby] -----------
$ py2rb tests/numpy/sqrt.py
require 'numo/narray'
def print_array(data)
datas = []
for i in data
if ("%.3f" % i.abs).to_f == 0
datas.push(("%.3f" % i.abs).to_f)
else
datas.push(("%.3f" % i).to_f)
end
end
print(datas)
end
# Math functions
x1 = Numo::DFloat.new(((6-(0))/(0.1).to_f).ceil).seq(0, 0.1)
y1 = Numo::NMath.sqrt(x1)
for y in [x1]
print(y.size)
print_array(y.to_a)
end
-- [python] ---------
* tests/numpy/sum.py
# coding: utf-8
import numpy as np
x = np.array([1, 5])
w = np.array([2, 9])
b = 5
z = np.sum(w*x) + b
print(z)
z = (w * 3).sum()
print(z)
-- [ruby] -----------
$ py2rb tests/numpy/sum.py
require 'numo/narray'
x = Numo::NArray.cast([1, 5])
w = Numo::NArray.cast([2, 9])
b = 5
z = ((w * x).sum()) + b
print(z)
z = (w * 3).sum()
print(z)
-- [python] ---------
* tests/numpy/trigonometric_funcitons.py
# coding: utf-8
import numpy as np
def print_array(data):
datas = []
for i in data:
if float("%.3f" % abs(i)) == 0:
datas.append(float("%.3f" % abs(i)))
else:
datas.append(float("%.3f" % i))
print(datas)
""" Trigonometric functions """
x1 = np.arange(0, 6, 0.1)
x2 = np.arange(-0.9, 1, 0.1)
x3 = np.arange(1, 6, 0.1)
y1 = np.sin(x1)
y2 = np.cos(x1)
y3 = np.tan(x1)
yh1 = np.sinh(x1)
yh2 = np.cosh(x1)
yh3 = np.tanh(x1)
ay1 = np.arcsin(x2)
ay2 = np.arccos(x2)
ay3 = np.arctan(x1)
ayh1 = np.arcsinh(x1)
ayh2 = np.arccosh(x3)
ayh3 = np.arctanh(x2)
for y in [x1, x2, x3, y1, y2, y3, yh1, yh2, yh3, ay1, ay2, ay3, ayh1, ayh2, ayh3]:
print(len(y))
print_array(list(y))
-- [ruby] -----------
$ py2rb tests/numpy/trigonometric_funcitons.py
require 'numo/narray'
def print_array(data)
datas = []
for i in data
if ("%.3f" % i.abs).to_f == 0
datas.push(("%.3f" % i.abs).to_f)
else
datas.push(("%.3f" % i).to_f)
end
end
print(datas)
end
# Trigonometric functions
x1 = Numo::DFloat.new(((6-(0))/(0.1).to_f).ceil).seq(0, 0.1)
x2 = Numo::DFloat.new(((1-(-0.9))/(0.1).to_f).ceil).seq(-0.9, 0.1)
x3 = Numo::DFloat.new(((6-(1))/(0.1).to_f).ceil).seq(1, 0.1)
y1 = Numo::NMath.sin(x1)
y2 = Numo::NMath.cos(x1)
y3 = Numo::NMath.tan(x1)
yh1 = Numo::NMath.sinh(x1)
yh2 = Numo::NMath.cosh(x1)
yh3 = Numo::NMath.tanh(x1)
ay1 = Numo::NMath.asin(x2)
ay2 = Numo::NMath.acos(x2)
ay3 = Numo::NMath.atan(x1)
ayh1 = Numo::NMath.asinh(x1)
ayh2 = Numo::NMath.acosh(x3)
ayh3 = Numo::NMath.atanh(x2)
for y in [x1, x2, x3, y1, y2, y3, yh1, yh2, yh3, ay1, ay2, ay3, ayh1, ayh2, ayh3]
print(y.size)
print_array(y.to_a)
end
-- [python] ---------
* tests/numpy/type.py
# coding: utf-8
import numpy as np
print(np.int8)
print(np.int16)
print(np.int32)
print(np.int64)
print(np.int)
print(np.uint8)
print(np.uint16)
print(np.uint32)
print(np.uint64)
print(np.uint)
print(np.float32)
print(np.float64)
-- [ruby] -----------
$ py2rb tests/numpy/type.py
require 'numo/narray'
print(Numo::Int8)
print(Numo::Int16)
print(Numo::Int32)
print(Numo::Int64)
print(Numo::Int64)
print(Numo::UInt8)
print(Numo::UInt16)
print(Numo::UInt32)
print(Numo::UInt64)
print(Numo::UInt64)
print(Numo::SFloat)
print(Numo::DFloat)
-- [python] ---------
* tests/os/path_basename.py
import os
print(os.path.basename('foo/bar/hoge.txt'))
-- [ruby] -----------
$ py2rb tests/os/path_basename.py
print(File.basename("foo/bar/hoge.txt"))
-- [python] ---------
* tests/os/path_dirname.py
import os
print(os.path.dirname(__file__))
-- [ruby] -----------
$ py2rb tests/os/path_dirname.py
print(File.dirname(__FILE__))
-- [python] ---------
* tests/os/path_join.py
import os
print(os.path.join('foo/bar/', 'hoge.txt'))
-- [ruby] -----------
$ py2rb tests/os/path_join.py
print(File.join("foo/bar/","hoge.txt"))
-- [python] ---------
* tests/os/walk.py
import os
for dirpath, dirnames, filenames in os.walk('tests/os/testdir'):
print('<dirpath>')
print(dirpath)
print('<dirnames>')
for dirname in dirnames:
print(dirname)
print('<filenames>')
for filename in filenames:
print(filename)
-- [ruby] -----------
$ py2rb tests/os/walk.py
for (dirpath, dirnames, filenames) in PyLib.walk("tests/os/testdir")
print("<dirpath>")
print(dirpath)
print("<dirnames>")
for dirname in dirnames
print(dirname)
end
print("<filenames>")
for filename in filenames
print(filename)
end
end
-- [python] ---------
* tests/random/random_random.py
import random
x = random.random()
if 0 < x < 1:
print("OK")
else:
print("NG")
-- [ruby] -----------
$ py2rb tests/random/random_random.py
x = Random.rand()
if (0 < x) and (x < 1)
print("OK")
else
print("NG")
end
-- [python] ---------
* tests/six/integer_types.py
import six
if type(1) in six.integer_types:
print('Integer')
-- [ruby] -----------
$ py2rb tests/six/integer_types.py
if [Integer].include?(1.class)
print("Integer")
end
-- [python] ---------
* tests/six/iteritems.py
import six
a = {'a':1,'b':2,'c':3 }
items = dict()
for k, v in six.iteritems(a):
items[k] = v
print(items['a'])
print(items['b'])
print(items['c'])
-- [ruby] -----------
$ py2rb tests/six/iteritems.py
a = {"a" => 1, "b" => 2, "c" => 3}
items = {}
for (k, v) in a.to_a
items[k] = v
end
print(items["a"])
print(items["b"])
print(items["c"])
-- [python] ---------
* tests/six/itervalues.py
import six
foo = { 'a':'b' }
for f in six.itervalues(foo):
print(f)
-- [ruby] -----------
$ py2rb tests/six/itervalues.py
foo = {"a" => "b"}
for f in foo.values
print(f)
end
-- [python] ---------
* tests/six/moves.range.py
import six
xr = six.moves.range(20,40)
for x in xr:
print(x)
-- [ruby] -----------
$ py2rb tests/six/moves.range.py
xr = 20.upto(40-1)
for x in xr
print(x)
end
-- [python] ---------
* tests/six/py23.py
import six
if six.PY2:
print('Python 2')
elif six.PY3:
print('Python 3')
-- [ruby] -----------
$ py2rb tests/six/py23.py
if is_bool(false)
print("Python 2")
else
if is_bool(true)
print("Python 3")
end
end
-- [python] ---------
* tests/strings/count.py
txt = "the quick brown fox jumped over the lazy dogthe"
c = txt.count("the")
print(c)
c = txt.count("the",0,-20)
print(c)
c = txt.count("the",3)
print(c)
c = txt.count("the",4,15)
print(c)
c = txt.count("the",1,len(txt))
print(c)
c = txt.count("the",4,len(txt)-1)
print(c)
-- [ruby] -----------
$ py2rb tests/strings/count.py
txt = "the quick brown fox jumped over the lazy dogthe"
c = txt.count("the")
print(c)
c = txt.count("the", 0, -20)
print(c)
c = txt.count("the", 3)
print(c)
c = txt.count("the", 4, 15)
print(c)
c = txt.count("the", 1, txt.size)
print(c)
c = txt.count("the", 4, txt.size - 1)
print(c)
-- [python] ---------
* tests/strings/find.py
s = "the quick brown fox"
i = s.find("quick")
print(str(i))
i = s.find("dog")
print(str(i))
i = s.find("the")
print(str(i))
-- [ruby] -----------
$ py2rb tests/strings/find.py
s = "the quick brown fox"
i = s.index("quick")
print(i.to_s)
i = s.index("dog")
print(i.to_s)
i = s.index("the")
print(i.to_s)
-- [python] ---------
* tests/strings/join.py
a = ["a", "b", "c"]
print("".join(a))
print(" ".join(a))
print("x".join(a))
print("x ".join(a))
-- [ruby] -----------
$ py2rb tests/strings/join.py
a = ["a", "b", "c"]
print(a.join(""))
print(a.join(" "))
print(a.join("x"))
print(a.join("x "))
-- [python] ---------
* tests/strings/lstrip0.py
s1 = "\n\nabc\n\n\n"
s2 = "\t abc\n\t \n"
s3 = " abc "
for s in [s1,s2,s3]:
print("original("+s+")")
print("strip("+s.lstrip()+")")
-- [ruby] -----------
$ py2rb tests/strings/lstrip0.py
s1 = "
abc
"
s2 = "\t abc
\t
"
s3 = " abc "
for s in [s1, s2, s3]
print(("original(" + s) + ")")
print(("strip(" + s.lstrip()) + ")")
end
-- [python] ---------
* tests/strings/lstrip1.py
s = "abcxyz"
print("original("+s+")")
print("strip("+s.lstrip("cba")+")")
-- [ruby] -----------
$ py2rb tests/strings/lstrip1.py
s = "abcxyz"
print(("original(" + s) + ")")
print(("strip(" + s.lstrip("cba")) + ")")
-- [python] ---------
* tests/strings/replace.py
txt = "the quick brown fox jumped over thethe lazy dog"
txt2 = txt.replace("the","a")
print(txt)
print(txt2)
-- [ruby] -----------
$ py2rb tests/strings/replace.py
txt = "the quick brown fox jumped over thethe lazy dog"
txt2 = txt.gsub("the", "a")
print(txt)
print(txt2)
-- [python] ---------
* tests/strings/rfind.py
s = "the quick brown quick the fox"
i = s.rfind("quick")
print(str(i))
i = s.rfind("dog")
print(str(i))
i = s.rfind("the")
print(str(i))
-- [ruby] -----------
$ py2rb tests/strings/rfind.py
s = "the quick brown quick the fox"
i = s.rindex("quick")
print(i.to_s)
i = s.rindex("dog")
print(i.to_s)
i = s.rindex("the")
print(i.to_s)
-- [python] ---------
* tests/strings/rstrip0.py
s1 = "abc\n\n\n"
s2 = "abc\n\t \n"
s3 = "abc "
for s in [s1,s2,s3]:
print("original("+s+")")
print("strip("+s.rstrip()+")")
-- [ruby] -----------
$ py2rb tests/strings/rstrip0.py
s1 = "abc
"
s2 = "abc
\t
"
s3 = "abc "
for s in [s1, s2, s3]
print(("original(" + s) + ")")
print(("strip(" + s.rstrip()) + ")")
end
-- [python] ---------
* tests/strings/rstrip1.py
s = "abcxyz"
print("original("+s+")")
print("strip("+s.rstrip("yzx")+")")
-- [ruby] -----------
$ py2rb tests/strings/rstrip1.py
s = "abcxyz"
print(("original(" + s) + ")")
print(("strip(" + s.rstrip("yzx")) + ")")
-- [python] ---------
* tests/strings/split.py
s="the quick brown fox jumped over the lazy dog"
t = s.split(" ")
for v in t:
print(v)
r = s.split("e")
for v in r:
print(v)
x = s.split()
for v in x:
print(v)
# 2-arg version of split not supported
# y = s.split(" ",7)
# for v in y:
# print v
-- [ruby] -----------
$ py2rb tests/strings/split.py
s = "the quick brown fox jumped over the lazy dog"
t = s.split_p(" ")
for v in t
print(v)
end
r = s.split_p("e")
for v in r
print(v)
end
x = s.split()
for v in x
print(v)
end
-- [python] ---------
* tests/strings/splitlines.py
txt = """
aaa
bcfdss
sdsd
wqarwqr
werewr"""
lines = txt.splitlines()
for line in lines:
print(line)
-- [ruby] -----------
$ py2rb tests/strings/splitlines.py
txt = "
aaa
bcfdss
sdsd
wqarwqr
werewr"
lines = txt.split("
")
for line in lines
print(line)
end
-- [python] ---------
* tests/strings/string_format_combined_simple.py
a = "well"
b = "seems to work"
c = "something else"
d = 10
f = 15
s = "%s: %d, %s: %d, %s: %d" % (a, d, b, f, c, d)
print(s)
-- [ruby] -----------
$ py2rb tests/strings/string_format_combined_simple.py
a = "well"
b = "seems to work"
c = "something else"
d = 10
f = 15
s = "%s: %d, %s: %d, %s: %d" % [a, d, b, f, c, d]
print(s)
-- [python] ---------
* tests/strings/string_format_d.py
a = 1.123456
b = 10
c = -30
d = 34
e = 123.456
f = 19892122
# form 0
s = "b=%d" % b
print(s)
# form 1
s = "b,c,d=%d+%d+%d" % (b,c,d)
print(s)
# form 2
s = "b=%(b)0d and c=%(c)d and d=%(d)d" % { 'b':b,'c':c,'d':d }
print(s)
# width,flags
s = "e=%020d e=%+d e=%20d e=%-20d (e=%- 20d)" % (e,e,e,e,e)
print(s)
-- [ruby] -----------
$ py2rb tests/strings/string_format_d.py
a = 1.123456
b = 10
c = -30
d = 34
e = 123.456
f = 19892122
s = "b=%d" % b
print(s)
s = "b,c,d=%d+%d+%d" % [b, c, d]
print(s)
s = "b=%<b>0d and c=%<c>d and d=%<d>d" % {"b": b, "c": c, "d": d}
print(s)
s = "e=%020d e=%+d e=%20d e=%-20d (e=%- 20d)" % [e, e, e, e, e]
print(s)
-- [python] ---------
* tests/strings/string_format_d_simple.py
a = 1.123456
b = 10
c = -30
d = 34
e = 123.456
f = 19892122
# form 0
s = "b=%d" % b
print(s)
# form 1
s = "b,c,d=%d+%d+%d" % (b,c,d)
print(s)
# form 2
#s = "b=%(b)0d and c=%(c)d and d=%(d)d" % { 'b':b,'c':c,'d':d }
print(s)
# width,flags
#s = "e=%020d e=%+d e=%20d e=%-20d (e=%- 20d)" % (e,e,e,e,e)
print(s)
-- [ruby] -----------
$ py2rb tests/strings/string_format_d_simple.py
a = 1.123456
b = 10
c = -30
d = 34
e = 123.456
f = 19892122
s = "b=%d" % b
print(s)
s = "b,c,d=%d+%d+%d" % [b, c, d]
print(s)
print(s)
print(s)
-- [python] ---------
* tests/strings/string_format_f_simple.py
a = 1.123456
b = 10
c = -30
d = 34
e = 123.456789
f = 892122.129899
# form 0
s = "b=%f" % a
print(s)
# form 1
s = "b,c,d=%f+%f+%f" % (a, e, f)
print(s)
-- [ruby] -----------
$ py2rb tests/strings/string_format_f_simple.py
a = 1.123456
b = 10
c = -30
d = 34
e = 123.456789
f = 892122.129899
s = "b=%f" % a
print(s)
s = "b,c,d=%f+%f+%f" % [a, e, f]
print(s)
-- [python] ---------
* tests/strings/string_format_i.py
a = 1.123456
b = 10
c = -30
d = 34
e = 123.456
f = 19892122
# form 0
s = "b=%i" % b
print(s)
# form 1
s = "b,c,d=%i+%i+%i" % (b,c,d)
print(s)
# form 2
s = "b=%(b)i and c=%(c)i and d=%(d)i" % { 'b':b,'c':c,'d':d }
print(s)
# width,flags
s = "e=%020i e=%+i e=%20i e=%-20i (e=%- 20i)" % (e,e,e,e,e)
print(s)
-- [ruby] -----------
$ py2rb tests/strings/string_format_i.py
a = 1.123456
b = 10
c = -30
d = 34
e = 123.456
f = 19892122
s = "b=%i" % b
print(s)
s = "b,c,d=%i+%i+%i" % [b, c, d]
print(s)
s = "b=%<b>i and c=%<c>i and d=%<d>i" % {"b": b, "c": c, "d": d}
print(s)
s = "e=%020i e=%+i e=%20i e=%-20i (e=%- 20i)" % [e, e, e, e, e]
print(s)
-- [python] ---------
* tests/strings/string_format_s_simple.py
a = "well"
b = "seems to work"
c = "something else"
# form 0
s = "b=%s" % a
print(s)
# form 1
s = "b,c,d=%s+%s+%s" % (a, b, c)
print(s)
-- [ruby] -----------
$ py2rb tests/strings/string_format_s_simple.py
a = "well"
b = "seems to work"
c = "something else"
s = "b=%s" % a
print(s)
s = "b,c,d=%s+%s+%s" % [a, b, c]
print(s)
-- [python] ---------
* tests/strings/string_format_u.py
a = 1.123456
b = 10
c = -30
d = 34
e = 123.456
f = 19892122
# form 0
s = "b=%u" % b
print(s)
# form 1
s = "b,c,d=%u+%u+%u" % (b,c,d)
print(s)
# form 2
s = "b=%(b)0u and c=%(c)u and d=%(d)u" % { 'b':b,'c':c,'d':d }
print(s)
# width,flags
s = "e=%020u e=%+u e=%20u e=%-20u (e=%- 20u)" % (e,e,e,e,e)
print(s)
-- [ruby] -----------
$ py2rb tests/strings/string_format_u.py
a = 1.123456
b = 10
c = -30
d = 34
e = 123.456
f = 19892122
s = "b=%u" % b
print(s)
s = "b,c,d=%u+%u+%u" % [b, c, d]
print(s)
s = "b=%<b>0u and c=%<c>u and d=%<d>u" % {"b": b, "c": c, "d": d}
print(s)
s = "e=%020u e=%+u e=%20u e=%-20u (e=%- 20u)" % [e, e, e, e, e]
print(s)
-- [python] ---------
* tests/strings/strings_in_strings.py
print(""""Hello World!" <- should 'mess' up '''thing'''?""")
-- [ruby] -----------
$ py2rb tests/strings/strings_in_strings.py
print("\"Hello World!\" <- should \'mess\' up \'\'\'thing\'\'\'?")
-- [python] ---------
* tests/strings/strip.py
s1 = "\n\nabc\n\n\n"
s2 = "\t abc\n\t \n"
s3 = " abc "
for s in [s1,s2,s3]:
print("original("+s+")")
print("strip("+s.strip()+")")
-- [ruby] -----------
$ py2rb tests/strings/strip.py
s1 = "
abc
"
s2 = "\t abc
\t
"
s3 = " abc "
for s in [s1, s2, s3]
print(("original(" + s) + ")")
print(("strip(" + s.strip()) + ")")
end
-- [python] ---------
* tests/strings/strip1.py
s = "yxabcxyz"
print("original("+s+")")
print("strip("+s.strip("yzx")+")")
-- [ruby] -----------
$ py2rb tests/strings/strip1.py
s = "yxabcxyz"
print(("original(" + s) + ")")
print(("strip(" + s.strip("yzx")) + ")")
-- [python] ---------
* tests/strings/ulcase.py
s = "aBcddEzUh"
print(s)
s = s.upper()
print(s)
s = s.lower()
print(s)
-- [ruby] -----------
$ py2rb tests/strings/ulcase.py
s = "aBcddEzUh"
print(s)
s = s.upcase()
print(s)
s = s.downcase()
print(s)
-- [python] ---------
* tests/strings/zipstring.py
s1 = "hello"
s2 = "world"
s3 = "abcd"
s4 = list(zip(s1,s2,s3))
for item in s4:
print("----")
for val in item:
print(val)
-- [ruby] -----------
$ py2rb tests/strings/zipstring.py
s1 = "hello"
s2 = "world"
s3 = "abcd"
s4 = zip_p(s1, s2, s3).to_a
for item in s4
print("----")
for val in item
print(val)
end
end
-- [python] ---------
* tests/unittest/assertAlmostEqual.py
import unittest
class TestRunnable(unittest.TestCase):
def test_runnable(self):
#(first, second, places=7, msg=None, delta=None)
self.assertAlmostEqual(1.0, 1.00000001, 7)
self.assertAlmostEqual(1.0, 1.00000001, 7, '''comment test''')
self.assertAlmostEqual(1.0, 1.00000001, msg='''comment test''', delta=1e-8)
unittest.main()
-- [ruby] -----------
$ py2rb tests/unittest/assertAlmostEqual.py
require 'test/unit'
class TestRunnable < Test::Unit::TestCase
def test_runnable()
assert_in_delta(1.00000001, 1.0, 1e-1*1e-7)
assert_in_delta(1.00000001, 1.0, 1e-1*1e-7, "comment test")
assert_in_delta(1.00000001, 1.0, 1e-08, "comment test")
end
end
-- [python] ---------
* tests/unittest/assertEqual.py
import unittest
class TestRunnable(unittest.TestCase):
def test_runnable(self):
self.assertEqual('test', 'test', '''comment test''')
unittest.main()
-- [ruby] -----------
$ py2rb tests/unittest/assertEqual.py
require 'test/unit'
class TestRunnable < Test::Unit::TestCase
def test_runnable()
assert_equal("test", "test", "comment test")
end
end
-- [python] ---------
* tests/unittest/assertIn.py
import unittest
class Test_Unit(unittest.TestCase):
def test_hoge(self):
self.assertIn('foo', ['foo', 'bar'], 'message test')
unittest.main()
-- [ruby] -----------
$ py2rb tests/unittest/assertIn.py
require 'test/unit'
class Test_Unit < Test::Unit::TestCase
def test_hoge()
assert_include(["foo", "bar"], "foo", "message test")
end
end
-- [python] ---------
* tests/unittest/assertIs.py
import unittest
class Test_Unit(unittest.TestCase):
def test_hoge(self):
self.assertIs('foo', 'foo', 'message test')
unittest.main()
-- [ruby] -----------
$ py2rb tests/unittest/assertIs.py
require 'test/unit'
class Test_Unit < Test::Unit::TestCase
def test_hoge()
assert_equal("foo", "foo", "message test")
end
end
-- [python] ---------
* tests/unittest/assertIsInstance.py
import unittest
class Test_Unit(unittest.TestCase):
def test_hoge(self):
self.assertIsInstance('foo', str)
self.assertIsInstance(1, int, 'message test')
unittest.main()
-- [ruby] -----------
$ py2rb tests/unittest/assertIsInstance.py
require 'test/unit'
class Test_Unit < Test::Unit::TestCase
def test_hoge()
assert_true ("foo").is_a?(String)
assert_true (1).is_a?(Integer), "message test"
end
end
-- [python] ---------
* tests/unittest/assertRaises.py
import unittest
class MyException(Exception):
pass
class MyException2(Exception):
pass
class MyException3(Exception):
pass
class Foo:
def test(self):
raise MyException
class Bar:
def test(self, a, b, c=1, d=2):
if a != 'a':
raise MyException
if c == 1:
raise MyException2
else:
raise MyException3
def test(a, b, c=1, d=2):
if a != 'a':
raise MyException
if c == 1:
raise MyException2
else:
raise MyException3
def test2():
raise MyException
class TestRunnable(unittest.TestCase):
def bar(self):
assert False
def test_runnable(self):
''' NameError: name 'foo' is not defined '''
with self.assertRaises(NameError):
foo
foo = Foo()
self.assertRaises(MyException, foo.test)
bar = Bar()
self.assertRaises(MyException, bar.test,'aa', 'b')
self.assertRaises(MyException2, bar.test,'a', 'b')
self.assertRaises(MyException2, bar.test,'a', 'b', d=20)
self.assertRaises(MyException3, bar.test,'a', 'b', c=10, d=20)
self.assertRaises(MyException, test, 'aa', 'b', c=10, d=20)
self.assertRaises(MyException2, test, 'a', 'b')
self.assertRaises(MyException3, test, 'a', 'b', c=10, d=20)
self.assertRaises(MyException, test2)
self.assertRaises(AssertionError, self.bar)
class TestRunnable2(TestRunnable):
def test_runnable2(self):
self.assertRaises(AssertionError, self.bar)
unittest.main()
-- [ruby] -----------
$ py2rb tests/unittest/assertRaises.py
require 'test/unit'
class MyException < Exception
# pass
end
class MyException2 < Exception
# pass
end
class MyException3 < Exception
# pass
end
class Foo
def test()
raise MyException
end
end
class Bar
def test(a, b, c: 1, d: 2)
if a != "a"
raise MyException
end
if c == 1
raise MyException2
else
raise MyException3
end
end
end
def test(a, b, c: 1, d: 2)
if a != "a"
raise MyException
end
if c == 1
raise MyException2
else
raise MyException3
end
end
def test2()
raise MyException
end
class TestRunnable < Test::Unit::TestCase
def bar()
raise unless false
end
def test_runnable()
# NameError: name 'foo' is not defined
assert_raise(NameError) {
foo
}
foo = Foo.new()
assert_raise(MyException){foo.test()}
bar = Bar.new()
assert_raise(MyException){bar.test("aa", "b")}
assert_raise(MyException2){bar.test("a", "b")}
assert_raise(MyException2){bar.test("a", "b", d: 20)}
assert_raise(MyException3){bar.test("a", "b", c: 10, d: 20)}
assert_raise(MyException){test("aa", "b", c: 10, d: 20)}
assert_raise(MyException2){test("a", "b")}
assert_raise(MyException3){test("a", "b", c: 10, d: 20)}
assert_raise(MyException){test2()}
assert_raise(RuntimeError){bar()}
end
end
class TestRunnable2 < TestRunnable
def test_runnable2()
assert_raise(RuntimeError){bar()}
end
end
-- [python] ---------
* tests/unittest/assertTrue.py
import unittest
class TestRunnable(unittest.TestCase):
def test_runnable(self):
self.assertTrue(True, '''comment test''')
unittest.main()
-- [ruby] -----------
$ py2rb tests/unittest/assertTrue.py
require 'test/unit'
class TestRunnable < Test::Unit::TestCase
def test_runnable()
assert(true, "comment test")
end
end
-- [python] ---------
* tests/unittest/class.py
import unittest
class TestRunnable(unittest.TestCase):
pass
-- [ruby] -----------
$ py2rb tests/unittest/class.py
require 'test/unit'
class TestRunnable < Test::Unit::TestCase
# pass
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment