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  

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
srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call th...
New
Tee
can someone please explain to me how Enum.reduce works with maps
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod -- where is this set? Thanks.
New
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
johnnyicon
Hi all, I've just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I'm trying to use Postg...
New

Other popular topics Top

peerreynders
Manning 2016 Halloween weekend sale via Deal of the Day Friday, October 28 - Half off all MEAPs - code WM102816LT Saturday, October 29 ...
326 29600 154
New
dotdotdotPaul
Okay, I'm having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I'm sure I'...
New
Tee
can someone please explain to me how Enum.reduce works with maps
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: https://hexdocs.pm/ecto/Ecto.Schema.html#module-...
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
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
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
AstonJ
by Lance Halvorsen Elixir and Phoenix are generating tremendous excitement as an unbeatable platform for building modern web application...
460 27162 124
New

We're in Beta

About us Mission Statement