vishal-h

vishal-h

Convert this python code into elixir

How would you write the accepted answer of https://stackoverflow.com/questions/19293481/how-to-elegantly-interleave-two-lists-of-uneven-length-in-python in Elixir?

More specifically, this code

from itertools import groupby

len_ab = len(a) + len(b)
groups = groupby(((a[len(a)*i//len_ab], b[len(b)*i//len_ab]) for i in range(len_ab)),
                 key=lambda x:x[0])
[j[i] for k,g in groups for i,j in enumerate(g)]

Most Liked

isaac-rstor

isaac-rstor

here’s a slightly more idiomatic version, although I think there might be some corner cases where it’s not as even as it could be:

defmodule M do 

  @doc """
  interleaves a short list b, into a long list a, such that the
  presence of the short list is evenly spaced in the long list.

  iex> M.interleave([1,2,3,4,5,6,7],[:a, :b])
  [1, 2, :a, 3, 4, 5, :b, 6, 7]
  """
  def interleave(a, b) do
    a_ct = Enum.count(a)
    b_ct = Enum.count(b)

    # calculates how many items are in the cycle of drawing from a vs b.
    recurrence = div(a_ct, b_ct) + 1

    # calculate how much we have to offset the recurrence by to center it.
    offset = div(a_ct + b_ct - ((b_ct - 1) * recurrence), 2)

    # bootstrap the initial condition
    interleave(a, b, offset, recurrence, [])
  end

  # terminating condition: we've exhausted all the items; since we put values on the front
  # in the tail calls, reverse the list.
  def interleave([], [], _, _, rev_list), do: Enum.reverse(rev_list)
  def interleave(a, [b_hd | b_tl], n, recurrence, list_so_far) 
    when rem(n, recurrence) == 0 do
    # draw from the shorter list every <recurrence>.  Put on front
    # of the list we're building, then tail call in.
    interleave(a, b_tl, n + 1, recurrence, [b_hd | list_so_far])
  end
  def interleave([a_hd | a_tl], b, n, recurrence, list_so_far) do
    # draw from the longer list.  Put on front of the list we're building, 
    # then tail call in.
    interleave(a_tl, b, n + 1, recurrence, [a_hd | list_so_far])
  end  

end

if the enum.reverse thing is a bit confusing, you can also do this:

def interleave([], [], _, _, list), do: list
def interleave(a, [b_hd | b_tl], n, interval, list_so_far) 
  when rem(n, interval) == 0 do
  interleave(a, b_tl, n + 1, interval, list_so_far ++ [b_hd])
end
def interleave([a_hd | a_tl], b, n, interval, list_so_far) do
  interleave(a_tl, b, n + 1, interval, list_so_far ++ [a_hd])
end  

Last Post!

UnderRated

UnderRated

Nice work …

Where Next?

Popular in Questions Top

Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID&lt;0.412.0&gt; terminating ** (Postgrex.Error) FATAL...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New

Other popular topics Top

minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
chrismccord
Phoenix 1.4.0 released Phoenix 1.4 is out! This release ships with exciting new features, most notably with HTTP2 support, improved deve...
688 31494 112
New
axelson
This post is a wiki (feel free to hit the edit button near the bottom right of this post to add your own changes!) This post collects co...
239 49084 226
New
AstonJ
Seen any cool LiveView demos, sample apps or examples? Please post them here! :003:
New
AngeloChecked
What learn first? Rust or Elixir Hi Elixir community! I’m here because i want learn a new language. I’m a junior developer and mainly i ...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New

We're in Beta

About us Mission Statement