灵丹妙药中的嵌套列表理解

时间:2016-04-12 16:40:27

标签: elixir

为了学习Elixir,我想解决这个问题:https://projecteuler.net/problem=96

为了通过董事会,我会这样开始: 在python:

row_indexes = ["A","B","C","D","E","F","G","H","I"];
col_indexes = ["1","2","3","4","5","6","7","8","9"];
row_box_indexes = [["A","B","C"],["D","E","F"],["G","H","I"]];
col_box_indexes = [["1","2","3"],["4","5","6"],["7","8","9"]];

cols = [[r+c for r in row_indexes] for c in col_indexes]
rows = [[r+c for c in col_indexes] for r in row_indexes]
boxes = [[r+c for c in C for r in R] for C in col_box_indexes for R in row_box_indexes]

print(cols) // [['A1', 'B1', 'C1', 'D1', 'E1', 'F1', 'G1', 'H1', 'I1'],...,['A9', 'B9', 'C9', 'D9', 'E9', 'F9', 'G9', 'H9', 'I9']]

我正在努力使用elixir中的列表理解我试过这个,但它给我一个列表,包含我的所有结果

row_indexes = ["A","B","C","D","E","F","G","H","I"];
col_indexes = ["1","2","3","4","5","6","7","8","9"];
row_box_indexes = [["A","B","C"],["D","E","F"],["G","H","I"]];
col_box_indexes = [["1","2","3"],["4","5","6"],["7","8","9"]];

# in iex
for c <- col_indexes,
    x <- (for r <- row_indexes, do: r<>c),
    do: x

# ["A1", "B1", "C1", "D1", "E1", "F1", "G1", "H1", "I1", "A2", "B2", "C2", "D2",..., "I5", "A6", "B6", "C6", "D6", "E6", ...]

1)在Elixir中解决这个问题的好方法是不是很好?

2)你能解释一下我如何在python中获得与print(cols)相同的结果吗?

谢谢:)

2 个答案:

答案 0 :(得分:1)

两种理解之间存在差异。在python中,你使用内部的一个在外部理解上生成一个列表,在Elixir版本中,没有嵌套的理解来创建嵌套列表。

标题中var a = "a", b = "b", c = "c"; 的结果当然是一个列表,但它将沿着每个for r <- row_indexes, do: r<>c的结果进行迭代,以创建笛卡尔积的值c和r。

因此,理解的每次迭代都会为您提供当前c和通讯员col_index的值。当你只返回理解索引的第二个键时,你会得到一个列表。

一个修复方法是对行索引进行实际的嵌套式理解,如下所示:

r<>c

答案 1 :(得分:0)

谢谢劳罗的回答! 所以是的,理解是不同的,并且不可能在python和Elixir中做同样的事情 这个解决方案(可能不是最好的......)比python更长,但它可以工作:

  @doc """
  generate all the rows coordinates
      [[{0,0},{1,0},{2,0},{3,0},{4,0},{5,0},{6,0},{7,0},{8,0},],...]
  """
  def create_rows(size \\ 9) do
    Enum.reduce(0..size - 1, [], fn(ord,acc) ->
      col = Enum.reduce(0..size - 1, [], fn(abs, accu) ->
        [{abs,ord}|accu]
      end)
      |> Enum.reverse
      [col | acc]
    end)
    |> Enum.reverse
  end

它会产生这个:

[
  [{0,0},{1,0},{2,0},{3,0},{4,0},{5,0},{6,0},{7,0},{8,0},],
  [{0,1},{1,1},{2,1},{3,1},{4,1},{5,1},{6,1},{7,1},{8,1},],
  [{0,2},{1,2},{2,2},{3,2},{4,2},{5,2},{6,2},{7,2},{8,2},],
  [{0,3},{1,3},{2,3},{3,3},{4,3},{5,3},{6,3},{7,3},{8,3},],
  [{0,4},{1,4},{2,4},{3,4},{4,4},{5,4},{6,4},{7,4},{8,4},],
  [{0,5},{1,5},{2,5},{3,5},{4,5},{5,5},{6,5},{7,5},{8,5},],
  [{0,6},{1,6},{2,6},{3,6},{4,6},{5,6},{6,6},{7,6},{8,6},],
  [{0,7},{1,7},{2,7},{3,7},{4,7},{5,7},{6,7},{7,7},{8,7},],
  [{0,8},{1,8},{2,8},{3,8},{4,8},{5,8},{6,8},{7,8},{8,8},],
]