Building sucessive union of lists/arrays using comprehension and iteration - list

Afternoon-I'm currently trying to read up on/implement more clever ways to form the union of sub lists after imposing varying conditions on the original list (or, more generally, any list)-specifically the successive union over what may be a large number of sublists. the data within may be strings, or numerical data.
For example, I could form sub lists of the following list based on the condition if 'a' appears in the ith position of the list.
mylist = [a b c d
d a b c
c b a d
b d c a]
mysublist1 = [item for item in mylist if item[0] == a]
mysublist = [ a b c d]
In this example, I could repeat this process and change the condition to be the ith position of the list and generate 4 sublists. I could then-for demonstrations sake, reform the original list using the handy set functions
set(thisset).union(thatset)
However, without being clever this will take n-1 instances of these guys (forming the first union, then taking successive unions)-which can get dicey.
Is anyone aware of any methods that would make this a bit more elegant? I have tried appending sets to a list and then defining the successive union over the size of this list be fruitful (but I'm getting some type errors!)
Thanks!

Related

Problem with a list in the form of [(key, [..]) ; ...]

I'm trying to learn OCaml since I'm new to the language and I stumbled across this problem where I can't seem to find a way to see, in a function where I need to merge 2 kinds of these lists, if there is already an element with a key, and if so how to join the elements that come after. Would appreciate any guidance.
For example if I have:
l1: [(k, [e]); (ka, [])]
l2: [(k, [f; g])]
How can I end up with:
fl: [(k, [e; f; g]); (ka, [])]
Basically, how can I filter the key k from both lists while making their elements combine.
There are functions in the standard OCaml library for dealing with lists of pairs where the first element of each pair is a key. You will find them described here: https://ocaml.org/releases/4.12/api/List.html under Association lists.
I will repeat what #ivg says. This is not how you want to solve your problem if you have more than just a few pairs to work with.
First of all, using lists as mappings is a bad idea. It is much better to use dedicated data structures such as maps and hash tables.
Answering your question directly, you can concatenate two lists using the (#) operator, e.g.,
# [1;2;3] # [4;5;6];;
- : int list = [1; 2; 3; 4; 5; 6]
If you don't want repetitive elements when you merge then, and I feel like I repeat myself, it is bad to use lists for sets, it is better to use dedicated data structures such as sets and hash sets. But if you want to continue, then you can merge two lists without repetitions by checking if an element is already in the list before prepending to it. Easy to implement but hard to run, in a sense that it takes quadratic time to merge two lists this way.
If you still want to stick with the list of pairs, then you will find that the List.assoc function is useful, as it finds a value by key. The overall algorithm would be, given two lists, xs and ys, fold over elements of ys using xs as the initial value acc, and for each (ky,y) in ys if ky is already in acc, find the associated with ky value x and remove (List.remove_assoc) it, then merge x and y and prepend the merged value with the acc list, otherwise (if it is not in acc) just prepend (ky,y) to acc`. Note that this algorithm doesn't preserve order, so if it matters you need something more complex. Also, if your keys are sorted you can make it a little bit more efficient and easier to implement.
I guess you're doing this to practice with list.
What I would do is store the already found keys in an accumulator
let mergePairs yourList =
let rec aux accKeys = function
| [] -> []
| x :: xs -> let k,v = x in if (* k in accKeys *) then aux accKeys xs (*we suppress already
existing keys*)
else (k, v # (* get all the list of the other pairs with key = k in xs*))
:: aux (k::accKeys) xs
in aux [] yourList;;

How to read each element within a tuple from a list

I want to write a program which will read in a list of tuples, and in the tuple it will contain two elements. The first element can be an Object, and the second element will be the quantity of that Object. Just like: Mylist([{Object1,Numbers},{Object2, Numbers}]).
Then I want to read in the Numbers and print the related Object Numbers times and then store them in a list.
So if Mylist([{lol, 3},{lmao, 2}]), then I should get [lol, lol, lol, lmao, lmao] as the final result.
My thought is to first unzip those tuples (imagine if there are more than 2) into two tuples which the first one contains the Objects while the second one contains the quantity numbers.
After that read the numbers in second tuples and then print the related Object in first tuple with the exact times. But I don't know how to do this. THanks for any help!
A list comprehension can do that:
lists:flatten([lists:duplicate(N,A) || {A, N} <- L]).
If you really want printing too, use recursion:
p([]) -> [];
p([{A,N}|T]) ->
FmtString = string:join(lists:duplicate(N,"~p"), " ")++"\n",
D = lists:duplicate(N,A),
io:format(FmtString, D),
D++p(T).
This code creates a format string for io:format/2 using lists:duplicate/2 to replicate the "~p" format specifier N times, joins them with a space with string:join/2, and adds a newline. It then uses lists:duplicate/2 again to get a list of N copies of A, prints those N items using the format string, and then combines the list with the result of a recursive call to create the function result.

Prolog return value comparation

I'm traying to learn the basics of logic programming.
I solved some exercises, and now I'm having trouble on creating a function that take two arguments, a list of non empty lists whose elements concatenated together form the second argument.
By the time I created a function that concat the elements of a list of lists:
concat([[]|L],L3):- concat(L,L3).
concat([[Head|L1]|L2],[Head|L3]):- concat([L1|L2],L3),!.
Now, what I need to know is how to take the return value of that function and compare it with a list (the second argument of the function).
This is one approach that will allow down to single elements in a sublist, but not an empty sublist:
concat([[L]], [L]).
concat([[H],L|T], [H|R]) :- concat([L|T], R).
concat([[H1,H2|T]|LT], [H1|RT]) :- concat([[H2|T]|LT], RT).
The method here to avoid an empty list is to call out two head elements in the recursive clause, and a solitary element list in the base case. This prevents empty sublists from succeeding, as requested in the comments of the original post.
If you have a variable, Y that is already instantiated, and you want to know if it is the result of concatenating the list of lists, LL, you simply query:
concat(LL, Y).
This will be true if Y is the concatenation of list LL and false if it is not. You don't have to "return and compare" (as, for example, in C, you might say, concat(LL) == Y, or concat(LL, X); if (X == Y)...). This is because concat is a relation defined between the two arguments and it determine if the query can be made true by following the stated rules (clauses of the predicate).
If you already obtained a result and want to determine if it's unifiable to another variable, Z, then you can say:
concat(X, Y), Y = Z.
Note that, in Prolog, concat(X, Y) == Z is not correct to determine if the result of the predicate is equal to Z because it is not a function that returns a value.
Prolog doesn't have functions or return values in the sense of a procedural programming language. It has predicates, which assert a relationship. It has terms, which include variables which comes with some strictures:
All variables are local, and
A variable, once assigned a value, ceases to be variable. That's why it's called unification.
So....
If you want a predicate that will take two lists and produce their concatenation, you'll need to pass it a 3rd variable. You might invoke it like this:
concat([a,b],[c,d],X).
which asserts that X is the concatenation of [a,b] and [c,d]. Prolog's inference engine will then evaluate the truth or falseness of the assertion.
Most recursive problems has a few special cases and a more general case. The implementation of such a concat/3 predicate might look something like this (annotated to explain what it's doing).
First, we have one special (and terminating) case: If the left-hand list is empty, the concatenation is simply the right-hand list.
concat( [] , Bs , Bs ).
Next, we have the one general case: if the left-hand list is non-empty, we need to prepend it to the concatentation that we're building (and then recurse down.)
concat( [A|As] , Bs , [A|Cs] ) :-
concat(As,Bs,Cs).
That's all there is two it. You'll also notice that it's bi-directional: it's perfectly happy to split lists apart as well. Invoking it like this:
concat( Prefix , Suffix, [a,b,c,d] ).
will, on backtracking, produce all the possible ways that [a,b,c,d] could be split into a prefix and suffix:
Prefix Suffix
--------- ---------
[] [a,b,c,d]
[a] [b,c,d]
[a,b] [c,d]
[a,b,c] [d]
[a,b,c,d] []
You just need the base case
concat([],[]).
concat([[]|L],L3):- concat(L,L3).
concat([[Head|L1]|L2],[Head|L3]):- concat([L1|L2],L3).
It also works for empty (sub)lists.
I've removed the useless cut.

Making two lists identical in python 2.7

I have two lists in python.
a=[1,4,5]
b=[4,1,5]
What i need is to order b according to a. Is there any methods to do it so simply without any
loops?
The easiest way to do this would be to use zip to combine the elements of the two lists into tuples:
a, b = zip(*sorted(zip(a, b)))
sorted will compare the tuples by their first element (the element from a) first; zip(*...) will "unzip" the sorted list.
or may be just check everything is perfect then..copy list a for b
if all(x in b for x in a) and len(a)==len(b):
b=a[:]
If you want to make list2 identical to list1, you don't need to mess with order or re-arrange anything, just replace list2 with a copy of list1:
list2 = list(list1)
list() takes any iterable and produces a new list from it, so we can use this to copy list1, thus creating two lists that are exactly the same.
It might also be possible to just do list2 = list1, but do note that this will cause any changes to either to affect the other (as they point to the same object), so this is probably not what you want.
If list2 is referenced elsewhere, and thus needs to remain the same object, it's possible to replace every value in the list using list2[:] = list1.
In general, you probably want the first solution.
Sort b based on items' index in a, with all items not in a at the end.
>>> a=[1,4,5,2]
>>> b=[4,3,1,5]
>>> sorted(b, key=lambda x:a.index(x) if x in a else len(a))
[1, 4, 5, 3]

Why is [1..n] not handled the same way as [n..1] in Haskell?

I was trying to solve a problem that required the maximum value of a list after being mapped over by a function. The list is a range from a to b where a>b or b>a. Because Haskell can also define decreasing lists i thought that i didn't need to check if a>b and there was no need to flip the bounds to b..a. The function looks somewhat like this:
f a b = maximum . map aFunction $ [a..b]
But if the list is decreasing i.e. a>b then Haskell gives me an exception:
Prelude.maximum: empty list
So for some reason a decreasing list hands over an empty list to the maximum function. Why is that?
I know that maximum is defined in terms of a foldl1 max and that foldl1 needs a non empty list but i don't know why a list like [10..1] is empty when handed to a foldl1.
[a..b] desugars to enumFromTo a b. For standard numeric types (modulo a couple of quirks for floating), this keeps adding one until you are >= b. So where b < a this is empty.
You can change the increment by using the following syntax [a,a'..b] which then takes steps in increments of a'-a. So [10,9..1] will be what you want.
This is because of the way the sequence is defined in Haskell Report Arithmetic Sequences
:
[ e1..e3 ] = enumFromTo e1 e3
and Haskell Report The Enum Class
The sequence enumFromTo e1 e3 is the list [e1,e1 + 1,e1 + 2, ... e3]. The list is empty if e1 > e3.
(emphasis added).
They are handled exactly the same way. You start from the first bound and count up.