View Subcategory
Gather together corresponding elements from multiple lists
Given several lists, gather together the first element from every list, the second element from every list, and so on for all corresponding index values in the lists. E.g. for these three lists, first =
['Bruce', 'Tommy Lee', 'Bruce'], last = ['Willis', 'Jones', 'Lee'], years = [1955, 1946, 1940] the result should produce 3 actors. The middle actor should be Tommy Lee Jones.
python
first = ['Bruce', 'Tommy Lee', 'Bruce']
last = ['Willis', 'Jones', 'Lee']
years = [1955, 1946, 1940]
actors = zip(first, last, years)
assert len(actors) == 3
assert actors[1] == ('Tommy Lee', 'Jones', 1946)
last = ['Willis', 'Jones', 'Lee']
years = [1955, 1946, 1940]
actors = zip(first, last, years)
assert len(actors) == 3
assert actors[1] == ('Tommy Lee', 'Jones', 1946)
csharp
String[] first = { "Bruce", "Tommy Lee", "Bruce" };
String[] last = { "Willis", "Jones", "Lee" };
int[] years = { 1955, 1946, 1940 };
var actors = first.Zip(last, (f, l) => Tuple.Create(f, l)).Zip(years, (t, y) => Tuple.Create(t.Item1, t.Item2, y)).ToArray();
Debug.Assert(actors[1].Equals(Tuple.Create("Tommy Lee", "Jones", 1946)));
String[] last = { "Willis", "Jones", "Lee" };
int[] years = { 1955, 1946, 1940 };
var actors = first.Zip(last, (f, l) => Tuple.Create(f, l)).Zip(years, (t, y) => Tuple.Create(t.Item1, t.Item2, y)).ToArray();
Debug.Assert(actors[1].Equals(Tuple.Create("Tommy Lee", "Jones", 1946)));
java
String[] first = new String[]{"Bruce", "Tommy Lee", "Bruce"};
String[] last = new String[]{"Willis", "Jones", "Lee"};
String[] years = new String[]{"1955", "1946", "1940"};
List<String[]> list = new ArrayList<String[]>(); list.add(first); list.add(last); list.add(years);
String[] result = zip(",", list);
String[] last = new String[]{"Willis", "Jones", "Lee"};
String[] years = new String[]{"1955", "1946", "1940"};
List<String[]> list = new ArrayList<String[]>(); list.add(first); list.add(last); list.add(years);
String[] result = zip(",", list);
fantom
r := [,]
first.size.times |Int i| { r.add([first[i], last[i], years[i]]) }
echo(r)
first.size.times |Int i| { r.add([first[i], last[i], years[i]]) }
echo(r)
clojure
(defn gatherer [listOfLists]
(if (empty? (first listOfLists))
() ; the base case for recursion
(cons
(map first listOfLists) ; get the first element of each of the lists
(gatherer (map rest listOfLists)) ; gather all the subsequent ones
)
)
)
(def firstnames '("Bruce" "Tommy Lee" "Bruce"))
(def lastnames '("Willis" "Jones" "Lee"))
(def years '(1955 1946 1940))
(println (gatherer [firstnames lastnames years]))
; -> ((Bruce Willis 1955) (Tommy Lee Jones 1946) (Bruce Lee 1940))
(if (empty? (first listOfLists))
() ; the base case for recursion
(cons
(map first listOfLists) ; get the first element of each of the lists
(gatherer (map rest listOfLists)) ; gather all the subsequent ones
)
)
)
(def firstnames '("Bruce" "Tommy Lee" "Bruce"))
(def lastnames '("Willis" "Jones" "Lee"))
(def years '(1955 1946 1940))
(println (gatherer [firstnames lastnames years]))
; -> ((Bruce Willis 1955) (Tommy Lee Jones 1946) (Bruce Lee 1940))
(def firstnames ["Bruce" "Tommy Lee" "Bruce"])
(def lastnames ["Willis" "Jones" "Lee"])
(def years [1955 1946 1940])
(println (map (fn [f l y] [f l y]) firstnames lastnames years))
(def lastnames ["Willis" "Jones" "Lee"])
(def years [1955 1946 1940])
(println (map (fn [f l y] [f l y]) firstnames lastnames years))
List Combinations
Given two source lists (or sets), generate a list (or set) of all the pairs derived by combining elements from the individual lists (sets). E.g. given suites =
['H', 'D', 'C', 'S'] and faces = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'], generate the deck of 52 cards, confirm the deck size and check it contains an expected card, say 'Ace of Hearts'.
python
suites = ('H', 'D', 'C', 'S')
faces = ('2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A')
deck = [(face,suite) for suite in suites for face in faces]
assert len(deck) == 52
assert ('A', 'H') in deck
faces = ('2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A')
deck = [(face,suite) for suite in suites for face in faces]
assert len(deck) == 52
assert ('A', 'H') in deck
csharp
using System;
using System.Collections.Generic;
using System.Linq;
namespace Combinations
{
class Program
{
public static void Main(string[] args)
{
// Define the given lists
// Since List`1 implements the interface IEnumerable`1, this can easily be redefined as List`1.
IEnumerable<string> suites = new string[] { "H", "D", "C", "S" };
IEnumerable<string> faces = new string[] { "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A" };
// LINQ Query to perform a Cartesian product and create an anonymous type to hold the results.
// "var" is required to define this as an IEnumerable`1
var deck =
from suite in suites // For each suite in suites
from face in faces // Match it with a face in face.
select new
{
Suite = suite,
Face = face
};
// Verify the count (uses LINQ extension)
if (deck.Count() == 52)
{
Console.WriteLine("Count matches!");
}
// Verify that the Ace of Hearts is in the deck (uses LINQ extension)
if (deck.Contains(new {Suite = "H", Face = "A"}))
{
Console.WriteLine("Ace of Hearts found!");
}
// Example of how to iterate through the list.
// "var" here is required since we are using an anonymous type
foreach(var card in deck)
{
Console.WriteLine("Suite: {0} Face: {1}", card.Suite, card.Face);
}
// If you desire to work with a List`1, you can convert this to a normal list at any time:
Console.WriteLine("\nConverting to list!");
var list = deck.ToList();
Console.WriteLine("Suite: {0} Face: {1}", list[5].Suite, list[5].Face);
Console.WriteLine("List count: {0}", list.Count); // 52
Console.ReadLine();
}
}
}
using System.Collections.Generic;
using System.Linq;
namespace Combinations
{
class Program
{
public static void Main(string[] args)
{
// Define the given lists
// Since List`1 implements the interface IEnumerable`1, this can easily be redefined as List`1.
IEnumerable<string> suites = new string[] { "H", "D", "C", "S" };
IEnumerable<string> faces = new string[] { "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A" };
// LINQ Query to perform a Cartesian product and create an anonymous type to hold the results.
// "var" is required to define this as an IEnumerable`1
var deck =
from suite in suites // For each suite in suites
from face in faces // Match it with a face in face.
select new
{
Suite = suite,
Face = face
};
// Verify the count (uses LINQ extension)
if (deck.Count() == 52)
{
Console.WriteLine("Count matches!");
}
// Verify that the Ace of Hearts is in the deck (uses LINQ extension)
if (deck.Contains(new {Suite = "H", Face = "A"}))
{
Console.WriteLine("Ace of Hearts found!");
}
// Example of how to iterate through the list.
// "var" here is required since we are using an anonymous type
foreach(var card in deck)
{
Console.WriteLine("Suite: {0} Face: {1}", card.Suite, card.Face);
}
// If you desire to work with a List`1, you can convert this to a normal list at any time:
Console.WriteLine("\nConverting to list!");
var list = deck.ToList();
Console.WriteLine("Suite: {0} Face: {1}", list[5].Suite, list[5].Face);
Console.WriteLine("List count: {0}", list.Count); // 52
Console.ReadLine();
}
}
}
java
SortedSet<AbstractMap.SimpleImmutableEntry<String, String> > cards =
new TreeSet<AbstractMap.SimpleImmutableEntry<String, String> >(new CardComparator());
for (String suite : suites)
for (String face : faces)
cards.add(new AbstractMap.SimpleImmutableEntry<String, String>(suite, face));
Boolean containsEntry = cards.contains(new AbstractMap.SimpleImmutableEntry<String, String>("h", "A"));
if (containsEntry) System.out.println("Deck contains 'Ace of Hearts'");
else System.out.println("'Ace of Hearts' not in deck");
new TreeSet<AbstractMap.SimpleImmutableEntry<String, String> >(new CardComparator());
for (String suite : suites)
for (String face : faces)
cards.add(new AbstractMap.SimpleImmutableEntry<String, String>(suite, face));
Boolean containsEntry = cards.contains(new AbstractMap.SimpleImmutableEntry<String, String>("h", "A"));
if (containsEntry) System.out.println("Deck contains 'Ace of Hearts'");
else System.out.println("'Ace of Hearts' not in deck");
fantom
r := [,]
["2","3","4","5","6","7","8","9","10","J","Q","K","A"].each |Str c|
{ ["H","D","C","S"].each |Str s| { r.add([c,s]) } }
q := ["A","H"]
result := r.contains(q)
echo("Deck size=${r.size}, contains $q? -> $result")
["2","3","4","5","6","7","8","9","10","J","Q","K","A"].each |Str c|
{ ["H","D","C","S"].each |Str s| { r.add([c,s]) } }
q := ["A","H"]
result := r.contains(q)
echo("Deck size=${r.size}, contains $q? -> $result")
clojure
(def suites ["H" "D" "C" "S"])
(def faces [2 3 4 5 6 7 8 9 10 "J" "Q" "K" "A"])
(defn listCards [] (for [s suites f faces] [f s]))
(some (partial = ["A" "H"]) (listCards))
; -> true
(count (listCards))
; -> 52
(def faces [2 3 4 5 6 7 8 9 10 "J" "Q" "K" "A"])
(defn listCards [] (for [s suites f faces] [f s]))
(some (partial = ["A" "H"]) (listCards))
; -> true
(count (listCards))
; -> 52
Perform an operation on every item of a list
Perform an operation on every item of a list, e.g.
for the list
the list of sizes of the strings, e.g.
for the list
["ox", "cat", "deer", "whale"] calculate
the list of sizes of the strings, e.g.
[2, 3, 4, 5]
python
print map(lambda x: len(x), ["ox", "cat", "deer", "whale"])
print [len(x) for x in ['ox', 'cat', 'deer', 'whale']]
csharp
using System.Collections.Generic;
public class OperationOnEach {
public static void Main() {
var list = new List<string>() { "ox", "cat", "deer", "whale" };
list.ForEach( System.Console.WriteLine );
}
}
public class OperationOnEach {
public static void Main() {
var list = new List<string>() { "ox", "cat", "deer", "whale" };
list.ForEach( System.Console.WriteLine );
}
}
java
public class SolutionXX {
public static void main(String[] args) {
String[] list = {"ox", "cat", "deer", "whale"};
for (String str : list) {
System.out.println(str.length() + " ");
}
}
}
public static void main(String[] args) {
String[] list = {"ox", "cat", "deer", "whale"};
for (String str : list) {
System.out.println(str.length() + " ");
}
}
}
fantom
["ox", "cat", "deer", "whale"].map { it.size }
clojure
(map count ["ox" "cat" "deer" "whale"])
Split a list of things into numbers and non-numbers
Given a list that might contain e.g. a string, an integer, a float and a date,
split the list into numbers and non-numbers.
split the list into numbers and non-numbers.
python
import re
data = '34234aff340980adf0e0fa0fefl' ## or ''.join(array)
nonDigits = re.findall(re.compile('\D'), data)
digits = re.findall(re.compile('\d'), data)
data = '34234aff340980adf0e0fa0fefl' ## or ''.join(array)
nonDigits = re.findall(re.compile('\D'), data)
digits = re.findall(re.compile('\d'), data)
csharp
using System;
using System.Collections.Generic;
using System.Linq;
// AFAIK, there just isn't a good way to do this in C#
public class ListSplitter {
public static bool IsNumeric(object o) {
var d = new Decimal();
return decimal.TryParse(o.ToString(), out d);
}
public static void Main() {
var list = new List<object>() { "foo", DateTime.Now, 1, "bar", 2.4 };
// the Where method does the work...
var numbers = list.Where( el => IsNumeric(el) );
var nonNumbers = list.Where( el => ! IsNumeric(el) );
}
}
using System.Collections.Generic;
using System.Linq;
// AFAIK, there just isn't a good way to do this in C#
public class ListSplitter {
public static bool IsNumeric(object o) {
var d = new Decimal();
return decimal.TryParse(o.ToString(), out d);
}
public static void Main() {
var list = new List<object>() { "foo", DateTime.Now, 1, "bar", 2.4 };
// the Where method does the work...
var numbers = list.Where( el => IsNumeric(el) );
var nonNumbers = list.Where( el => ! IsNumeric(el) );
}
}
java
public class NumbersSolution {
public static void main(String[] args) {
List<Object> items = Arrays.asList(new Object[] { new Date(), 12L, 15.4, 99, "x" } ) ;
List<Object> numbers = new ArrayList<Object>() ;
List<Object> nonNumbers = new ArrayList<Object>() ;
for (Object item : items )
(item instanceof Number ? numbers : nonNumbers).add(item) ;
}
}
public static void main(String[] args) {
List<Object> items = Arrays.asList(new Object[] { new Date(), 12L, 15.4, 99, "x" } ) ;
List<Object> numbers = new ArrayList<Object>() ;
List<Object> nonNumbers = new ArrayList<Object>() ;
for (Object item : items )
(item instanceof Number ? numbers : nonNumbers).add(item) ;
}
}
public class NumbersSolution {
public static void main() {
List<Object> numbers = new ArrayList<Object>() ;
List<Object> nonNumbers = new ArrayList<Object>() ;
for (Object item : new Object[] { new Date(), 12L, 15.4, 99, "x" } )
(item instanceof Number ? numbers : nonNumbers).add(item) ;
}
}
public static void main() {
List<Object> numbers = new ArrayList<Object>() ;
List<Object> nonNumbers = new ArrayList<Object>() ;
for (Object item : new Object[] { new Date(), 12L, 15.4, 99, "x" } )
(item instanceof Number ? numbers : nonNumbers).add(item) ;
}
}
fantom
things := ["hello", 25, 3.14, Time.now]
numbers := things.findType(Num#)
nonNumbers := things.exclude { numbers.contains(it) }
numbers := things.findType(Num#)
nonNumbers := things.exclude { numbers.contains(it) }
clojure
(def jumble [3 "Bill" 5.7 '("A" "B" "C")]) ; int, string, float, list
(defn numberNonNumberSorter [jumbledList]
(if (empty? jumbledList)
(hash-map :numbers [], :nonnumbers []) ; recursion base case - return two empty lists
(let [head (first jumbledList)] ; let <head> be the first element in the list
(let [tailresult (numberNonNumberSorter (rest jumbledList))] ; tailresult applies recursively to the remainder
(if (number? head) ; is head a number?
(hash-map
:numbers (cons head (tailresult :numbers)) ; add <head> to the numbers
:nonnumbers (tailresult :nonnumbers)) ; leave nonnumbers the same
(hash-map
:numbers (tailresult :numbers) ; leave numbers the same
:nonnumbers (cons head (tailresult :nonnumbers))) ; add <head> to nonnumbers
)
)
)
)
)
(println (numberNonNumberSorter jumble))
; -> {:nonnumbers (Bill (A B C)), :numbers (3 5.7)}
(defn numberNonNumberSorter [jumbledList]
(if (empty? jumbledList)
(hash-map :numbers [], :nonnumbers []) ; recursion base case - return two empty lists
(let [head (first jumbledList)] ; let <head> be the first element in the list
(let [tailresult (numberNonNumberSorter (rest jumbledList))] ; tailresult applies recursively to the remainder
(if (number? head) ; is head a number?
(hash-map
:numbers (cons head (tailresult :numbers)) ; add <head> to the numbers
:nonnumbers (tailresult :nonnumbers)) ; leave nonnumbers the same
(hash-map
:numbers (tailresult :numbers) ; leave numbers the same
:nonnumbers (cons head (tailresult :nonnumbers))) ; add <head> to nonnumbers
)
)
)
)
)
(println (numberNonNumberSorter jumble))
; -> {:nonnumbers (Bill (A B C)), :numbers (3 5.7)}
(group-by number? ["hello" 42 3.14 (Date.)])
