数组算法中出现频率最高的元素,需要 python 代码转换为 ruby

Most frequent element in array algo, need python code converted to ruby

下面是我写的 python 代码,它将找到数组中最常见的元素,我想将下面的代码转换为 ruby 具有与 ruby 等价物相同的格式到 python 关键字,即对于 python 语法 "not in" 我想知道 ruby 等同于它等..,所有测试用例都应该有效。谢谢!

def most_frequent(given_list):
    max_count = -1
    max_item = None
    count = {}
    for i in given_list:
        if i not in count:
            count[i] = 1
        else:
            count[i] += 1
        if count[i] > max_count:
            max_count = count[i]
            max_item = i
    return max_item

# NOTE: The following input values will be used for testing your solution.
# most_frequent(list1) should return 1.
list1 = [1, 3, 1, 3, 2, 1]
# most_frequent(list2) should return 3.
list2 = [3, 3, 1, 3, 2, 1]
# most_frequent(list3) should return None.
list3 = []
# most_frequent(list4) should return 0.
list4 = [0]
# most_frequent(list5) should return -1.
list5 = [0, -1, 10, 10, -1, 10, -1, -1, -1, 1]

result1 = most_frequent(list1)
result2 = most_frequent(list2)
result3 = most_frequent(list3)
result4 = most_frequent(list4)
result5 = most_frequent(list5)
print result1, result2, result3, result4, result5

已转换 Ruby 代码:

def most_frequent(given_list)
  max_count = -1
  max_item = nil
  count = {}
  for i in given_list
    count[i] ||= 1
    count[i] += 1
    if count[i] > max_count
      max_count = count[i]
      max_item = i
    end
  end
  max_item
end

注意:Ruby 伙计们不会像这样编写代码,ruby 中提供了更简洁的方法来编写此代码。

在 ruby 而不是 None 使用 nil 如果你想在输出中使用 None 那么最后将 max_item 替换为 max_items || 'None'

要打印 result 的值,请使用 puts