Hal
Hal

Reputation: 219

How would I best translate this Python script to Lua?

I am attempting to translate this Python to Lua, as someone unfamiliar with Python. The function is taken from http://rosettacode.org/wiki/Sierpinski_triangle#Python

def sierpinski(n):
    d = ["*"]
    for i in xrange(n):
        sp = " " * (2 ** i)
        d = [sp+x+sp for x in d] + [x+" "+x for x in d]
    return d

print "\n".join(sierpinski(4))

This is what I have so far, but it does not give the desired output. Am I analyzing the Python wrong? I don't know Python myself, so I assume this is the case.

function each(array,operation)
    --  Do an operation on each object in an array
    local out = {}
    for _,obj in pairs(array) do
        print(obj)
        table.insert(out,operation(obj))
    end
    return out
end

function join(...)
    --  Join two tables
    local out = {}
    for _,arr in pairs({...}) do
        for _,v in pairs(arr) do
            table.insert(out,v)
        end
    end
    return out
end

function sierpinski(n)
    local triangle = {"*"}
    for i = 1,n do
        local sp = (" "):rep(2^n)
        triangle = join(
            each(triangle,(function(x)
                return sp..x..sp
            end)),
            each(triangle,(function(x)
                return x.." "..x
            end))
        )
    end
    return table.concat(triangle,"\n")
end

print(sierpinski(4))

Upvotes: 2

Views: 1440

Answers (2)

Winston
Winston

Reputation: 71

A shorter version:

local function sierpinski(n)
  local d = {'*'}
  for i = 0, n - 1 do
    local sp = string.rep(' ', 2^i)
    local len = #d
    for i = 1, len do
      local x = d[i]
      d[i] = sp .. x .. sp
      d[i+len] = x .. ' ' .. x
    end
  end
  return d
end

print(table.concat(sierpinski(4), '\n'))

Upvotes: 2

Dair
Dair

Reputation: 16240

So your code is almost correct just a couple things:

    print(obj)

This line produces unnecessary printing which screws up some stuff.

for i = 1,n do

Because of different indexing, between Python Lua, this should be: 0,n-1.

    local sp = (" "):rep(2^n)

n should be i.

All and all this works on my machine:

function each(array,operation)
    --  Do an operation on each object in an array
    local out = {}
    for _,obj in pairs(array) do
        table.insert(out,operation(obj))
    end
    return out
end

function join(...)
    --  Join two tables
    local out = {}
    for _,arr in pairs({...}) do
        for _,v in pairs(arr) do
            table.insert(out,v)
        end
    end
    return out
end

function sierpinski(n)
    local triangle = {"*"}
    for i = 0,n-1 do
        local sp = (" "):rep(2^i)
        triangle = join(each(triangle,(function(x) return sp..x..sp end)), each(triangle,(function(x) return x.." "..x end)))
    end
    return table.concat(triangle,"\n")
end

Upvotes: 3

Related Questions