-1

hi I'm trying to convert this python code to Lua

names=['Deepak','Reema','John','Deepak','Munna','Reema','Deepak','Amit','John','Reema']
d={}
for i in range(len(names)-1):
    x=names[i]
    c=0
    for j in range(i,len(names)):
        if names[j]==names[i]:
            c=c+1
    count=dict({x:c})
    if x not in d.keys():
        d.update(count)
print (d)

I got all the other parts working from top but I couldn't figure out how to convert this part into Lua

    if x not in d.keys():
        d.update(count)

would be really great if someone can help me make sense of this conversion

Piglet
  • 27,501
  • 3
  • 20
  • 43

1 Answers1

1
  if x not in d.keys():
        d.update(count)

x is the name currently indexed in that loop cycle

d is a dictionary that is used to store the count of each name

c is a dictionary with a single entry, the count c of x in names

So that line basically says:

if the current name x has not been counted yet (is not in our dictionary), add its count c to d using the name in x as key.

This code is not very efficient as it counts the names every time, even if that name has already been counted. The order should be changed so you only count if there is no count in d, yet.

There is also no need to iterate over the whole array for each entry. That nested loop is nonsense. You can count that in one go.

You shouldn't learn from whatever resource that is.

In Lua the snippet above would look something like:

if not d[x] then d[x] = c end

or simply

d[x] = d[x] or c

This is how you could implement it in Lua efficiently.

local names= {'Deepak','Reema','John','Deepak','Munna','Reema','Deepak',
  'Amit','John','Reema'}
local counts = {}    
for _, v in ipairs(names) do
  counts[v] = counts[v] and counts[v] + 1 or 1
end
Piglet
  • 27,501
  • 3
  • 20
  • 43