Here's my code for performing a selection sort using Groovy:
class SelectionSorting {
void sorting() {
def sortmethod = {
List data = [ 1, 5, 2, 3, 7, 4, 6, 8, 9, ]
def n = data.size()
println "Before sort : " + data
for(def i in 0..n) {
def position=i
for(def j in i+1..n) {
if(data[position] > data[i])
position=i
}
if(position!=i) {
swap(data[i],data[position])
}
}
println "After sort : " + data
}
sortmethod()
}
}
SelectionSorting s = new SelectionSorting()
s.sorting()
However, the output I see is still an unsorted array:
Before sort : [1, 5, 2, 3, 7, 4, 6, 8, 9]
After sort : [1, 5, 2, 3, 7, 4, 6, 8, 9]
I am very new to Groovy. I'm supposed to insert the logic within a closure only. I'm not sure what I need to change in the closure I have created in my code above. Please help.
You are using the wrong index when calculating the position of the minimum value; you should use j instead of i (added println to show iterations):
def selectionSort = { data ->
int n = data.size()
for (int i = 0; i < n - 1; i++) {
// Find the index (position) of the minimum value
position = i
for(int j = i + 1; j < n; j++) {
if(data[j] < data[position]) {
position = j
}
}
// Swap
if (position != i) {
temp = data[position]
data[position] = data[i]
data[i] = temp
}
println data
}
println "result: $data"
}
So that selectionSort([1,5,2,4,3,8,7,9]) yields:
[1, 5, 2, 4, 3, 8, 7, 9]
[1, 2, 5, 4, 3, 8, 7, 9]
[1, 2, 3, 4, 5, 8, 7, 9]
[1, 2, 3, 4, 5, 8, 7, 9]
[1, 2, 3, 4, 5, 8, 7, 9]
[1, 2, 3, 4, 5, 7, 8, 9]
[1, 2, 3, 4, 5, 7, 8, 9]
result: [1, 2, 3, 4, 5, 7, 8, 9]
Related
I would like to append ids to a list which meet a specific condition.
output = []
areac = [4, 4, 4, 4, 1, 6, 7,8,9,6, 10, 11]
arean = [1, 1, 1, 4, 5, 6, 7,8,9,10, 10, 10]
id = [1, 2, 3, 4, 5, 6, 7,8,9,10, 11, 12]
dist = [2, 2, 2, 4, 5, 6, 7.2,5,5,5, 8.5, 9.1]
for a,b,c,d in zip(areac,arean,id,dist):
if a >= 5 and b==b and d >= 3:
output.append(c)
print(comp)
else:
pass
The condition is the following:
- areacount has to be >= 5
- At least 3 ids with a distance of >= 3 with the same area_number
So the id output should be [10,11,12].I already tried a different attempt with Counter that didn't work out. Thanks for your help!
Here you go:
I changed the list names to something more descriptive.
output = []
area_counts = [4, 4, 4, 4, 1, 6, 7, 8, 9, 6, 10, 11]
area_numbers = [1, 1, 1, 4, 5, 6, 7, 8, 9, 10, 10, 10]
ids = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
distances = [2, 2, 2, 4, 5, 6, 7.2, 5, 5, 5, 8.5, 9.1]
temp_numbers, temp_ids = [], []
for count, number, id, distance in zip(counts, numbers, ids, distances):
if count >= 5 and distance >= 3:
temp_numbers.append(number)
temp_ids.append(id)
for (number, id) in zip(temp_numbers, temp_ids):
if temp_numbers.count(number) == 3:
output.append(id)
output will be:
[10, 11, 12]
I was hoping to take the average of a list using another list with the start and stop indices.
for example:
a = [3, 9]
b = [0, 1, 12, 9, 0, 8, 9, 3, 3, 5, 7, 1, 4, 6, 6]
I want to take the average of the numbers from b[3] to b[9] and this is what I have so far
counter = a[0]
sum = b[counter]
while counter < a[1] + 1:
counter += 1
sum = sum + b[counter]
denominator = a[1] - a[0] + 1
avg = sum/denominator
But after checking, it seems to be giving the wrong thing
you could use statistics.mean
from statistics import mean
a = [3, 9]
b = [0, 1, 12, 9, 0, 8, 9, 3, 3, 5, 7, 1, 4, 6, 6]
mean(b[a[0]: a[1] + 1])
or you could use:
sum(b[a[0]: a[1] + 1]) / len(b[a[0]: a[1] + 1])
I would suggest the following:
from statistics import mean
a = [3, 9]
b = [0, 1, 12, 9, 0, 8, 9, 3, 3, 5, 7, 1, 4, 6, 6]
avg = mean(b[a[0]:a[1]+1])
print (avg)
I need to explore every permutations of a list. Let's say I have this initiated variable:
samplelist = [1, 2, 3, 4, 5, 6, 7, 8, 9]
An example output would be:
output = [[1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 3, 2, 4, 5, 6, 7, 8, 9], [1, 3, 4, 2, 5, 6, 7, 8, 9], [1, 3, 5, 3, 2, 6, 7, 8, 9]] .... and so on.
Here's what I did:
import itertools
samplelist = [1, 2, 3, 4, 5, 6, 7, 8, 9]
def combinations(iterable, r):
pool = tuple(iterable)
n = len(pool)
if r > n:
return
indices = range(r)
yield tuple(pool[i] for i in indices)
while True:
for i in reversed(range(r)):
if indices[i] != i + n - r:
break
else:
return
indices[i] += 1
for j in range(i+1, r):
indices[j] = indices[j-1] + 1
yield tuple(pool[i] for i in indices)
list(combinations_with_replacement(samplelist, 9))
Since the length of the list is 9, the factorial of 9 is 362,880. I'm trying to get all these combinations of the elements in the list
But my output is not what I'm trying to achieve.
itertools.permutations(samplelist) returns the 9! lists
I am constructing decision tree in scikit-learn and tree is missing leaf #2. I wonder why? Here is my example:
import numpy as np
from sklearn.tree import DecisionTreeClassifier, export_graphviz
def leaf_ordering():
X = np.genfromtxt('X.csv', delimiter=',')
Y = np.genfromtxt('Y.csv',delimiter=',')
dt = DecisionTreeClassifier(min_samples_leaf=100, random_state=99)
dt.fit(X, Y)
print(set(dt.apply(X)))
leaf_ordering()
link to file X
link to file Y
Here is output: {1, 3, 4}. As you can see there is no leaf #2.
Nodes 0 and 2 in your example are both non-leaf nodes. In my example below, you can see from the export that 0, 1, and 4 are all internal tree nodes, and 2, 3, 5, and 6 are the leaves, and so all the predictions are going to be in one of those 4.
In [35]: X = np.random.random([100, 5])
In [36]: y = X.sum(axis=1) + np.random.random(100)
In [37]: dt = DecisionTreeRegressor(max_depth=2)
In [38]: dt.fit(X, y)
Out[38]:
DecisionTreeRegressor(criterion='mse', max_depth=2, max_features=None,
max_leaf_nodes=None, min_samples_leaf=1, min_samples_split=2,
min_weight_fraction_leaf=0.0, presort=False, random_state=None,
splitter='best')
In [39]: dt.apply(X)
Out[39]:
array([6, 3, 3, 3, 6, 6, 3, 6, 3, 6, 2, 3, 3, 5, 3, 5, 5, 6, 3, 3, 3, 3, 3,
3, 3, 6, 6, 3, 3, 3, 3, 5, 3, 5, 3, 3, 3, 3, 2, 3, 3, 3, 6, 3, 3, 3,
3, 6, 3, 5, 2, 3, 3, 6, 3, 3, 3, 3, 3, 6, 6, 3, 6, 6, 3, 5, 6, 3, 3,
3, 3, 6, 3, 3, 2, 3, 6, 2, 6, 2, 3, 3, 6, 2, 5, 6, 3, 3, 3, 6, 5, 3,
3, 3, 6, 6, 3, 3, 6, 5])
In [40]: export_graphviz(dt)
In [41]: !cat tree.dot
digraph Tree {
node [shape=box] ;
0 [label="X[2] <= 0.7003\nmse = 0.4442\nsamples = 100\nvalue = 3.0586"] ;
1 [label="X[4] <= 0.1842\nmse = 0.3332\nsamples = 65\nvalue = 2.8321"] ;
0 -> 1 [labeldistance=2.5, labelangle=45, headlabel="True"] ;
2 [label="mse = 0.0426\nsamples = 7\nvalue = 1.9334"] ;
1 -> 2 ;
3 [label="mse = 0.2591\nsamples = 58\nvalue = 2.9406"] ;
1 -> 3 ;
4 [label="X[0] <= 0.3576\nmse = 0.3782\nsamples = 35\nvalue = 3.4791"] ;
0 -> 4 [labeldistance=2.5, labelangle=-45, headlabel="False"] ;
5 [label="mse = 0.1212\nsamples = 10\nvalue = 2.9395"] ;
4 -> 5 ;
6 [label="mse = 0.3179\nsamples = 25\nvalue = 3.695"] ;
4 -> 6 ;
}
I have a collection of ID list to be saved into the database
if(!session.ids)
session.ids = []
session.ids.add(params.id)
and I found out that list has duplicates, like
[1, 2, 4, 9, 7, 10, 8, 6, 6, 5]
Then I wanted to remove all duplicates by applying something like :
session.ids.removeAll{ //some clousure case }
I found only this:
http://groovy.codehaus.org/groovy-jdk/java/util/Collection.html
I am not a Groovy person , but I believe you can do something like this :
[1, 2, 4, 9, 7, 10, 8, 6, 6, 5].unique { a, b -> a <=> b }
Have you tried session.ids.unique() ?
How about:
session.ids = session.ids.unique( false )
Update
Differentiation between unique() and unique(false) : the second one does not modify the original list.
def originalList = [1, 2, 4, 9, 7, 10, 8, 6, 6, 5]
//Mutate the original list
def newUniqueList = originalList.unique()
assert newUniqueList == [1, 2, 4, 9, 7, 10, 8, 6, 5]
assert originalList == [1, 2, 4, 9, 7, 10, 8, 6, 5]
//Add duplicate items to the original list again
originalList << 2 << 4 << 10
// We added 2 to originalList, and they are in newUniqueList too! This is because
// they are the SAME list (we mutated the originalList, and set newUniqueList to
// represent the same object.
assert originalList == newUniqueList
//Do not mutate the original list
def secondUniqueList = originalList.unique( false )
assert secondUniqueList == [1, 2, 4, 9, 7, 10, 8, 6, 5]
assert originalList == [1, 2, 4, 9, 7, 10, 8, 6, 5, 2, 4, 10]
Use unique
def list = ["a", "b", "c", "a", "b", "c"]
println list.unique()
This will print
[a, b, c]
def unique = myList as Set
Converts myList to a Set. When you use complex (self-defined classes) make sure you have thought about implementing hashCode() and equals() correctly.
If it is intended that session.ids contain unique ids, then you could do:
if(!session.ids)
session.ids = [] as Set
Then when you do:
session.ids.add(params.id)
duplicates will not be added.
Also you can use this syntax:
session.ids << params.id
Merge two arrays and make elements unique:
def arr1 = [1,2,3,4]
def arr2 = [1,2,5,6,7,8]
def arr3 = [1,5,6,8,9]
Let's look at mergings:
arr1.addAll(arr2, arr3)
// [1, 2, 3, 4, [1, 2, 5, 6, 7, 8], [1, 5, 6, 8, 9]]
def combined = arr1.flatten()
// [1, 2, 3, 4, 1, 2, 5, 6, 7, 8, 1, 5, 6, 8, 9]
def combined = arr1.flatten().unique()
// [1, 2, 3, 4, 5, 6, 7, 8, 9]
def combined = (arr1 + arr2 + arr3).flatten().unique()
def combined = (arr1 << arr2 << arr3).flatten().unique()
def combined = arr1.plus(arr2).plus(arr3).flatten().unique()
Output will be:
println combined
[1, 2, 3, 4, 5, 6, 7, 8, 9]