All Problems
Output a string to the console
Write the string
"Hello World!" to STDOUT
python
print "Hello World!"
csharp
System.Console.WriteLine("Hello World!")
erlang
io:format("Hello, World!~n").
clojure
(println "Hello World!")
Retrieve a string containing ampersands from the variables in a url
My PHP script first does a query to obtain customer info for a form. The form has first name and last name fields among others. The customer has put entries such as
The script variable for first name $_REQUEST
I have tried various functions like urldecode but all to no avail. I even tried encoding the url before the view screen is painted so that the url looks like
Of course this fails for the same reasons. What is a better approach?
"Ron & Jean" in the first name field in the database. Then the edit form script is called with variables such as
"http://myserver.com/custinfo/edit.php?mode=view&fname=Ron & Jean&lname=Smith".
The script variable for first name $_REQUEST
['firstname'] never gets beyond the "Ron" value because of the ampersand in the data.
I have tried various functions like urldecode but all to no avail. I even tried encoding the url before the view screen is painted so that the url looks like
"http://myserver/custinfo/edit.php?mode=view&fname="Ronxxnbsp;xxamp;xxnbsp;Jean"&lname=SMITH". (sorry I had to add the xx to replace the ampersand or it didn't display meaningful url contents the browser sees.)
Of course this fails for the same reasons. What is a better approach?
python
# I'm not really sure this is what the site is for,
# but the one unsolved problem for python was grating me.
# Anyway, I think this is what you're looking for.
from urllib import urlencode
query_dict = {'mode': 'view',
'fname': 'Ron & Jean',
'lname': 'Smith'}
print urlencode(query_dict.items())
# Which will be 'lname=Smith&mode=view&fname=Ron+%26+Jean'.
# but the one unsolved problem for python was grating me.
# Anyway, I think this is what you're looking for.
from urllib import urlencode
query_dict = {'mode': 'view',
'fname': 'Ron & Jean',
'lname': 'Smith'}
print urlencode(query_dict.items())
# Which will be 'lname=Smith&mode=view&fname=Ron+%26+Jean'.
erlang
% encode ampersand in your string using %XX where XX is hex code for ampersand
% optionally encode spaces for completeness sake to keep URL solid
URL = "http://myserver.com/custinfo/edit.php?mode=view&fname=Ron%20%26%20Jean&lname=Smith",
{_, Query} = string:tokens(URL, "?"),
KeyValuePairs = string:tokens(Query, "&"),...
% optionally encode spaces for completeness sake to keep URL solid
URL = "http://myserver.com/custinfo/edit.php?mode=view&fname=Ron%20%26%20Jean&lname=Smith",
{_, Query} = string:tokens(URL, "?"),
KeyValuePairs = string:tokens(Query, "&"),...
clojure
(->> {"mode" "view"
"fname" "Ron & Jean"
"lname" "Smith"}
(map #(str (URLEncoder/encode (first %) "UTF-8")
"="
(URLEncoder/encode (second %) "UTF-8")))
(reduce (fn [url e] (str url "&" e))
"http://myserver.com/custinfo/edit.php"))
"fname" "Ron & Jean"
"lname" "Smith"}
(map #(str (URLEncoder/encode (first %) "UTF-8")
"="
(URLEncoder/encode (second %) "UTF-8")))
(reduce (fn [url e] (str url "&" e))
"http://myserver.com/custinfo/edit.php"))
string-wrap
Wrap the string
Expected output:
> The quick brown fox jumps over the lazy dog. The quick brown fox jumps over t
> he lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox
> jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The qui
> ck brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy
> dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps o
> ver the lazy dog. The quick brown fox jumps over the lazy dog.
"The quick brown fox jumps over the lazy dog. " repeated ten times to a max width of 78 chars, starting each line with "> "
Expected output:
> The quick brown fox jumps over the lazy dog. The quick brown fox jumps over t
> he lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox
> jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The qui
> ck brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy
> dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps o
> ver the lazy dog. The quick brown fox jumps over the lazy dog.
python
def wrap(string, length):
while len(string):
print("> " + string[0:length - 1])
string = string[length - 1:].strip()
wrap("The quick brown fox jumps over the lazy dog. " * 10, 78)
while len(string):
print("> " + string[0:length - 1])
string = string[length - 1:].strip()
wrap("The quick brown fox jumps over the lazy dog. " * 10, 78)
erlang
wrapper(String, Times, Length) ->
StrList = lists:reverse(formatter(string:copies(String, Times), Length, [])),
lists:foreach(fun(Str) -> io:format("~p~n", [Str]) end, StrList).
formatter([], _Length, Acc) -> Acc;
formatter(String, Length, Acc) when length(String) > Length - 1->
{Head, Tail} = lists:split(Length - 1, String),
formatter(string:strip(Tail), Length, [[$>, $ | Head] | Acc]);
formatter(String, Length, Acc) ->
formatter([], Length, [[$>, $ | String] | Acc]).
StrList = lists:reverse(formatter(string:copies(String, Times), Length, [])),
lists:foreach(fun(Str) -> io:format("~p~n", [Str]) end, StrList).
formatter([], _Length, Acc) -> Acc;
formatter(String, Length, Acc) when length(String) > Length - 1->
{Head, Tail} = lists:split(Length - 1, String),
formatter(string:strip(Tail), Length, [[$>, $ | Head] | Acc]);
formatter(String, Length, Acc) ->
formatter([], Length, [[$>, $ | String] | Acc]).
clojure
(defn string-wrap [s]
(if (= 0 (count s))
nil
(lazy-seq (cons (apply str (take 78 s))
(string-wrap (drop 78 s))))))
(let [s (apply str (repeat 10 "The quick brown fox jumps over the lazy dog. "))]
(doseq [line (string-wrap s)]
(println "> " line)))
(if (= 0 (count s))
nil
(lazy-seq (cons (apply str (take 78 s))
(string-wrap (drop 78 s))))))
(let [s (apply str (repeat 10 "The quick brown fox jumps over the lazy dog. "))]
(doseq [line (string-wrap s)]
(println "> " line)))
Define a string containing special characters
Define the literal string
"\#{'}${"}/"
python
# yes, Python has way too many forms of string literals :)
print "\\#{'}${\"}/"
print "\\#{'}${"'"'"}/"
print r"""\#{'}${"}/"""
print '\\#{\'}${"}/'
print '\\#{'"'"'}${"}/'
print r'''\#{'}${"}/'''
print "\\#{'}${\"}/"
print "\\#{'}${"'"'"}/"
print r"""\#{'}${"}/"""
print '\\#{\'}${"}/'
print '\\#{'"'"'}${"}/'
print r'''\#{'}${"}/'''
csharp
string verbatim = @"\#{'}${""""}/";
string cStyle = "\\#{'}${\"\"}/";
string cStyle = "\\#{'}${\"\"}/";
erlang
Special = "\\#{'}\${\"}/",
clojure
(def special "\\#{'}${\"}/")
Define a multiline string
Define the string:
"This
Is
A
Multiline
String"
python
text = """This
Is
A
Multiline
String"""
Is
A
Multiline
String"""
# with proper indentation
text = (
"This\n"
"Is\n"
"A\n"
"Multiline\n"
"String"
)
text = (
"This\n"
"Is\n"
"A\n"
"Multiline\n"
"String"
)
csharp
string output = "This\nIs\nA\nMultiline\nString";
string output = @"This
Is
A
Multiline
String";
Is
A
Multiline
String";
erlang
Text = "This\nIs\nA\nMultiline\nString",
clojure
(def multiline "This\nIs\nA\nMultiline\nString")
Define a string containing variables and expressions
Given variables a=3 and b=4 output
"3+4=7"
python
class EvalDict(dict):
def __getitem__(s, k):
return eval(k, s)
a=3; b=4
"%(a)d+%(b)d=%(a+b)d" % EvalDict(locals())
def __getitem__(s, k):
return eval(k, s)
a=3; b=4
"%(a)d+%(b)d=%(a+b)d" % EvalDict(locals())
a=3; b=4
"%d+%d=%d" % (a, b, a+b)
"%d+%d=%d" % (a, b, a+b)
csharp
int a = 3;
int b = 4;
Console.WriteLine("{0}+{1}={2}", a,b,a+b);
int b = 4;
Console.WriteLine("{0}+{1}={2}", a,b,a+b);
erlang
A = 3, B = 4,
io:format("~B+~B=~B~n", [A, B, (A+B)]).
io:format("~B+~B=~B~n", [A, B, (A+B)]).
clojure
(format "%d + %d = %d" a b (+ a b))
Reverse the characters in a string
Given the string
"reverse me", produce the string "em esrever"
python
"reverse me"[::-1]
csharp
var str = "reverse me";
Console.WriteLine(new String(str.Reverse().ToArray()));
Console.WriteLine(new String(str.Reverse().ToArray()));
erlang
Reversed = lists:reverse("reverse me"),
Reversed = revchars("reverse me"),
clojure
(require '[clojure.contrib.str-utils2 :as str])
(str/reverse "reverse me")
(str/reverse "reverse me")
(apply str (reverse "reverse me"))
Reverse the words in a string
Given the string
"This is a end, my only friend!", produce the string "friend! only my end, the is This"
python
' '.join(reversed("This is a end, my only friend!".split()))
csharp
var str = "This is a end, my only friend!";
str = String.Join(" ", str.Split().Reverse().ToArray());
Console.WriteLine(str);
str = String.Join(" ", str.Split().Reverse().ToArray());
Console.WriteLine(str);
erlang
Reversed = string:join(lists:reverse(string:tokens("This is the end, my only friend!", " ")), " "),
clojure
(require '[clojure.contrib.str-utils2 :as str])
(str/join " " (reverse (str/split "this is the end, my only friend!" #" ")))
(str/join " " (reverse (str/split "this is the end, my only friend!" #" ")))
(apply str (interpose " " (reverse (re-seq #"[^\s]+" "This is the end, my only friend!"))))
Text wrapping
Wrap the string
> The quick brown fox jumps over the lazy dog. The quick brown fox jumps
> over the lazy dog. The quick brown fox jumps over the lazy dog. The
> quick brown fox jumps over the lazy dog. The quick brown fox jumps
> over the lazy dog. The quick brown fox jumps over the lazy dog. The
> quick brown fox jumps over the lazy dog. The quick brown fox jumps
> over the lazy dog. The quick brown fox jumps over the lazy dog. The
> quick brown fox jumps over the lazy dog.
"The quick brown fox jumps over the lazy dog. " repeated ten times to a max width of 78 chars, starting each line with "> ", yielding this result:
> The quick brown fox jumps over the lazy dog. The quick brown fox jumps
> over the lazy dog. The quick brown fox jumps over the lazy dog. The
> quick brown fox jumps over the lazy dog. The quick brown fox jumps
> over the lazy dog. The quick brown fox jumps over the lazy dog. The
> quick brown fox jumps over the lazy dog. The quick brown fox jumps
> over the lazy dog. The quick brown fox jumps over the lazy dog. The
> quick brown fox jumps over the lazy dog.
python
import textwrap
print textwrap.fill("The quick brown fox jumps over the lazy dog. " * 10,
72, initial_indent="> ", subsequent_indent="> ")
print textwrap.fill("The quick brown fox jumps over the lazy dog. " * 10,
72, initial_indent="> ", subsequent_indent="> ")
csharp
using System;
using System.Text;
using System.Linq; // used for Array.ToList() extension
public class TextWrapper {
/// <summary>
/// Wrap the given text to a given width.
/// </summary>
/// <param name="text">The text to be wrapped</param>
/// <param name="width">The maximum width of each line</param>
/// <param name="prefix">Begin each line with this prefix</param>
/// <returns>The wrapped text</returns>
public string Wrap(string text, int width, string prefix) {
var words = text.Split(' ').ToList();
var result = new StringBuilder(prefix);
width = width - prefix.Length;
prefix = "\n" + prefix;
int lineSize = 0;
foreach (var word in words) {
int wordLen = word.Length;
// Do we need to start a new line?
if ((lineSize + wordLen) > width) {
result.Remove(result.Length - 1, 1); // remove trailing space
lineSize = 0;
result.Append( prefix );
}
result.Append(word).Append(' ');
lineSize += wordLen + 1;
}
return result.ToString();
}
public static void Main() {
var prefix = "> ";
var sentence = "The quick brown fox jumps over the lazy dog. ";
var text = "";
for (int i = 0; i < 10; i++)
text += sentence;
// The description said lines of length 78, but
// the example was 72...
Console.WriteLine(new TextWrapper().Wrap(text, 72, prefix));
}
}
using System.Text;
using System.Linq; // used for Array.ToList() extension
public class TextWrapper {
/// <summary>
/// Wrap the given text to a given width.
/// </summary>
/// <param name="text">The text to be wrapped</param>
/// <param name="width">The maximum width of each line</param>
/// <param name="prefix">Begin each line with this prefix</param>
/// <returns>The wrapped text</returns>
public string Wrap(string text, int width, string prefix) {
var words = text.Split(' ').ToList();
var result = new StringBuilder(prefix);
width = width - prefix.Length;
prefix = "\n" + prefix;
int lineSize = 0;
foreach (var word in words) {
int wordLen = word.Length;
// Do we need to start a new line?
if ((lineSize + wordLen) > width) {
result.Remove(result.Length - 1, 1); // remove trailing space
lineSize = 0;
result.Append( prefix );
}
result.Append(word).Append(' ');
lineSize += wordLen + 1;
}
return result.ToString();
}
public static void Main() {
var prefix = "> ";
var sentence = "The quick brown fox jumps over the lazy dog. ";
var text = "";
for (int i = 0; i < 10; i++)
text += sentence;
// The description said lines of length 78, but
// the example was 72...
Console.WriteLine(new TextWrapper().Wrap(text, 72, prefix));
}
}
erlang
TextWrap = textwrap(string:copies(Input, 10), 73 - length(Prefix)),
lists:foreach(fun (Line) -> io:format("~s~n", [string:concat(Prefix, Line)]) end, string:tokens(TextWrap, "\n")).
lists:foreach(fun (Line) -> io:format("~s~n", [string:concat(Prefix, Line)]) end, string:tokens(TextWrap, "\n")).
clojure
(doseq [line (re-seq #".{0,70} "
(apply str
(repeat 10 "The quick brown fox jumps over the lazy dog. ")))]
(println ">" line))
(apply str
(repeat 10 "The quick brown fox jumps over the lazy dog. ")))]
(println ">" line))
Remove leading and trailing whitespace from a string
Given the string
" hello " return the string "hello".
python
assert 'hello' == ' hello '.strip()
csharp
string str = " hello ";
str = str.Trim();
Console.WriteLine(str);
str = str.Trim();
Console.WriteLine(str);
erlang
Trimmed = string:strip(S),
clojure
(use 'clojure.contrib.str-utils2)
(trim " hello ")
(trim " hello ")
(clojure.string/trim " hello ")
(.trim " hello ")
Simple substitution cipher
Take a string and return the ROT13 and ROT47 (Check Wikipedia) version of the string.
For example:
String is: Hello World #123
ROT13 returns: Uryyb Jbeyq #123
ROT47 returns: w6==@ (@C=5 R`ab
For example:
String is: Hello World #123
ROT13 returns: Uryyb Jbeyq #123
ROT47 returns: w6==@ (@C=5 R`ab
python
# rot13, readable
rot13_tbl = string.maketrans("ABCDEFGHIJKLMabcdefghijklmNOPQRSTUVWXYZnopqrstuvwxyz", "NOPQRSTUVWXYZnopqrstuvwxyzABCDEFGHIJKLMabcdefghijklm")
string.translate("Hello World #123", rot13_tbl)
#
# "a bad programmer can write bad code in any language"
#
# rot13, "clever"
string.translate("Hello World #123", string.maketrans(string.lowercase+string.uppercase, string.lowercase[13:]+string.lowercase[:13]+string.uppercase[13:]+string.uppercase[:13]))
# rot47, very "clever"
''.join([ord(c) in range(33,127) and chr(((ord(c)-33+47)%(127-33))+33) or c for c in "Hello World #123"])
rot13_tbl = string.maketrans("ABCDEFGHIJKLMabcdefghijklmNOPQRSTUVWXYZnopqrstuvwxyz", "NOPQRSTUVWXYZnopqrstuvwxyzABCDEFGHIJKLMabcdefghijklm")
string.translate("Hello World #123", rot13_tbl)
#
# "a bad programmer can write bad code in any language"
#
# rot13, "clever"
string.translate("Hello World #123", string.maketrans(string.lowercase+string.uppercase, string.lowercase[13:]+string.lowercase[:13]+string.uppercase[13:]+string.uppercase[:13]))
# rot47, very "clever"
''.join([ord(c) in range(33,127) and chr(((ord(c)-33+47)%(127-33))+33) or c for c in "Hello World #123"])
"Hello World #123".encode('rot13')
erlang
rot13(Str) ->
lists:map(fun(A) ->
if
A >= $A, A =< $Z -> ((A - $A + 13) rem 26) + $A;
A >= $a, A =< $z -> ((A - $a + 13) rem 26) + $a;
true -> A
end
end, Str).
rot47(Str) ->
lists:map(fun(A) ->
if
A >= $!, A =< $~ ->
((A - $! + 47) rem 94) + $!;
true -> A
end
end, Str).
lists:map(fun(A) ->
if
A >= $A, A =< $Z -> ((A - $A + 13) rem 26) + $A;
A >= $a, A =< $z -> ((A - $a + 13) rem 26) + $a;
true -> A
end
end, Str).
rot47(Str) ->
lists:map(fun(A) ->
if
A >= $!, A =< $~ ->
((A - $! + 47) rem 94) + $!;
true -> A
end
end, Str).
clojure
(use 'clojure.contrib.cond)
(defn rot13 [s]
(reduce str
(map #(char (let [c (bit-and (int (char %)) 0xDF)]
(+ % (cond-let [i]
(and (>= c (int \A)) (<= c (int \M))) 13
(and (>= c (int \N)) (<= c (int \Z))) -13
true 0))))
(map #(int (char %)) s))))
(defn rot47 [s]
(reduce str
(map #(char (+ % (cond-let [i]
(and (>= % (int \!)) (<= % (int \O))) 47
(and (>= % (int \P)) (<= % (int \~))) -47
true 0)))
(map #(int (char %)) s))))
(defn rot13 [s]
(reduce str
(map #(char (let [c (bit-and (int (char %)) 0xDF)]
(+ % (cond-let [i]
(and (>= c (int \A)) (<= c (int \M))) 13
(and (>= c (int \N)) (<= c (int \Z))) -13
true 0))))
(map #(int (char %)) s))))
(defn rot47 [s]
(reduce str
(map #(char (+ % (cond-let [i]
(and (>= % (int \!)) (<= % (int \O))) 47
(and (>= % (int \P)) (<= % (int \~))) -47
true 0)))
(map #(int (char %)) s))))
Make a string uppercase
Transform
"Space Monkey" into "SPACE MONKEY"
python
"Space Monkey".upper()
csharp
string output = "Space Monkey"
System.Console.WriteLine(output.ToUpper())
System.Console.WriteLine(output.ToUpper())
erlang
io:format("~s~n", [string:to_upper("Space Monkey")]).
clojure
(.toUpperCase "Space Monkey")
Make a string lowercase
Transform
"Caps ARE overRated" into "caps are overrated"
python
"Caps ARE overRated".lower()
csharp
string str = "Caps ARE overRated";
str = str.ToLower() ;
Console.WriteLine(str);
str = str.ToLower() ;
Console.WriteLine(str);
erlang
io:format("~s~n", [string:to_lower("Caps ARE overRated")]).
clojure
(.toLowerCase "Caps ARE overRated")
Capitalise the first letter of each word
Transform
"man OF stEEL" into "Man Of Steel"
python
from string import capwords
capwords("man OF stEEL")
capwords("man OF stEEL")
' '.join(s.capitalize() for s in "man OF stEEL".split())
"man OF stEEL".title()
csharp
System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase("man OF stEEL".ToLowerInvariant());
erlang
Caps = string:join(lists:map(fun(S) -> to_caps(S) end, string:tokens("man OF stEEL", " ")), " "),
clojure
(use 'clojure.contrib.str-utils2)
(join " " (map capitalize (split "man OF stEEL" #" ")))
(join " " (map capitalize (split "man OF stEEL" #" ")))
Find the distance between two points
python
# problem description doesn't say 2D points ;)
from math import sqrt
print sqrt(sum((x-y)**2 for x,y in zip(a, b)))
from math import sqrt
print sqrt(sum((x-y)**2 for x,y in zip(a, b)))
from math import hypot
print hypot(x2-x1, y2-y1)
print hypot(x2-x1, y2-y1)
csharp
System.Drawing.Point p = new System.Drawing.Point(13, 14),
p1 = new System.Drawing.Point(10, 10);
double distance = Math.Sqrt(Math.Pow(p1.X - p.X, 2) + Math.Pow(p1.Y - p.Y, 2)));
p1 = new System.Drawing.Point(10, 10);
double distance = Math.Sqrt(Math.Pow(p1.X - p.X, 2) + Math.Pow(p1.Y - p.Y, 2)));
erlang
Distance = distance({point, 34, 78}, {point, 67, -45}),
io:format("~.2f~n", [Distance]).
io:format("~.2f~n", [Distance]).
Distance = distance(point:new(34, 78), point:new(67, -45)),
io:format("~.2f~n", [Distance]).
io:format("~.2f~n", [Distance]).
clojure
(defstruct point :x :y)
(defn distance
"Euclidean distance between 2 points"
[p1 p2]
(Math/pow (+ (Math/pow (- (:x p1) (:x p2)) 2)
(Math/pow (- (:y p1) (:y p2)) 2))
0.5))
(distance (struct point 0 0) (struct point 1 1)) ; => 1.4142135623730951
(defn distance
"Euclidean distance between 2 points"
[p1 p2]
(Math/pow (+ (Math/pow (- (:x p1) (:x p2)) 2)
(Math/pow (- (:y p1) (:y p2)) 2))
0.5))
(distance (struct point 0 0) (struct point 1 1)) ; => 1.4142135623730951
(defn distance
"Euclidean distance between 2 points"
[[x1 y1] [x2 y2]]
(Math/sqrt
(+ (Math/pow (- x1 x2) 2)
(Math/pow (- y1 y2) 2))))
(distance [2 2] [3 3])
"Euclidean distance between 2 points"
[[x1 y1] [x2 y2]]
(Math/sqrt
(+ (Math/pow (- x1 x2) 2)
(Math/pow (- y1 y2) 2))))
(distance [2 2] [3 3])
Zero pad a number
Given the number 42, pad it to 8 characters like 00000042
python
"%08d" % 42
csharp
string.Format("{0,8:D8}", 42);
erlang
Formatted = io_lib:format("~8..0B", [42]),
io:format("~8..0B~n", [42]).
clojure
(defn pad
([x] (if (> 8 (.length (str x))) (pad (str 0 x)) (str x)))
)
([x] (if (> 8 (.length (str x))) (pad (str 0 x)) (str x)))
)
(defn pad [x]
(format "%08d" x))
(format "%08d" x))
(format "%08d" 42)
Right Space pad a number
Given the number 1024 right pad it to 6 characters
"1024 "
python
"%-6s" % 1024
str(1024).rjust(6)
'{0: <6}'.format(1024)
csharp
public class NumberRightPadding {
public static void Main() {
string withStringDotFormat = string.Format("{0,-6}", 1024);
string withToStringDotPadRight = 1024.ToString().PadRight(6);
}
}
public static void Main() {
string withStringDotFormat = string.Format("{0,-6}", 1024);
string withToStringDotPadRight = 1024.ToString().PadRight(6);
}
}
erlang
Formatted = io_lib:format("~-6B", [1024]),
io:format("~-6B~n", [1024]).
clojure
(let [s (str 1024)
l (count s)]
(str s (reduce str (repeat (- 6 l) " "))))
l (count s)]
(str s (reduce str (repeat (- 6 l) " "))))
Format a decimal number
Format the number 7/8 as a decimal with 2 places: 0.88
python
"%.2f" % (7 / 8.0)
round(7./8., 2)
csharp
public class FormatDecimal {
public static void Main() {
decimal result = decimal.Round( 7 / 8m, 2);
System.Console.WriteLine(result);
}
}
public static void Main() {
decimal result = decimal.Round( 7 / 8m, 2);
System.Console.WriteLine(result);
}
}
erlang
Formatted = io_lib:format("~.2f", [7/8]),
io:format("~.2f~n", [7/8]).
clojure
(format "%3.2f" (/ 7.0 8))
(* 0.01 (Math/round (* 100 (float (/ 7 8)))))
Left Space pad a number
Given the number 73 left pad it to 10 characters
" 73"
python
"%10s" % 73
csharp
public class NumberLeftPadding {
public static void Main() {
string withStringDotFormat = string.Format("{0,10}", 73);
string withToStringDotPadLeft = 73.ToString().PadLeft(10);
}
}
public static void Main() {
string withStringDotFormat = string.Format("{0,10}", 73);
string withToStringDotPadLeft = 73.ToString().PadLeft(10);
}
}
erlang
Formatted = io_lib:format("~10B", [73]),
io:format("~10B~n", [73]).
clojure
(let [s (str 73)
l (count s)]
(str (reduce str (repeat (- 10 l) " ")) s ))
l (count s)]
(str (reduce str (repeat (- 10 l) " ")) s ))
Generate a random integer in a given range
Produce a random integer between 100 and 200 inclusive
python
import random
random.randint(100, 200)
random.randint(100, 200)
# uses best entropy source available (e.g. /dev/urandom, CryptGenRandom, ...)
import random
print random.SystemRandom().randint(100,200)
import random
print random.SystemRandom().randint(100,200)
csharp
System.Random r = new System.Random();
int random = r.Next(100,201);
int random = r.Next(100,201);
erlang
RandomInt = gen_rand_integer(100, 200),
clojure
(+ (rand-int (- 201 100)) 100)
Generate a repeatable random number sequence
Initialise a random number generator with a seed and generate five decimal values. Reset the seed and produce the same values.
python
import random
random.seed(12345)
list1 = [random.randint(1,10) for x in range(5)]
random.seed(12345)
list2 = [random.randint(1,10) for x in range(5)]
assert(list1==list2)
random.seed(12345)
list1 = [random.randint(1,10) for x in range(5)]
random.seed(12345)
list2 = [random.randint(1,10) for x in range(5)]
assert(list1==list2)
csharp
using System;
public class RepeatableRandom {
public static void Main() {
var r = new Random(12); // seed is 12
for (int i = 0; i < 5; i++)
Console.WriteLine(r.Next());
r = new Random(12);
for (int i = 0; i < 5; i++)
Console.WriteLine(r.Next());
}
}
public class RepeatableRandom {
public static void Main() {
var r = new Random(12); // seed is 12
for (int i = 0; i < 5; i++)
Console.WriteLine(r.Next());
r = new Random(12);
for (int i = 0; i < 5; i++)
Console.WriteLine(r.Next());
}
}
erlang
setRNG(RNGState),
io:format("~w~n", [lists:map(fun (_) -> gen_rand_integer(100, 200) end, lists:seq(1, 5))]),
setRNG(RNGState),
io:format("~w~n", [lists:map(fun (_) -> gen_rand_integer(100, 200) end, lists:seq(1, 5))]).
io:format("~w~n", [lists:map(fun (_) -> gen_rand_integer(100, 200) end, lists:seq(1, 5))]),
setRNG(RNGState),
io:format("~w~n", [lists:map(fun (_) -> gen_rand_integer(100, 200) end, lists:seq(1, 5))]).
clojure
(dotimes [_ 2]
(let [r (java.util.Random. 12345)]
(dotimes [_ 5]
(println (.nextInt r 100))))
(println))
(let [r (java.util.Random. 12345)]
(dotimes [_ 5]
(println (.nextInt r 100))))
(println))
Check if a string matches a regular expression
Display
"ok" if "Hello" matches /[A-Z][a-z]+/
python
found = re.match(r'[A-Z][a-z]+', 'Hello')
if found:
print 'ok'
if found:
print 'ok'
csharp
if (Regex.IsMatch("Hello", "[A-Z][a-z]+"))
{
Console.WriteLine("ok");
}
{
Console.WriteLine("ok");
}
erlang
String = "Hello", Regexp = "[A-Z][a-z]+",
is_match(String, Regexp) andalso (begin io:format("ok~n"), true end).
is_match(String, Regexp) andalso (begin io:format("ok~n"), true end).
case re:run("Hello", "[A-Z][a-z]+") of {match, _} -> ok end.
clojure
(if (re-matches #"[A-Z][a-z]+" "Hello")
(println "ok"))
(println "ok"))
Check if a string matches with groups
Display
"two" if "one two three" matches /one (.*) three/
python
match = re.match(r'one (.*) three', 'one two three')
if match:
print match.group(1)
if match:
print match.group(1)
csharp
using System;
using System.Text.RegularExpressions;
public class RegexBackReference {
public static void Main() {
var oneTwoThree = "one two three";
var pattern = "one (.*) three";
Match match = Regex.Match(oneTwoThree, pattern);
// group 0 is the entire match. 1 is the first backreference
Console.WriteLine(match.Groups[1]);
}
}
using System.Text.RegularExpressions;
public class RegexBackReference {
public static void Main() {
var oneTwoThree = "one two three";
var pattern = "one (.*) three";
Match match = Regex.Match(oneTwoThree, pattern);
// group 0 is the entire match. 1 is the first backreference
Console.WriteLine(match.Groups[1]);
}
}
erlang
case re:run("one two three", "one (.*) three", [{capture, [1], list}]) of {match, Res} -> hd(Res) end.
clojure
(if-let [groups (re-matches #"one (.*) three" "one two three")]
(println (second groups)))
(println (second groups)))
Check if a string contains a match to a regular expression
Display
"ok" if "abc 123 @#$" matches /\d+/
python
found = re.search(r'\d+', 'abc 123 @#$')
if found:
print 'ok'
if found:
print 'ok'
csharp
if(System.Text.RegularExpressions.Regex.IsMatch("abc 123 @#$",@"\d+")){
Console.WriteLine("ok");
}
Console.WriteLine("ok");
}
erlang
% Erlang uses 'egrep'-compatible regular expressions, so shortcuts like '\d' not supported
String = "abc 123 @#$", Regexp = "[0-9]+",
is_match(String, Regexp) andalso (begin io:format("ok~n"), true end).
String = "abc 123 @#$", Regexp = "[0-9]+",
is_match(String, Regexp) andalso (begin io:format("ok~n"), true end).
case re:run("abc 123 @#$", "\\d+") of {match, _} -> ok end.
clojure
(if (re-find #"\d+" "abc 123 @#$")
(println "ok"))
(println "ok"))
Loop through a string matching a regex and performing an action for each match
Create a list
[fish1,cow3,boat4] when matching "(fish):1 sausage (cow):3 tree (boat):4" with regex /\((\w+)\):(\d+)/
python
map(''.join, re.findall(r"\((\w+)\):(\d+)", "(fish):1 sausage (cow):3 tree (boat):4"))
--------------------------------------------------------------------------
(''.join(m.groups()) for m in re.finditer(r"\((\w+)\):(\d+)", "(fish):1 sausage (cow):3 tree (boat):4"))
--------------------------------------------------------------------------
(''.join(m.groups()) for m in re.finditer(r"\((\w+)\):(\d+)", "(fish):1 sausage (cow):3 tree (boat):4"))
csharp
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
public static class extensions {
public static IList<string> Map(this string me, string pattern, Func<Match, string> action){
IList<string> matches = new List<string>();
foreach (Match match in Regex.Matches(me,pattern)){
matches.Add(action(match));
}
return matches;
}
}
class Test
{
static void Main()
{
IList<string> list = "(fish):1 sausage (cow):3 tree (boat):4".Map(@"\((\w+)\):(\d+)", (m) => {return m.Groups[1].Value + m.Groups[2].Value;});
}
}
using System.Collections.Generic;
using System.Text.RegularExpressions;
public static class extensions {
public static IList<string> Map(this string me, string pattern, Func<Match, string> action){
IList<string> matches = new List<string>();
foreach (Match match in Regex.Matches(me,pattern)){
matches.Add(action(match));
}
return matches;
}
}
class Test
{
static void Main()
{
IList<string> list = "(fish):1 sausage (cow):3 tree (boat):4".Map(@"\((\w+)\):(\d+)", (m) => {return m.Groups[1].Value + m.Groups[2].Value;});
}
}
erlang
solve(S) ->
R = "\\((\\w+?)\\):(\\d+)",
{match, M} = re:run(S,R, [global, {capture, all_but_first, list}]),
[ A++N || [A, N] <- M].
R = "\\((\\w+?)\\):(\\d+)",
{match, M} = re:run(S,R, [global, {capture, all_but_first, list}]),
[ A++N || [A, N] <- M].
clojure
(let [matcher (re-matcher #"\((\w+)\):(\d+)" "(fish):1 sausage (cow):3 tree (boat):4")]
(loop [match (re-find matcher)
lst []]
(if match
(recur (re-find matcher) (conj lst (str (second match) (nth match 2))))
lst)))
(loop [match (re-find matcher)
lst []]
(if match
(recur (re-find matcher) (conj lst (str (second match) (nth match 2))))
lst)))
Replace the first regex match in a string with a static string
Transform
"Red Green Blue" into "R*d Green Blue" by replacing /e/ with "*"
python
print re.sub(r'e', '*', 'Red Green Blue', 1)
erlang
{ok, Replaced, _} = regexp:sub("Red Green Blue", "e", "*"),
re:replace("Red Green Blue", "e", "*", [{return, list}]).
clojure
(.replaceFirst (re-matcher #"e" "Red Green Blue") "*")
Replace all regex matches in a string with a static string
Transform
"She sells sea shells" into "She X X shells" by replacing /se\w+/ with "X"
python
transformed = re.sub(r'se\w+', 'X', 'She sells sea shells')
csharp
using System.Text.RegularExpressions;
class SolutionXX
{
static void Main()
{
string text = "She sells sea shells";
string result = Regex.Replace(text, @"se\w+", "X");
}
}
class SolutionXX
{
static void Main()
{
string text = "She sells sea shells";
string result = Regex.Replace(text, @"se\w+", "X");
}
}
erlang
% Erlang uses 'egrep'-compatible regular expressions, so shortcuts like '\w' not supported
{ok, Replaced, _} = regexp:gsub("She sells sea shells", "se[A-Za-z0-9_]+", "X"),
{ok, Replaced, _} = regexp:gsub("She sells sea shells", "se[A-Za-z0-9_]+", "X"),
re:replace("She sells sea shells", "se\\w+", "X", [global, {return, list}]).
clojure
(.replaceAll (re-matcher #"se\w+" "She sells sea shells") "X")
Replace all regex matches in a string with a dynamic string
Transform
"The {Quick} Brown {Fox}" into "The kciuQ Brown xoF" by reversing words in braces using the regex /\{(\w+)\}/.
python
transformed = re.sub(r'\{(\w+)\}',
lambda match: match.group(1)[::-1],
'The {Quick} Brown {Fox}')
lambda match: match.group(1)[::-1],
'The {Quick} Brown {Fox}')
erlang
% Erlang regular expressions lack both group capture and backreferences, thus this problem is not directly
% solvable. Presented solution is close, but not on-spec
String = "The {Quick} Brown {Fox}",
{match, FieldList} = regexp:matches(String, "\{([A-Za-z0-9_]+)\}"),
NewString = lists:foldl(fun ({Start, Length}, S) -> replstr(S, lists:reverse(string:substr(S, Start, Length)), Start) end, String, FieldList),
% solvable. Presented solution is close, but not on-spec
String = "The {Quick} Brown {Fox}",
{match, FieldList} = regexp:matches(String, "\{([A-Za-z0-9_]+)\}"),
NewString = lists:foldl(fun ({Start, Length}, S) -> replstr(S, lists:reverse(string:substr(S, Start, Length)), Start) end, String, FieldList),
clojure
(def *string* "The {Quick} Brown {Fox}")
(def *regex* (re-pattern #"\{(\w+)\}"))
(println
(loop [result ""
src *string*
replace-strs (re-seq *regex* *string*)]
(if (empty? src)
result
(let [[match replacement] (first replace-strs)]
(if (= (first src) (first match))
; At the beginning of a sequence that should be replaced.
; Do replacement of a single match
(recur (str result (apply str (reverse replacement)))
(drop (count match) src)
(rest replace-strs))
; else, just copy one char from the source to the result
(recur (str result (first src))
(rest src)
replace-strs))))))
(def *regex* (re-pattern #"\{(\w+)\}"))
(println
(loop [result ""
src *string*
replace-strs (re-seq *regex* *string*)]
(if (empty? src)
result
(let [[match replacement] (first replace-strs)]
(if (= (first src) (first match))
; At the beginning of a sequence that should be replaced.
; Do replacement of a single match
(recur (str result (apply str (reverse replacement)))
(drop (count match) src)
(rest replace-strs))
; else, just copy one char from the source to the result
(recur (str result (first src))
(rest src)
replace-strs))))))
(clojure.string/replace "The {Quick} Brown {Fox}"
#"\{(\w+)\}"
(fn [[_ word]] (apply str (reverse word))))
#"\{(\w+)\}"
(fn [[_ word]] (apply str (reverse word))))
Define an empty list
Assign the variable
"list" to a list with no elements
python
list = []
csharp
var list = new List<object>();
erlang
List = [],
clojure
(list)
'()
Define a static list
Define the list
[One, Two, Three, Four, Five]
python
list = ['One', 'Two', 'Three', 'Four', 'Five']
print list
print list
csharp
IList<string> list = new string[]{"One","Two","Three","Four","Five"};
erlang
List = [one, two, three, four, five],
List = ['One', 'Two', 'Three', 'Four', 'Five'],
clojure
(def a '[One Two Three Four Five])
Join the elements of a list, separated by commas
Given the list
[Apple, Banana, Carrot] produce "Apple, Banana, Carrot"
python
print ", ".join(['Apple', 'Banana', 'Carrot'])
csharp
using System.Collections.Generic;
public class JoinEach {
public static void Main() {
var list = new List<string>() {"Apple", "Banana", "Carrot"};
System.Console.WriteLine( string.Join(", ", list.ToArray()) );
}
}
public class JoinEach {
public static void Main() {
var list = new List<string>() {"Apple", "Banana", "Carrot"};
System.Console.WriteLine( string.Join(", ", list.ToArray()) );
}
}
erlang
Result = string:join(Fruit, ", "),
Result = lists:foldl(fun (E, Acc) -> Acc ++ ", " ++ E end, hd(Fruit), tl(Fruit)),
Result = lists:flatten([ hd(Fruit) | [ ", " ++ X || X <- tl(Fruit)]]).
clojure
(apply str (interpose ", " '("Apple" "Banana" "Carrot")))
Join the elements of a list, in correct english
Create a function join that takes a List and produces a string containing an english language concatenation of the list. It should work with the following examples:
join(
join(
join(
join(
join(
[Apple, Banana, Carrot]) = "Apple, Banana, and Carrot"
join(
[One, Two]) = "One and Two"
join(
[Lonely]) = "Lonely"
join(
[]) = ""
python
def join(*x):
if len(x) <= 2:
return ' and '.join(x)
else:
return ', '.join(x[:-1] + ('and ' + x[-1],))
if __name__ == "__main__":
assert join("Apple", "Banana", "Carrot") == "Apple, Banana, and Carrot"
assert join("One", "Two") == "One and Two"
assert join("Lonely") == "Lonely"
assert join(*[]) == ""
if len(x) <= 2:
return ' and '.join(x)
else:
return ', '.join(x[:-1] + ('and ' + x[-1],))
if __name__ == "__main__":
assert join("Apple", "Banana", "Carrot") == "Apple, Banana, and Carrot"
assert join("One", "Two") == "One and Two"
assert join("Lonely") == "Lonely"
assert join(*[]) == ""
csharp
using System.Collections.Generic;
using System.Linq;
public class CSharpListToEnglishList {
public string JoinAsEnglishList (List<string> words) {
switch (words.Count) {
case 0: return "";
case 1: return words[0];
case 2: return string.Format("{0} and {1}", words.ToArray());
default:
return JoinAsEnglishList( new List<string>() {
string.Join(", ", words.Take(words.Count - 1).ToArray()) + ",",
words.Last()
});
}
}
// Driver...
public static void Main() {
var joiner = new CSharpListToEnglishList();
System.Console.WriteLine(
joiner.JoinAsEnglishList(new List<string>() { "Apple", "Banana", "Carrot", "Orange" }) );
System.Console.WriteLine(
joiner.JoinAsEnglishList(new List<string>() { "Apple", "Banana", "Carrot" }) );
System.Console.WriteLine(
joiner.JoinAsEnglishList(new List<string>() { "One", "Two" }) );
System.Console.WriteLine(
joiner.JoinAsEnglishList(new List<string>() { "Lonely" }) );
System.Console.WriteLine(
joiner.JoinAsEnglishList(new List<string>()) );
}
}
using System.Linq;
public class CSharpListToEnglishList {
public string JoinAsEnglishList (List<string> words) {
switch (words.Count) {
case 0: return "";
case 1: return words[0];
case 2: return string.Format("{0} and {1}", words.ToArray());
default:
return JoinAsEnglishList( new List<string>() {
string.Join(", ", words.Take(words.Count - 1).ToArray()) + ",",
words.Last()
});
}
}
// Driver...
public static void Main() {
var joiner = new CSharpListToEnglishList();
System.Console.WriteLine(
joiner.JoinAsEnglishList(new List<string>() { "Apple", "Banana", "Carrot", "Orange" }) );
System.Console.WriteLine(
joiner.JoinAsEnglishList(new List<string>() { "Apple", "Banana", "Carrot" }) );
System.Console.WriteLine(
joiner.JoinAsEnglishList(new List<string>() { "One", "Two" }) );
System.Console.WriteLine(
joiner.JoinAsEnglishList(new List<string>() { "Lonely" }) );
System.Console.WriteLine(
joiner.JoinAsEnglishList(new List<string>()) );
}
}
erlang
io:format("~s~n", [join(Fruit)]).
% ------
join([]) -> "";
join([W|Ws]) -> join(Ws, W).
join([], S) -> S;
join([W], S) -> join([], S ++ " and " ++ W);
join([W|Ws], S) -> join(Ws, S ++ ", " ++ W).
% ------
join([]) -> "";
join([W|Ws]) -> join(Ws, W).
join([], S) -> S;
join([W], S) -> join([], S ++ " and " ++ W);
join([W|Ws], S) -> join(Ws, S ++ ", " ++ W).
%% According to the reference manual, "string is not a data type in Erlang."
%% Instead it has lists of integers. But I/O functions in general accept
%% IO lists, where an IO list is either a list of IO lists or an integer.
%% This gives you O(1) string concatenation.
-module(commalist).
-export([join/1]).
join([]) -> "";
join([W]) -> W;
join([W1, W2]) -> [W1, " and ", W2];
join([W1, W2, W3]) -> [W1, ", ", W2, ", and ", W3];
join([W1|Ws]) -> [W1, ", ", join(Ws)].
%% Instead it has lists of integers. But I/O functions in general accept
%% IO lists, where an IO list is either a list of IO lists or an integer.
%% This gives you O(1) string concatenation.
-module(commalist).
-export([join/1]).
join([]) -> "";
join([W]) -> W;
join([W1, W2]) -> [W1, " and ", W2];
join([W1, W2, W3]) -> [W1, ", ", W2, ", and ", W3];
join([W1|Ws]) -> [W1, ", ", join(Ws)].
clojure
(defn join [lst]
(cond
(= (count lst) 0) ""
(= (count lst) 1) (first lst)
(= (count lst) 2) (str (first lst) " and " (second lst))
(> (count lst) 2) (loop [lst lst sb (StringBuilder.)]
(if (empty? lst)
(.toString sb)
(recur (rest lst) (.append sb (cond
(> (count lst) 2) (str (first lst) ", ")
(> (count lst) 1) (str (first lst) ", and ")
(= (count lst) 1) (str (first lst)))))))))
(cond
(= (count lst) 0) ""
(= (count lst) 1) (first lst)
(= (count lst) 2) (str (first lst) " and " (second lst))
(> (count lst) 2) (loop [lst lst sb (StringBuilder.)]
(if (empty? lst)
(.toString sb)
(recur (rest lst) (.append sb (cond
(> (count lst) 2) (str (first lst) ", ")
(> (count lst) 1) (str (first lst) ", and ")
(= (count lst) 1) (str (first lst)))))))))
(defn join
([lst]
(join lst false))
([lst is-long]
(condp = (count lst)
0 ""
1 (first lst)
2 (str (first lst) (if is-long ",") " and " (second lst))
(str (first lst) ", " (join (rest lst) true)))))
([lst]
(join lst false))
([lst is-long]
(condp = (count lst)
0 ""
1 (first lst)
2 (str (first lst) (if is-long ",") " and " (second lst))
(str (first lst) ", " (join (rest lst) true)))))
Produce the combinations from two lists
Given two lists, produce the list of tuples formed by taking the combinations from the individual lists. E.g. given the letters
["a", "b", "c"] and the numbers [4, 5], produce the list: [["a", 4], ["b", 4], ["c", 4], ["a", 5], ["b", 5], ["c", 5]]
python
[(x, y) for y in [1,2] for x in ['a','b','c']]
import itertools
[x for x in itertools.product(["a", "b", "c"], [4, 5])]
[x for x in itertools.product(["a", "b", "c"], [4, 5])]
csharp
using System.Collections.Generic;
public class ListCombiner {
public static void Main() {
var letters = new List<char>() { 'a', 'b', 'c' };
var numbers = new List<int>() { 1, 2, 3 };
// result is a list that contaings lists of objects
var result = new List<List<object>>();
foreach (var l in letters) {
foreach (var n in numbers) {
result.Add(new List<object>() { l, n });
}
}
}
}
public class ListCombiner {
public static void Main() {
var letters = new List<char>() { 'a', 'b', 'c' };
var numbers = new List<int>() { 1, 2, 3 };
// result is a list that contaings lists of objects
var result = new List<List<object>>();
foreach (var l in letters) {
foreach (var n in numbers) {
result.Add(new List<object>() { l, n });
}
}
}
}
erlang
Combinations =
lists:foldl(fun (Number, Acc) -> Acc ++ lists:map(fun (Letter) -> {Letter, Number} end, Letters) end, [], Numbers),
lists:foldl(fun (Number, Acc) -> Acc ++ lists:map(fun (Letter) -> {Letter, Number} end, Letters) end, [], Numbers),
Combinations = lists:keysort(2, sofs:to_external(sofs:product(sofs:set(Letters), sofs:set(Numbers))))
[[A, B] || A <- ["a", "b", "c"], B <- [4, 5]].
clojure
(defn combine [lst1 lst2]
(mapcat (fn [x] (map #(list % x) lst1)) lst2))
(mapcat (fn [x] (map #(list % x) lst1)) lst2))
(mapcat (fn [x] (map #(list % x) ["a", "b", "c"])) [4, 5])
From a List Produce a List of Duplicate Entries
Taking a list:
Write the code to produce a list of duplicates in the list:
["andrew", "bob", "chris", "bob"]
Write the code to produce a list of duplicates in the list:
["bob"]
python
import itertools
input = ["andrew", "bob", "chris", "bob"]
input.sort()
output = [k for k, g in itertools.groupby(input, lambda x: x) if len(list(g)) > 1]
input = ["andrew", "bob", "chris", "bob"]
input.sort()
output = [k for k, g in itertools.groupby(input, lambda x: x) if len(list(g)) > 1]
csharp
List<String> values = new List<string> {"andrew", "bob", "chris", "bob"};
var duplicates = values
.GroupBy(i => i)
.Where(j => j.Count() > 1)
.Select(s => s.Key);
foreach (var duplicate in duplicates)
{
Console.WriteLine(duplicate);
}
var duplicates = values
.GroupBy(i => i)
.Where(j => j.Count() > 1)
.Select(s => s.Key);
foreach (var duplicate in duplicates)
{
Console.WriteLine(duplicate);
}
erlang
{_, Result} = lists:foldl(
fun(X, {Uniq, Dupl}) -> case lists:member(X, Uniq) of
true -> {Uniq,[X | Dupl]};
_ -> {[X | Uniq], Dupl}
end
end,
{[], []},
List),
fun(X, {Uniq, Dupl}) -> case lists:member(X, Uniq) of
true -> {Uniq,[X | Dupl]};
_ -> {[X | Uniq], Dupl}
end
end,
{[], []},
List),
Fun = fun
([X | Xs], F) -> case lists:member(X, Xs) of
true -> [X | F(Xs, F)];
_ -> F(Xs, F)
end;
([], _) -> []
end,
Result = Fun(List, Fun).
([X | Xs], F) -> case lists:member(X, Xs) of
true -> [X | F(Xs, F)];
_ -> F(Xs, F)
end;
([], _) -> []
end,
Result = Fun(List, Fun).
clojure
(->> '("andrew" "bob" "chris" "bob")
(group-by identity)
(filter #(> (count (second %)) 1))
(map first))
(group-by identity)
(filter #(> (count (second %)) 1))
(map first))
Fetch an element of a list by index
Given the list
[One, Two, Three, Four, Five], fetch the third element ('Three')
python
list = ['One', 'Two', 'Three', 'Four', 'Five']
list[2]
list[2]
csharp
string[] items = new string[] { "One", "Two", "Three", "Four", "Five" };
List<string> list = new List<string>(items);
string third = list[2]; // "Three"
List<string> list = new List<string>(items);
string third = list[2]; // "Three"
// Make sure you import the System.Linq namespace.
// This is not the preferred way of indexing if you are using Lists.
string[] items = new string[] { "One", "Two", "Three", "Four", "Five" };
IEnumerable<string> list = new List<string>(items);
string third = list.ElementAt(2); // Three
// This is not the preferred way of indexing if you are using Lists.
string[] items = new string[] { "One", "Two", "Three", "Four", "Five" };
IEnumerable<string> list = new List<string>(items);
string third = list.ElementAt(2); // Three
erlang
Result = lists:nth(3, List),
Result = element(3, list_to_tuple(List)),
{Left, _} = lists:split(3, List), Result = lists:last(Left),
Result = nth0(2, List),
clojure
(nth '[One Two Three Four Five] 2)
Fetch the last element of a list
Given the list
[Red, Green, Blue], access the last element ('Blue')
python
list = ['Red', 'Green', 'Blue']
list[-1]
list[-1]
csharp
string[] items = new string[] { "Red", "Green", "Blue" };
List<string> list = new List<string>(items);
string last = list[list.Count - 1]; // "Blue"
List<string> list = new List<string>(items);
string last = list[list.Count - 1]; // "Blue"
// Make sure you import the System.Linq namespace.
// This is not the preferred way of finding the last element if you are using Lists.
string[] items = new string[] { "Red", "Green", "Blue" };
IEnumerable<string> list = new List<string>(items);
string last = list.Last(); // "Blue"
// This is not the preferred way of finding the last element if you are using Lists.
string[] items = new string[] { "Red", "Green", "Blue" };
IEnumerable<string> list = new List<string>(items);
string last = list.Last(); // "Blue"
erlang
Result = lists:last(List),
Result = last(List),
Result = hd(lists:reverse(List)),
Result = lists:nth(length(List), List),
clojure
(last '[One Two Three Four Five])
Find the common items in two lists
Given two lists, find the common items. E.g. given beans =
['broad', 'mung', 'black', 'red', 'white'] and colors = ['black', 'red', 'blue', 'green'], what are the bean varieties that are also color names?
python
beans = ['broad', 'mung', 'black', 'red', 'white']
colors = ['black', 'red', 'blue', 'green']
common = [b for b in beans if b in colors]
colors = ['black', 'red', 'blue', 'green']
common = [b for b in beans if b in colors]
beans = ['broad', 'mung', 'black', 'red', 'white']
colors = ['black', 'red', 'blue', 'green']
common = set(beans) & set(colors)
colors = ['black', 'red', 'blue', 'green']
common = set(beans) & set(colors)
csharp
// Make sure you import the System.Linq namespace.
// This example uses arrays as the underlying implementation, but any IEnumerable type can be used - including List.
IEnumerable<string> beans = new string[] { "beans", "mung", "black", "red", "white" };
IEnumerable<string> colors = new string[] { "black", "red", "blue", "green" };
var intersect = beans.Intersect(colors); // ['red', 'black']
// This example uses arrays as the underlying implementation, but any IEnumerable type can be used - including List.
IEnumerable<string> beans = new string[] { "beans", "mung", "black", "red", "white" };
IEnumerable<string> colors = new string[] { "black", "red", "blue", "green" };
var intersect = beans.Intersect(colors); // ['red', 'black']
erlang
Beans = sets:from_list([broad, mung, black, red, white]), Colors = sets:from_list([black, red, blue, green]),
Common = sets:to_list(sets:intersection(Beans, Colors)),
Common = sets:to_list(sets:intersection(Beans, Colors)),
clojure
(use 'clojure.set)
(let [beans '[broad mung black red white]
colors '[black red blue green]]
(intersection (set beans) (set colors)))
(let [beans '[broad mung black red white]
colors '[black red blue green]]
(intersection (set beans) (set colors)))
Display the unique items in a list
Display the unique items in a list, e.g. given ages =
[18, 16, 17, 18, 16, 19, 14, 17, 19, 18], display the unique elements, i.e. with duplicates removed.
python
ages = [18, 16, 17, 18, 16, 19, 14, 17, 19, 18]
unique_ages = list(set(ages))
unique_ages = list(set(ages))
csharp
using System.Collections.Generic;
using System.Linq;
public class UniqueElements {
public static void Main() {
var list = new List<int>() { 18, 16, 17, 18, 16, 19, 14, 17, 19, 18 };
var uniques = list.Distinct();
}
}
using System.Linq;
public class UniqueElements {
public static void Main() {
var list = new List<int>() { 18, 16, 17, 18, 16, 19, 14, 17, 19, 18 };
var uniques = list.Distinct();
}
}
erlang
Ages = sets:to_list(sets:from_list([18, 16, 17, 18, 16, 19, 14, 17, 19, 18])), io:format("~w~n", [Ages]).
lists:usort([18, 16, 17, 18, 16, 19, 14, 17, 19, 18]).
clojure
;; returns a set
(set [18, 16, 17, 18, 16, 19, 14, 17, 19, 18])
;;#{14 16 17 18 19}
;; returns a lazy sequence of the unique elements
(distinct [18, 16, 17, 18, 16, 19, 14, 17, 19, 18])
;;(18 16 17 19 14)
(set [18, 16, 17, 18, 16, 19, 14, 17, 19, 18])
;;#{14 16 17 18 19}
;; returns a lazy sequence of the unique elements
(distinct [18, 16, 17, 18, 16, 19, 14, 17, 19, 18])
;;(18 16 17 19 14)
Remove an element from a list by index
Given the list
[Apple, Banana, Carrot], remove the first element to produce the list [Banana, Carrot]
python
myList = ['Apple', 'Banana', 'Carrot']
print myList
del myList[0]
# or
myList.pop(0) # returns 'Apple'
print myList
print myList
del myList[0]
# or
myList.pop(0) # returns 'Apple'
print myList
csharp
class Solution1516
{
static void Main()
{
List<string> fruit = new List<string>() { "Apple", "Banana", "Carrot" };
fruit.RemoveAt(0);
}
}
{
static void Main()
{
List<string> fruit = new List<string>() { "Apple", "Banana", "Carrot" };
fruit.RemoveAt(0);
}
}
erlang
Result = tl(List),
[_|Result] = List,
N = 1, {Left, Right} = lists:split(N - 1, List), Result = Left ++ tl(Right),
Result = drop(1, List),
clojure
(let [fruit ["Apple" "Banana" "Carrot"]
index 0]
(concat
(take index fruit)
(drop (+ index 1) fruit)))
index 0]
(concat
(take index fruit)
(drop (+ index 1) fruit)))
Remove the last element of a list
python
myList = ['Apple', 'Banana', 'Carrot']
myList.pop()
myList.pop()
csharp
List<string> fruits = new List() { "apple", "banana", "cherry" };
fruits.RemoveAt(fruits.Length - 1);
fruits.RemoveAt(fruits.Length - 1);
erlang
Result = init(List),
Result = take(length(List) - 1, List),
Result = lists:reverse(tl(lists:reverse(List))),
clojure
(pop ["Apple" "Banana" "Carrot"])
Rotate a list
Given a list
["apple", "orange", "grapes", "bananas"], rotate it by removing the first item and placing it on the end to yield ["orange", "grapes", "bananas", "apple"]
python
l = ["apple", "orange", "grapes", "bananas"]
first, l = l[0], l[1:] + l[:1]
first, l = l[0], l[1:] + l[:1]
fruit = ['apple', 'orange', 'grapes', 'bananas']
fruit.append(fruit.pop(0))
fruit.append(fruit.pop(0))
csharp
var lst = new LinkedList<String>(new String[] {"apple", "orange", "grapes", "banana"});
lst.AddLast(lst.First());
lst.DeleteFirst();
lst.AddLast(lst.First());
lst.DeleteFirst();
erlang
N = 1, {Left, Right} = lists:split(N, List), Result = Right ++ Left,
N = 1, Result = rotate(N, List),
clojure
(let [fruit ["apple" "orange" "grapes" "bananas"]]
(concat (rest fruit) [(first fruit)])
(concat (rest fruit) [(first fruit)])
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)));
erlang
First = ['Bruce', 'Tommy Lee', 'Bruce'], Last = ['Willis', 'Jones', 'Lee'], Years = [1955, 1946, 1940],
Result = lists:zip3(First, Last, Years),
Result = lists:zip3(First, Last, Years),
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();
}
}
}
erlang
Cards = lists:foldl(fun (Suite, Acc) -> Acc ++ lists:flatmap(fun (Face) -> [{Suite, Face}] end, Faces) end, [], Suites),
io:format("Deck has ~B cards~n", [length(Cards)]),
IsMember = lists:member({h, 'A'}, Cards),
io:format("~s~n", [if IsMember -> "Deck contains 'Ace of Hearts'" ; true -> "'Ace of Hearts' not in deck" end]),
io:format("Deck has ~B cards~n", [length(Cards)]),
IsMember = lists:member({h, 'A'}, Cards),
io:format("~s~n", [if IsMember -> "Deck contains 'Ace of Hearts'" ; true -> "'Ace of Hearts' not in deck" end]),
Cards = sofs:to_external(sofs:product(sofs:set(Suites), sofs:set(Faces))),
io:format("Deck has ~B cards~n", [length(Cards)]),
IsMember = lists:member({h, 'A'}, Cards),
io:format("~s~n", [if IsMember -> "Deck contains 'Ace of Hearts'" ; true -> "'Ace of Hearts' not in deck" end]),
io:format("Deck has ~B cards~n", [length(Cards)]),
IsMember = lists:member({h, 'A'}, Cards),
io:format("~s~n", [if IsMember -> "Deck contains 'Ace of Hearts'" ; true -> "'Ace of Hearts' not in deck" end]),
Deck2 = [{S, V} || S <- [d, c, h, s], V <- [2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K', 'A']],
52 = length(Deck2),
true = lists:member({h, 'A'}, Deck2).
52 = length(Deck2),
true = lists:member({h, 'A'}, Deck2).
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 );
}
}
erlang
lists:map(fun (X) ->length(X) end, List).
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) );
}
}
erlang
% Wrapped call to the auxiliary function
number_split(Xs) ->
number_split(Xs, [], []).
% The auxiliary function
number_split([], Num, NonNum) ->
{Num, NonNum};
number_split([X|Xs], Num, NonNum) ->
case is_number(X) of
true ->
number_split(Xs, [X|Num], NonNum);
false ->
number_split(Xs, Num, [X|NonNum])
end.
number_split(Xs) ->
number_split(Xs, [], []).
% The auxiliary function
number_split([], Num, NonNum) ->
{Num, NonNum};
number_split([X|Xs], Num, NonNum) ->
case is_number(X) of
true ->
number_split(Xs, [X|Num], NonNum);
false ->
number_split(Xs, Num, [X|NonNum])
end.
List = ["hello", 25, 3.14, calendar:local_time()],
{Numbers, NonNumbers} = lists:partition(fun(E) -> is_number(E) end, List)
{Numbers, NonNumbers} = lists:partition(fun(E) -> is_number(E) end, List)
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.)])
Test if a condition holds for all items of a list
Given a list, test if a certain logical condition (i.e. predicate) holds for all items of the list.
python
all(x > 1 for x in [2,3,4])
erlang
Result = lists:all(Pred, List).
clojure
(every? #(> % 1) [2 3 4])
Test if a condition holds for any items of a list
Given a list, test if a certain logical condition (i.e. predicate) holds for any items of the list.
python
any(x > 3 for x in [2, 3, 4])
erlang
Result = lists:any(Pred, List).
clojure
; The standard library in Clojure has "not-any?" but (oddly enough) no "any?"
(defn any? [pred coll]
((complement not-any?) pred coll))
(any? #(> % 3) [2 3 4])
(defn any? [pred coll]
((complement not-any?) pred coll))
(any? #(> % 3) [2 3 4])
(some #(> % 3) [2 3 4])
Define an empty map
python
map = {}
erlang
Map = dict:new(),
Map = orddict:new(),
Map = gb_trees:empty(),
Map = ets:new(the_map_name, [set, private, {keypos, 1}]),
clojure
(def m {})
Define an unmodifiable empty map
python
import collections
EmptyDict = collections.namedtuple("EmptyDict", "")
e = EmptyDict()
EmptyDict = collections.namedtuple("EmptyDict", "")
e = EmptyDict()
erlang
% Erlang data structures are immutable - updating a 'map' sees a modified copy created
Map = dict:new(),
% Erlang data structures are immutable - updating a 'map' sees a modified copy created
Map = dict:new(),
clojure
; Clojure maps are immutable
(def m {})
(def m {})
Define an initial map
Define the map
{circle:1, triangle:3, square:4}
python
shapes = {'circle': 1, 'square': 4, 'triangle': 2}
erlang
Map = dict:from_list([{circle, 1}, {triangle, 3}, {square, 4}]),
Map0 = dict:new(),
% Erlang variables are 'single-assignment' i.e. they cannot be reassigned
Map1 = dict:store(circle, 1, Map0),
Map2 = dict:store(triangle, 3, Map1),
Map3 = dict:store(square, 4, Map2),
% Erlang variables are 'single-assignment' i.e. they cannot be reassigned
Map1 = dict:store(circle, 1, Map0),
Map2 = dict:store(triangle, 3, Map1),
Map3 = dict:store(square, 4, Map2),
Map0 = gb_trees:empty(),
Map1 = gb_trees:enter(circle, 1, Map0),
Map2 = gb_trees:enter(triangle, 3, Map1),
Map3 = gb_trees:enter(square, 4, Map2),
Map1 = gb_trees:enter(circle, 1, Map0),
Map2 = gb_trees:enter(triangle, 3, Map1),
Map3 = gb_trees:enter(square, 4, Map2),
Map = gb_trees:from_orddict(lists:keysort(1, [{circle, 1}, {triangle, 3}, {square, 4}])),
Map = ets:new(the_map_name, [ordered_set, private, {keypos, 1}]),
ets:insert(Map, [{circle, 1}, {triangle, 3}, {square, 4}]),
ets:insert(Map, [{circle, 1}, {triangle, 3}, {square, 4}]),
clojure
(def m '{circle 1 triangle 1 square 4})
Check if a key exists in a map
Given a map pets
{joe:cat,mary:turtle,bill:canary} print "ok" if an pet exists for "mary"
python
pets = dict(joe='cat', mary='turtle', bill='canary')
if ("mary" in pets) print "ok"
if ("mary" in pets) print "ok"
erlang
dict:is_key(mary, Pets) andalso begin io:format("ok~n"), true end.
IsMember = ets:member(Pets, mary), if (IsMember) -> io:format("ok~n") ; true -> false end.
case gb_trees:lookup(mary, Pets) of none -> false ; _ -> io:format("ok~n") end.
clojure
(if (contains? '{joe cat mary turtle bill canary} 'mary)
(println "ok"))
(println "ok"))
Retrieve a value from a map
Given a map pets
{joe:cat,mary:turtle,bill:canary} print the pet for "joe" ("cat")
python
print pets['joe']
erlang
dict:is_key(joe, Pets) andalso begin io:format("~w~n", [dict:fetch(joe, Pets)]), true end.
case dict:find(joe, Pets) of error -> false ; {ok, Pet} -> io:format("~w~n", [Pet]) end.
IsMember = ets:member(Pets, joe), if (IsMember) -> io:format("~w~n", [ets:lookup_element(Pets, joe, 2)]) ; true -> false end.
case ets:match(Pets, {joe, '$1'}) of [] -> false ; [[Pet]] -> io:format("~w~n", [Pet]) end.
case gb_trees:lookup(joe, Pets) of none -> false ; {value, Pet} -> io:format("~w~n", [Pet]) end.
clojure
(def pets '{joe cat mary turtle bill canary})
(println (get pets 'joe))
(println (get pets 'joe))
Add an entry to a map
Given an empty pets map, add the mapping from
"rob" to "dog"
python
pets['rob'] = 'dog'
erlang
Pets1 = dict:store(rob, dog, Pets0).
ets:insert(Pets, {rob, dog}).
Pets1 = gb_trees:enter(rob, dog, Pets0).
clojure
(assoc {} 'rob 'dog)
Remove an entry from a map
Given a map pets
{joe:cat,mary:turtle,bill:canary} remove the mapping for "bill" and print "canary"
python
print pets.pop('bill')
erlang
Pet = dict:fetch(bill, Pets0), Pets1 = dict:erase(bill, Pets0), io:format("~w~n", [Pet]),
Pet = ets:lookup_element(Pets, bill, 2), ets:delete(Pets, bill), io:format("~w~n", [Pet]),
{value, Pet} = gb_trees:lookup(bill, Pets0), Pets1 = gb_trees:delete(bill, Pets0), io:format("~w~n", [Pet]),
clojure
; Maps are immutable
; The following expression will return a new map without the 'bill key
(let [pets '{joe cat mary turtle bill canary}]
(println (get pets 'bill))
(dissoc pets 'bill))
; The following expression will return a new map without the 'bill key
(let [pets '{joe cat mary turtle bill canary}]
(println (get pets 'bill))
(dissoc pets 'bill))
Create a histogram map from a list
Given the list
[a,b,a,c,b,b], produce a map {a:2, b:3, c:1} which contains the count of each unique item in the list
python
from collections import defaultdict
h = defaultdict(int)
for k in "abacbb":
h[k] += 1
h = {}
for k in "abacbb":
h[k] = h.setdefault(k, 0) + 1
h = defaultdict(int)
for k in "abacbb":
h[k] += 1
h = {}
for k in "abacbb":
h[k] = h.setdefault(k, 0) + 1
from collections import Counter
h = Counter("abacbb")
print(h)
h = Counter("abacbb")
print(h)
csharp
using System.Collections.Generic;
using System.Linq;
// This is a "functional" C# approach
// NOTE: In C# "maps" are of type Dictionary<Tkey, TValue>
// so our histogram map is of type Dictionary<object, int>
public class HistogramMap {
public Dictionary<object, int> FromList(List<object> list) {
// The "Aggregate" method works like "inject" in many other languages.
return list.Aggregate(
new Dictionary<object, int>(),
(map, obj) => {
// If this is the first time we've seen this obj, set the count to 0
if (!map.ContainsKey(obj)) map[obj] = 0;
// Increment the count
map[obj]++;
// Return the map for the next iteration.
// NOTE: This does NOT return from our "FromList" method
return map;
}
);
}
public static void Main() {
// Create our Histogram Map from a new list
var map = new HistogramMap().FromList(
new List<object>() { 'a', 'b', 'a', 'c', 'b', 'b' }
);
// This just prints the result
System.Console.WriteLine (
string.Join (", ",
// "Select" works like "map" or "collect" in many other languages
map.Select( kvp =>
string.Format("{0} : {1}", kvp.Key, kvp.Value)
).ToArray()
)
);
}
}
using System.Linq;
// This is a "functional" C# approach
// NOTE: In C# "maps" are of type Dictionary<Tkey, TValue>
// so our histogram map is of type Dictionary<object, int>
public class HistogramMap {
public Dictionary<object, int> FromList(List<object> list) {
// The "Aggregate" method works like "inject" in many other languages.
return list.Aggregate(
new Dictionary<object, int>(),
(map, obj) => {
// If this is the first time we've seen this obj, set the count to 0
if (!map.ContainsKey(obj)) map[obj] = 0;
// Increment the count
map[obj]++;
// Return the map for the next iteration.
// NOTE: This does NOT return from our "FromList" method
return map;
}
);
}
public static void Main() {
// Create our Histogram Map from a new list
var map = new HistogramMap().FromList(
new List<object>() { 'a', 'b', 'a', 'c', 'b', 'b' }
);
// This just prints the result
System.Console.WriteLine (
string.Join (", ",
// "Select" works like "map" or "collect" in many other languages
map.Select( kvp =>
string.Format("{0} : {1}", kvp.Key, kvp.Value)
).ToArray()
)
);
}
}
new[] {"a","b","a","c","b","b"}
.GroupBy(s => s)
.Select(s => new { Value = s.Key, Count = s.Count() })
.ToList()
.ForEach(e => Console.WriteLine("{0} : {1} ", e.Value, e.Count));
.GroupBy(s => s)
.Select(s => new { Value = s.Key, Count = s.Count() })
.ToList()
.ForEach(e => Console.WriteLine("{0} : {1} ", e.Value, e.Count));
erlang
% Imperative Solution
Histogram = histogram(List),
Histogram = histogram(List),
% Functional (1) Solution
Histogram = histogram(List),
Histogram = histogram(List),
lists:foldl(fun(Elem, OldDict) ->
dict:update_counter(Elem, 1, OldDict)
end,
dict:new(),
[a,b,a,c,b,b])).
dict:update_counter(Elem, 1, OldDict)
end,
dict:new(),
[a,b,a,c,b,b])).
clojure
(let [l '[a b a c b b]]
(loop [m {}
d (distinct l)]
(let [item (first d)]
(if (zero? (count d))
m
(recur
(assoc m
item
(count
(filter #(= item %) l)))
(rest d))))))
(loop [m {}
d (distinct l)]
(let [item (first d)]
(if (zero? (count d))
m
(recur
(assoc m
item
(count
(filter #(= item %) l)))
(rest d))))))
(->> [:a :b :a :c :b :b]
(group-by identity)
(reduce (fn [m e] (assoc m (first e) (count (second e)))) {}))
(group-by identity)
(reduce (fn [m e] (assoc m (first e) (count (second e)))) {}))
(reduce conj {} (for [[x xs] (group-by identity "abacbb")] [x (count xs)]))
(frequencies ["a","b","a","c","b","b"])
(frequencies '[a b a c b b])
Categorise a list
Given the list
[one, two, three, four, five] produce a map {3:[one, two], 4:[four, five], 5:[three]} which sorts elements into map entries based on their length
python
c = defaultdict(list)
for k in ["one", "two", "four", "three", "five"]:
c[len(k)].append(k)
for k in ["one", "two", "four", "three", "five"]:
c[len(k)].append(k)
from itertools import groupby
lst = ["one", "two", "four", "three", "five"]
c = dict((k, list(g)) for k,g in
groupby(sorted(lst, key=lambda x: len(x)), key=lambda x: len(x)))
print(c)
lst = ["one", "two", "four", "three", "five"]
c = dict((k, list(g)) for k,g in
groupby(sorted(lst, key=lambda x: len(x)), key=lambda x: len(x)))
print(c)
csharp
using System.Collections.Generic;
using System.Linq;
public class ListCategorizer {
public static void Main() {
var list = new List<string>() { "one", "two", "three", "four", "five" };
var categories = list.GroupBy(el => el.Length)
.ToDictionary( g => g.Key, // key
g => g.ToList() ); // value
}
}
using System.Linq;
public class ListCategorizer {
public static void Main() {
var list = new List<string>() { "one", "two", "three", "four", "five" };
var categories = list.GroupBy(el => el.Length)
.ToDictionary( g => g.Key, // key
g => g.ToList() ); // value
}
}
erlang
% Imperative Solution
CatList = categorise(List),
CatList = categorise(List),
% Functional (1) Solution
CatList = categorise(List),
CatList = categorise(List),
clojure
(loop [m {}
l ["one" "two" "three" "four" "five"]]
(if (zero? (count l))
m
(let [item (first l)
key (count item)]
(recur
(assoc m key (cons item (get m key [])))
(rest l)))))
l ["one" "two" "three" "four" "five"]]
(if (zero? (count l))
m
(let [item (first l)
key (count item)]
(recur
(assoc m key (cons item (get m key [])))
(rest l)))))
(group-by count ["one" "two" "three" "four" "five"])
Perform an action if a condition is true (IF .. THEN)
Given a variable name, if the value is
"Bob", display the string "Hello, Bob!". Perform no action if the name is not equal.
python
if name == 'Bob':
print 'Hello, Bob!'
print 'Hello, Bob!'
csharp
if (name == "Bob") Console.WriteLine("Hello, {0}!", name);
erlang
if (Name == "Bob") -> io:format("Hello, ~s!~n", [Name]) ; true -> false end.
case Name of "Bob" -> io:format("Hello, ~s!~n", [Name]) ; _ -> false end.
Name == "Bob" andalso (begin io:format("Hello, ~s!~n", [Name]), true end).
clojure
(def person "Bob")
(if (= person "Bob")
(println "Hello, Bob!"))
(if (= person "Bob")
(println "Hello, Bob!"))
Perform different actions depending on a boolean condition (IF .. THEN .. ELSE)
Given a variable age, if the value is greater than 42 display
"You are old", otherwise display "You are young"
python
if age > 42:
print 'You are old'
else:
print 'You are young'
print 'You are old'
else:
print 'You are young'
print age > 42 and 'You are old' or 'You are young'
csharp
int age = 41;
if (age > 42)
System.Console.WriteLine("You are old");
else
System.Console.WriteLine("You are young");
if (age > 42)
System.Console.WriteLine("You are old");
else
System.Console.WriteLine("You are young");
erlang
if Age > 42 -> io:format("You are old~n") ; true -> io:format("You are young~n") end.
Message = if Age > 42 -> "old" ; true -> "young" end, io:format("You are ~s~n", [Message]).
case Age > 42 of true -> io:format("You are old~n") ; false -> io:format("You are young~n") end.
case Age of _ when Age > 42 -> io:format("You are old~n") ; _ -> io:format("You are young~n") end.
Message = case Age of _ when Age > 42 -> "old" ; _ -> "young" end, io:format("You are ~s~n", [Message]).
Age > 42 andalso (begin io:format("You are old~n"), true end) orelse (begin io:format("You are young~n"), true end).
(fun (X) when X > 42 -> io:format("You are old~n"); (_) -> io:format("You are young~n") end)(Age).
(fun () when Age > 42 -> io:format("You are old~n"); () -> io:format("You are young~n") end)().
io:format("You are ~s~n", [if Age > 42 -> "old" ; true -> "young" end]).
clojure
(def age 41)
(if (> age 42) "You are old" "You are young")
(if (> age 42) "You are old" "You are young")
Perform different actions depending on several boolean conditions (IF .. THEN .. ELSIF .. ELSE)
python
if age > 84:
print 'You are really ancient'
elif age > 30:
print 'You are middle-aged'
else:
print 'You are young'
print 'You are really ancient'
elif age > 30:
print 'You are middle-aged'
else:
print 'You are young'
csharp
if (age > 84) Console.WriteLine("You are really ancient");
else if (age > 30) Console.WriteLine("You are middle-aged");
else Console.WriteLine("You are young");
else if (age > 30) Console.WriteLine("You are middle-aged");
else Console.WriteLine("You are young");
Console.WriteLine("You are {0}", ((age > 84) ? "really ancient" : (age > 30) ? "middle-aged" : "young"));
erlang
if
Age > 84 -> io:format("You are really ancient~n");
Age > 30 -> io:format("You are middle-aged~n");
true -> io:format("You are young~n")
end.
Age > 84 -> io:format("You are really ancient~n");
Age > 30 -> io:format("You are middle-aged~n");
true -> io:format("You are young~n")
end.
case Age of
_ when Age > 84 -> io:format("You are really ancient~n");
_ when Age > 30 -> io:format("You are middle-aged~n");
true -> io:format("You are young~n")
end.
_ when Age > 84 -> io:format("You are really ancient~n");
_ when Age > 30 -> io:format("You are middle-aged~n");
true -> io:format("You are young~n")
end.
clojure
(println
(condp <= age
84 "You are really ancient"
30 "You are middle aged"
"You are young"))
(condp <= age
84 "You are really ancient"
30 "You are middle aged"
"You are young"))
Replacing a conditional with many branches with a switch/case statement
Many languages support more compact forms of branching than just if ... then ... else such as switch or case or match. Use such a form to add an appropriate placing suffix to the numbers 1..40, e.g. 1st, 2nd, 3rd, 4th, ..., 11th, 12th, ... 39th, 40th
python
def affix(num):
num = num == 1 and str(num) + 'st' or num == 2 and str(num) + 'nd' or \
num == 3 and str(num) +'rd' or str(num) + 'th'
return num
print [affix(x) for x in xrange(1,41)]
num = num == 1 and str(num) + 'st' or num == 2 and str(num) + 'nd' or \
num == 3 and str(num) +'rd' or str(num) + 'th'
return num
print [affix(x) for x in xrange(1,41)]
csharp
public static string GetOrdinal(int i)
{
if (i > 10 && i < 20) return i.ToString() + "th";
switch (i % 10)
{
case 1:
return i.ToString() + "st";
case 2:
return i.ToString() + "nd";
case 3:
return i.ToString() + "rd";
default:
return i.ToString() + "th";
}
}
{
if (i > 10 && i < 20) return i.ToString() + "th";
switch (i % 10)
{
case 1:
return i.ToString() + "st";
case 2:
return i.ToString() + "nd";
case 3:
return i.ToString() + "rd";
default:
return i.ToString() + "th";
}
}
public static string GetOrdinal(int i)
{
if (i > 10 && i < 20) return i.ToString() + "th";
switch (i % 10)
{
case 1:
return i.ToString() + "st";
break;
case 2:
return i.ToString() + "nd";
break;
case 3:
return i.ToString() + "rd";
break;
default:
return i.ToString() + "th";
break;
}
}
{
if (i > 10 && i < 20) return i.ToString() + "th";
switch (i % 10)
{
case 1:
return i.ToString() + "st";
break;
case 2:
return i.ToString() + "nd";
break;
case 3:
return i.ToString() + "rd";
break;
default:
return i.ToString() + "th";
break;
}
}
erlang
Suffix = case Num of
N when N > 10, N < 20 -> "th";
N when N rem 10 =:= 1 -> "st";
N when N rem 10 =:= 2 -> "nd";
N when N rem 10 =:= 3 -> "rd";
_ -> "th"
end,
io_lib:format("~w~s", [Num, Suffix])
N when N > 10, N < 20 -> "th";
N when N rem 10 =:= 1 -> "st";
N when N rem 10 =:= 2 -> "nd";
N when N rem 10 =:= 3 -> "rd";
_ -> "th"
end,
io_lib:format("~w~s", [Num, Suffix])
clojure
(def n 112)
(println (str n
(let [rem (mod n 100)]
(if (and (>= rem 11) (<= rem 13))
"th"
(condp = (mod n 10)
1 "st"
2 "nd"
3 "rd"
"th")))))
(println (str n
(let [rem (mod n 100)]
(if (and (>= rem 11) (<= rem 13))
"th"
(condp = (mod n 10)
1 "st"
2 "nd"
3 "rd"
"th")))))
Perform an action multiple times based on a boolean condition, checked before the first action (WHILE .. DO)
Starting with a variable x=1, Print the sequence
"1,2,4,8,16,32,64,128," by doubling x and checking that x is less than 150.
python
x = 1
while x < 150:
print '%s, ' % x,
x *= 2
while x < 150:
print '%s, ' % x,
x *= 2
csharp
int x = 1;
while (x < 150)
{
x *= 2;
Console.Write("{0},", x);
}
while (x < 150)
{
x *= 2;
Console.Write("{0},", x);
}
erlang
X = 1, print_while_X_less_150(X).
Pred = fun (X) -> X < 150 end,
Action = fun (X) -> io:format("~B,", [X]), X * 2 end,
X = 1,
while_do(Pred, Action, X).
Action = fun (X) -> io:format("~B,", [X]), X * 2 end,
X = 1,
while_do(Pred, Action, X).
clojure
(take-while #(< % 150) (iterate #(* 2 %) 1))
Perform an action multiple times based on a boolean condition, checked after the first action (DO .. WHILE)
Simulate rolling a die until you get a six. Produce random numbers, printing them until a six is rolled. An example output might be
"4,2,1,2,6"
python
import random, itertools
def dice():
while True:
yield random.randint(1,6)
print ", ".join(str(d) for d in itertools.takewhile(lambda x: x < 6, dice()))
def dice():
while True:
yield random.randint(1,6)
print ", ".join(str(d) for d in itertools.takewhile(lambda x: x < 6, dice()))
csharp
System.Random die = new System.Random();
int roll;
do
{
roll = die.Next(1, 6);
Console.Write(roll);
if (roll < 6) Console.Write(",");
}
while (roll != 6);
int roll;
do
{
roll = die.Next(1, 6);
Console.Write(roll);
if (roll < 6) Console.Write(",");
}
while (roll != 6);
erlang
Pred = fun (DiceRoll) -> DiceRoll =/= 6 end,
Action = fun (DiceRoll) -> io:format("~B,", [DiceRoll]), dice_roll() end,
do_while(Pred, Action, dice_roll()).
Action = fun (DiceRoll) -> io:format("~B,", [DiceRoll]), dice_roll() end,
do_while(Pred, Action, dice_roll()).
-module(dice).
-export([start/0]).
start() ->
roll(dice_roll()).
roll(6) ->
io:format("6~n", []);
roll(N) ->
io:format("~B,", [N]),
roll(dice_roll()).
dice_roll() -> random:uniform(6).
-export([start/0]).
start() ->
roll(dice_roll()).
roll(6) ->
io:format("6~n", []);
roll(N) ->
io:format("~B,", [N]),
roll(dice_roll()).
dice_roll() -> random:uniform(6).
clojure
(loop [r (rand-int 6)]
(if (= r 5)
nil
(do
(println r)
(recur (rand-int 6)))))
(if (= r 5)
nil
(do
(println r)
(recur (rand-int 6)))))
Perform an action a fixed number of times (FOR)
Display the string
"Hello" five times like "HelloHelloHelloHelloHello"
python
print "Hello" * 5
for i in range(5):
print "Hello"
print "Hello"
csharp
string text = "Hello";
for (int i = 0; i < 5; i++)
{
Console.Write(text);
}
for (int i = 0; i < 5; i++)
{
Console.Write(text);
}
erlang
dotimes(5, fun () -> io:format("Hello") end).
lists:foreach(fun (_) -> io:format("Hello") end, lists:seq(1, 5)).
clojure
(dotimes [_ 5]
(print "Hello"))
(print "Hello"))
Perform an action a fixed number of times with a counter
Display the string
"10 .. 9 .. 8 .. 7 .. 6 .. 5 .. 4 .. 3 .. 2 .. 1 .. Liftoff!"
python
print " .. ".join(str(i) for i in range(10, 0, -1)), ".. liftoff!"
csharp
for (int i = 10; i > 0; i--)
{
Console.Write("{0} .. ", i);
}
Console.WriteLine("Liftoff!");
{
Console.Write("{0} .. ", i);
}
Console.WriteLine("Liftoff!");
erlang
fromto(10, 1, -1, fun (X) -> io:format("~B .. ", [X]) end), io:format("Liftoff!~n").
lists:foreach(fun (X) -> io:format("~B .. ", [X]) end, lists:seq(10, 1, -1)), io:format("Liftoff!~n").
clojure
(dotimes [i 10]
(print (str (- 10 i) " .. ")))
(println "Liftoff!")
(print (str (- 10 i) " .. ")))
(println "Liftoff!")
Read the contents of a file into a string
python
contents = open('myFile.txt', 'rt').read()
csharp
string contents = System.IO.File.ReadAllText("filename.txt");
erlang
Text = readfile("Solution607.erl"),
Text = readfile("Solution608.erl"),
clojure
(slurp "/tmp/foobar")
Process a file one line at a time
Open the source file to your solution and print each line in the file, prefixed by the line number, like:
1> First line of file
2> Second line of file
3> Third line of file
1> First line of file
2> Second line of file
3> Third line of file
python
for no, line in enumerate(open(__file__)):
print "{0}> {1}".format(no+1, line.rstrip())
print "{0}> {1}".format(no+1, line.rstrip())
csharp
int counter = 0;
// If the file is large, you would want to buffer this instead of reading everything at once
foreach (string line in System.IO.File.ReadAllLines("filename.txt"))
{
Console.WriteLine("{0}> {1}", ++counter, line);
}
// If the file is large, you would want to buffer this instead of reading everything at once
foreach (string line in System.IO.File.ReadAllLines("filename.txt"))
{
Console.WriteLine("{0}> {1}", ++counter, line);
}
erlang
Reader = fun (IODevice) -> io:get_line(IODevice, "") end,
Worker = fun (Line, N) -> io:format("~B> ~s", [N, Line]), N + 1 end,
while_not_eof("Solution609.erl", Reader, Worker, 1).
Worker = fun (Line, N) -> io:format("~B> ~s", [N, Line]), N + 1 end,
while_not_eof("Solution609.erl", Reader, Worker, 1).
Reader = fun (Filename) -> {ok, Contents} = file:read_file(Filename), Contents end,
Transformer = fun (Line, N) -> string:concat(string:concat(integer_to_list(N), "> "), Line) end,
Printer = fun (Line) -> io:format("~s~n", [Line]) end,
Lines = string:tokens(binary_to_list(Reader("Solution610.erl")), "\n"),
NewLines = lists:zipwith(Transformer, Lines, lists:seq(1, length(Lines))),
lists:foreach(Printer, NewLines).
Transformer = fun (Line, N) -> string:concat(string:concat(integer_to_list(N), "> "), Line) end,
Printer = fun (Line) -> io:format("~s~n", [Line]) end,
Lines = string:tokens(binary_to_list(Reader("Solution610.erl")), "\n"),
NewLines = lists:zipwith(Transformer, Lines, lists:seq(1, length(Lines))),
lists:foreach(Printer, NewLines).
clojure
(defn read-line-by-line [fn]
(reduce str (map (partial format "%d> %s\n")
(iterate inc 1)
(read-lines fn))))
(reduce str (map (partial format "%d> %s\n")
(iterate inc 1)
(read-lines fn))))
Write a string to a file
python
open('test.txt', 'wt').write('Hello World!')
csharp
System.IO.File.WriteAllText("filename.txt", "Some text to write to the file");
erlang
Line = "This line overwites file contents!\n",
{ok, IODevice} = file:open("test.txt", [write]), file:write(IODevice, Line), file:close(IODevice).
{ok, IODevice} = file:open("test.txt", [write]), file:write(IODevice, Line), file:close(IODevice).
clojure
(with-out-writer "output.txt" (println "Hello file!"))
Append to a file
python
open('test.txt', 'at').write('Hello World!\n')
csharp
System.IO.File.AppendAllText("filename.txt", "Some text to append to the file");
erlang
Line = "This line appended to file!\n",
{ok, IODevice} = file:open("test.txt", [append]), file:write(IODevice, Line), file:close(IODevice).
{ok, IODevice} = file:open("test.txt", [append]), file:write(IODevice, Line), file:close(IODevice).
clojure
(with-out-append-writer "output.txt" (println "This is appended to the file"))
Process each file in a directory
python
import os
results = (process(f) for f in os.listdir(".") if os.path.isfile(f))
results = (process(f) for f in os.listdir(".") if os.path.isfile(f))
csharp
foreach (string filename in System.IO.Directory.GetFiles(directory)) ProcessFile(filename);
erlang
% File basenames only - many tasks require absolute paths to work
lists:foreach(fun (FileOrDirPath) -> Worker(FileOrDirPath) end, file:list_dir(Directory)).
lists:foreach(fun (FileOrDirPath) -> Worker(FileOrDirPath) end, file:list_dir(Directory)).
% Absolute paths provided - will accomodate most tasks
lists:foreach(fun (FileOrDirPath) -> Worker(FileOrDirPath) end, list_dir_path(Directory)).
lists:foreach(fun (FileOrDirPath) -> Worker(FileOrDirPath) end, list_dir_path(Directory)).
clojure
; (defn process-file [f] "process one file" body...)
(map process-file (.listFiles (File. ".")))
(map process-file (.listFiles (File. ".")))
Process each file in a directory recursively
python
import os
results = (process(os.path.join(p, n)) for p,d,l in os.walk(".") for n in l)
results = (process(os.path.join(p, n)) for p,d,l in os.walk(".") for n in l)
erlang
filelib:fold_files(Directory, ".*", true, fun (FileOrDirPath, Acc) -> Worker(FileOrDirPath), Acc end, []).
process_dir(Directory, Worker).
clojure
; (defn process-file [f] "process one file" body...)
(map process-file (file-seq (File. ".")))
(map process-file (file-seq (File. ".")))
Parse a date and time from a string
Given the string
"2008-05-06 13:29", parse it as a date representing 6th March, 2008 1:29:00pm in the local time zone.
python
import time
time.strptime("2008-05-06 13:29", "%Y-%m-%d %H:%M")
time.strptime("2008-05-06 13:29", "%Y-%m-%d %H:%M")
csharp
DateTime parsedDate = DateTime.Parse("2008-05-06 13:29");
// Ideally, you would catch the potential FormatException or use DateTime.TryParse in production code.
// Ideally, you would catch the potential FormatException or use DateTime.TryParse in production code.
erlang
% AFAIK, no datetime-parsing library exists; 'parse_to_datetime' is a simplistic, problem-specific hack
LocalDateTime = erlang:universaltime_to_localtime(parse_to_datetime("2008-05-06 13:29:34")),
LocalDateTime = erlang:universaltime_to_localtime(parse_to_datetime("2008-05-06 13:29:34")),
clojure
(.. (SimpleDateFormat. "yyyy-MM-dd HH:mm")
(parse "2008-05-06 13:29"))
(parse "2008-05-06 13:29"))
Display information about a date
Display the day of month, day of year, month name and day name of the day 8 days from now.
python
from datetime import datetime, timedelta
eightDaysFromNow = datetime.now() + timedelta(days=8)
print eightDaysFromNow.strftime('%d') # day of month
print eightDaysFromNow.strftime('%j') # day of year
print eightDaysFromNow.strftime('%B') # month name FULL
print eightDaysFromNow.strftime('%A') # day of week name FULL
eightDaysFromNow = datetime.now() + timedelta(days=8)
print eightDaysFromNow.strftime('%d') # day of month
print eightDaysFromNow.strftime('%j') # day of year
print eightDaysFromNow.strftime('%B') # month name FULL
print eightDaysFromNow.strftime('%A') # day of week name FULL
csharp
DateTime date = DateTime.Today.AddDays(8);
Console.WriteLine("Day of month: " + date.Day);
Console.WriteLine("Day of year: " + date.DayOfYear);
Console.WriteLine("Month name: " + date.ToString("MMMM"));
Console.WriteLine("Day name: " + date.ToString("dddd"));
// The two ToString calls will use the current locale.
// To get localised month and day names, see http://msdn.microsoft.com/en-us/library/8tfzyc64.aspx
Console.WriteLine("Day of month: " + date.Day);
Console.WriteLine("Day of year: " + date.DayOfYear);
Console.WriteLine("Month name: " + date.ToString("MMMM"));
Console.WriteLine("Day name: " + date.ToString("dddd"));
// The two ToString calls will use the current locale.
// To get localised month and day names, see http://msdn.microsoft.com/en-us/library/8tfzyc64.aspx
clojure
(let [cal (Calendar/getInstance)]
(.add cal Calendar/DAY_OF_YEAR 8)
(println (.format (SimpleDateFormat. "d, D, MMMM, EEEE")
(.getTime cal))))
(.add cal Calendar/DAY_OF_YEAR 8)
(println (.format (SimpleDateFormat. "d, D, MMMM, EEEE")
(.getTime cal))))
Display a date in different locales
Display a language/locale friendly version of New Year's Day for 2009 for several languages/locales. E.g. for languages English, French, German, Italian, Dutch the output might be something like:
Thursday, January 1, 2009
jeudi 1 janvier 2009
giovedì 1 gennaio 2009
Donnerstag, 1. Januar 2009
donderdag 1 januari 2009
(Indicate in comments where possible if any language specific or operating system configuration needs to be in place.)
Thursday, January 1, 2009
jeudi 1 janvier 2009
giovedì 1 gennaio 2009
Donnerstag, 1. Januar 2009
donderdag 1 januari 2009
(Indicate in comments where possible if any language specific or operating system configuration needs to be in place.)
python
from datetime import datetime
from locale import setlocale, LC_TIME
now = datetime(2009, 1, 1)
locales = ('en_us', 'fr_fr', 'it_it', 'de_de', 'nl_nl')
for locale in locales:
setlocale(LC_TIME, locale)
print now.strftime('%A, %B %d %Y')
from locale import setlocale, LC_TIME
now = datetime(2009, 1, 1)
locales = ('en_us', 'fr_fr', 'it_it', 'de_de', 'nl_nl')
for locale in locales:
setlocale(LC_TIME, locale)
print now.strftime('%A, %B %d %Y')
csharp
using System.Globalization;
DateTime newYearsDay = new DateTime(2009, 1, 1);
CultureInfo[] locales = {
CultureInfo.CreateSpecificCulture("en-US"),
CultureInfo.CreateSpecificCulture("fr-FR"),
CultureInfo.CreateSpecificCulture("de-DE"),
CultureInfo.CreateSpecificCulture("it-IT"),
CultureInfo.CreateSpecificCulture("nl-NL")
};
foreach (CultureInfo locale in locales)
{
Console.WriteLine(newYearsDay.ToString("D", locale));
}
DateTime newYearsDay = new DateTime(2009, 1, 1);
CultureInfo[] locales = {
CultureInfo.CreateSpecificCulture("en-US"),
CultureInfo.CreateSpecificCulture("fr-FR"),
CultureInfo.CreateSpecificCulture("de-DE"),
CultureInfo.CreateSpecificCulture("it-IT"),
CultureInfo.CreateSpecificCulture("nl-NL")
};
foreach (CultureInfo locale in locales)
{
Console.WriteLine(newYearsDay.ToString("D", locale));
}
clojure
(let [time (.getTime (GregorianCalendar. 2009 Calendar/JANUARY 1))]
(doseq [locale ["en" "fr" "it" "de" "nl"]]
(println (.format (DateFormat/getDateInstance DateFormat/FULL
(Locale. locale))
time))))
(doseq [locale ["en" "fr" "it" "de" "nl"]]
(println (.format (DateFormat/getDateInstance DateFormat/FULL
(Locale. locale))
time))))
Display the current date and time
Create a Date object representing the current date and time. Print it out.
If you can also do this without creating a Date object you can show that too.
If you can also do this without creating a Date object you can show that too.
python
from datetime import datetime
print datetime.utcnow()
print datetime.utcnow()
csharp
// Creating a variable first:
DateTime now = DateTime.Now;
Console.WriteLine(now);
// Without creating a variable:
Console.WriteLine(DateTime.Now);
DateTime now = DateTime.Now;
Console.WriteLine(now);
// Without creating a variable:
Console.WriteLine(DateTime.Now);
erlang
io:format("~p~n", [calendar:local_time()])
clojure
(import 'java.util.Date)
(println (str (Date.)))
(println (str (Date.)))
Define a class
Declare a class named Greeter that takes a string on creation and greets using this string if you call the
"greet" method.
python
class Greeter(object):
""" Greet someone.
"""
def __init__(self, whom):
self._whom = whom
def greet(self):
print "Hello, %s!" % self._whom
Greeter("world").greet()
""" Greet someone.
"""
def __init__(self, whom):
self._whom = whom
def greet(self):
print "Hello, %s!" % self._whom
Greeter("world").greet()
csharp
using System;
class Greeter
{
private string name {get;set;}
public void Greet(){
Console.WriteLine("Hello, {0}",name);
}
public Greeter(string name){
this.name = name;
}
}
class Test
{
static void Main()
{
new Greeter("Dante").Greet();
}
}
class Greeter
{
private string name {get;set;}
public void Greet(){
Console.WriteLine("Hello, {0}",name);
}
public Greeter(string name){
this.name = name;
}
}
class Test
{
static void Main()
{
new Greeter("Dante").Greet();
}
}
erlang
Greeter = make_greeter("world!"),
Greeter(greet).
Greeter(greet).
clojure
(defprotocol IGreeter
(greet [this]))
(deftype Greeter [whom]
IGreeter
(greet [this]
(println (str "Hello, " whom))))
(greet (Greeter. "world"))
(greet [this]))
(deftype Greeter [whom]
IGreeter
(greet [this]
(println (str "Hello, " whom))))
(greet (Greeter. "world"))
(defn greeter [whom]
{:whom whom})
(defn greet [g]
(println (str "Hello, " (:whom g))))
(greet (greeter "world"))
{:whom whom})
(defn greet [g]
(println (str "Hello, " (:whom g))))
(greet (greeter "world"))
Instantiate object with mutable state
Reimplement the Greeter class so that the
For example, if the greetee is changed to
Hello, Tommy!
The getter would then be used to display the line:
I have just greeted Tommy.
'whom' property or data member remains private but is mutable, and is provided with getter and setter methods. Invoke the setter to change the greetee, invoke 'greet', then use the getter in displaying the line, "I have just greeted {whom}.".
For example, if the greetee is changed to
'Tommy' using the setter, the 'greet' method would display:
Hello, Tommy!
The getter would then be used to display the line:
I have just greeted Tommy.
python
class Greeter(object):
_whom = None
def __init__(self, whom):
self._whom = whom
@property
def whom(self):
return self._whom
@propset(whom)
def whom(self, value=None):
self._whom = value
def greet(self):
print 'Helo, %s!' % self._whom
greeter = Greeter('Winston')
greeter.greet()
greeter.whom = 'Tommy'
greeter.greet()
class Greeter(object):
_whom = None
def __init__(self, whom):
self._whom = whom
@property
def whom(self):
return self._whom
@propset(whom)
def whom(self, value=None):
self._whom = value
def greet(self):
print 'Helo, %s!' % self._whom
greeter = Greeter('Winston')
greeter.greet()
greeter.whom = 'Tommy'
greeter.greet()
# required for Python 2.5 or less
def propset(prop):
assert isinstance(prop, property)
def helper(func):
return property(prop.fget, func, prop.fdel, prop.__doc__)
return helper
class Greeter(object):
_whom = None
def __init__(self, whom):
self._whom = whom
@property
def whom(self):
return self._whom
@propset(whom)
def whom(self, value=None):
self._whom = value
def greet(self):
print 'Helo, %s!' % self._whom
greeter = Greeter('Winston')
greeter.greet()
greeter.whom = 'Tommy'
greeter.greet()
def propset(prop):
assert isinstance(prop, property)
def helper(func):
return property(prop.fget, func, prop.fdel, prop.__doc__)
return helper
class Greeter(object):
_whom = None
def __init__(self, whom):
self._whom = whom
@property
def whom(self):
return self._whom
@propset(whom)
def whom(self, value=None):
self._whom = value
def greet(self):
print 'Helo, %s!' % self._whom
greeter = Greeter('Winston')
greeter.greet()
greeter.whom = 'Tommy'
greeter.greet()
csharp
class Greeter
{
public string Name {get;set;}
public void Greet(){
Console.WriteLine("Hello, {0}",Name);
}
public Greeter(string name){
this.Name = name;
}
// Driver
public static void Main()
{
var g = new Greeter("Dante");
g.Name = "Tommy";
g.Greet();
Console.Write("I have just greated {0}", g.Name);
}
}
{
public string Name {get;set;}
public void Greet(){
Console.WriteLine("Hello, {0}",Name);
}
public Greeter(string name){
this.Name = name;
}
// Driver
public static void Main()
{
var g = new Greeter("Dante");
g.Name = "Tommy";
g.Greet();
Console.Write("I have just greated {0}", g.Name);
}
}
clojure
(defn greeter [whom]
(atom {:whom whom}))
(defn get-whom [g]
(:whom @g))
(defn set-whom [g whom]
(swap! g #(conj % {:whom whom})))
(defn greet [g]
(println (str "Hello, " (:whom @g) "!")))
; using the "class"
(let [g (greeter "world")]
(greet g)
(set-whom g "Tommy")
(greet g)
(println (str "I have just greeted " (get-whom g) ".")))
; or same effect without using any variables
(println (str "I have just greeted "
(get-whom (doto (greeter "world")
(greet)
(set-whom "Tommy")
(greet)))
"."))
(atom {:whom whom}))
(defn get-whom [g]
(:whom @g))
(defn set-whom [g whom]
(swap! g #(conj % {:whom whom})))
(defn greet [g]
(println (str "Hello, " (:whom @g) "!")))
; using the "class"
(let [g (greeter "world")]
(greet g)
(set-whom g "Tommy")
(greet g)
(println (str "I have just greeted " (get-whom g) ".")))
; or same effect without using any variables
(println (str "I have just greeted "
(get-whom (doto (greeter "world")
(greet)
(set-whom "Tommy")
(greet)))
"."))
Implement Inheritance Heirarchy
Implement a Shape abstract class which will form the base of an inheritance hierarchy that models 2D geometric shapes. It will have:
* A non-mutable
* A
* A
* A non-mutable
'name' property or data member set by derived or descendant classes at construction time
* A
'area' method intended to be overridden by derived or descendant classes ( double precision floating point return value)
* A
'print' method (also for overriding) will display the shape's name, area, and all shape-specific values
Two derived or descendant classes will be created:
* Circle -> Constructor requires a 'radius' argument, and a 'circumference' method to be implemented
* Rectangle -> Constructor requires 'length' and 'breadth' arguments, and a 'perimeter' method to be implemented
Instantiate an object of each class, and invoke each objects 'print' method to show relevant details.
python
#Start with the import statements.
import math # necessary to get the value of pi
class Shape(object):
"""Shape Class"""
def __init__(self):
"""Constructor method"""
pass #Do nothing here
def area(self):
"""The area method"""
pass #Do nothing here
def print_(self):
"""
The print method. Note the trailing underscore - this is because
there is a reserved statement called 'print' in python 2.x. The
trailing underscore is the accepted method of re-using names without
rebinding them
"""
print 'The name is: %s' % self.name #Print the only property we currently have
def _getName(self):
"""The getter method for the 'name' property.
Note that getter methods are generally discouraged in python"""
return self._name
_name = None # The leading underscore gives a weak non-public value
# to a variable. Two leading underscores will mangle its
# name at runtime, to make it more difficult to access.
# Note there is no real 'private' variable type in python.
name = property(_getName, doc='The name of this object')
# property statements work like: property(fget=None, fset=None, fdel=None, doc=None)
class Circle(Shape):
"""Circle Class - a sub class of shape"""
def __init__(self, radius, name='Circle'):
"""Constructor method again"""
Shape.__init__(self) # init the super class
self.radius = radius # Store the radius
self._setCircumference()# Function call
self._name = name
def _setCircumference(self):
self.circumference = 2*math.pi*self.radius
def area(self):
'''Return the area of this circle'''
tmpAera = math.pi * self.radius**2
return tmpAera
def print_(self):
'''The print method'''
super(Circle, self).print_() # This calls the print_ method in
# the super classes of Circle, in
# this case Shape
print 'The radius is: %f' % self.radius
print 'The circumference is %f' % self.circumference
print 'The area is: %f' % self.area()
class Rectangle(Shape):
"""The Rectangle Class"""
def __init__(self, length, breadth, name='Rectangle'):
Shape.__init__(self)
self._name = name
self.length = length
self.breadth = breadth
self.perimeter()
def area(self):
return self.breadth*self.length
def perimeter(self):
self._perimeter = self.breadth*2+self.length*2
return self._perimeter # You have a method return a value and still
# safely call it without handling the return
# value. This would be collected by garbage
# collection.
def print_(self):
super(Rectangle, self).print_()
print 'The length is %f and the breadth is %f' %(self.length, self.breadth)
print 'The perimeter is: %f' %self._perimeter
print 'The area is: %f' % self.area()
if __name__ == '__main__':
rectangle = Rectangle(5,3)
circle = Circle(5, name='Round and Round')
rectangle.print_()
circle.print_()
import math # necessary to get the value of pi
class Shape(object):
"""Shape Class"""
def __init__(self):
"""Constructor method"""
pass #Do nothing here
def area(self):
"""The area method"""
pass #Do nothing here
def print_(self):
"""
The print method. Note the trailing underscore - this is because
there is a reserved statement called 'print' in python 2.x. The
trailing underscore is the accepted method of re-using names without
rebinding them
"""
print 'The name is: %s' % self.name #Print the only property we currently have
def _getName(self):
"""The getter method for the 'name' property.
Note that getter methods are generally discouraged in python"""
return self._name
_name = None # The leading underscore gives a weak non-public value
# to a variable. Two leading underscores will mangle its
# name at runtime, to make it more difficult to access.
# Note there is no real 'private' variable type in python.
name = property(_getName, doc='The name of this object')
# property statements work like: property(fget=None, fset=None, fdel=None, doc=None)
class Circle(Shape):
"""Circle Class - a sub class of shape"""
def __init__(self, radius, name='Circle'):
"""Constructor method again"""
Shape.__init__(self) # init the super class
self.radius = radius # Store the radius
self._setCircumference()# Function call
self._name = name
def _setCircumference(self):
self.circumference = 2*math.pi*self.radius
def area(self):
'''Return the area of this circle'''
tmpAera = math.pi * self.radius**2
return tmpAera
def print_(self):
'''The print method'''
super(Circle, self).print_() # This calls the print_ method in
# the super classes of Circle, in
# this case Shape
print 'The radius is: %f' % self.radius
print 'The circumference is %f' % self.circumference
print 'The area is: %f' % self.area()
class Rectangle(Shape):
"""The Rectangle Class"""
def __init__(self, length, breadth, name='Rectangle'):
Shape.__init__(self)
self._name = name
self.length = length
self.breadth = breadth
self.perimeter()
def area(self):
return self.breadth*self.length
def perimeter(self):
self._perimeter = self.breadth*2+self.length*2
return self._perimeter # You have a method return a value and still
# safely call it without handling the return
# value. This would be collected by garbage
# collection.
def print_(self):
super(Rectangle, self).print_()
print 'The length is %f and the breadth is %f' %(self.length, self.breadth)
print 'The perimeter is: %f' %self._perimeter
print 'The area is: %f' % self.area()
if __name__ == '__main__':
rectangle = Rectangle(5,3)
circle = Circle(5, name='Round and Round')
rectangle.print_()
circle.print_()
csharp
// While abstract classes do exist in C#, it is most common to use
// an interface in this type of situation.
// It is a common idiom to prefix interface names with an I
public interface IShape {
string Name { get; }
double Area { get; }
void Print();
}
public class Circle : IShape {
private double Radius { get; set; }
public Circle(double radius) {
Name = "Circle";
Radius = radius;
}
public string Name { get; private set; }
public double Area {
get {
return Math.PI * Radius * Radius;
}
}
public double Circumference {
get {
return Math.PI * (Radius + Radius);
}
}
public void Print() {
Console.WriteLine( " Name: {0}\n Area: {1}\n Circumference: {2}\n Radius: {3}",
this.Name,
this.Area,
this.Circumference,
this.Radius
);
}
}
public class Rectangle : IShape {
private double Length { get; set; }
private double Breadth { get; set; }
public Rectangle(double length, double breadth) {
Name = "Rectangle";
Length = length;
Breadth = breadth;
}
public string Name { get; private set; }
public double Area {
get {
return Length * Breadth;
}
}
public double Perimeter {
get {
return (Length * 2) + (Breadth * 2 );
}
}
public void Print() {
Console.WriteLine( " Name: {0}\n Area: {1}\n Perimeter: {2}\n Length: {3}\n Breadth: {4}",
this.Name,
this.Area,
this.Perimeter,
this.Length,
this.Breadth
);
}
}
// Driver
public class InheritanceHeirarchy {
public static void _Main() {
var c = new Circle(2.1);
c.Print();
Console.WriteLine();
var r = new Rectangle(2.2, 3.3);
r.Print();
}
}
// an interface in this type of situation.
// It is a common idiom to prefix interface names with an I
public interface IShape {
string Name { get; }
double Area { get; }
void Print();
}
public class Circle : IShape {
private double Radius { get; set; }
public Circle(double radius) {
Name = "Circle";
Radius = radius;
}
public string Name { get; private set; }
public double Area {
get {
return Math.PI * Radius * Radius;
}
}
public double Circumference {
get {
return Math.PI * (Radius + Radius);
}
}
public void Print() {
Console.WriteLine( " Name: {0}\n Area: {1}\n Circumference: {2}\n Radius: {3}",
this.Name,
this.Area,
this.Circumference,
this.Radius
);
}
}
public class Rectangle : IShape {
private double Length { get; set; }
private double Breadth { get; set; }
public Rectangle(double length, double breadth) {
Name = "Rectangle";
Length = length;
Breadth = breadth;
}
public string Name { get; private set; }
public double Area {
get {
return Length * Breadth;
}
}
public double Perimeter {
get {
return (Length * 2) + (Breadth * 2 );
}
}
public void Print() {
Console.WriteLine( " Name: {0}\n Area: {1}\n Perimeter: {2}\n Length: {3}\n Breadth: {4}",
this.Name,
this.Area,
this.Perimeter,
this.Length,
this.Breadth
);
}
}
// Driver
public class InheritanceHeirarchy {
public static void _Main() {
var c = new Circle(2.1);
c.Print();
Console.WriteLine();
var r = new Rectangle(2.2, 3.3);
r.Print();
}
}
clojure
(defmulti area :Shape)
(defmulti print :Shape)
; Circle methods
(defn circle [r]
{:Shape :Circle
:name "Circle"
:radius r})
(defn circumference [c]
(* 2 Math/PI (:radius c)))
(defmethod area :Circle [c]
(* Math/PI (:radius c) (:radius c)))
(defmethod print :Circle [c]
(println (format "I am a %s with ->" (:name c)))
(println (format "Radius: %.2f" (:radius c)))
(println (format "Area: %.2f" (area c)))
(println (format "Circumference: %.2f" (circumference c))))
; Rectangle methods
(defn rectangle [l b]
{:Shape :Rectangle
:name "Rectangle"
:length l
:breadth b})
(defn perimeter [r]
(+ (* 2 (:length r)) (* 2 (:breadth r))))
(defmethod area :Rectangle [r]
(* (:length r) (:breadth r)))
(defmethod print :Rectangle [r]
(println (format "I am a %s with ->" (:name r)))
(println (format "Length, Width: %.2f, %.2f" (:length r) (:breadth r)))
(println (format "Area: %.2f" (area r)))
(println (format "Perimeter: %.2f" (perimeter r))))
; usage of the "classes"
(let [shapes (list (circle 4.2) (rectangle 2.7 3.1) (rectangle 6.2 2.6) (circle 17.3))]
(doseq [shape shapes]
(print shape)))
(defmulti print :Shape)
; Circle methods
(defn circle [r]
{:Shape :Circle
:name "Circle"
:radius r})
(defn circumference [c]
(* 2 Math/PI (:radius c)))
(defmethod area :Circle [c]
(* Math/PI (:radius c) (:radius c)))
(defmethod print :Circle [c]
(println (format "I am a %s with ->" (:name c)))
(println (format "Radius: %.2f" (:radius c)))
(println (format "Area: %.2f" (area c)))
(println (format "Circumference: %.2f" (circumference c))))
; Rectangle methods
(defn rectangle [l b]
{:Shape :Rectangle
:name "Rectangle"
:length l
:breadth b})
(defn perimeter [r]
(+ (* 2 (:length r)) (* 2 (:breadth r))))
(defmethod area :Rectangle [r]
(* (:length r) (:breadth r)))
(defmethod print :Rectangle [r]
(println (format "I am a %s with ->" (:name r)))
(println (format "Length, Width: %.2f, %.2f" (:length r) (:breadth r)))
(println (format "Area: %.2f" (area r)))
(println (format "Perimeter: %.2f" (perimeter r))))
; usage of the "classes"
(let [shapes (list (circle 4.2) (rectangle 2.7 3.1) (rectangle 6.2 2.6) (circle 17.3))]
(doseq [shape shapes]
(print shape)))
Implement and use an Interface
Create a Serializable interface consisting of
* Accept a stream or handle or descriptor argument for the source or destination
* Save to destination or restore from source the properties or data members of the implementing class (restrict yourself to the primitive types
Next, create a Person class which has
'save' and 'restore' methods, each of which:
* Accept a stream or handle or descriptor argument for the source or destination
* Save to destination or restore from source the properties or data members of the implementing class (restrict yourself to the primitive types
'int' and 'string')
Next, create a Person class which has
'name' and 'age' properties or data members and implements this interface. Instantiate a Person object, save it to a serial stream, and instantiate a new Person object by restoring it from the serial stream.
python
import pickle
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return "Name: {name}, age: {age}".format(name=self.name, age=self.age)
person = Person("Gaylord Focker", 21)
with open("person.pickle", "wb") as outstream:
pickle.dump(person, outstream)
with open("person.pickle", "rb") as instream:
deserialized_person = pickle.load(instream)
print(deserialized_person)
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return "Name: {name}, age: {age}".format(name=self.name, age=self.age)
person = Person("Gaylord Focker", 21)
with open("person.pickle", "wb") as outstream:
pickle.dump(person, outstream)
with open("person.pickle", "rb") as instream:
deserialized_person = pickle.load(instream)
print(deserialized_person)
clojure
(defn person [name age]
{:name name :age age})
(defn show [p]
(println (format "Name=%s Age=%d" (:name p) (:age p))))
(defn save [p filename]
(with-out-writer filename (pr p)))
(defn restore [filename]
(read (PushbackReader. (reader filename))))
(let [p (person "Ken" 38)]
(show p)
(save p *person-fn*))
(let [ser-p (restore *person-fn*)]
(show ser-p))
{:name name :age age})
(defn show [p]
(println (format "Name=%s Age=%d" (:name p) (:age p))))
(defn save [p filename]
(with-out-writer filename (pr p)))
(defn restore [filename]
(read (PushbackReader. (reader filename))))
(let [p (person "Ken" 38)]
(show p)
(save p *person-fn*))
(let [ser-p (restore *person-fn*)]
(show ser-p))
Check your language appears on the langref.org site
Your language name should appear within the HTML found at the http:
//langreg.org main page.
python
from urllib import urlopen
print urlopen('http://langref.org').read().find('python') >= 0 and 'found' or 'not found'
print urlopen('http://langref.org').read().find('python') >= 0 and 'found' or 'not found'
erlang
URL = "http://langref.org/", Language = "erlang", Regexp = ".*" ++ URL ++ Language ++ ".*",
case http:request(URL) of
{ok, {_, _, Body}} ->
case regexp:first_match(Body, Regexp) of
{match, _, _} -> io:format("Language ~s exists @ ~s~n", [Language, URL]);
_ -> false
end;
{error, ErrorInfo} -> throw("Error: " ++ http:format_error(ErrorInfo))
end,
case http:request(URL) of
{ok, {_, _, Body}} ->
case regexp:first_match(Body, Regexp) of
{match, _, _} -> io:format("Language ~s exists @ ~s~n", [Language, URL]);
_ -> false
end;
{error, ErrorInfo} -> throw("Error: " ++ http:format_error(ErrorInfo))
end,
clojure
(def *url* "http://langref.org/")
(def *lang* "clojure")
(with-open [ stream (.openStream (URL. *url*)) ]
(let [ body (str (line-seq (BufferedReader. (InputStreamReader. stream)))) ]
(str "Language " *lang* " does "
(if-not (re-matches (re-pattern (str ".*" *url* *lang* ".*")) body) "not ")
"exist")))
(def *lang* "clojure")
(with-open [ stream (.openStream (URL. *url*)) ]
(let [ body (str (line-seq (BufferedReader. (InputStreamReader. stream)))) ]
(str "Language " *lang* " does "
(if-not (re-matches (re-pattern (str ".*" *url* *lang* ".*")) body) "not ")
"exist")))
Send an email
Use library functions, classes or objects to create a short email addressed to your own email address. The subject should be,
"Greetings from langref.org", and the user should be prompted for the message body, and whether to cancel or proceed with sending the email.
python
import smtplib
import locale
from email.mime.text import MIMEText
encoding = locale.getpreferredencoding()
def main():
smtp_servername = "smtp.example.com"
from_addr = "ernie@example.com"
to_addr = "cookie.monster@mailinator.com"
body = raw_input("Enter the email message ")
if not raw_input("Send email? y/N ") in ["y", "Y"]:
print "aborting"
return
message = MIMEText(body, _charset=encoding)
message["From"] = from_addr
message["To"] = to_addr
message["Subject"] = "Greetings from langref.org"
server = smtplib.SMTP(smtp_servername)
server.sendmail(from_addr, to_addr, message.as_string())
if __name__ == "__main__":
main()
import locale
from email.mime.text import MIMEText
encoding = locale.getpreferredencoding()
def main():
smtp_servername = "smtp.example.com"
from_addr = "ernie@example.com"
to_addr = "cookie.monster@mailinator.com"
body = raw_input("Enter the email message ")
if not raw_input("Send email? y/N ") in ["y", "Y"]:
print "aborting"
return
message = MIMEText(body, _charset=encoding)
message["From"] = from_addr
message["To"] = to_addr
message["Subject"] = "Greetings from langref.org"
server = smtplib.SMTP(smtp_servername)
server.sendmail(from_addr, to_addr, message.as_string())
if __name__ == "__main__":
main()
Process an XML document
Given the XML Document:
<shopping>
<item name=
<item name=
</shopping>
Print out the total cost of the items, e.g. $14.50
<shopping>
<item name=
"bread" quantity="3" price="2.50"/>
<item name=
"milk" quantity="2" price="3.50"/>
</shopping>
Print out the total cost of the items, e.g. $14.50
python
from xml.dom.minidom import parseString
document = parseString(
"""<shopping>
<item name="bread" quantity="3" price="2.50"/>
<item name="milk" quantity="2" price="3.50"/>
</shopping>""").documentElement
total = sum([float(item.getAttribute('price')) *
int(item.getAttribute('quantity'))
for item in document.getElementsByTagName('item')])
print '$%.2f' % total
document = parseString(
"""<shopping>
<item name="bread" quantity="3" price="2.50"/>
<item name="milk" quantity="2" price="3.50"/>
</shopping>""").documentElement
total = sum([float(item.getAttribute('price')) *
int(item.getAttribute('quantity'))
for item in document.getElementsByTagName('item')])
print '$%.2f' % total
csharp
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
doc.LoadXml(
@"<shopping>
<item name='bread' quantity='3' price='2.50'/>
<item name='milk' quantity='2' price='3.50'/>
</shopping>");
string decimalSeparator= System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator;
double sum=0;
foreach(System.Xml.XmlNode nodo in doc.SelectNodes("/shopping/item")){
sum += int.Parse(nodo.Attributes["quantity"].InnerText) * double.Parse(nodo.Attributes["price"].InnerText.Replace(".",decimalSeparator));
}
Console.WriteLine("{0:#.00}",sum);
doc.LoadXml(
@"<shopping>
<item name='bread' quantity='3' price='2.50'/>
<item name='milk' quantity='2' price='3.50'/>
</shopping>");
string decimalSeparator= System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator;
double sum=0;
foreach(System.Xml.XmlNode nodo in doc.SelectNodes("/shopping/item")){
sum += int.Parse(nodo.Attributes["quantity"].InnerText) * double.Parse(nodo.Attributes["price"].InnerText.Replace(".",decimalSeparator));
}
Console.WriteLine("{0:#.00}",sum);
erlang
-include_lib("xmerl/include/xmerl.hrl").
-export([get_total/1]).
get_total(ShoppingList) ->
{XmlElt, _} = xmerl_scan:string(ShoppingList),
Items = xmerl_xpath:string("/shopping/item", XmlElt),
Total = lists:foldl(fun(Item, Tot) ->
[#xmlAttribute{value = PriceString}] = xmerl_xpath:string("/item/@price", Item),
{Price, _} = string:to_float(PriceString),
[#xmlAttribute{value = QuantityString}] = xmerl_xpath:string("/item/@quantity", Item),
{Quantity, _} = string:to_integer(QuantityString),
Tot + Price*Quantity
end,
0, Items),
io:format("$~.2f~n", [Total]).
-export([get_total/1]).
get_total(ShoppingList) ->
{XmlElt, _} = xmerl_scan:string(ShoppingList),
Items = xmerl_xpath:string("/shopping/item", XmlElt),
Total = lists:foldl(fun(Item, Tot) ->
[#xmlAttribute{value = PriceString}] = xmerl_xpath:string("/item/@price", Item),
{Price, _} = string:to_float(PriceString),
[#xmlAttribute{value = QuantityString}] = xmerl_xpath:string("/item/@quantity", Item),
{Quantity, _} = string:to_integer(QuantityString),
Tot + Price*Quantity
end,
0, Items),
io:format("$~.2f~n", [Total]).
clojure
(println (format "Total cost of items are $%#.2f"
(->> (xml-seq (parse *xml-input-stream*))
(filter #(= :item (:tag %))) ; Remove all but the item tags
(map :attrs) ; Keep the attributes
(map (fn [e] (str "(* " (:quantity e) " " (:price e) ")"))) ; Get the total price as a sexp
(map read-string) ; "(* quantity price)" -> (* quantity price)
(map eval) ; (* quantity price) -> quantity*price
(apply +)))) ; Sum all elements
(->> (xml-seq (parse *xml-input-stream*))
(filter #(= :item (:tag %))) ; Remove all but the item tags
(map :attrs) ; Keep the attributes
(map (fn [e] (str "(* " (:quantity e) " " (:price e) ")"))) ; Get the total price as a sexp
(map read-string) ; "(* quantity price)" -> (* quantity price)
(map eval) ; (* quantity price) -> quantity*price
(apply +)))) ; Sum all elements
create some XML programmatically
Given the following CSV:
bread,3,2.50
milk,2,3.50
Produce the equivalent information in XML, e.g.:
<shopping>
<item name=
<item name=
</shopping>
bread,3,2.50
milk,2,3.50
Produce the equivalent information in XML, e.g.:
<shopping>
<item name=
"bread" quantity="3" price="2.50" />
<item name=
"milk" quantity="2" price="3.50" />
</shopping>
python
from xml.dom import minidom
csv = """bread,3,2.50
milk,2,3.50"""
doc = minidom.Document()
shopping = doc.createElement("shopping")
for line in csv.split("\n"):
name, quantity, price = line.split(",")
el = doc.createElement("item")
el.setAttribute("name", name)
el.setAttribute("quantity", quantity)
el.setAttribute("price", price)
shopping.appendChild(el)
print shopping.toprettyxml()
csv = """bread,3,2.50
milk,2,3.50"""
doc = minidom.Document()
shopping = doc.createElement("shopping")
for line in csv.split("\n"):
name, quantity, price = line.split(",")
el = doc.createElement("item")
el.setAttribute("name", name)
el.setAttribute("quantity", quantity)
el.setAttribute("price", price)
shopping.appendChild(el)
print shopping.toprettyxml()
from xml.etree.ElementTree import Element, SubElement, tostring
csv = """bread,3,2.50
milk,2,3.50"""
root = Element('shopping')
for line in csv.split("\n"):
name, quantity, price = line.split(",")
SubElement(root,'item', {'name' : name,
'quantity' : quantity,
'price' : price })
print tostring(root)
csv = """bread,3,2.50
milk,2,3.50"""
root = Element('shopping')
for line in csv.split("\n"):
name, quantity, price = line.split(",")
SubElement(root,'item', {'name' : name,
'quantity' : quantity,
'price' : price })
print tostring(root)
csharp
string cvs ="bread,3,2.50\nmilk,2,3.50";
IList<string> rows = cvs.Split('\n');
System.Text.StringBuilder sb = new System.Text.StringBuilder("<shopping>");
foreach(string row in rows){
IList<string> data = row.Split(',');
sb.AppendFormat("<item name='{0}' quantity='{1}' price='{2}' />",data[0],data[1],data[2]);
}
sb.Append("</shopping>");
IList<string> rows = cvs.Split('\n');
System.Text.StringBuilder sb = new System.Text.StringBuilder("<shopping>");
foreach(string row in rows){
IList<string> data = row.Split(',');
sb.AppendFormat("<item name='{0}' quantity='{1}' price='{2}' />",data[0],data[1],data[2]);
}
sb.Append("</shopping>");
erlang
to_xml(ShoppingList) ->
Items = lists:map(fun(L) ->
[Name, Quantity, Price] = string:tokens(L, ","),
{item, [{name, Name}, {quantity, Quantity}, {price, Price}], []}
end, string:tokens(ShoppingList, "\n")),
xmerl:export_simple([{shopping, [], Items}], xmerl_xml).
Items = lists:map(fun(L) ->
[Name, Quantity, Price] = string:tokens(L, ","),
{item, [{name, Name}, {quantity, Quantity}, {price, Price}], []}
end, string:tokens(ShoppingList, "\n")),
xmerl:export_simple([{shopping, [], Items}], xmerl_xml).
clojure
(defn list->xml-item [lst]
(let [[name quantity price] (map str lst)]
{:tag :item
:attrs {:name name
:quantity quantity
:price price}}))
(defn cvs->xml [r]
(->> (map #(read-string (str "(" % ")")) (line-seq r))
(map list->xml-item)
(assoc {:tag :shopping} :content)
(emit)
(with-out-str)))
(println (cvs->xml *cvs-reader*))
(let [[name quantity price] (map str lst)]
{:tag :item
:attrs {:name name
:quantity quantity
:price price}}))
(defn cvs->xml [r]
(->> (map #(read-string (str "(" % ")")) (line-seq r))
(map list->xml-item)
(assoc {:tag :shopping} :content)
(emit)
(with-out-str)))
(println (cvs->xml *cvs-reader*))
Find all Pythagorean triangles with length or height less than or equal to 20
Pythagorean triangles are right angle triangles whose sides comply with the following equation:
a * a + b * b = c * c
where c represents the length of the hypotenuse, and a and b represent the lengths of the other two sides. Find all such triangles where a, b and c are non-zero integers with a and b less than or equal to 20. Sort your results by the size of the hypotenuse. The expected answer is:
a * a + b * b = c * c
where c represents the length of the hypotenuse, and a and b represent the lengths of the other two sides. Find all such triangles where a, b and c are non-zero integers with a and b less than or equal to 20. Sort your results by the size of the hypotenuse. The expected answer is:
[3, 4, 5]
[6, 8, 10]
[5, 12, 13]
[9, 12, 15]
[8, 15, 17]
[12, 16, 20]
[15, 20, 25]
python
from math import sqrt
a = 1
ret = []
while a <= 20:
b = 1
while b <= 20:
c = sqrt((a**2)+(b**2))
if int(c) == c and sorted([a,b,int(c)]) not in ret:
ret.append(sorted([a,b,int(c)]))
b +=1
a +=1
print ret
or if you wanna get snarky..
print sorted(set([tuple(sorted((a,b,int(sqrt((a**2)+(b**2)))))) for a in xrange(1,21) for \
b in xrange(1,21) if int(sqrt((a**2)+(b**2))) == sqrt((a**2)+(b**2))]))
a = 1
ret = []
while a <= 20:
b = 1
while b <= 20:
c = sqrt((a**2)+(b**2))
if int(c) == c and sorted([a,b,int(c)]) not in ret:
ret.append(sorted([a,b,int(c)]))
b +=1
a +=1
print ret
or if you wanna get snarky..
print sorted(set([tuple(sorted((a,b,int(sqrt((a**2)+(b**2)))))) for a in xrange(1,21) for \
b in xrange(1,21) if int(sqrt((a**2)+(b**2))) == sqrt((a**2)+(b**2))]))
erlang
find_all_pythagorean_triangles(L) ->
lists:sort(fun({_, _, H1}, {_, _, H2}) -> H1 =< H2 end,
[ { X, Y, Z } ||
X <- lists:seq(1,L),
Y <- lists:seq(1,L),
Z <- lists:seq(1,2*L),
X*X + Y*Y =:= Z*Z,
Y > X,
Z > Y
]).
main(_) ->
List = find_all_pythagorean_triangles(20).
lists:sort(fun({_, _, H1}, {_, _, H2}) -> H1 =< H2 end,
[ { X, Y, Z } ||
X <- lists:seq(1,L),
Y <- lists:seq(1,L),
Z <- lists:seq(1,2*L),
X*X + Y*Y =:= Z*Z,
Y > X,
Z > Y
]).
main(_) ->
List = find_all_pythagorean_triangles(20).
clojure
(defn pythagorean [a b c] (= (+ (* a a) (* b b)) (* c c)))
(defn intsqrt [cc]
(. (. Math sqrt cc) intValue)
)
(defn triples [maxSize]
(filter not-empty
(for [a (range 1 20) b (range a 20)]
(let [c (intsqrt (+ (* a a) (* b b)))]
(if (pythagorean a b c)
[a b c]
()
)))))
(triples 20)
; -> ([3 4 5] [5 12 13] [6 8 10] [8 15 17] [9 12 15] [12 16 20] [15 20 25])
(defn sortByHypotenuse [triples]
(sort-by #(first (rest (rest %))) triples)
)
(sortByHypotenuse (triples 20))
; -> ([3 4 5] [6 8 10] [5 12 13] [9 12 15] [8 15 17] [12 16 20] [15 20 25])
(defn intsqrt [cc]
(. (. Math sqrt cc) intValue)
)
(defn triples [maxSize]
(filter not-empty
(for [a (range 1 20) b (range a 20)]
(let [c (intsqrt (+ (* a a) (* b b)))]
(if (pythagorean a b c)
[a b c]
()
)))))
(triples 20)
; -> ([3 4 5] [5 12 13] [6 8 10] [8 15 17] [9 12 15] [12 16 20] [15 20 25])
(defn sortByHypotenuse [triples]
(sort-by #(first (rest (rest %))) triples)
)
(sortByHypotenuse (triples 20))
; -> ([3 4 5] [6 8 10] [5 12 13] [9 12 15] [8 15 17] [12 16 20] [15 20 25])
(doseq [pt (sort-by #(% 2)
(for [a (range 1 21)
b (range a 21)
:let [aa+bb (+ (* a a) (* b b))
c (Math/round (Math/sqrt aa+bb))]
:when (= aa+bb (* c c))]
[a b c]))]
(println pt))
(for [a (range 1 21)
b (range a 21)
:let [aa+bb (+ (* a a) (* b b))
c (Math/round (Math/sqrt aa+bb))]
:when (= aa+bb (* c c))]
[a b c]))]
(println pt))
Greatest Common Divisor
Find the largest positive integer that divides two given numbers without a remainder. For example, the GCD of 8 and 12 is 4.
python
def gcd_recursive(i, j):
if min(i, j) == 0:
return max(i, j)
else:
return gcd_recursive(min(i, j), abs(i - j))
def gcd_iterative(i, j):
while min(i, j) != 0:
i, j = min(i, j), abs(i - j)
return max(i, j)
if __name__ == "__main__":
print gcd_recursive(8, 12)
print gcd_iterative(8, 12)
if min(i, j) == 0:
return max(i, j)
else:
return gcd_recursive(min(i, j), abs(i - j))
def gcd_iterative(i, j):
while min(i, j) != 0:
i, j = min(i, j), abs(i - j)
return max(i, j)
if __name__ == "__main__":
print gcd_recursive(8, 12)
print gcd_iterative(8, 12)
from fractions import gcd
print gcd(8, 12)
print gcd(8, 12)
csharp
public static int gcd(int a, int b)
{
if (b == 0)
return a;
else
return gcd(b, a % b);
}
{
if (b == 0)
return a;
else
return gcd(b, a % b);
}
erlang
-module(gcd).
-export([gcd/2]).
gcd(A, 0) -> A;
gcd(A, B) -> gcd(B, A rem B).
-export([gcd/2]).
gcd(A, 0) -> A;
gcd(A, B) -> gcd(B, A rem B).
clojure
(defn gcd [a b]
(if (zero? b)
a
(recur b (mod b a))))
(if (zero? b)
a
(recur b (mod b a))))
produces a copy of its own source code
In computing, a quine is a computer program which produces a copy of its own source code as its only output.
python
# adapted from a Quine by Sean B. Palmer
print (lambda s='print (lambda s=%r: (s %% s))()': (s % s))()
print (lambda s='print (lambda s=%r: (s %% s))()': (s % s))()
x='x=%r;print(x%%x)';print(x%x)
clojure
(def s"(def s%s)(printf s(pr-str s))")(printf s(pr-str s))
Subdivide A Problem To A Pool Of Workers (No Shared Data)
Take a hard to compute problem and split it up between multiple worker threads. In your solution, try to fully utilize available cores or processors. (I'm looking at you, Python!)
Note: In this question, there should be no need for shared state between worker threads while the problem is being solved. Only after every thread completes computation are the answers recombined into a single output.
Example:
-Input-
(In python syntax)
In other words, a list of random strings.
-Output-
(In python syntax)
In other words, all possible permutations of each input string are computed.
Note: In this question, there should be no need for shared state between worker threads while the problem is being solved. Only after every thread completes computation are the answers recombined into a single output.
Example:
-Input-
(In python syntax)
["ab", "we", "tfe", "aoj"]
In other words, a list of random strings.
-Output-
(In python syntax)
[ ["ab", "ba", "aa", "bb", "a", "b"], ["we", "ew", "ww", "ee", "w", "e"], ...
In other words, all possible permutations of each input string are computed.
python
import multiprocessing
import itertools
task_input = ["ab", "we", "tfe", "aoj"]
def all_subperms(s):
return set(reduce(
list.__add__,
([''.join(p) for p in itertools.product(s, repeat=r) if p]
for r in xrange(len(s) + 1))))
p = multiprocessing.Pool(len(task_input))
task_output = p.map(all_subperms, task_input)
print map(list, task_output)
import itertools
task_input = ["ab", "we", "tfe", "aoj"]
def all_subperms(s):
return set(reduce(
list.__add__,
([''.join(p) for p in itertools.product(s, repeat=r) if p]
for r in xrange(len(s) + 1))))
p = multiprocessing.Pool(len(task_input))
task_output = p.map(all_subperms, task_input)
print map(list, task_output)
clojure
(defn perm-chars [l]
"Returns a list of all possible permutations of strings with the
same size as the input string. This function will return duplicates
if the same character occurs multiple time in the string.
Ex: ab -> (aa ab ba ab)"
(if (string? l)
(recur (repeat (count l) l))
(let [s (first l)
r (rest l)]
(if (empty? r)
(map identity s)
(->> s
(map (fn [c] (map #(str c %) (perm-chars r))))
(flatten))))))
(defn perm-sz [s]
"Returns a list of all possible permutations of the input
string. May return duplicats.
Ex: ab -> (aa ab ba bb a b a b)"
(if-not (empty? s)
(let [r (perm-chars s)]
(if (= (count s) 1)
r
(->> r
(map #(perm-sz (apply str (rest %))))
(flatten)
(lazy-cat r))))))
(defn perm [s]
"Returns a list of all possible permutations of the input
string. The list of string is sorted and does not contain
duplicates.
Ex: ab -> (a aa ab b ba bb)"
(->> (reduce (fn [s e] (conj s e)) #{} (perm-sz s))
(map str)
(sort)))
(println (pmap perm ["ab" "we" "tfe" "aoj"]))
"Returns a list of all possible permutations of strings with the
same size as the input string. This function will return duplicates
if the same character occurs multiple time in the string.
Ex: ab -> (aa ab ba ab)"
(if (string? l)
(recur (repeat (count l) l))
(let [s (first l)
r (rest l)]
(if (empty? r)
(map identity s)
(->> s
(map (fn [c] (map #(str c %) (perm-chars r))))
(flatten))))))
(defn perm-sz [s]
"Returns a list of all possible permutations of the input
string. May return duplicats.
Ex: ab -> (aa ab ba bb a b a b)"
(if-not (empty? s)
(let [r (perm-chars s)]
(if (= (count s) 1)
r
(->> r
(map #(perm-sz (apply str (rest %))))
(flatten)
(lazy-cat r))))))
(defn perm [s]
"Returns a list of all possible permutations of the input
string. The list of string is sorted and does not contain
duplicates.
Ex: ab -> (a aa ab b ba bb)"
(->> (reduce (fn [s e] (conj s e)) #{} (perm-sz s))
(map str)
(sort)))
(println (pmap perm ["ab" "we" "tfe" "aoj"]))
(require 'cojure.contrib.combinatorics)
(pmap (fn [str]
(apply concat (map #(selections str (inc %))
(range (count str)))))
["ab", "we", "tfe", "aoj"])
(pmap (fn [str]
(apply concat (map #(selections str (inc %))
(range (count str)))))
["ab", "we", "tfe", "aoj"])
Subdivide A Problem To A Pool Of Workers (Shared Data)
Take a hard to compute problem and split it up between multiple worker threads. In your solution, try to fully utilize available cores or processors. (I'm looking at you, Python!)
Note: In this question, there should be a need for shared state between worker threads while the problem is being solved.
Example:
-Conway Game of Life-
From Wikipedia:
The universe of the Game of Life is an infinite two-dimensional orthogonal grid of square cells, each of which is in one of two possible states, live or dead. Every cell interacts with its eight neighbors, which are the cells that are directly horizontally, vertically, or diagonally adjacent. At each step in time, the following transitions occur:
1. Any live cell with fewer than two live neighbours dies, as if caused by underpopulation.
2. Any live cell with more than three live neighbours dies, as if by overcrowding.
3. Any live cell with two or three live neighbours lives on to the next generation.
4. Any dead cell with exactly three live neighbours becomes a live cell.
The initial pattern constitutes the seed of the system. The first generation is created by applying the above rules simultaneously to every cell in the seed—births and deaths happen simultaneously, and the discrete moment at which this happens is sometimes called a tick (in other words, each generation is a pure function of the one before). The rules continue to be applied repeatedly to create further generations.
--However, for our purposes, we will assign a size to the game
Notice that in this problem, at each step or
Note: In this question, there should be a need for shared state between worker threads while the problem is being solved.
Example:
-Conway Game of Life-
From Wikipedia:
The universe of the Game of Life is an infinite two-dimensional orthogonal grid of square cells, each of which is in one of two possible states, live or dead. Every cell interacts with its eight neighbors, which are the cells that are directly horizontally, vertically, or diagonally adjacent. At each step in time, the following transitions occur:
1. Any live cell with fewer than two live neighbours dies, as if caused by underpopulation.
2. Any live cell with more than three live neighbours dies, as if by overcrowding.
3. Any live cell with two or three live neighbours lives on to the next generation.
4. Any dead cell with exactly three live neighbours becomes a live cell.
The initial pattern constitutes the seed of the system. The first generation is created by applying the above rules simultaneously to every cell in the seed—births and deaths happen simultaneously, and the discrete moment at which this happens is sometimes called a tick (in other words, each generation is a pure function of the one before). The rules continue to be applied repeatedly to create further generations.
--However, for our purposes, we will assign a size to the game
"board": 2^k * 2^k . That is, the board should be easy to subdivide.
Notice that in this problem, at each step or
"tick", each thread/process will need to share data with its neighborhood.
clojure
; This is a "glider"
(def *start*
[".O......"
"..O....."
"OOO....."
"........"
"........"
"........"
"........"])
(def *width* (count (first *start*)))
(def *height* (count *start*))
(def *live* \O)
(def *dead* \.)
(def *n-generations-to-show* 3)
(defn cell-at
([b coord]
(cell-at b coord {:col 0 :row 0}))
([b coord offset]
(let [x (mod (+ (:col coord) (:col offset)) *width*)
y (mod (+ (:row coord) (:row offset)) *height*)]
(nth (nth b y) x))))
(defn neighbor-count [b coord]
(->> (for [x (range -1 2) y (range -1 2)] {:col x :row y})
(filter #(not (= {:col 0 :row 0} %)))
(map (partial cell-at b coord))
(reduce (fn [sum n] (+ sum (if (= *live* n) 1 0))) 0)))
(defn next-generation-cell [b coord]
(let [nc (neighbor-count b coord)]
(cond (< nc 2) *dead*
(> nc 3) *dead*
(= nc 3) *live*
true (cell-at b coord))))
(defn next-generation-row [b row]
(->> (range *width*)
(map #(next-generation-cell b {:col % :row row}))
(apply str)))
(defn next-generation [b]
(->> (range *height*)
(pmap #(next-generation-row b %))))
(defn generation-seq [b]
(let [ng (next-generation b)]
(lazy-seq (cons ng (generation-seq ng)))))
(doseq [g (take *n-generations-to-show* (generation-seq *start*))]
(doseq [l g]
(println l))
(println))
(shutdown-agents)
; This version calculates each separate line on a separate thread (pmap in next-generation)
(def *start*
[".O......"
"..O....."
"OOO....."
"........"
"........"
"........"
"........"])
(def *width* (count (first *start*)))
(def *height* (count *start*))
(def *live* \O)
(def *dead* \.)
(def *n-generations-to-show* 3)
(defn cell-at
([b coord]
(cell-at b coord {:col 0 :row 0}))
([b coord offset]
(let [x (mod (+ (:col coord) (:col offset)) *width*)
y (mod (+ (:row coord) (:row offset)) *height*)]
(nth (nth b y) x))))
(defn neighbor-count [b coord]
(->> (for [x (range -1 2) y (range -1 2)] {:col x :row y})
(filter #(not (= {:col 0 :row 0} %)))
(map (partial cell-at b coord))
(reduce (fn [sum n] (+ sum (if (= *live* n) 1 0))) 0)))
(defn next-generation-cell [b coord]
(let [nc (neighbor-count b coord)]
(cond (< nc 2) *dead*
(> nc 3) *dead*
(= nc 3) *live*
true (cell-at b coord))))
(defn next-generation-row [b row]
(->> (range *width*)
(map #(next-generation-cell b {:col % :row row}))
(apply str)))
(defn next-generation [b]
(->> (range *height*)
(pmap #(next-generation-row b %))))
(defn generation-seq [b]
(let [ng (next-generation b)]
(lazy-seq (cons ng (generation-seq ng)))))
(doseq [g (take *n-generations-to-show* (generation-seq *start*))]
(doseq [l g]
(println l))
(println))
(shutdown-agents)
; This version calculates each separate line on a separate thread (pmap in next-generation)
Create a multithreaded "Hello World"
Create a program which outputs the string
Example:
-Output-
Thread one says Hello World!
Thread two says Hello World!
Thread four says Hello World!
Thread three says Hello World!
-Notice that the threads can print in any order.
"Hello World" to the console, multiple times, using separate threads or processes.
Example:
-Output-
Thread one says Hello World!
Thread two says Hello World!
Thread four says Hello World!
Thread three says Hello World!
-Notice that the threads can print in any order.
python
#!/usr/bin/python
from threading import Thread
Nthread = ['one','two','three','four']
def ThreadSpeaks(number):
print "Thread", number, "says Hello World!"
if __name__ == "__main__":
for n in range(0,len(Nthread)):
th =Thread(target=ThreadSpeaks, args=(Nthread[n],))
th.start()
from threading import Thread
Nthread = ['one','two','three','four']
def ThreadSpeaks(number):
print "Thread", number, "says Hello World!"
if __name__ == "__main__":
for n in range(0,len(Nthread)):
th =Thread(target=ThreadSpeaks, args=(Nthread[n],))
th.start()
erlang
-module(spam).
-export([spam/1]).
spam(N) when N<5 ->
spawn(fun() -> io:format("Hello World from thread ~p~n",[N]) end),
spam(N+1);
spam(_) -> void.
-export([spam/1]).
spam(N) when N<5 ->
spawn(fun() -> io:format("Hello World from thread ~p~n",[N]) end),
spam(N+1);
spam(_) -> void.
clojure
(doseq [msg ["one" "two" "three" "four"]]
(future (println "Thread" msg "says Hello World!")))
(future (println "Thread" msg "says Hello World!")))
(dorun (pmap #(println (str "Thread " % " says Hello World!")) '("one" "two" "three" "four")))
(dorun (map (fn [n] (.start (Thread. #(println (str "Thread " n " says Hello World!")))))
'("one" "two" "three" "four")))
'("one" "two" "three" "four")))
Create read/write lock on a shared resource.
Create multiple threads or processes who are either readers or writers. There should be more readers then writers.
(From Wikipedia):
Multiple readers can read the data in parallel but an exclusive lock is needed while writing the data. When a writer is writing the data, readers will be blocked until the writer is finished writing.
Example:
-Output-
Thread one says that the value is 8.
Thread three says that the value is 8.
Thread two is taking the lock.
Thread four tried to read the value, but could not.
Thread five tried to write to the value, but could not.
Thread two is changing the value to 9.
Thread two is releasing the lock.
Thread four says that the value is 9.
...
--Notice that when a needed resource is locked, a thread can set a timer and try again in the future, or wait to be notified that the resource is no longer locked.
(From Wikipedia):
Multiple readers can read the data in parallel but an exclusive lock is needed while writing the data. When a writer is writing the data, readers will be blocked until the writer is finished writing.
Example:
-Output-
Thread one says that the value is 8.
Thread three says that the value is 8.
Thread two is taking the lock.
Thread four tried to read the value, but could not.
Thread five tried to write to the value, but could not.
Thread two is changing the value to 9.
Thread two is releasing the lock.
Thread four says that the value is 9.
...
--Notice that when a needed resource is locked, a thread can set a timer and try again in the future, or wait to be notified that the resource is no longer locked.
python
#!/usr/bin/python
from threading import Thread, Lock
import time
thread_readers = ['one','two','three']
thread_writer = ['four','five']
lock = Lock()
value = 0
def Threadread(number):
global value
while True:
if lock.acquire(False):
print "Thread", number, "is taking the lock"
value += 1
print "Thread", number, "is changing the value to", value
print "Thread", number, "is releasing the lock."
lock.release()
else:
print "Thread", number, "tried to write to the value, but could not."
def Threadwrite(number):
global value
while True:
if lock.acquire(False):
print "Thread", number ,"four says that the value is", value
else:
print "Thread", number ,"tried to read the value, but could not."
if __name__ == "__main__":
for n in range(0,len(thread_readers)):
th =Thread(target=Threadread, args=(thread_readers[n],))
th.start()
for n in range(0,len(thread_writer)):
th =Thread(target=Threadwrite, args=(thread_writer[n],))
th.start()
from threading import Thread, Lock
import time
thread_readers = ['one','two','three']
thread_writer = ['four','five']
lock = Lock()
value = 0
def Threadread(number):
global value
while True:
if lock.acquire(False):
print "Thread", number, "is taking the lock"
value += 1
print "Thread", number, "is changing the value to", value
print "Thread", number, "is releasing the lock."
lock.release()
else:
print "Thread", number, "tried to write to the value, but could not."
def Threadwrite(number):
global value
while True:
if lock.acquire(False):
print "Thread", number ,"four says that the value is", value
else:
print "Thread", number ,"tried to read the value, but could not."
if __name__ == "__main__":
for n in range(0,len(thread_readers)):
th =Thread(target=Threadread, args=(thread_readers[n],))
th.start()
for n in range(0,len(thread_writer)):
th =Thread(target=Threadwrite, args=(thread_writer[n],))
th.start()
clojure
; NOTE! Using explicit locking is NOT the Clojure way. It was done
; this way in order to comply exactly with the problem
; specification. Sharing data in Clojure would normally be done by
; using "atom", "agent" or "ref" depending on situation. None of those
; methods would ever result in the reader not being able to read (as
; required by the problem) since reading is wait-free in clojure.
(def *readers* (map #(agent %) '("one" "two" "three")))
(def *writers* (map #(agent %) '("four" "five")))
(def *mutex* (agent :unlocked))
(def *value* 0)
; mutex implementation
(defn lock [state who success-fn fail-fn]
(send who (if (= state :locked) fail-fn success-fn))
:locked)
(defn unlock [mutex]
:unlocked)
; Must be invoked with send-off since this handler blocks
(defn rand-sleep [state next-fn]
(Thread/sleep (rand-int 5))
(send *agent* next-fn)
state)
; Reader functions
(declare try-read)
(defn reader-got-lock [name]
(println (format "Thread %s says that the value is %d." name *value*))
(send *mutex* unlock)
(send-off *agent* rand-sleep try-read)
name)
(defn reader-did-not-get-lock [name]
(println (format "Thread %s tried to read the value, but could not." name))
(send-off *agent* rand-sleep try-read)
name)
(defn try-read [name]
(send *mutex* lock *agent* reader-got-lock reader-did-not-get-lock)
name)
; Writer functions
(declare try-write)
(defn writer-got-lock [name]
(println (format "Thread %s is taking the lock." name))
(def *value* (rand-int 10))
(println (format "Thread %s is changing the value to %d." name *value*))
(send *mutex* unlock)
(println (format "Thread %s is relasing the lock." name))
(send-off *agent* rand-sleep try-write)
name)
(defn writer-did-not-get-lock [name]
(println (format "Thread %s tried to write the value, but could not." name))
(send-off *agent* rand-sleep try-write)
name)
(defn try-write [name]
(send *mutex* lock *agent* writer-got-lock writer-did-not-get-lock)
name)
(dorun (map #(send % try-write) *writers*))
(dorun (map #(send % try-read) *readers*))
; this way in order to comply exactly with the problem
; specification. Sharing data in Clojure would normally be done by
; using "atom", "agent" or "ref" depending on situation. None of those
; methods would ever result in the reader not being able to read (as
; required by the problem) since reading is wait-free in clojure.
(def *readers* (map #(agent %) '("one" "two" "three")))
(def *writers* (map #(agent %) '("four" "five")))
(def *mutex* (agent :unlocked))
(def *value* 0)
; mutex implementation
(defn lock [state who success-fn fail-fn]
(send who (if (= state :locked) fail-fn success-fn))
:locked)
(defn unlock [mutex]
:unlocked)
; Must be invoked with send-off since this handler blocks
(defn rand-sleep [state next-fn]
(Thread/sleep (rand-int 5))
(send *agent* next-fn)
state)
; Reader functions
(declare try-read)
(defn reader-got-lock [name]
(println (format "Thread %s says that the value is %d." name *value*))
(send *mutex* unlock)
(send-off *agent* rand-sleep try-read)
name)
(defn reader-did-not-get-lock [name]
(println (format "Thread %s tried to read the value, but could not." name))
(send-off *agent* rand-sleep try-read)
name)
(defn try-read [name]
(send *mutex* lock *agent* reader-got-lock reader-did-not-get-lock)
name)
; Writer functions
(declare try-write)
(defn writer-got-lock [name]
(println (format "Thread %s is taking the lock." name))
(def *value* (rand-int 10))
(println (format "Thread %s is changing the value to %d." name *value*))
(send *mutex* unlock)
(println (format "Thread %s is relasing the lock." name))
(send-off *agent* rand-sleep try-write)
name)
(defn writer-did-not-get-lock [name]
(println (format "Thread %s tried to write the value, but could not." name))
(send-off *agent* rand-sleep try-write)
name)
(defn try-write [name]
(send *mutex* lock *agent* writer-got-lock writer-did-not-get-lock)
name)
(dorun (map #(send % try-write) *writers*))
(dorun (map #(send % try-read) *readers*))
Separate user interaction and computation.
Allow your program to accept user interaction while conducting a long running computation.
Example:
Hello user! Please input a string to permute: (input thread)
abcdef
Passing on abcdef... (input thread)
Please input another string to permute: (input thread)
lol
Passing on lol... (input thread)
Done Work On abcdef! (worker thread)
Please input another string to permute: (input thread)
EXIT
Quitting, I
--Notice, that this could be accomplished on the command line or within a GUI. The point is that computation and user interaction should take place on separate threads of control.
Example:
Hello user! Please input a string to permute: (input thread)
abcdef
Passing on abcdef... (input thread)
Please input another string to permute: (input thread)
lol
Passing on lol... (input thread)
Done Work On abcdef! (worker thread)
["abcdef", "abcefd", ... ] (worker thread)
Please input another string to permute: (input thread)
EXIT
Quitting, I
'll let my worker thread know... (input thread)
We're quitting! Alright! (worker thread)
--Notice, that this could be accomplished on the command line or within a GUI. The point is that computation and user interaction should take place on separate threads of control.
clojure
(defn background-computation [_ s]
(let [res (permutations s)]
(println (format "Done Work On %s!" s))
(println res)))
(defn shutdown-app [_]
(println "We're quitting! Alright!")
(shutdown-agents))
(println "Hello user! Please input a string to permute: ")
(let [worker-agent (agent nil)]
(loop [input (str (read))]
(if (= input "EXIT")
(do (println "Quitting, I'll let my worker thread know...")
(send worker-agent shutdown-app))
(do (println (format "Passing on %s..." input))
(send worker-agent background-computation input)
(println "Please input another string to permute: ")
(recur (str (read)))))))
(let [res (permutations s)]
(println (format "Done Work On %s!" s))
(println res)))
(defn shutdown-app [_]
(println "We're quitting! Alright!")
(shutdown-agents))
(println "Hello user! Please input a string to permute: ")
(let [worker-agent (agent nil)]
(loop [input (str (read))]
(if (= input "EXIT")
(do (println "Quitting, I'll let my worker thread know...")
(send worker-agent shutdown-app))
(do (println (format "Passing on %s..." input))
(send worker-agent background-computation input)
(println "Please input another string to permute: ")
(recur (str (read)))))))
Put a internationalizate of HelloWorld program
Set locale to
In pseudocode:
Void main ()
"es" (spanish) and provide a program that changes outputs ("Helloworld") depending of locale.
In pseudocode:
Void main ()
{
Locale.set("es")
print.translate("Helloworld, Locale.get)
}
180
"http://www.ecigarettefresh.com/cartomizer-ecigarette-c-7.html ">Cartomizer E-Cigarette<
/a>strong>"http://www.ecigarettefresh.com/cartomizer-ecigarette-c-7.html ">Electronic Cigarette<
/a>strong>"http://www.ecigarettefresh.com/cartomizer-ecigarette-c-7.html ">Smokeless Cigarettes<
/a>strong>"http://www.ecigarettefresh.com/cartomizer-ecigarette-c-7.html ">discount Electronic Cigarette<
/a>strong>"http://www.ecigarettefresh.com/disposable-ecigarette-c-8.html ">Disposable E-Cigarette<
/a>strong>"http://www.ecigarettefresh.com/accessories-c-6.html ">Accessories<
/a>strong>"http://www.ecigarettefresh.com/mini-ecigarette-c-13.html ">Mini E-cigarette<
/a>strong>"http://www.ecigarettefresh.com/esmoking-c-11.html ">electric cigarette outlet<
/a>strong>"http://www.ecigarettefresh.com/smokeless-cigarettes-c-12.html ">Smokeless Cigarettes online<
/a>strong>"http://www.ecigarettefresh.com/ecigarette-c-9.html ">Electronic Cigarette online<
/a>strong>. "http://blog.allluxurywatches.com"> outlet blog <
/a>
outlet a>"http://blog.linksoflondonshopping.com"> About ecigarettefresh.com blog
180
"http://www.lovembtshoes.com/ ">mbt boots<
/a>strong>"http://www.lovembtshoes.com/ ">mbt shoes<
/a>strong>"http://www.lovembtshoes.com/ ">buy mbt boots<
/a>strong>"http://www.lovembtshoes.com/ ">discount mbt shoes<
/a>strong>"http://www.lovembtshoes.com/ ">mbt shoes online<
/a>strong>"http://www.lovembtshoes.com/mbt-tariki-c-50.html ">MBT Tariki shoes outlet<
/a>strong>"http://www.lovembtshoes.com/mbt-karibu-c-18.html ">wholesale MBT Karibu shoes<
/a>strong>"http://www.lovembtshoes.com/mbt-kafala-black-leather-women-shoes-p-68.html ">buy MBT Kafala shoes<
/a>strong>"http://www.lovembtshoes.com/mbt-meli-c-33.html ">MBT Meli<
/a>strong>"http://www.lovembtshoes.com/mbt-kifundo-c-25.html ">discount MBT Kifundo<
/a>strong>. "http://blog.bootsonlinecompany.com"> Bia blog <
/a>
Bia a>"http://blog.linkuggbootsoutlet.com"> About lovembtshoes.com blog
180
[Mall3411] - $175.01 : </title>
html; charset=utf-8" />
keywords" content="Low Cost Custom-Made bretelles sexy mariage mariée robe de mariée Robes [Mall3411] Robes de Mariée Robes de mariée 2012 Robe de mariée sexy Robes de mariée robes Quinceanera Robes de bal Robes de soirée Robes de bal Robes de soirée Robes de cocktail " />
description" content=" Low Cost Custom-Made bretelles sexy mariage mariée robe de mariée Robes [Mall3411] - Nom de l'article: " />
- TOP_MENU_HOME
- Robes de cocktail
- Robes de soirée
- Robes de mariée
- Robes de bal
- Contactez-nous
- http:
//fr.weddingdressescompany.com/»,«http:/fr.weddingdressescompany.com/' ) " > Marque page