Sort a list of lists in Groovy - list

Sorry if this is a straight forward thing, I'm new to Groovy. I'm trying to figure out how to sort this list on the "uses" key in each sub list, but I can't seem to get it figured out:
[[name:foo, uses:2], [name:bar, uses:1], [name:baz, uses:4]]
I'm hoping to get the following result:
[[name:baz, uses:4], [name:foo, uses:2], [name:bar, uses:1]]
Does someone out there know how to best handle this? I checked similar questions but couldn't find anything pertaining to Groovy.
Thanks in advance.

The easiest way to do it would be to use the sort method
def sorted = lists.sort( {a, b -> b["uses"] <=> a["uses"] } )
sorted.each {
println it
}
// prints
// [name:baz, uses:4]
// [name:foo, uses:2]
// [name:bar, uses:1]

I think I figured it out...
sort{a,b -> b['uses'] <=> a['uses']}
...seems to do the trick.

just wanted to add a shorter version
[[name:'foo', uses:2], [name:'bar', uses:1], [name:'baz', uses:4]].sort{-it.uses}​​​​​

Related

Prolog predicate doesn't resolve

This may be a rookie mistake, but I'm trying to solve this question:
Find the query to obtain the following answer using the findall predicate: Obtain a list of persons who work in a city other than the one where they live:
L = [suzy, paul].
This is the database:
city(ottawa,ontario).
city(toronto,ontario).
city(kingston,ontario).
city(gatineau,quebec).
city(montreal,quebec).
company(shopify,ottawa).
company(rossvideo,ottawa).
company(dium,gatineau).
company(uber,toronto).
company(deepmind,montreal).
company(google,toronto).
person(annie,gatineau).
person(paul,gatineau).
person(suzy,gatineau).
person(robert,gatineau).
person(tom,ottawa).
person(tim,kingston).
person(joe,montreal).
person(jane,ottawa).
person(marie,ottawa).
person(jack,toronto).
person(simon,toronto).
employee(annie,dium).
employee(tom,shopify).
employee(jane,shopify).
employee(marie,shopify).
employee(joe,deepmind).
employee(jack,google).
employee(simon,google).
employee(suzy,shopify).
employee(paul,rossvideo).
employee(marie,rossvideo).
employee(simon,uber).
Here is the predicate I tried to use to solve it:
worksIn(n, Y) :-
employee(n, Comp),
company(Comp, Y).
But it only returns false. Does anyone know how to fix it?
I did:
worksIn(P):- person(P,CL), employee(P, CO), company(CO, CW), CL/=CW.
so the final answer is:
findall(P, worksIn(P), L).
I'm not sure if we can add the "worksIn" thing in or not
when use variables, first letter must be uppercase.

Trying to import dictionary to work with from a url; 'unicode' object not callable

I'm new to coding and have searched as best I can to find out how to solve this before asking.
I'm trying to pull information from poloniex.com REST api, which is in JSon format I believe. I can import the data, and work with it a little bit, but when I try to call and use the elements in the contained dictionaries, I get "'unicode' object not callable". How can I use this information? The end goal with this data is to pull the "BTC: "(volume)" for each coin pair and test if it is <100, and if not, append it to a new list.
The data is presented like this or you can see yourself at https://poloniex.com/public?command=return24hVolume:
{"BTC_LTC":{"BTC":"2.23248854","LTC":"87.10381314"},"BTC_NXT":{"BTC":"0.981616","NXT":"14145"}, ... "totalBTC":"81.89657704","totalLTC":"78.52083806"}
And my code I've been trying to get to work with currently looks like this(I've tried to iterate the information I want a million different ways, so I dunno what example to give for that part, but this is how I am importing the data):
returnvolume = urllib2.urlopen(urllib2.Request('https://poloniex.com/public?command=return24hVolume'))
coinvolume = json.loads(returnvolume.read())
coinvolume = dict(coinvolume)
No matter how I try to use the data I've pulled, I get an error stating:
"unicode' object not callable."
I'd really appreciate a little help, I'm concerned I may be approaching this the wrong way as I haven't been able to get anything to work, or maybe I'm just missing something rudimentary, I'm not sure.
Thank you very much for your time!
Thanks to another user, downshift, I have discovered the answer!
d = {}
for k, v in coinvolume.items():
try:
if float(v['BTC']) > 100:
d[k] = v
except KeyError:
d[k] = v
except TypeError:
if v > 100:
d[k] = k
This creates a new list, d, and adds every coin with a 'BTC' volume > 100 to this new list.
Thanks again downshift, and I hope this helps others as well!

How do I transform this code into a list comprehension?

I have this code in Python2.7 and I wanna (if possible) transform this code into a list comprehension.
z=[]
if p==1:
z.append('a')
if m==2:
z.append('b')
print ''.join(z)
The problem is it gives me an error (syntax error) when I transformed the code like this:
z=['b' if m==2 'a' if p==1]
print ''.join(z)
Or
z=['a' if p==1 'b' if ==m]
print ''.join(z)
Please let me know if this question has a duplicate.
I would appreciate your advice.
This is a tricky one. I came up with a solution that uses enumerate and an inline if statement to tell the difference between the two if statements. Honestly, using a list comp for this will probably obfuscate the code and it'd be better to just stick with the simpler if statements you already have.
values = ['a', 'b'] # put the append arguments in here, you can also inline this but I put it apart to make the line shorter
z = [val for idx, val in enumerate(values) if (m==2 and p==1 if idx==1 else p==1)]

Groovy Collect List of Lists

I have a list of lists similar to this:
[[NAME:JFK, ENUMBER:E12365576], [NAME:Connor Moore, ENUMBER:E12365575]]
I know that if i do:
data.collect {s -> s.eNumber}
I get:
["E12365576", "E12365575"]
What I want to end up with though is something like:
["E12365576 JFK", "E12365575 Connor Moore"]
//Or, If possible something like below
["E12365576 (JFK)", "E12365575 (Connor Moore)"]
I've been looking and haven't found something similar to help me figure it out. Any help is appreciated, thanks
data.collect {s -> "$s.ENUMBER ($s.NAME)" }
or, more precisely
data.collect { "$it.ENUMBER ($it.NAME)" }
by using implicit it

convert List[Tuple2[A,B]] to Tuple2[Seq[A],Seq[B]]

Stuck here, trying to convert a List of case class tuples to a tuple of sequences and multi-assign the result.
val items = repo.foo.list // gives me a List[(A,B)]
I can pull off multi-assignment like so:
val(a,b) = (items.map(_._1).toSeq, items.map(_._2).toSeq)
but it would be nicer to do in 1 step, along the lines of:
val(a,b) = repo.foo.list.map{case(a,b) => (a,b)}
I am not sure if I understood the question correctly. Maybe unzip works for what you want?
Here is a link with some examples: http://daily-scala.blogspot.de/2010/03/unzip.html
For a more general case you can look at product-collections. A CollSeqN is both a Seq[TupleN[A1..An]] and a TupleN[Seq[A1..An]]
In your example you could extract the Seqs like so:
items._1
items._2
...