【问题标题】:How do I compute the argmax of a function on a list in Stanza?如何计算 Stanza 列表中函数的 argmax?
【发布时间】:2021-02-26 00:55:18
【问题描述】:

我想知道是否有一个函数可以计算 Stanza 中数字列表(整数、长整数、浮点数)numbers 上的函数 f 的 argmax。

它将具有以下行为:

defn argmax (f, numbers: Tuple) :
  val N = length(numbers)
  if N == 0 :
    fatal("Can't compute the argmax of an empty tuple")

  var max-index = 0
  var max-value = numbers[0]

  for idx in 1 to N do :
    val value = f(numbers[idx])
    if value > max-value :
      max-index = idx
      max-value = value
  
  max-index

defn f (x) :
  x * x

println $ argmax(f, [1, 6, 2, 5])

结果:

1

谢谢!

【问题讨论】:

    标签: stanza


    【解决方案1】:

    创建argmax 的一种方法是函数式风格,如下所示:

    defn argmax (nums:Tuple<Comparable>) :
      reduce(fn (a, b) : a when (a[1] > b[1]) else b, zip(0 to false, nums))[0]
    

    在组合索引和值的元组上应用成对的max。要完成解决方案,您将使用以下内容:

    defn f (x) :
      x * x
    
    defn argmax (f, nums:Tuple<Comparable>) :
      argmax(map(f, nums))
    

    【讨论】:

      【解决方案2】:

      您可以使用一对函数 argmax!argmax?,这是序列操作可能失败的节中的常见习惯用法(在这种情况下,当元组为空时)

      例如:

      defpackage argmax: 
        import core
        import collections
      
      defn argmax? (vals:Seqable<Comparable>) -> False|Int:
        false when empty?(to-seq(vals)) else argmax!(vals)
      
      defn argmax! (vals:Seqable<Comparable>) -> Int: 
        defn compare (left:[Comparable, Int], right:[Comparable, Int]):
          left when left[0] > right[0] else right
        val [_, argmax] = reduce(compare, zip(vals, 0 to false))
        argmax
      
      val vals = [1, 6, 2, 5]
      println("argmax of [%,] is: %_" % [vals, argmax!(vals)])
      println("argmax of empty tuple is: %_" % [argmax?([])])
      

      要将函数应用于任意序列,您可以使用seq

      val vals = [1, 6, 2, 5]
      defn f (x): 
        x * x
      println("argmax of f = %_" % [argmax?(seq(f, vals))])
      

      类型注释是可选的,它们只是为了清楚起见

      【讨论】:

        猜你喜欢
        • 2020-04-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-30
        • 1970-01-01
        • 2022-11-17
        • 2017-02-25
        • 1970-01-01
        相关资源
        最近更新 更多