Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 11-20 of 20 total

Ruby : sort an array of hashes

// will sort an array of hashes by key

my_arr.sort_by { |my_item| my_item[:my_key] }

call sort with a block

From http://practicalruby.blogspot.com/2006/05/call-sort-with-block.html:

I needed to sort a list of partners today so I added:
class Partner
  def <=>(other)
     self.name <=> other.name
  end
end

However, I could have just done:
Partner.find(:all).sort { |one, other| one.name <=> other.name }

Doc for sort here.

From Comments:
You could also have used sort_by as long as the target supports the spaceship operator. ie:
Partner.find(:all).sort_by { |partner| partner.name }

With active_support required (or 'facet/symbol/to_proc' from the facets library) you can even:
Partner.find(:all).sort_by(&:name)


Sweet.

Python sorting

list.sort() work in place (doesn't return anything)
If you want a version that return result, use sorted() function.
>>> a = [5, 2, 3, 1, 4]
>>> a.sort()    # become [1, 2, 3, 4, 5]
>>> a.sort(cmp) # same as above

>>> a = "This is a test string from Andrew".split()
>>> a.sort(key=str.lower) # using key is simpler
# ['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']

>>> import operator 
>>> L = [('c', 2), ('d', 1), ('a', 4), ('b', 3)]
>>> sorted(L, key=operator.itemgetter(1))
[('d', 1), ('c', 2), ('b', 3), ('a', 4)]
# itemgetter allows easy Schwartzian transform

3 equivalent ways
- key=operator.itemgetter(1)
- key=lambda x: x[1]
- cmp=lambda a,b: cmp(a[1], b[1])

Learn more at Sorting Howto.

Counting frequency in a list

>>> alist = [ '1', '1', '2', '1', '3', '4', '1', '3']
>>> [(a, alist.count(a)) for a in set(alist)]
[('1', 4), ('3', 2), ('2', 1), ('4', 1)]
>>> sorted(_, key=lambda x: -x[1])  # rank them
[('1', 4), ('3', 2), ('2', 1), ('4', 1)]

Return block of files, all dirs first

    dir-file-sort: func [
        {Returns the block of files with directories first, followed by
        files, with each group sorted.}
        block [any-block!]
        /local result
    ][
        result: copy []
        foreach blk lib/ser/split block [:dir?] none [
            append result sort blk
        ]
    ]

multi-level-sort function

    multi-level-sort: func [
        "Returns a copy of the block, sorted on the given items (all ascending)"
        block   [any-block!]
        offsets [any-block!]
        /local idx result
    ][
        idx: make block length? block
        repeat i length? block [
            append idx append/only reduce [i] excerpt block/:i offsets
        ]
        sort/skip/compare idx 2 2
        result: make block length? block
        foreach [index data] idx [
            append/only result block/:index
        ]
        result
    ]

Priority Queue

pq = PriorityQueue()

pq.put(('b', 1))
pq.put(('a', 1))
pq.put(('c', 1))
pq.put(('z', 0))
pq.put(('d', 2))

while not pq.empty():
  print pq.get(),   
# z b a c d

Get the implementation of Priority Queue here.

sort a data.frame by a given column

data <- sort.data.frame(data, key = "LOC")


where the function "sort.data.frame" is as follows:

sort.data.frame <- function(x, key, ...) {
    if (missing(key)) {
        rn <- rownames(x)
        if (all(rn %in% 1:nrow(x))) rn <- as.numeric(rn)
        x[order(rn, ...), , drop=FALSE]
    } else {
        x[do.call("order", c(x[key], ...)), , drop=FALSE]
    }
}

sorted for python before 2.4

def sorted(seq):
  seq.sort()
  return seq

php glob_rsort_modtime()

<?php
/**
 FUNCTION: glob_rsort_modtime()
 * Glob reverse sorted by file modification time.
 *
 * Returns an array of files matching the given glob pattern, sorted 
 * by their modification times in descending order.  The array keys
 * hold the filepath and the values hold the mtime.  On error, array
 * will be indexed and contain 'false' and an error message.
 *
 * {@source}
 *
 * @param string $patt Pattern to search, including glob braces.
 * @return array filename => mtime OR false, 'errormsg'.
 */
function glob_rsort_modtime( $patt ) {
    if ( ( $files = @glob($patt, GLOB_BRACE) ) === false ) {
        return array( false, 'Glob error.');
    }
    if ( !count($files) ) {
        return array( false, 'No files found.');
    }
    $rtn = array();
    foreach ( $files as $filename ) {
        $rtn[$filename] = filemtime($filename);
    }
    arsort($rtn);
    reset($rtn);
    return $rtn;
}

$files = glob_rsort_modtime( './*' ) ;
echo'<pre>'.print_r($files, true).'</pre>';
?> 
« Newer Snippets
Older Snippets »
Showing 11-20 of 20 total