Julia lang remove duplicates in a list of tuples considering the second element - tuples

Is there an easy way to remove duplicates of a list of tuples where for the duplicates only the second element is considered? For example when I have the following list:
a = [("a",1),("b",3),("c",4),("d",8),("e",1)]
I want to end up with:
a = [("b",3),("c",4),("d",8),("e",1)]
I doesn't matter if I keep "a" or "e".

Yes, you can use the unique(f, itr) method to do this; it returns the elements of itr where f returns unique values.
julia> unique(x->x[2], a)
4-element Array{Tuple{String,Int64},1}:
("a", 1)
("b", 3)
("c", 4)
("d", 8)

Related

Apply function to one element of tuple in Scala

I'm using Scala and I have a tuple (String, List[Int]) like this:
("tom", [1,2,3])
I need to apply a function to the second element of this tuple and to return a list of tuples. Say, I want to multiply the elements in the list by 2, so the output should be:
[("tom", 2), ("tom", 4), ("tom", 6)]
How to do this?
As #Luis says, the idea is that you use map.
First you get your list out of the input tuple. Here's one way to do it.
val name, values = ("tom", List(1,2,3))
Next you iterate over that list. For each element, you convert it into a new tuple with a constant name and the value multiplied by 2.
val result = values.map(x => (name, 2*x))

Erlang function that returns two values

I have Erlang function that returns the last element of a list
lastElement([H|[]]) ->H;
lastElement([H|T]) ->lastElement(T).
and a function that returns a list without last element
withoutLastElement([H|[]], Result) ->Result;
withoutLastElement([H|T]) ->withoutLastElement(T, [H|Result]).
so i browse the same list for two times, and for more efficiency i want to do only a function that returns the last element of a list and returns this list without this element in one browse, this is easy in another language but i can't do that in Erlang so any help and thank you all.
You'd usually return the two values in a tuple:
list_and_last(List) ->
list_and_last(List, []).
list_and_last([H], Result) ->
{H, Result};
list_and_last([H|T], Result) ->
list_and_last(T, [H|Result]).
Calling list_and_last with [1,2,3] returns {3,[2,1]}.
In Erlang you can return a tuple, so you simply define a tuple with the last element and the list:
... -> {last_element, list}
You retrieve the value with pattern matching:
{Element, List} = last_element_and_new_list(The_List)
The last element and list will be bound to the respective variables. Note that you can return more than two values in a tuple.
You can simply reverse the list:
List = [1, 2, 3, 4, 5, 6],
[Last | Rest] = lists:reverse(List)

Intersection of two nested lists in Python

I've a problem with the nested lists. I want to compute the lenght of the intersection of two nested lists with the python language. My lists are composed as follows:
list1 = [[1,2], [2,3], [3,4]]
list2 = [[1,2], [6,7], [4,5]]
output_list = [[1,2]]
How can i compute the intersection of the two lists?
I think there are two reasonable approaches to solving this issue.
If you don't have very many items in your top level lists, you can simply check if each sub-list in one of them is present in the other:
intersection = [inner_list for inner in list1 if inner_list in list2]
The in operator will test for equality, so different list objects with the same contents be found as expected. This is not very efficient however, since a list membership test has to iterate over all of the sublists. In other words, its performance is O(len(list1)*len(list2)). If your lists are long however, it may take more time than you want it to.
A more asymptotically efficient alternative approach is to convert the inner lists to tuples and turn the top level lists into sets. You don't actually need to write any loops yourself for this, as map and the set type's & operator will take care of it all for you:
intersection_set = set(map(tuple, list1)) & set(map(tuple, list2))
If you need your result to be a list of lists, you can of course, convert the set of tuples back into a list of lists:
intersection_list = list(map(list, intersection_set))
What about using sets in python?
>>> set1={(1,2),(2,3),(3,4)}
>>> set2={(1,2),(6,7),(4,5)}
>>> set1 & set2
set([(1, 2)])
>>> len(set1 & set2)
1
import json
list1 = [[1,2], [2,3], [3,4]]
list2 = [[1,2], [6,7], [4,5]]
list1_str = map(json.dumps, list1)
list2_str = map(json.dumps, list2)
output_set_str = set(list1_str) & set(list2_str)
output_list = map(json.loads, output_set_str)
print output_list

How can I fold the nth and (n+1)th elements into a new list in Scala?

Let's say I have List(1,2,3,4,5) and I want to get
List(3,5,7,9), that is, the sums of the element and the previous (1+2, 2+3,3+4,4+5)
I tried to do this by making two lists:
val list1 = List(1,2,3,4)
val list2 = (list1.tail ::: List(0)) // 2,3,4,5,0
for (n0_ <- list1; n1th_ <- list2) yield (n0_ + n1_)
But that combines all the elements with each other like a cross product, and I only want to combine the elements pairwise. I'm new to functional programming and I thought I'd use map() but can't seem to do so.
List(1, 2, 3, 4, 5).sliding(2).map(_.sum).to[List] does the job.
Docs:
def sliding(size: Int): Iterator[Seq[A]]
Groups elements in fixed size blocks by passing a "sliding window" over them (as opposed to partitioning them, as is done in grouped.)
You can combine the lists with zip and use map to add the pairs.
val list1 = List(1,2,3,4,5)
list1.zip(list1.tail).map(x => x._1 + x._2)
res0: List[Int] = List(3, 5, 7, 9)
Personally I think using sliding as Infinity has is the clearest, but if you want to use a zip-based solution then you might want to use the zipped method:
( list1, list1.tail ).zipped map (_+_)
In addition to being arguably clearer than using zip, it is more efficient in that the intermediate data structure (the list of tuples) created by zip is not created with zipped. However, don't use it with infinite streams, or it will eat all of your memory.

scala - Getting a read-only sublist view of a List

I would like a List, Seq, or even an Iterable that is a read-only view of a part of a List, in my specific case, the view will always start at the first element.
List.slice, is O(n) as is filter. Is there anyway of doing better than this - I don't need any operations like +, - etc. Just apply, map, flatMap, etc to provide for list comprehension syntax on the sub list.
Is the answer to write my own class whose iterators keep a count to know where the end is?
How about Stream? Stream is Scala's way to laziness. Because of Stream's laziness, Stream.take(), which is what you need in this case, is O(1). The only caveat is that if you want to get back a List after doing a list comprehension on a Stream, you need to convert it back to a List. List.projection gets you a Stream which has most of the opeations of a List.
scala> val l = List(1, 2, 3, 4, 5)
l: List[Int] = List(1, 2, 3, 4, 5)
scala> val s = l.projection.take(3)
s: Stream[Int] = Stream(1, ?)
scala> s.map(_ * 2).toList
res0: List[Int] = List(2, 4, 6)
scala> (for (i <- s) yield i * 2).toList
res1: List[Int] = List(2, 4, 6)
List.slice and List.filter both return Lists -- which are by definition immutable.The + and - methods return a different List, they do not change the original List. Also, it is hard to do better than O(N). A List is not random access, it is a linked list. So imagine if the sublist that you want is the last element of the List. The only way to access that element is to iterate over the entire List.
Well, you can't get better than O(n) for drop on a List. As for the rest:
def constantSlice[T](l: List[T], start: Int, end: Int): Iterator[T] =
l.drop(start).elements.take(end - start)
Both elements and take (on Iterator) are O(1).
Of course, an Iterator is not an Iterable, as it is not reusable. On Scala 2.8 a preference is given to returning Iterable instead of Iterator. If you need reuse on Scala 2.7, then Stream is probably the way to go.