如何查找一个数组是否是另一个数组的子集? [英] How to find if an array is subset of another array?

查看:381
本文介绍了如何查找一个数组是否是另一个数组的子集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,我们可以使用set或itertools查找另一个列表的一个列表的子集,我们如何在Lua中做同样的事情?

In Python we can use set or itertools to find the subset of one list of another list, how do we do the same in Lua ?

a = {1,2,3}
b = {2,3}

我如何检查b是a的子集?

How do i check that b is a subset of a ?

推荐答案

可以在Lua中使用表作为成员资格测试的查找表来实现集(

Sets can be implemented in Lua using tables as look-ups for membership testing (as done in Programming in Lua). The keys in the table are the elements of the set and the values are either true if the element belongs to the set or nil otherwise.

a = {[1]=true, [2]=true, [3]=true}
b = {[2]=true, [3]=true}

-- Or create a constructor
function set(list)
   local t = {}
   for _, item in pairs(list) do
       t[item] = true
   end
   return t
end

a = set{1, 2, 3}
b = set{2, 3}

这种形式的书写集操作也很简单(如此处).

Writing set operations is straightforward in this form as well (as here).

function subset(a, b)
   for el, _ in pairs(a) do
      if not b[el] then
         return false
      end
    end
   return true
end

print(subset(b, a)) -- true
print(subset(set{2, 1}, set{2, 2, 3, 1})) -- true

a[1] = nil -- remove 1 from a
print(subset(a, b)) -- true

如果ab必须保持数组形式,则子集可以这样实现:

If a and b must remain in array form then subset can be implemented like so:

function arraysubset(a, b)
   local s = set(b)
   for _, el in pairs(a) -- changed to iterate over values of the table
      if not s[el] then
         return false
      end
   end
   return true
end

这篇关于如何查找一个数组是否是另一个数组的子集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆