How to print all values in foreach - groovy

Groovy for-each returns only one value.which is first value please check it once.how to print all values
def list = [1,2,3,4]
for(item in list){
return item
}

def list = [1,2,3,4]
for(item in list){
print item
}
return is completely different thing. it is used for a function/method to evaluate a value.

You return from the method during the very first iteration of the loop. The loop will never execute more than the first iteration for that reason.

Related

using for loop to count list elements in a string

Im beginner in python, learning it for biology purposes.
Ok, lets suppose I want to write a function that will iterate over a list to count how many of its elements in the string using for loop
def counting(string,lista):
for element in lista:
element_count=string.count(element)
return element_count
so when using the above function to find how many A and C in my string
print(counting('AABCDEF',['A','C']))
It seems the function only return the count of C in the string which is 1, what I want to get both elements count. It seems adding a print line inside the loop body will solve the problem,
def counting(string,lista):
for element in lista:
element_count=string.count(element)
print(element_count)
return element_count
is there a way to get the same output without using the print statement?
Thanks in advance
Return the result as a list.
def counting(string,lista):
temp = []
for element in lista:
temp.append(string.count(element))
return temp
print(counting('AABCDEF',['A','C']))
The result is
[2, 1]
To print some verbose,
def counting(string, lista):
temp = []
for element in lista:
temp.append('{} count is {}'.format(element, string.count(element)))
return ', '.join(temp)
print(counting('AABCDEF', ['A','C']))
Then
A count is 2, C count is 1

Returning multiple value in python return function

My function prints the the index of every element in list that is divided by 2 in a given list. I want to know if there is a way to return all the indexes rather than printing?
def printEvenIndex(referenceTuple):
for i in referenceTuple:
if i % 2 ==0:
indexOfEvenIntegers = referenceTuple.index(i)
print(indexOfEvenIntegers)
return indexOfEvenIntegers
referenceTuple = (6,5,3,4,1)
print(printEvenIndex(referenceTuple))
Right now print statement prints 0 ,3 which is valid.
But return function is returning 3 only. Is there a way to tell return function to return every element that is divisible by 2? I want to return all the index rather than print it.
Just create a list and append your indexes there:
def readEvenIndexes(referenceTuple):
""" Named it readEventIndexes, as we are not printing anymore """
indexes = []
for index, i in enumerate(referenceTuple):
if i % 2 ==0:
indexes.append(index)
return indexes
referenceTuple = (6,5,3,4,1)
print(readEvenIndexes(referenceTuple))

Create Map with CollectEntries in Groovy

I have the following list:
appList = [DevOpsApplication, 01.01.01]
I would like to create a map using collectEntries. I know that it refers to the current element of an iteration (shortcut for { it -> it }). Therefore, I tried to use the index:
def appMap = appList.collectEntries { [(it[0]):it[1]] }
However, this gives me:
[D:e, 0:1]
But I want [DevOpsApplication: 01.01.01]. Is there a way to do this?
Additionally, In future I would like this to expand to more than 2 elements (e.g. [DevOpsApplication, 01.01.01, AnotherDevOpsApplication, 02.02.02]) with the desired output of [DevOpsApplication: 01.01.01, AnotherDevOpsApplication: 02.02.02].
How will this be possible?
A very short version to do this would be:
def appList = ["DevOpsApplication", "01.01.01"]
def appMap = [appList].collectEntries() // XXX
assert appMap == [DevOpsApplication: "01.01.01"]
How does it work: the function collectEntries takes, is expected to return a map or a two element list. Your appList is already that. So put that in another list, call collectEntries on it. When no function is given to collectEntries it uses the identity function.
Bonus: what if appList has much more elements? You can use collate to build the tuples.
def appList = ["DevOpsApplication", "01.01.01", "Some", "More"]
def appMap = appList.collate(2).collectEntries() // XXX
assert appMap == [DevOpsApplication: "01.01.01", Some: "More"]
I also found another method. Groovy can convert the values of an Object array and convert them into a map with the toSpreadMap(). However, the array must have an even number of elements.
def appList = ['DevOpsApplication', '01.01.01']
def appMap = appList.toSpreadMap()
You're iterating element-by-element and (because your elements are String-typed) mapping 0 substrings to 1 substrings.
You can use this to skip one element in each iteration and map each element at even indices to the one after it:
def appList = ['DevOpsApplication', '01.01.01']
def appMap = (0..(appList.size()-1)).findAll{0 == it%2}
.collectEntries{[(appList[it]): appList[it+1]]}
That returns [DevOpsApplication:01.01.01] as expected.

Compare list of objects without equal defined

I have a class without equal function defined. I need to compare two lists of this objects. There is some sample of my current solution:
def fromRecords = [new FooRecord(['ABC', 123L]), new FooRecord(['XYZ', 789L])]
storage.write(fromRecords)
def toRecords = storage.read()
for (int i = 0; i < outRecords.size(); i++) {
assert outRecords[i].contents == records[i].contents
}
Is there more elegant groovy way to perform same comparison?
You don't need to loop, the equals method on the lists should take care of comparing order and check element-wise equality:
assert outRecords.contents == records.contents
The == operator will result in outRecords.contents.equals(records.contents) being called, which will check List equality (taking care of order and list content - element by element .equals checks).

Python - Create a recursion function

my question is basically this: Create a recursion function that takes a nested list as a
parameter and returns the sub-list that has minimum difference between its maximum and minimum elements.
For example: Function should return [1,2] for input [[1,199,59],[1,2],[3,8]]
I searched Google and stackoverflow, but i could not find this specific example.
What i would like to get help is with iteration. I want to, using recursion, iterate over each sub-list(can be as many as possible). I have achieved this with a for loop, but i cannot grasp the idea of iteration by using recursion method.
So far, i have this:
def sublist(mylist):
if len(mylist) == 0:
return []
elif len(mylist) == 1:
return mylist
else:
a = (mylist[0][0]) - (mylist[0][-1])
if a < sublist(mylist[1:]):
return mylist[0]
sublist([[1,199,58],[1,2],[3,8]])
This part, ( sublist(mylist[1:]) ) i know is clearly wrong. I'm trying to compare the value a, with the values from the mylist[1:]. I would appreciate much advice here.
Updated:
def differences(mylist):
diff = max(mylist) - min(mylist)
return diff
def sublist(nestedlist):
if len(nestedlist) == 1:
return nestedlist[0]
else:
if differences(nestedlist[0]) < differences(sublist(nestedlist[1:])):
return nestedlist[0]
else:
return sublist(nestedlist[1:])
print(sublist([[1,199,59],[1,2],[3,8]]))
i am assuming that you want to use recursion for the first level of the list. So, without giving you the code 100%, you have to do something like that:
1) create a method e.g diferences(list) that calculates the differences of a list and returns a list with the parameter list and the min difference i.e differences([1,2]) should return [1, [1,2]]. call it once on the first sublist i.e min = differences(mylist[0])
2) create your sublist method like this:
def sublist(initial_list):
# 1) call differences() method for the first sublist of the 'initial_list'
# 2) update 'min' with differences(initial_list[0])if differences(inilitial_list[0])[0] < min[0];
# 3) call sublist() again now removing the sublist you checked before from the arguement
# 4) (the following should be at the start of your sublist() method)
if len(initial_list) = 1:
if differences(initial_list) < min:
return initial_list
else: return min[1]
Hope that helps

Resources