I have two lists that consist of strings, both immmutable:
def list1 = [ "A", "B", "C" ]
list2 = ["D", "E", F"]
List 2 is being returned by a custom function I have made. Is there a way to take these two immutable lists and combine both of their elements with inject? I have tried numerous combinations without success. I have googled extensively for this. I cannot change this to a mutable list. I am aware that it would be much easier to simply combine two lists then make them immutable, but alas, this is not what I am aiming for.
Following is the desired output:
[ "A", "B", "C", "D", "E", F"]
The solution here will be used to solve a larger problem. I am merely simplifying this to the base case.
Thank you.
Edit: I have to use the inject method. I am aware that I can simply use + or iterate through each list with a loop to get the desired result. This is strictly limited to using .inject in Groovy.
//Set as Immutable
def list1 = ["A", "B", "C"].asImmutable()
def list2 = ["D", "E", "F"].asImmutable()
//Supports Immutablity
try {list1 << 'Z'} catch(e){assert e instanceof UnsupportedOperationException}
try {list2 << 'Z'} catch(e){assert e instanceof UnsupportedOperationException}
//Desired result using "inject"
def result = list2.inject(list1){init, val -> [init] << val}.flatten()
assert result == ['A', 'B', 'C', 'D', 'E', 'F']
//Immutable Test
assert list1 == ["A", "B", "C"]
assert list2 == ["D", "E", "F"]
//Supports Immutablity after operation
try {list1 << 'Z'} catch(e){assert e instanceof UnsupportedOperationException}
try {list2 << 'Z'} catch(e){assert e instanceof UnsupportedOperationException}
Related
I am trying to find a way to detect a sequence of strings in a list.
I.E.:
for the list List1 = ["A", "B", "C", "D", "E"], how do I write a program that detects the sequence
"A", "B", "C" and returns / prints "True"?
Thank you!
List1 = ["A", "B", "C", "D", "E"]
Axiom = "A", "B" (I am aware that this is a tuple, and therefore would not be detected)
for item in List1:
if List1[0]==Axiom:
print("True")
Expected Output:
True
This question already has an answer here:
Prolog flatten list
(1 answer)
Closed 1 year ago.
How can I flatten a list in Prolog, for example:
from A = [["a","b"],["c"]]
to B = ["a", "b", "c"] ?
A list can be flattened using maplist and append, in the following way.
A two-level list may be flattened as shown.
?- A=[["a","b"],["c"]],maplist(append,[A],[B]).
A = [["a", "b"], ["c"]],
B = ["a", "b", "c"].
A three-level may be flattened with two passes of the command.
?- A=[[["a","b"]],[["c"]]],maplist(append,[A],[B]),maplist(append,[B],[C]).
A = [[["a", "b"]], [["c"]]],
B = [["a", "b"], ["c"]],
C = ["a", "b", "c"].
Mixtures of two and three levels in a list results in an error from two passes of the command.
?- A=[[["a","b"]],[["c"]],["d"]],maplist(append,[A],[B]),maplist(append,[B],[C]).
false.
Mixtures of two and three levels in a list can only be partially flattened with one pass of the command.
?- A=[[["a","b"]],[["c"]],["d"]],maplist(append,[A],[B]).
A = [[["a", "b"]], [["c"]], ["d"]],
B = [["a", "b"], ["c"], "d"].
This is what I tried:
def reverse(given_list):
"""Reverses the order of a list (does not create a new object; simply reverses the order of the list.
>>> r = ["Mario", "Bowser", "Luigi"]
>>> reverse(r)
>>> r
["Luigi", "Bowser", "Mario"]
"""
given_list = sorted(given_list, key = given_list.index, reverse = True)
list_1 = ["a", "b", "c", "d"]
reverse(list_1)
print(list_1)
However, list_1 remains unchanged when I run this function. How can I get my function to generate the output as shown in the docstring?
Please help.
You need to return the given_list as a result of your method and use that in your print statement. E.g.:
def reverse(given_list):
given_list = sorted(given_list, key = given_list.index, reverse = True)
return given_list
list_1 = ["a", "b", "c", "d"]
list_1_reversed = reverse(list_1)
print(list_1_reversed)
When giving list_1 as a parameter to the method, a copy will be created and used. So this question is about the scope of variables. You can find information on scope of variables in your favorite book about python or via googling.
I have a list of String as below:-
val a = listOf("G", "F", "E", "D", "C", "B", "A")
I will get another list from the server. For example:-
val b = listOf("A", "G", "C")
List from the server may contain fewer elements or more elements but will not contain elements other than the first list.
So, after sorting output should be like
// G, C, A
You are not trying to sort, you are trying to filter
fun filterByServer(server: List<String>, local: List<String>)
= local.filter { value -> server.contains(value) }
filter takes a predicate in this case if your local value is contained on the server list
You can use map and sorted to achieve that easily on the condition that a do not have repetition -
val a = listOf("G", "F", "E", "D", "C", "B", "A")
val b = listOf("A", "G", "C")
val there = b.map{ v -> a.indexOf(v)}.sorted().map{v -> a[v]}
println(there)
Output:: [G, C, A]
Alternate sorter way as pointed by #jsamol in comment -
val there = b.sortedBy { a.indexOf(it) }
You can create a custom comparator based on the indices of letters in the a list. Then use the List.sortedWith function to sort the b list.
e.g.
val a = listOf("G", "F", "E", "D", "C", "B", "A")
val b = listOf("A", "G", "C")
val indexedA: Map<String, Int> = a.mapIndexed { index, s -> s to index }.toMap()
val comparator = object: Comparator<String> {
override fun compare(s1: String, s2: String): Int {
val i1 = indexedA[s1]
val i2 = indexedA[s2]
return if (i1 == null || i2 == null) throw RuntimeException("unable to compare $s1 to $s2")
else i1.compareTo(i2)
}
}
val c = b.sortedWith(comparator)
System.out.println(c)
I've converted the list a to a map: Letter to Index as an optimization.
If I understand the requirement, what we're really doing here is filtering the first list, according to whether its elements are in the second. So another approach would be to do that explicitly.
val a = listOf("G", "F", "E", "D", "C", "B", "A")
val b = listOf("A", "G", "C").toSet() // or just setOf(…)
val there = a.filter{ it in b }
There's a bit more processing in creating the set, but the rest is faster and scales better, as there's no sorting or scanning, and checking for presence in a set is very fast.
(In fact, that would work fine if b were a list; but that wouldn't perform as well for big lists.)
I have two lists that I need to merge into a new list, but the new list needs to contain merged indexes of the original lists. For example:
List1 = [1, 2, 3]
List2 = [a, b, c]
I need the output to be:
finalList = [1a, 2b, 3c]
I need to be able to do this in groovy. I appreciate any help you can provide.
Assuming both lists are the same size, in Groovy 2.4+,
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
assert ['1a', '2b', '3c'] == list1.withIndex().collect { it, index -> it + list2[index] }
Alternatively and a bit more simply in Groovy 1.5+,
assert ['1a', '2b', '3c'] == [list1, list2].transpose()*.sum()
The following is very close to doelleri's solution:
In Groovy 2.4+
println ([list1, list2].transpose().collect{it -> it[0] + it[1]})
OUTPUT
[1a, 2b, 3c]