小编Fys*_*ysx的帖子

Python:list()作为字典的默认值

我有Python代码,看起来像:

if key in dict:
  dict[key].append(some_value)
else:
  dict[key] = [some_value]
Run Code Online (Sandbox Code Playgroud)

但我认为应该有一些方法可以绕过这个'if'语句.我试过了

dict.setdefault(key, [])
dict[key].append(some_value)
Run Code Online (Sandbox Code Playgroud)

dict[key] = dict.get(key, []).append(some_value)
Run Code Online (Sandbox Code Playgroud)

但两人都抱怨"TypeError:unhashable type:'list'".有什么建议?谢谢!

python dictionary default-value

22
推荐指数
1
解决办法
2万
查看次数

Scala Extractor with Argument

Scala中是否存在允许提取器采用自定义参数的语法?这个例子有点人为.假设我在整数上有一个二叉搜索树,如果它的值可以被某个自定义值整除,我想匹配当前节点.

使用F#活动模式,我可以执行以下操作:

type Tree =
    | Node of int * Tree * Tree
    | Empty  

let (|NodeDivisibleBy|_|) x t =
    match t with
    | Empty -> None
    | Node(y, l, r) -> if y % x = 0 then Some((l, r)) else None

let doit = function
    | NodeDivisibleBy(2)(l, r) -> printfn "Matched two: %A %A" l r
    | NodeDivisibleBy(3)(l, r) -> printfn "Matched three: %A %A" l r
    | _ -> printfn "Nada"

[<EntryPoint>]
let main args =
    let …
Run Code Online (Sandbox Code Playgroud)

f# scala pattern-matching active-pattern extractor

9
推荐指数
2
解决办法
651
查看次数

f#中的seq <int>与Lazy <LazyList <int >>的性能

有用于产生汉明数的无限流(即所有的正整数公知的解决方案n,其中n = 2^i * 3^j * 5^k).我在F#中以两种不同的方式实现了这一点.第一种方法使用seq<int>.解决方案很优雅,但性能很糟糕.第二种方法使用尾部被包裹的自定义类型Lazy<LazyList<int>>.解决方案很笨重,但性能却令人惊叹.

有人可以解释为什么性能使用seq<int>如此糟糕,如果有办法解决它?谢谢.

方法1使用seq<int>.

// 2-way merge with deduplication
let rec (-|-) (xs: seq<int>) (ys: seq<int>) =
    let x = Seq.head xs
    let y = Seq.head ys
    let xstl = Seq.skip 1 xs
    let ystl = Seq.skip 1 ys
    if x < y then seq { yield x; yield! xstl -|- ys }
    elif x > y then seq { yield y; yield! …
Run Code Online (Sandbox Code Playgroud)

f# infinite seq hamming-numbers

7
推荐指数
2
解决办法
697
查看次数

scala不会警告未使用的计算或值

我有这个小scala示例:

object Test {
  def add(x: Int, y: Int) = {
    val z = x - y
    x match {
      case 0 => 0 - y
      case 1 => 1 - y
      case _ => x - y
    }
    x + y
  }

  def main(args: Array[String]) {
    println(add(5, 6))
  }
}
Run Code Online (Sandbox Code Playgroud)

我觉得scala应警告'z'和'x匹配......'未被使用.我没有注意到任何编译器选项可以打开更多警告.我正在使用scala 2.10.1.

思考?谢谢!

compiler-construction warnings scala scalac

5
推荐指数
1
解决办法
713
查看次数