[Question]
      [
Here is a simple [ASCII art](http://en.wikipedia.org/wiki/ASCII_art) snowman:
```
_===_
(.,.)
( : )
( : )
```
Let's make him some friends. This will be the general pattern for our ASCII art snowpeople:
```
 HHHHH
 HHHHH
X(LNR)Y
X(TTT)Y
 (BBB)
```
The leading spaces and the parentheses are always the same for all snowpeople. The different letters represent sections of the pattern that can individually change. Each section has exactly four presets for what ASCII characters can fill it.
By mixing and matching these presets for all eight sections, we can make a variety of snowpeople.
# All Presets
(Notice that spaces are put on otherwise empty lines so the section shape is always correct.)
### H is for Hat
1. Straw Hat
```

_===_
```
2. Mexican Hat
```
 ___
.....
```
3. Fez
```
  _
 /_\
```
4. [Russian Hat](http://en.wikipedia.org/wiki/Ushanka)
```
 ___
(_*_)
```
### N is for Nose/Mouth
1. Normal `,`
2. Dot `.`
3. Line `_`
4. None
### L is for Left Eye
1. Dot `.`
2. Bigger Dot `o`
3. Biggest Dot `O`
4. Closed `-`
### R is for Right Eye
(Same list as left eye.)
### X is for Left Arm
1. Normal Arm
```

<
```
2. Upwards Arm
```
\

```
3. Downwards Arm
```

/
```
4. None
```

```
### Y is for Right Arm
1. Normal Arm
```

>
```
2. Upwards Arm
```
/

```
3. Downwards Arm
```

\
```
4. None
```

```
### T is for Torso
1. Buttons  `:`
2. Vest `] [`
3. Inward Arms `> <`
4. None
### B is for Base
1. Buttons  `:`
2. Feet `" "`
3. Flat `___`
4. None
# Challenge
Write a program that takes in an eight character string (via stdin or command line) in the format `HNLRXYTB`, where each letter is a digit from 1 to 4 that denotes which preset to use for the corresponding section of the snowperson. Print the full snowperson to stdout.
For example, the input `11114411` is the snowman at the top of the page. (First `1`: he has a straw hat, second `1`: he has a normal nose, etc.)
Another example, the snowperson for input `33232124`:
```
   _
  /_\
\(o_O)
 (] [)>
 (   )
```
# Details
* Any amounts and combinations of leading/trailing spaces and leading/trailing newlines are allowed as long as...
	+ the snowperson has all their sections arranged correctly with respect to one another, and
	+ there are never more than 64 total whitespace characters (the general pattern is only 7×5, so you probably won't hit this limit).You don't need to print rows/columns of the pattern if they only contain whitespace. e.g. the empty line of the straw hat is not required.
* You must use the ordering of the parts as they are given above.
* Instead of a program, you may write a function that takes the digit string as an argument. The output should be printed normally or returned as a string.
* You may treat the input as an integer instead of a string if preferred.
# Scoring
The shortest code in bytes wins.
***Bonus question:*** Which of the 65536 distinct snowpeople is your favorite?

[Answer]
# JavaScript ES6, 210 208 202 bytes
```
s=>` 0
8(213)9
4(6)5
 (7)`.replace(/\d/g,p=>`_===_1 ___
 .....1  _
  /_\\1 ___
 (_*_)1,1.1_11.1o101-1.1o101-1<11/11>11\\11 : 1] [1> <1   1 : 1" "1___1   11\\11 11/11 `.split(1)[s[p>7?p-4:p]-1+p*4]||' ')
```
This is an anonymous function; you use it by executing `([function code])('42232124')`. The most aggravating part of this was the arms, which take up 2 lines, so I had to include code for both top and bottom.
The Stack Snippet below has ungolfed, un-ES6-ified, commented code. And you can use it to easily test the code and try out different combinations. **Edit:** I'm having way too much fun with this. I've added several new features, including a way to generate a random snowman.
Thanks to Yair Rand for saving six bytes.
```
var f=function(s){
  return' 0\n8(213)9\n4(6)5\n (7)' // Start with a placeholder string with all the static components
    .replace(/\d/g,function(p){ // Go through each placeholder number to replace it with its value
    // The massive string below holds all the possible body parts, separated by 1 for easy splitting.
    // The two at the end are for the top of the arms
    return'_===_1 ___\n .....1  _\n  /_\\1 ___\n (_*_)1,1.1_11.1o101-1.1o101\
-1<11/11>11\\11 : 1] [1> <1   1 : 1" "1___1   11\\11 11/11 '.split(1)
    [s[p>7?p-4:p]-1 // Get the value from the input string. If the current body part
                    // is the top of the two-line arms (8 or 9), drop it down to 4 or 5
                    // Subtract 1 to account for the 0-indexed array.
     +p*4] // multiply by 4 to skip to the relevant code
     ||' ' // To save bytes in the above string, spaces are empty strings, so replace them here
  })
}
// Code for the interactive version follows
// http://codepen.io/hsl/pen/bdEgej
function updateRadios(){$('input[type="radio"]').each(function(){if($(this).is(":checked")){var t=$(this).data("p"),i=$(this).data("v");input[t]=i}}),inputS=input.join(""),update()}var input=[],inputS=$("#code").val(),update=function(){$("#p").text(f(inputS)),$("#code").val(inputS)};$('input[type="radio"]').change(updateRadios),$("#code").keyup(function(){inputS=$(this).val(),update()}),updateRadios(),$("#random").click(function(){for(var t=0;8>t;t++)$("div:eq("+t+") input:eq("+Math.floor(4*Math.random())+")").prop("checked",!0);updateRadios()});
```
```
body{font-family:sans-serif}h2{font-size:18px;font-weight:400}label{display:block}div{display:inline-block;margin:0 10px}#code{width:70px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div><h2>Hat</h2><label><input type="radio" name="p1" data-p="1" data-v="1"> Straw hat</label><label><input type="radio" name="p1" data-p="1" data-v="2"> Mexican hat</label><label><input type="radio" name="p1" data-p="1" data-v="3"> Fez</label><label><input type="radio" name="p1" data-p="1" data-v="4" checked> Russian hat</label></div><div><h2>Nose/mouth</h2><label><input type="radio" name="p2" data-p="2" data-v="1"> Normal</label><label><input type="radio" name="p2" data-p="2" data-v="2" checked> Dot</label><label><input type="radio" name="p2" data-p="2" data-v="3"> Line</label><label><input type="radio" name="p2" data-p="2" data-v="4"> None</label></div><div><h2>Left eye</h2><label><input type="radio" name="p3" data-p="3" data-v="1"> Dot</label><label><input type="radio" name="p3" data-p="3" data-v="2" checked> Bigger dot</label><label><input type="radio" name="p3" data-p="3" data-v="3"> Biggest dot</label><label><input type="radio" name="p3" data-p="3" data-v="4"> Closed</label></div><div><h2>Right eye</h2><label><input type="radio" name="p4" data-p="4" data-v="1"> Dot</label><label><input type="radio" name="p4" data-p="4" data-v="2"> Bigger dot</label><label><input type="radio" name="p4" data-p="4" data-v="3" checked> Biggest dot</label><label><input type="radio" name="p4" data-p="4" data-v="4"> Closed</label></div><div><h2>Left arm</h2><label><input type="radio" name="p5" data-p="5" data-v="1"> Normal</label><label><input type="radio" name="p5" data-p="5" data-v="2" checked> Upwards</label><label><input type="radio" name="p5" data-p="5" data-v="3"> Downwards</label><label><input type="radio" name="p5" data-p="5" data-v="4"> None</label></div><div><h2>Right arm</h2><label><input type="radio" name="p6" data-p="6" data-v="1" checked> Normal</label><label><input type="radio" name="p6" data-p="6" data-v="2"> Upwards</label><label><input type="radio" name="p6" data-p="6" data-v="3"> Downwards</label><label><input type="radio" name="p6" data-p="6" data-v="4"> None</label></div><div><h2>Torso</h2><label><input type="radio" name="p7" data-p="7" data-v="1"> Buttons</label><label><input type="radio" name="p7" data-p="7" data-v="2" checked> Vest</label><label><input type="radio" name="p7" data-p="7" data-v="3"> Inward arms</label><label><input type="radio" name="p7" data-p="7" data-v="4"> None</label></div><div><h2>Base</h2><label><input type="radio" name="p8" data-p="8" data-v="1"> Buttons</label><label><input type="radio" name="p8" data-p="8" data-v="2"> Feet</label><label><input type="radio" name="p8" data-p="8" data-v="3"> Flat</label><label><input type="radio" name="p8" data-p="8" data-v="4" checked> None</label></div><br><button id="random">Randomize</button><pre id="p"></pre><input type="text" id="code">
```
[Answer]
# CJam, ~~135~~ ~~134~~ ~~132~~ ~~130~~ ~~126~~ 125 bytes
```
0000000: 4e22285b200a5c225f2a295c2d2e2f6f2c3e4f3a3c3d5d225f  N"([ .\"_*)\-./o,>O:<=]"_
0000019: 2422dd7382d6bfab28707190992f240c362ee510262bd07a77  $".s....(pq../$.6...&+.zw
0000032: 08556de9dcdb566c676817c2b87f5ecb8bab145dc2f2f76e07  .Um...Vlgh....^....]...n.
000004b: 22323536624b623224663d4e2f7b5f2c342f2f7d25723a7e2e  "256bKb2$f=N/{_,4//}%r:~.
0000064: 3d2828342423346222205f0a20222e2a6f6f736572372f4e2a  =((4$#4b" _. ".*ooser7/N*
```
To create the file on your machine, execute `xxd -r > snowman.cjam`, paste the reversible hexdump from above, press `Enter` and finally `Ctrl` + `D`.
Alternatively, you can try the code online using the [CJam interpreter](http://cjam.aditsu.net/#code=N%22(%5B%20%0A%5C%22_*)%5C-.%2Fo%2C%3EO%3A%3C%3D%5D%22_%24%22%C3%9Ds%C2%82%C3%96%C2%BF%C2%AB(pq%C2%90%C2%99%2F%24%0C6.%C3%A5%10%26%2B%C3%90zw%08Um%C3%A9%C3%9C%C3%9BVlgh%17%C3%82%C2%B8%7F%5E%C3%8B%C2%8B%C2%AB%14%5D%C3%82%C3%B2%C3%B7n%07%22256bKb2%24f%3DN%2F%7B_%2C4%2F%2F%7D%25r%3A~.%3D((4%24%234b%22%20_%0A%20%22.*ooser7%2FN*&input=12222212).
### Bonus
My favorite snowman is Olaf:
```
$ LANG=en_US cjam snowman.cjam <<< 12222212
 _===_
\(o.o)/
 ( : )
 (" ")
```
*Winter's a good time to stay in and cuddle, but put me in summer and I'll be a… happy snowman!*
### Idea
The hex string
```
dd7382d6bfab28707190992f240c362ee510262bd07a7708
556de9dcdb566c676817c2b87f5ecb8bab145dc2f2f76e07
```
encodes the possible choices for all parts of the snowman, including the fixed ones. Let's call this string **P**.
To decode it, we convert **P** (here treated as an array of integers) from base 256 to base 20 and replace each of the resulting integers by the corresponding character of the string **M**:
```
([
"_*)\-./o,>O:<=]
```
This results in the string **T**:
```
/(_*_)"_===_/....., /_\
 ,._
-.oO
-.oO
   <\  /
   >/  \
    : ] [> <
    : " "___
 ((()
```
The first line encodes all hat choices, the last all fixed body parts. The other lines contain the 28 variable body parts.
We split **T** at linefeeds and divide the strings of the resulting array into four parts of equal length. Then, we read the input from STDIN, push the array of its digits in base 10 and select the corresponding elements of the split strings. We take advantage of the fact that arrays wrap around in CJam, so the element at index 4 of an array of length 4 is actually the first element. The last divided string does not correspond to any input, so it will get selected entirely.
We handle the hat by shifting the first element out of the resulting array. The index in **M** of first character, read as a base 4 number, reveals the number of spaces and underscores in the first line of the hat. We print those characters, a linefeed, a space and the remainder of the shifted string. Then, we push an additional linefeed on the bottom of the stack.
For the body parts, we concatenate the string corresponding to all of them. Let's call this string **S**. To assemble the body parts, we perform transliteration: we take each character of the string **M**, compute its index in **sort(M)** and replace it by the corresponding character of **S**. We take advantage of the fact that the transliteration operator automatically pads **S** to match the length of **sort(M)** by repeating the last character of **S** as many times as necessary.
Finally, we divide the resulting string into substrings of length 7 and place a linefeed between each pair of substrings.
### Code
Suppose that the variables `M` and `P` contain the strings **M** and **P**.
```
N        e# Push a linefeed.
M_$      e# Push M and a sorted copy.
P256bKb  e# Push P and convert it from base 256 to base 20.
2$       e# Push a copy of M.
f=       e# Compute T by retrieving the proper chars from M.
N/       e# Split T at linefeeds.
{_,4//}% e# Divide each string into four substrings of equal length.
r:~      e# Read a number from STDIN and push the array of its digits in base 10.
.=       e# Get the corresponding chunks from T.
((       e# Shift out the first string and that string's first character.
4$#      e# Find its index in M.
4b       e# Compute its digits in base 4.
" _
 ".*     e# Repeat the space and underscore that many times in place.
oo       e# Print the result and the shifted string.
s        e# Flatten the remainder of the array. This pushes S.
er       e# Perform transliteration.
7/       e# Split into chunks of length 7.
N*       e# Join using linefeeds.
```
[Answer]
# CJam, 164 bytes
Generates the snowman left-to-right, top-to-bottom. This eliminates the need for any kind of string joining or repositioning operations, as I just leave every piece of the snowman on the stack. And then, due to the automatic stack dump at the end of programs:
♫ *CJam wants to build a snowman!* ♫
```
q:Q;SS"
 _===_,___
 ....., _
  /_\,___
 (_*_)"',/0{Q=~(=}:G~N" \ "4G'(".oO-"_2G",._ "1G@3G')" / "5GN"< / "4G'(" : ] [> <   "3/6G')"> \ "5GNS'(" : \" \"___   "3/7G')
```
[Try it online.](http://cjam.aditsu.net/#code=q%3AQ%3BSS%22%0A%20_%3D%3D%3D_%2C___%0A%20.....%2C%20_%0A%20%20%2F_%5C%2C___%0A%20(_*_)%22'%2C%2F0%7BQ%3D~(%3D%7D%3AG~N%22%20%5C%20%224G'(%22.oO-%22_2G%22%2C._%20%221G%403G')%22%20%2F%20%225GN%22%3C%20%2F%20%224G'(%22%20%3A%20%5D%20%5B%3E%20%3C%20%20%20%223%2F6G')%22%3E%20%5C%20%225GNS'(%22%20%3A%20%5C%22%20%5C%22___%20%20%20%223%2F7G')&input=33232124)
### Bonus
Thinking outside the box! `32443333` gives a snow(wo)man bride. You've gotta try a bit to see it, but there are the inward arms, fez + downwards arms = veil, and the head is actually in the fez/veil. The generally large form is the billowy dress, and the "eyes" and "nose" are folds in the dress.
```
   _
  /_\
 (-.-)
/(> <)\
 (___)
```
Other "eye" choices are a bit risqué...
[Answer]
# Python, ~~276~~ 289 bytes
```
V='.oO-'
def F(d):
 D=lambda i:int(d[i])-1
 print"  "+("","___"," _ ","___")[D(0)]+"\n "+\
"_. (=./_=._*=.\\__. )"[D(0)::4]+"\n"+\
" \\  "[D(4)]+"("+V[D(2)]+',._ '[D(1)]+V[D(3)]+")"+" /  "[D(5)]+'\n'+\
"< / "[D(4)]+"("+" ]> :    [< "[D(6)::4]+")"+"> \\ "[D(5)]+"\n ("+\
' "_ : _  "_ '[D(7)::4]+")"
```
This code has 8 extra bytes(`\`\*4) for readability.
Builds the snowman up bit by bit.
# Bonus
`F("44444432")` gives "sleepy russian bear":
```
  ___
 (_*_)
 (- -)
 (> <)
 (" ")
```
[Answer]
# TI-BASIC, 397 bytes
**Important:** If you want to test this out, download it from [here](https://www.dropbox.com/s/exwuo6zm9xsn7q6/SNOWMAN.8xp?dl=0) and send that file to your calculator. Do *not* try to copy the code below into TI-Connect CE's program editor or SourceCoder 3 or something to build and send it to your calculator; in TI-Connect's case, it'll say it has an invalid token. SC3 uses the backslash as a comment delimiter (`//` starts a comment in SC3; `/\/`, though, will export as `//`) and so it won't export the arms and hat and such correctly, causing the program to both display the incorrect body parts and throw an ERROR:DOMAIN every now and then. Fun stuff!
**Important #2:** I'm too lazy to fix the download at the moment, so when you transfer it to your calc, change the `7` on the third line from the bottom to `X+6`. The code below is fixed if you need to compare.
```
Input Str9
seq(inString("1234",sub(Str9,I,1)),I,1,length(Ans→L1
"      ___   _   ___ →Str1
"_===_..... /_\ (_*_)→Str2
",._ →Str3
"•oO-→Str4
"<\/ →Str5
">/\ →Str6
" : ] [> <   →Str7
" : ¨ ¨___   →Str8
"Str1Str2Str3Str4Str5Str6Str7Str8→Str0
For(X,3,5
Output(X,2,"(   )
End
L1
Output(3,3,sub(Str4,Ans(3),1)+sub(Str3,Ans(2),1)+sub(Str4,Ans(4),1
Ans(5
Output(4-(Ans=2),1,sub(Str5,Ans,1
L1(6
Output(4-(Ans=2),7,sub(Str6,Ans,1
L1-1
For(X,1,2
Output(X+3,3,sub(expr(sub(Str0,X+6,1)),1+3Ans(X+6),3
Output(X,2,sub(expr(sub(Str0,X,1)),1+5Ans(1),5
End
```
**Bonus:** I'm particularly fond of `12341214`.
```
 _===_
 (O.-)/
<( : )
 (   )
```
Some notes:
* It can definitely be golfed more, no question about that. I'm nearly positive that I can combine a majority, if not all, of the outputting into a single For( loop. Also, I'm pretty sure that I can merge some strings together.
* In Str4 (the eyes) I use the "plot dot" (`[2ND] → [0]CATALOG → [3]θ → scroll down, it's between ﹢ (small plus) and · (interpunct)`) as opposed to a period so that the eyes don't line up with the comma, because that looks weird as hell.
* In Str8 (base) I had to use a diaeresis (¨) instead of double quotes because there's no way to escape characters in TI-BASIC, and double quotes are used to start/end strings.
* In TI-BASIC, there's no need to close parentheses and brackets if they're followed by a colon, newline or → (used for var assignment), and double quotes (strings) can stay unclosed when followed by a newline or →.
[Answer]
# Python 2, ~~354~~ ~~280~~ ~~241~~ 261 bytes
```
def s(g):H,N,L,R,X,Y,T,B=[int(c)-1for c in g];e='.oO-';print(' '*9+'_ _ ___ _ _\n\n\n\n    _. (=./_=._*=.\\__. )')[H::4]+'\n'+' \\  '[X]+'('+e[L]+',._ '[N]+e[R]+')'+' /  '[Y]+'\n'+'< / '[X]+"("+' ]> :    [< '[T::4]+')'+'> \\ '[Y]+'\n ('+' "_ : _  "_ '[B::4]+")"
```
Calling `s('33232124')` gives:
```
   _
  /_\
\(o_O)
 (] [)>
 (   )
```
But my favorites are `44242123` and `41341144`:
```
  ___      ___
 (_*_)    (_*_)
\(o -)    (O,-)
 (] [)>  <(   )>
 (___)    (   )
```
[Answer]
# CJam, ~~150~~ 145 bytes
Base convert **all** the things!
```
"b8li'
U9gN;|"125:Kb8bl:~f="r  pL|P3{cR`@L1iT"Kb21b"G.HMtNY7VM=BM@$^$dX8a665V"KbFb"=_./ <[(*-oO,\":"f=_"/<[(""\>])"er+4/f=.=7/N*
```
SE mangles unprintables, so [here](http://pastebin.com/J4eFVDtR) is a copy on Pastebin. Make sure you copy the "RAW Paste Data" part, not the part next to line numbers. You can [try it online](http://cjam.aditsu.net/#code=%22%02b8%11li%27%0A%07U9gN%3B%7C%22125%3AKb8bl%3A%7Ef%3D%22%02r%09pL%7CP3%19%7B%0EcR%60%40%1DL1i%07T%15%22Kb21b%22%01G%0F%1D.H%17M%13tNY7V%15M%3DBM%40%24%5E%08%24%1B%1EdX8a665V%22KbFb%22%3D_.%2F%20%3C%5B%28*-oO%2C%5C%22%3A%22f%3D_%22%2F%3C%5B%28%22%22%5C%3E%5D%29%22er%2B4%2Ff%3D.%3D7%2FN*&input=14441133), but the permalink may not work in some browsers.
## Explanation
The `"b8li'U9gN;|"125:Kb8bp` part generates the array
```
[1 0 0 0 0 0 0 0 0 0 0 0 0 0 4 0 2 1 3 0 5 4 0 6 6 6 0 5 0 0 7 7 7 0]
```
which maps each digit of the input to where the digit is used. Anything which is common to all inputs (e.g. leading spaces and `()`) is arbitrarily assigned a 0, except the first which is assigned 1 so that base convert can work.
`l:~f=` then converts each digit to an int and maps accordingly, e.g. for `14441133` we get
```
[2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 3 2 4 1 2 1 1 3 3 3 1 2 1 1 4 4 4 1]
```
`"G.HMtNY7VM=BM@$^$dX8a665V"KbFb"=_./ <[(*-oO,\":"f=` gives the string
```
"_=./  /  < /  [<(((((_. _ _     _ __*=._-.oO ,._  \"_ :   : _"
```
after which we duplicate, replace `/<[(` with `\>])` and append to give a long string. Then we split the string into groups of 4 and map according to another array `"r pL|P3{cR`@L1iT"Kb21b`, thus getting an array of length-4 strings describing all possible options at each cell (e.g. `_=./` is all possible options for the second character on the second line, starting from the Russian hat).
Finally we map the options to the inputs accordingly `.=`, split into rows of length 7 `7/` and riffle in some newlines `N*`.
## Test runs
```
11111111
 _===_
 (.,.)
<( : )>
 ( : )
22222222
  ___
 .....
\(o.o)/
 (] [)
 (" ")
33333333
   _
  /_\
 (O_O)
/(> <)\
 (___)
44444444
  ___
 (_*_)
 (- -)
 (   )
 (   )
```
[Answer]
# C, ~~280 272~~ 264 bytes
Only partially golfed at this point, but this is a fun challenge.
```
#define P(n)[s[n]&3],
f(char*s){printf("  %.3s\n %.5s\n%c(%c%c%c)%c\n%c(%.3s)%c\n (%.3s)",
"___   ___ _"+*s%4*3,"(_*_)_===_..... /_\\"+*s%4*5,"  \\ "P(4)"-.o0"P(2)
" ,._"P(1)"-.o0"P(3)"  /"P(5)" < /"P(4)"    : ] [> <"+s[6]%4*3," > \\"P(5)
"    : \" \"___"+s[7]%4*3);}
```
(With some extra \n for readability.) I expect the `define` should go away with further golfing.
A more readable version is
```
#define P(n)[s[n]&3],
f(char *s) {
  printf("  %.3s\n"
         " %.5s\n"
         "%c(%c%c%c)%c\n"
         "%c(%.3s)%c\n"
         " (%.3s)",
         "___   ___ _"+*s%4*3,                  /* Top of hat. */
         "(_*_)_===_..... /_\\"+*s%4*5,         /* Lower hat. */
         "  \\ "P(4)                            /* Upper left arm. */
         "-.o0"P(2)                             /* Left eye. */
         " ,._"P(1)                             /* Nose. */
         "-.o0"P(3)                             /* Right eye. */
         "  /"P(5)                              /* Upper right arm. */
         " < /"P(4)                             /* Lower left arm. */
         "    : ] [> <"+s[6]%4*3,               /* Torso. */
         " > \\"P(5)                            /* Lower right arm. */
         "    : \" \"___"+s[7]%4*3              /* Base. */
         );
}
```
[Answer]
# C, 212 bytes
```
d;main(){char*t="##3#b#b3#bbb3#b#b##\r#3b1#+3@12b3@1b-3@1_b3b1#,#\r7#_##+51rR04/1b#61rR0,8#2##\r7?#2#+9#`A#9=###9#^?#,8A#_#\r#+:#%b#:=#b#:#%b#,#",p[9];for(gets(p);d=*t++;putchar(d-3))d=d<51?d:(p[d-51]-53)[t+=4];}
```
A readable version:
```
d;
main()
{
    char *t = "##3#b#b3#bbb3#b#b##\r"
              "#3b1#+3@12b3@1b-3@1_b3b1#,#\r"
              "7#_##+51rR04/1b#61rR0,8#2##\r"
              "7?#2#+9#`A#9=###9#^?#,8A#_#\r"
              "#+:#%b#:=#b#:#%b#,#",
        p[9]; // 9 bytes is just enough for the input string of length 8
    for (gets(p); d = *t++; putchar(d-3))
        d = d < 51 ? d : (p[d - 51] - 53)[t += 4];
}
```
I took the idea from [the answer by Reto Koradi](https://codegolf.stackexchange.com/a/49914/25315). There were several fun improvements I did, which may warrant posting a separate answer:
* Converted from function to program (+10)
* Moved newlines into the control string (-7)
* Added 3 to all character codes to have fewer escaped chars like `\"` (-3)
* Reading from the string with autoincrement; also replaced `t[i++]` by `*t++` (-4)
* Replaced `while` by `for`; removed `{}` (-4)
* Simplified loop termination: reading until `\0` (-9)
* [Transformed `t[...],t+=4` to `(...)[t+=4]`](https://stackoverflow.com/questions/381542/with-c-arrays-why-is-it-the-case-that-a5-5a) to eliminate the comma operator (-1)
Why all that trouble? To share my favorite one, snow ghost:
```
   _
  /_\
\(. .)/
 (   )
 (___)
```
[Answer]
# JavaScript, 489 (without newlines and tabs)
```
x=' ';
d="   ";
h=['\n_===_',' ___ \n.....','  _  \n /_\\ ',' ___ \n(_*-)'];
n=[',','.','_',x];
e=['.','o','O','-'];
y=['>',,'\\',x];
u=['<',,'/',x];
t=[' : ','[ ]','> <',d;
b=[' : ','" "',"___",d];
j=process.argv[2].split('').map(function(k){return parseInt(k)-1});
q=j[4]==1;
w=j[5]==1;
console.log([
    h[j[0]].replace(/(.*)\n(.*)/g, " $1\n $2"),
    (q?'\\':x)+'('+e[j[2]]+n[j[1]]+e[j[3]]+')'+(w?'/':x),
    (!q?u[j[4]]:x)+'('+t[j[6]]+')'+(!w?y[j[5]]:x),
    x+'('+b[j[7]]+')'].join('\n'));
```
run with `node snowman.js 33232124`
[Answer]
# Pyth, 203 bytes
```
M@GCHgc"  ___
  ___
   _"bhzgc" (_*_)
 _===_
 .....
  /_\\"bhzs[g"  \ "@z4\(g"-.oO"@z2g" ,._"@z1g"-.oO"@z3\)g"  / "@z5)s[g" < /"@z4\(gc"
 :
] [
> <"b@z6\)g" > \\"@z5)++" ("gc"
 :
\" \"
___"bez\)
```
Lol. Try it online: [Pyth Compiler/Executor](https://pyth.herokuapp.com/?code=M%40GCHgc%22%20%20___%0A%0A%20%20___%0A%20%20%20_%22bhzgc%22%20(_*_)%0A%20_%3D%3D%3D_%0A%20.....%0A%20%20%2F_%5C%5C%22bhzs%5Bg%22%20%20%5C%20%22%40z4%5C(g%22-.oO%22%40z2g%22%20%2C._%22%40z1g%22-.oO%22%40z3%5C)g%22%20%20%2F%20%22%40z5)s%5Bg%22%20%3C%20%2F%22%40z4%5C(gc%22%20%20%20%0A%20%3A%20%0A%5D%20%5B%0A%3E%20%3C%22b%40z6%5C)g%22%20%3E%20%5C%5C%22%40z5)%2B%2B%22%20(%22gc%22%20%20%20%0A%20%3A%20%0A%5C%22%20%5C%22%0A___%22bez%5C)&input=33232124&debug=0)
### Explanation
First I define a helper function `g`, which takes a list and a char as input, converts the char into its ASCII-value and takes correspondent element (modular wrapping).
```
M@GCH  def g(G,H): return G[ord(H)]
```
The other things is just printing line by line. For instance the first line is:
```
 c"  ___\n\n  ___\n   _"b     split the string "  ___\n\n  ___\n   _" at "\n"
                         hz   first char in input
g                             apply g and print
```
Btw. I experimented a little bit with `.F"{:^7}"`, which centers a string. Using it, I could save a few spaces in my code, but it doesn't save any bytes at the end.
[Answer]
# Haskell, ~~361~~ ~~306~~ 289 bytes
```
o l a b=take a$drop((b-1)*a)l
n="\n"
p i=id=<<["  ",o"    \n _===____ \n ..... _  \n  /_\\ ___ \n (_*_)"11a,n,o" \\  "1e,o"(.(o(O(-"2c,o",._ "1 b,o".)o)O)-)"2d,o" /  "1f,n,o"< / "1e,o"( : )(] [)(> <)(   )"5g,o"> \\ "1f,n," (",o" : )\" \")___)   )"4h]where[a,b,c,d,e,f,g,h]=map(read.(:[]))i
```
Usage:
```
putStrLn $ p "12333321"
 _===_
 (O.O)
/(] [)\
 ( : )
```
How it works: index every element of the list of `[hat options, left upper arm options, left eye options, ..., base options]` with the corresponding input number and concatenate it into a single list. I've split the left and right arm into an upper and lower part, so that I can build the snowman line by line.
My favorite is the classic `11112211`.
Edit: switched from list of strings to strings for the parts (hat, eye, ...). Needs a second parameter, the length of the substring to take.
Edit II: extracted common substrings
[Answer]
# R, ~~436~~ 437 bytes
Here's my first try on [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), using R which isn't the shortest but still fun. At least I'm beating JavaScript (for now)...
```
H=c("_===_"," ___\n .....","  _\n  /_\\"," ___\n (_*_)")
N=c(",",".","_"," ")
L=c(".","o","O","-")
X=c(" ","\\"," "," ")
S=c("<"," ","/"," ")
Y=c(" ","/"," ","")
U=c(">"," ","\\","")
T=c(" : ","] [","> <","   ")
B=c(" : ","\" \"","___","   ")
f=function(x){i=as.integer(strsplit(x,"")[[1]]);cat(" ",H[i[1]],"\n",X[i[5]],"(",L[i[3]],N[i[2]],L[i[4]],")",Y[i[6]],"\n",S[i[5]],"(",T[i[7]],")",U[i[6]],"\n"," (",B[i[8]], ")",sep="")}
```
Testing:
```
> f("12344321")
 _===_
 (O.-)
 (] [)\
 ( : )
```
I actually struggled with `X` and `Y` being multilined but with stuff in between, ended up separating each line in (`X`, `S`) and (`Y`, `U`).
`function` and conversion from string to integer are also very verbose.
**Edit 436 => 437**
Had to fix a missing empty space noticed by @OganM
I could reduce to 428 replacing the line breaks between variables with `;`, but the "one-lined" code looks so bad and unreadable I won't be that greedy.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 199 bytes
Inspired by [Reto Koradi](https://codegolf.stackexchange.com/a/49914/80745) and [anatolyg](https://codegolf.stackexchange.com/a/49941/80745).
```
for($t='  0 _ _0 ___0 _ _
 0_. (0=./_0=._*0=.\_0_. )
4 \  (2.oO-1,._ 3.oO-)5 /
4< / (6 ]> 6:   6 [< )5> \
 (7 "_ 7: _ 7 "_ )';$d=$t[$i++];$r+="$d"){if($d-ge48){$d=$t[$i+"$args"["$d"]-49]
$i+=4}}$r
```
[Try it online!](https://tio.run/##RZBbboMwFET/vYqRaxVTCuHhkJbE2UIXQJCFxKNItESGtIoQa6cmQen5GM9cj2XZ5@631P1n2bYzqyAxzlWnORukBfhQUEaUujkCX3ngvvQ2yoh6MXJSy8wmAieAh1734QavnkK0OHuLDUDEwSw8RnZEnACIkR5gb4/mCAHfgSrsEnPBzdnWnhWSDSlrHCfbM@1Iygpqj03FWeHWpXizx0eDslzXPU2XSuaK94yYoRTTxPQ8kWfzIiswCBEE1j1GURiFQSis/92FNYYrj/KdNYoV8zVP@Lqiyn863QxlAtq3ZXm@Ql/6vsm/UV9yXdD5Dw "PowerShell – Try It Online")
Note: The line 3 has 2 trail spaces, line 4 has a trail space.
My favorite is `44444444` "sleepy russian guard":
```
 ___
(_*_)
(- -)
(   )
(   )
```
[Answer]
# CJam, ~~200~~ 191 bytes
This can surely be golfed a lot. (Specially if I base encode it). But here goes for starters:
```
7S*"_===_  ___  .....   _    /_\   ___  (_*_)"+6/2/Nf*",._ "1/".oO-"1/_" <\  /   >/  \  "2/4/~" : ] [> <    : \" \"___   "3/4/~]l~Ab:(]z::=:L0=N4{L=}:K~0='(2K1K3K')5K0=N4K1='(6K')5K1=NS'(7K')
```
Input goes into STDIN. For example, input `23232223` gives:
```
  ___
 .....
\(o_O)/
 (] [)
 (___)
```
[Try it online here](http://cjam.aditsu.net/#code=7S*%22_%3D%3D%3D_%20%20___%20%20.....%20%20%20_%20%20%20%20%2F_%5C%20%20%20___%20%20(_*_)%22%2B6%2F2%2FNf*%22%2C._%20%221%2F%22.oO-%221%2F_%22%20%3C%5C%20%20%2F%20%20%20%3E%2F%20%20%5C%20%20%222%2F4%2F~%22%20%3A%20%5D%20%5B%3E%20%3C%20%20%20%20%3A%20%5C%22%20%5C%22___%20%20%20%223%2F4%2F~%5Dl~Ab%3A(%5Dz%3A%3A%3D%3AL0%3DN4%7BL%3D%7D%3AK~0%3D'(2K1K3K')5K0%3DN4K1%3D'(6K')5K1%3DNS'(7K')&input=33232124)
[Answer]
## C, ~~233~~ 230 bytes
```
char*t="  0 _ _0 ___0 _ _   0_. (0=./_0=._*0=.\\_0_. ) 4 \\  (2.oO-1,._ 3.oO-)5 /  4< / (6 ]> 6:   6 [< )5> \\  (7 \"_ 7: _ 7 \"_ ) ";i,r,d;f(char*p){while(r++<35){d=t[i]-48;putchar(t[d<0?i:i+p[d]-48]);i+=d<0?1:5;r%7?0:puts("");}}
```
With newlines and whitespace for better readability:
```
char* t = "  0 _ _0 ___0 _ _   0_. (0=./_0=._*0=.\\_0_. ) 4 \\  (2.oO-1,._ 3.oO-)5 /  4< / (6 ]> 6:   6 [< )5> \\  (7 \"_ 7: _ 7 \"_ ) ";
i, r, d;
f(char* p)
{
    while (r++ < 35)
    {
        d = t[i] - 48;
        putchar(t[d < 0 ? i : i + p[d] - 48]);
        i += d < 0 ? 1 : 5;
        r % 7 ? 0 : puts("");
    }
}
```
The whole thing is fairly brute force. It uses a table that contains one entry for each of the 35 (5 lines with length 7) characters. Each entry in the table is either:
* A constant character: , `(`, `)`. Length of table entry is 1 character.
* Index of body part, followed by the 4 possible characters depending on the part selection in the input. Length of table entry is 5 characters.
The code then loops over the 35 characters, and looks up the value in the table.
[Answer]
# Python 3, ~~349~~ ~~336~~ ~~254~~ 251 bytes
So much for doing my thesis.
Here's the content of the file *snowman.py*:
```
l='_===_| ___\n .....|  _\n  /_\| ___\n (_*_)| : |] [|> <|   |>| |\| | : |" "|___|   '.split('|')
l[4:4]=' \  .oO-,._ .oO- /  < / '
def s(a):print(' {}\n{}({}{}{}){}\n{}({}){}\n ({})'.format(*[l[4*m+int(a[int('0421354657'[m])])-1]for m in range(10)]))
```
And this is how I conjure my favourite snowman:
```
s('11112311')
 _===_
\(.,.)
 ( : )\
 ( : )
```
## Explanation
```
# Create a list containing the 4 * 10 body parts of the snowman in order of drawing:
#   hats,
#   upper left arms, left eyes, noses, right eyes, upper right arms,
#   lower left arms, torso's, lower right arms,
#   bases
l='_===_| ___\n .....|  _\n  /_\| ___\n (_*_)| : |] [|> <|   |>| |\| | : |" "|___|   '.split('|')
l[4:4]=' \  .oO-,._ .oO- /  < / '
# This is the function that draws the snowman
# All the lines of this function are golfed in a single statement, but seperated here for clearity
def s(a):
    # In this list comprehension I put the elements of l that are chosen according to the parameters
    list_comprehension = []
    # m is the number of the body part to draw
    for m in range(10):
        # Get the index for the choice of the m-th bodypart
        # (example: the 2nd bodypart (m = 1: the upper left arm) is in the 4th place of the arguments list)
        choice_index = int('0421354657'[m])
        # n is the parameter of the current bodypart
        n = int(a[choice_index]) - 1
        # Add the body part from list l to the list comprehenseion
        list_comprehension.append( l[4 * m + n] )
    # Print the list comprehension with the static parts
    print(' {}\n{}({}{}{}){}\n{}({}){}\n ({})'.format(*list_comprehension))
```
[Answer]
# R 414 Bytes
Slightly modified version of Molx's version
```
W =c("_===_"," ___\n .....","  _\n  /_\\"," ___\n (_*_)",",",".","_"," ",".","o","O","-"," ","\\"," "," ","<"," ","/"," "," ","/"," ","",">"," ","\\",""," : ","] [","> <","   "," : ","\" \"","___","   ")
f=function(x){i=as.integer(strsplit(x,"")[[1]]);cat(" ",W[i[1]],"\n",W[i[5]+12],"(",W[i[3]+8],W[i[2]+4],W[i[4]+8],")",W[i[6]+20],"\n",W[i[5]+16],"(",W[i[7]+28],")",W[i[6]+24],"\n"," (",W[i[8]+32], ")",sep="")}
```
Just merged the seperate variables into one. Shawing of some space that was used for `X=c(` routine.
[Answer]
# Haskell, 333 bytes
My first submission! Builds the snowman from top to bottom, left to right. I split the arms into two functions for each arm, the part next to head and the part next to the body.
The function s takes a list of integers and concatenates the output of the functions which produce the body parts given correct sublists of the input.
```
a=y["\n _===_\n","  ___ \n .....\n","   _  \n  /_\\ \n","  ___ \n (_*_)\n"]
d=y",._ "
c=y".oO-"
e=y"< / "
j=y" \\  "
f=y"> \\ "
k=y" /  "
y w n=w!!(n-1)
h=y[" : ","] [","> <","   "]
b=y[" ( : ) \n"," (\" \") \n"," (___) \n"," (   ) \n"]
s(m:x:o:p:n:q:t:l:_)=putStr$a m++j x:'(':c o:d n:c p:')':k q:'\n':e x:'(':h t++')':f q:'\n':b l
```
It relies on the function
```
y :: [a] -> Int -> a
y w n=w!!(n-1)
```
which returns the nth element of the list it is given. This allows for the list of hats in a, as well as things like
```
k=y" /  "
```
all of these functions use a beta reduction so their argument is passed as the index to the y function.
Output:
```
λ> s $ repeat 1
 _===_
 (.,.)
<( : )>
 ( : )
λ> s $ repeat 2
  ___
 .....
\(o.o)/
 (] [)
 (" ")
λ> s $ repeat 3
   _
  /_\
 (O_O)
/(> <)\
 (___)
λ> s $ repeat 4
  ___
 (_*_)
 (- -)
 (   )
 (   )
```
[Answer]
# JavaScript (ES6), 247
Not as good ad @NinjaBearMonkey's :(
Test in snippet (with Firefox)
```
S=p=>([h,n,c,d,l,r,t,b,e,x]=[...p,' .oO-',`1_===_1 ___
 .....1  _
  /_\\1 ___
 (_*_)1 : 1] [1> <1   1 : 1" "1___1   `.split(1)],` ${x[h]}
${'  \\  '[l]}(${e[c]+' ,._ '[n]+e[d]})${'  /  '[r]}
${' < / '[l]}(${x[3-~t]})${' > \\ '[r]}
 (${x[7-~b]})`)
// TEST //
function go()
{
  var n=N.value
  if (/^[1-8]{8}$/.test(n)) {
    s=S(n)
    OUT.innerHTML = s+'\n'+n+'\n\n'+ OUT.innerHTML
  }
  else N.focus()
}

```
```
<input id=N maxlength=8><button onclick="go()">Test</button>
<pre id=OUT></pre>
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~137~~ ~~135~~ ~~128~~ ~~122~~ 121 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
…( )7ÝJ»•αγʒδÓ₂©8¥ŽQxΣxêÿ•sÅвJIvN”</[(
._-=:"ÆŸ,*”º•DùÙÂ+;Èγтáì³ÓW©ÎÂ_`ƒ≠îj*ΓçÊ~ÞÒ¸β¦oåb/õ47/vÎΓ”›≠øØZµλÝº•20вè¶¡Nè4äyè.;
```
-6 bytes thanks to *@Grimy*.
[Try it online](https://tio.run/##Ad0AIv9vc2FiaWX//@KApiggKTfDnUrCu@KAos6xzrPKks60w5PigoLCqTjCpcW9UXjOo3jDqsO/4oCic8OF0LJKSXZO4oCdPC9bKAouXy09OiLDhsW4LCrigJ3CuuKAokTDucOZw4IrO8OIzrPRgsOhw6zCs8OTV8Kpw47Dgl9gxpLiiaDDrmoqzpPDp8OKfsOew5LCuM6ywqZvw6ViL8O1NDcvdsOOzpPigJ3igLriiaDDuMOYWsK1zrvDncK64oCiMjDQssOowrbCoU7DqDTDpHnDqC47//80NDExNDQzMg) or [verify a few more test cases](https://tio.run/##LY09S0JRHMb38ymiJbN7tfMChhYuTQ5CU1CDKTQUkYMg3qi4XCiqwcG71GBkpWlEkKaYEsF5sKHhYF/hfpHbuXl/w394Xv5PsZQv7O36x2UrvZA0fM9uReYWE6hn5Niz79Wb6v3U1Dtcz3FkZ0U2J58bFfVQwTO@tF/C2bSbscpZz66vxrcjJJYz15LzOJ8MjajW5EiH1vGBGzhLKVyo3q@DBl5kD@6m7KAKJ7fzXfMu7/C6H1UunnB1ilvU5FB1ZauIZiGOvkjEy6gqVz/07FEQHuJ6S/bVGLMFtjztoi0HspFFW@DRQjuW8k8MOUj7lDNOKWVEHyoEpYRrhVEmCGUB2hIsVDgTgmuI@IdrSwQtPqsHEBZCeEgYFsI3zcOieZA/sv4A).
**Explanation:**
We first create the template-string:
```
…( )         # Push string "( )"
7ÝJ          # Push a list in the range [0,7] joined together: "01234567"
»            # Join both by a newline: "( )\n01234567"
•αγʒδÓ₂©2°ćì₂òη₆½•
             # Push compressed integer 80545642885242518310229085147411483894
 s           # Swap to get the earlier created string at the top of the stack
  Åв         # Convert the large integer to base-"( )\n01234567",
             # which basically converts to base-length, and indexes into the string:
             #  [" ","0","0","0","0","0","\n"," ","0","0","0","0","0","\n","4","(","2","1","3",")","5","\n","4","(","6","6","6",")","5","\n"," ","(","7","7","7",")"]
    J        # And join it to a single string: " 00000\n 00000\n4(213)5\n4(666)5\n (777)"
```
Which looks like this:
```
 00000
 00000
4(213)5
4(666)5
 (777)
```
Then I loop over the digits of the input:
```
I            # Get the input
 v           # Loop `y` over each of its digits:
```
And do the following:
Push the (0-indexed) index `N` of the list:
```
  N          # Push the index of the loop
```
Push all possible parts as a list of character lists:
```
  ”</[(
  ._-=:"ÆŸ,*”
            "# Push dictionary string "</[(\n._-=:" Oo,*"
   º         # Mirror each line: "</[()]\>\n._-=:" Oo,**,oO ":=-_."
  •DùÙÂ+;Èγтáì³ÓW©ÎÂ_`ƒ≠îj*ΓçÊ~ÞÒ¸β¦oåb/õ47/vÎΓ”›≠øØZµλÝº•
             # Push compressed integer 492049509496347122906361438631265789982480759119518961177677313610613993948059787418619722816092858096158180892708001681647316210
   20в       # Convert it to Base-20 as list: [15,10,10,10,15,3,10,19,10,4,15,15,15,15,15,10,12,12,12,10,15,10,10,10,15,9,9,9,9,9,15,15,10,15,15,15,1,10,6,15,8,15,18,9,10,8,11,9,17,16,8,11,9,17,16,8,15,15,15,0,6,15,15,1,8,15,15,15,7,1,15,15,6,8,15,15,15,15,13,15,5,15,2,7,15,0,8,15,15,15,15,13,15,14,15,14,10,10,10]
      è      # Index each into the string: [" ","_","_","_"," ","(","_","*","_",")"," "," "," "," "," ","_","=","=","=","_"," ","_","_","_"," ",".",".",".",".","."," "," ","_"," "," "," ","/","_","\"," ","\n"," ",",",".","_","\n","-",".","o","O","\n","-",".","o","O","\n"," "," "," ","<","\"," "," ","/","\n"," "," "," ",">","/"," "," ","\","\n"," "," "," "," ",":"," ","]"," ","[",">"," ","<","\n"," "," "," "," ",":"," ","""," ",""","_","_","_"]
       ¶¡    # Split it by the newline character: [[" ","_","_","_"," ","(","_","*","_",")"," "," "," "," "," ","_","=","=","=","_"," ","_","_","_"," ",".",".",".",".","."," "," ","_"," "," "," ","/","_","\"," "],[" ",",",".","_"],["-",".","o","O"],["-",".","o","O"],[" "," "," ","<","\"," "," ","/"],[" "," "," ",">","/"," "," ","\"],[" "," "," "," ",":"," ","]"," ","[",">"," ","<"],[" "," "," "," ",":"," ","""," ",""","_","_","_"]]
```
Use the loop index `N` to get the character-list of the part we are currently working with:
```
  Nè         # Index the loop index into it
             #  i.e. 6 → [" "," "," "," ",":"," ","]"," ","[",">"," ","<"]
```
Then split the character list into four equal part, and use the input-digit `y` (which is 1-indexed) to index into it. (NOTE: Since 05AB1E is 0-indexed, but the input is 1-indexed, it would be logical to decrease the digit by 1 before indexing. However, since 05AB1E has automatic wraparound (i.e. indexing `3` in list `[1,3,5]` will result in `1`), I simply rotated the parts once so parts with nr 4 in the challenge description, are at the front of the lists.)
```
    4ä       # Split it into 4 equal parts
             #  i.e. [[" "," "," "],[" ",":"," "],["]"," ","["],[">"," ","<"]]
      yè     # Index the input-digit `y` into it (with automatic wraparound)
             #  i.e. 4 → [" "," "," "]
```
And then replace the 0-indexed index of the loop we pushed at first, one by one with the part-characters:
```
  .;         # Replace first; every index of the loop `N` in the template-string
             # is replaced one by one with the characters
```
And in the end the result is output implicitly.
[See this 05AB1E tip of mine (section *How to compress large integers?* and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand how the compression parts work.
---
As for my favorite, it's still [the same 'snow rabbit' as 1.5 year ago when I posted my Java solution](https://codegolf.stackexchange.com/a/125628/52210):
```
44114432:
   _
 (_*_)
 (. .)
 (> <)
 (" ")
```
[Answer]
# Java 8, ~~548~~ ~~545~~ ~~432~~ ~~401~~ ~~399~~ 397 bytes
```
a->{int q=50,H=a[0]-49,N=a[1],L=a[2],R=a[3],X=a[4],Y=a[5];return"".format(" %s%n %s%n%c(%c%c%c)%c%n%c(%s)%c%n (%s)",H<1?"":H%2<1?" ___":"  _","_===_s.....s /_\\s(_*_)".split("s")[H],X==q?92:32,L<q?46:L<51?111:L<52?79:45,N<q?44:N<51?46:N<52?95:32,R<q?46:R<51?111:R<52?79:45,Y==q?47:32,X<q?60:32+X%2*15,"   s : s] [s> <".split("s")[a[6]%4],92-(Y%3+Y%6/4)*30,"   s : s\" \"s___".split("s")[a[7]%4]);}
```
-2 bytes thanks to *@ceilingcat*.
[Try it here.](https://tio.run/##dVNNb@IwEL33V4wsRUrApPgjIAIpWu2FA5sDvYAgirxpupsuBIhNparit7PjkN0WRF8kz9jzZvzisV/Uq@psd3n58vTnlK2V1vBDFeX7HUBRmrx6VlkOsZ0CPJqqKH9B5ma/VbVMQHlDXD/e4aCNMkUGMZQQwUl1Ht4xG/ZR0KWTSC27SUcOaIweS@gUDU/oDI1I6ByNTOgCTZAMq9wcqpIQ/3lbbZRxCTjaKevByVwns5@HQz3TtQfWIXQyYmNCwonDrQNpmpKQAKSEkjSKolT7Fhru09VKu2kr9Yivd@sC99DEW06skmg/HvBQcDod7ceyF05HARszxqzDx/1BKAMa25AMYxtCSmwjg8Amzc5Js39Js4@khS0t@5Y1R1avi1577vAWCyiKBA0h6ASW@gFGF7LUspc4eDwD3nEXjmgvnN699Fqi@5G2IrAi2v7vZWLfJnrD42loG7Q7/Fxjg5o@vW6LJ9hgn91zT@tmnptsco0lmOAC/4GTusX/VxFSMna5KpDLGZdXXG5xXUHyW1zBpRSIK24NcV1BWg3ihjKLy1Xe4FrvGbd2k42yz5e6Pqya1DwA3RzV45s2@cbfHoy/w4BZl65u461r6t4Il37mat9sv@MD@lZV6s31vK/ZjZLj6S8)
**Explanation:**
```
a->{             // Method with character-array parameter and String return-type
  int q=50,      //  Temp integer with value 50 to reduce the byte-count
      H=a[0]-49, //  The hat-character as unicode value minus 49: 1=0; 2=1; 3=2; 4=3
      N=a[1],L=a[2],R=a[3],X=a[4],Y=a[5];
                 //  Most of the other characters as unicode values: 1=49; 2=50; 3=51; 4=52
  return"".format(" %s%n %s%n%c(%c%c%c)%c%n%c(%s)%c%n (%s)",
                                               // Return the snowman with:
    H<1?"":H%2<1?" ___":"  _",                 //  The top of the hat
    "_===_s.....s /_\\s(_*_)".split("s")[H],   //  + the bottom of the hat
    X==q?92:32,                                //  + the top of the left arm
    L<q?46:L<51?111:L<52?79:45,                //  + the left eye
    N<q?44:N<51?46:N<52?95:32,                 //  + the nose
    R<q?46:R<51?111:R<52?79:45,                //  + the right eye
    Y==q?47:32,                                //  + the top of the right arm
    X<q?60:32+X%2*15,                          //  + the bottom of the left arm
    "   s : s] [s> <".split("s")[a[6]%4],      //  + the torso
    92-(Y%3+Y%6/4)*30,                         //  + the bottom of the right arm
    "   s : s\" \"s___".split("s")[a[7]%4]);}  //  + the feet
```
**My favorite:**
```
44114432:
   _
 (_*_)
 (. .)
 (> <)
 (" ")
```
I don't know why, but it looks kinda cute. Like a bunny with a Russian hat instead of ears.
[Answer]
# C# 9.0 (.NET 4.8) - ~~1813 1803 1821 1815~~ 1812+30=~~1843 1833 1851 1845~~ 1842 bytes
A Windows Forms application; likely can be improved on in terms of size. Contains a massive one-liner. The extra 30 bytes is from adding `<LangVersion>9.0</LangVersion>` to the project file.
```
using System;using System.Windows.Forms;class P:Form{string[]h={$@"
_===_",$@"___
.....",$@"_
/_\",$@"___
(_*_)"},s={" : ","] [","> <","   "},z={" : ","\" \"","___","   "};string n=",._ ",e=".oO-",x="< / ",y="> \\ ";TextBox t;Button b,d;Label l;[STAThread]static void Main(){Application.EnableVisualStyles();Application.SetCompatibleTextRenderingDefault(false);Application.Run(new P());}P(){t=new();b=new();d=new();l=new();SuspendLayout();t.Location=new(0,0);t.MaxLength=8;t.Size=new(269,23);t.TabIndex=0;b.Location=new(-1,22);b.Size=new(200,25);b.TabIndex=1;b.Text="Build the snowman!";b.UseVisualStyleBackColor=true;b.Click+=m;d.Location=new(198,22);d.Size=new(72,25);d.TabIndex=2;d.Text="Random";d.UseVisualStyleBackColor=true;d.Click+=(_,_)=>{int a=0;Random r=new();for(int i=0;i<8;i++)a+=r.Next(1,5)*(int)Math.Pow(10,i);m(a.ToString(),null);};l.AutoSize=false;l.Font=new("Consolas",9);l.Location=new(0,41);l.Size=new(269,73);l.TextAlign=System.Drawing.ContentAlignment.MiddleCenter;Font=new("Segoe UI",9);ClientSize=new(269,114);Controls.Add(l);Controls.Add(t);Controls.Add(b);Controls.Add(d);MaximizeBox=false;FormBorderStyle=FormBorderStyle.FixedSingle;Text="Snowman Maker";l.SendToBack();t.BringToFront();ResumeLayout(true);}void m(object q,EventArgs k){t.Enabled=false;b.Enabled=false;d.Enabled=false;if(q is string j)t.Text=j;if(t.Text.Length!=8||!int.TryParse(t.Text,out _))MessageBox.Show("Invalid input format.");else{int[]a=new int[8];for(int i=0;i<8;i++){a[i]=t.Text[i]-'0'-1;if(a[i]>3){MessageBox.Show("Invalid input format.");t.Enabled=true;b.Enabled=true;d.Enabled=true;return;}}l.Text=$@"{h[a[0]]}
{(a[4]==1?'\\':' ')}({e[a[2]]}{n[a[1]]}{e[a[3]]}){(a[5]==1?'/':' ')}
{x[a[4]]}({s[a[6]]}){y[a[5]]}
({z[a[7]]})";}t.Enabled=true;b.Enabled=true;d.Enabled=true;}}
```
A more readable version, with comments (though with the same confusing variable naming):
```
using System;
using System.Windows.Forms;
class Program : Form
{
    string[] h = {$@"
_===_",$@"___
.....",$@"_
/_\",$@"___
(_*_)"}, // Hats
    s = {" : ","] [","> <","   "}, // Torso
    z = {" : ","\" \"","___","   "}; // Base
    string n = ",._ ", e = ".oO-", x = "< / ", y = "> \\ "; // Nose, eyes, left arm, right arm
    //Controls
    TextBox t;
    Button b, d;
    Label l;
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.Run(new Program()); // I put all the control code in Program; please don't do this in normal code
    }
    Program()
    {
        // Initialize everything
        t = new(); // Taking advantage of the short contructors in C# 9.0
        b = new();
        d = new();
        l = new();
        SuspendLayout();
        // TextBox properties
        t.Location = new(0, 0);
        t.MaxLength = 8;
        t.Size = new(269, 23);
        t.TabIndex = 0;
        // 'Build the snowman' button properties
        b.Location = new(-1, 22);
        b.Size = new(200, 25);
        b.TabIndex = 1;
        b.Text = "Build the snowman!";
        b.UseVisualStyleBackColor = true;
        b.Click += m;
        // 'Random' button properties
        d.Location = new(198,22);
        d.Size = new(72,25);
        d.TabIndex = 2;
        d.Text = "Random";
        d.UseVisualStyleBackColor = true;
        d.Click += (_,_) =>
        {
            int a = 0;
            Random r = new();
            for(int i = 0; i < 8; i++)
                a += r.Next(1,5) * (int)Math.Pow(10,i); // Math.Pow returns a number that satisfies 1 <= n < 5, not 1 <= n <= 5
            m(a.ToString(), null); // Since I don't need the "sender" field, I use it to send the random input. Please don't do this in a normal program.
        };
        // Label properties
        l.AutoSize = false;
        l.Font = new("Consolas", 9);
        l.Location = new(0, 41);
        l.Size = new(269, 73);
        l.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // This lets us omit some spaces, while making the form look nicer as well
        // Form properties
        Font = new("Segoe UI", 9);
        ClientSize = new(269, 114);
        Controls.Add(l);
        Controls.Add(t);
        Controls.Add(b);
        Controls.Add(d);
        MaximizeBox = false;
        FormBorderStyle=FormBorderStyle.FixedSingle;
        Text="Snowman Maker";
        l.SendToBack();
        t.BringToFront();
        ResumeLayout(true);
    }
    // Event handler for the 'Build the snowman' button
    void m(object sender, EventArgs k)
    {
        // Disable all the inputs, in case the user tries to mess with the data while the function is running.
        // This is probably unneeded since modern computers run so quickly, but I kept it anyway.
        t.Enabled = false;
        b.Enabled = false;
        d.Enabled = false;
        if(sender is string j) // Accept input from 'Random' button
            t.Text=j;
        if(t.Text.Length != 8|| !int.TryParse(t.Text, out _)) // Discard the out parameter since we don't need it
            MessageBox.Show("Invalid input format.");
        else
        {
            int[] a = new int[8];
            // Read from the TextBox.
            for (int i = 0; i < 8; i++)
            {
                a[i] = t.Text[i] - '0' - 1;
                if(a[i] > 3)
                {
                    MessageBox.Show("Invalid input format.");
                    // Re-enable the inputs and cancel the operation.
                    t.Enabled = true;
                    b.Enabled = true;
                    d.Enabled = true;
                    return;
                }
            }
            // Set the label text; uses an interpolated multiline string ($ makes it interpolated, @ makes it accept newlines and automatically escape characters (excluding " ))
            l.Text=$@"{h[a[0]]}
{((a[4] == 1) ? '\\' : ' ')}({e[a[2]]}{n[a[1]]}{e[a[3]]}){((a[5] == 1) ? '/' : ' ')}
{x[a[4]]}({s[a[6]]}){y[a[5]]}
({z[a[7]]})";
        }
        t.Enabled = true;
        b.Enabled = true;
        d.Enabled = true;
    }
}
```
The compact version was so painful to edit (I absolutely hate scrolling left and right) that I split it into a lot of lines and removed the unnecessary newlines after I was done with it:
```
using System;using System.Windows.Forms;class P:Form{string[]h={$@"
_===_",$@"___
.....",$@"_
/_\",$@"___
(_*_)"},s={" : ","] [","> <","   "},z={" : ","\" \"","___","   "};string n=",._ ",e=".oO-",x="< / ",y="> \\ ";TextBox t;
Button b,d;Label l;[STAThread]static void Main(){Application.EnableVisualStyles();Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new P());}P(){t=new();b=new();d=new();l=new();SuspendLayout();t.Location=new(0,0);t.MaxLength=8;t.Size=new(269,23
);t.TabIndex=0;b.Location=new(-1,22);b.Size=new(200,25);b.TabIndex=1;b.Text="Build the snowman!";b.UseVisualStyleBackColor=true;b.Click+=m;d.
Location=new(198,22);d.Size=new(72,25);d.TabIndex=2;d.Text="Random";d.UseVisualStyleBackColor=true;d.Click+=(_,_)=>{int a=0;Random r=new();
for(int i=0;i<8;i++)a+=r.Next(1,5)*(int)Math.Pow(10,i);m(a.ToString(),null);};l.AutoSize=false;l.Font=new("Consolas",9);l.Location=new(0,41);
l.Size=new(269,73);l.TextAlign=System.Drawing.ContentAlignment.MiddleCenter;Font=new("Segoe UI",9);ClientSize=new(269,114);Controls.Add(l);
Controls.Add(t);Controls.Add(b);Controls.Add(d);FormBorderStyle=FormBorderStyle.FixedSingle;MaximizeBox=false;Text="Snowman Maker";l.
SendToBack();t.BringToFront();ResumeLayout(true);}void m(object q,EventArgs k){t.Enabled=false;b.Enabled=false;d.Enabled=false;if(q is string
j)t.Text=j;if(t.Text.Length!=8||!int.TryParse(t.Text,out _))MessageBox.Show("Invalid input format.");else{int[]a=new int[8];for(int i=0;i<8;
i++){a[i]=t.Text[i]-'0'-1;if(a[i]>3){MessageBox.Show("Invalid input format.");t.Enabled=true;b.Enabled=true;d.Enabled=true;return;}}l.Text=$@"{h[a[0]]}
{(a[4]==1?'\\':' ')}({e[a[2]]}{n[a[1]]}{e[a[3]]}){(a[5]==1?'/':' ')}
{x[a[4]]}({s[a[6]]}){y[a[5]]}
({z[a[7]]})";}t.Enabled=true;b.Enabled=true;d.Enabled=true;}}
```
To run this code, make a Windows Forms Application project in Visual Studio for .NET Framework 4.8 (or whatever editor you use for C#), remove Form1.cs and delete it from the project, save the project, and add `<LangVersion>9.0</LangVersion>` to the project file. Then, you can copy the code into Program.cs (overwrite everything) and run it.
[Answer]
# F#, 369 bytes
```
let f(g:string)=
 let b=" "
 let p=printfn
 let i x=int(g.[x])-49
 p"  %s  "["";"___";" _ ";"___"].[i 0]
 p" %s "["_===_";".....";" /_\ ";"(_*_)"].[i 0]
 p"%s(%c%c%c)%s"[b;"\\";b;b].[i 4]".oO-".[i 2]",._ ".[i 1]".oO-".[i 3][b;"/";b;b;b].[i 5]
 p"%s(%s)%s"["<";b;"/";b].[i 4][" : ";"] [";"> <";"   "].[i 6][">";b;"\\";b].[i 5]
 p" (%s) "[" : ";"\" \"";"___";"   "].[i 7]
```
[Try it online!](https://tio.run/##TVDRaoQwEHz3K5YFQUvNnV7a0tP41uf2PYZwHqcIrYqRcv16uxttMYEwm52ZbKZxyXWYbsvyeZuhidqzm6eub2MVAN/UCgFXOKqROnPTr2UHd0Vl1Ap9N3EiXwMYESB0AKgRc7TW0gkWNmyE7uBoPI1YRLJKKeYIXsw92IrZkX2w8Z4fuii88o5Dh7rOsaowr/PaU6RBMbwnyDgz@CjoRcbp7v5kWHXwok329O/svCsW3PWczVYjnHkcA5rOEgoekX7n28/ULr3Cz7KzBHbk763qCqHaxfGnfzGLLt76efr5GCjG0gQc6tel6@Eytd9A@TceCc0ZHJclk1kmZZqefgE)
Because `g` uses an array accessor, I need to explicitly specify the type in the function definition as a `string`, which is why the function definition has `(g:string)`.
Apart from that, it's usually an array of `strings` accessed by an index. The hat, left and right arms which would go on separate lines are split into separate top and bottom arrays. The `i` function changes a number in the argument `g` into the array index. And the letter `b` replaces the one-space strings in the arrays.
Great challenge! My favourite snowman is probably `242244113`:
```
  ___
 .....
 (o o)
 ( : )
 ( : )
```
im watching you
[Answer]
# PHP, 378 bytes
```
<?$f=str_split;$r=$f($argv[1]);$p=[H=>'   _===____..... _  /_\ ___(_*_)',N=>',._ ',L=>'.oO-',R=>'.oO-',X=>' <\  /  ',Y=>' >/  \  ',T=>' : ] [> <   ',B=>' : " "___   '];echo preg_replace_callback("/[A-Z]/",function($m){global$A,$p,$r,$f;$g=$m[0];return$f($f($p[$g],strlen($p[$g])/4)[$r[array_search($g,array_keys($p))]-1])[(int)$A[$g]++];},'  HHH
 HHHHH
X(LNR)Y
X(TTT)Y
 (BBB)');
```
[Try it online!](https://tio.run/##PZBRa8IwEMff9ykOCTSZqZ3Tp9U47FMfxIH0QRdDqCWtYm1DWgcy9tXXXdjYEfL//467Izl7ssOweCWl6HqnO1uf@5g4QUpKcld9yKliMbFCpmIZAIAWQmiMiQ/QAJE@ADLVj5oFfINVfKIh4Gt0k/YtDPj23@38jMUBmwAr9p6WaA@eMk8voEAuYQE@k/xmRjDC@T6jYlOcWrDOVNoZW@eF0UVe18e8uNBRJFfhu4pGvLw1RX9uG0qu7LOq22NekxUnlhPHSRmTSpCrfFKxM/3NNf6jeKwkleK4gto0f8SiOZPEydy5/K47k7viREnFf/li7h0WMqZCXJGk56ZnZOX7xmMVf3FcVpqmD/5C2dH1Zsv2qFmWoQJNkoQFLB6GYTadYcyfv1vrn90NYfMD)
I like [wise Mr. Owl](https://www.youtube.com/watch?v=O6rHeD5x2tI) `31333342`
```
   _
  /_\
 (O,O)
/(   )\
 (" ")
```
[Answer]
## Python 2.7, 257 bytes (i think)
```
H,N,L,R,X,Y,T,B=map(int,i)
l='\n'
s=' '
e=' .o0-'
F='  \  / '
S=' < / \ >'
o,c='()'
print s+'      _ _ ___ _ _\n\n\n\n    _. (=./_=._*=.\__. )'[H::4]+l+F[X]+o+e[L]+' ,._ '[N]+e[R]+c+F[-Y]+l+S[X]+o+'  ]> :    [< '[T::4]+c+S[-Y]+l+s+o+'  "_ : _  "_ '[B::4]+c
```
where 'i' is the input as an string (e.g "13243213")
[Answer]
# Clojure (~~407~~ 402 bytes)
```
(defn a[s](let[[H N L R X Y T B](into[](map #(-(int %)49)(into[]s)))h(["""  ___""   _""  ___"]H)i([" _===_"" .....""  /_\\"" (_*_)"]H)n([","".""_"" "]N)e[".""o""O""-"]l([" ""\\"" "" "]X)m(["<"" ""/"" "]X)r(["""/"""""]Y)u([">""""\\"""]Y)t([" : ""] [""> <""   "]T)b([" : ""   ""___""   "]B)d(["""\" \""""""]B)f(str \newline)](str h f i f l "(" (e L) n (e R) ")" r f m "(" t ")" u f " (" b ")" f "  " d)))
```
Hopefully that's clear to everyone.
And if not...
Ungolfed version:
```
(defn build-a-snowman [s]
  (let [ [H N L R X Y T B] (into [] (map #(- (int %) 49) (into [] s)))
         hat1     ([""       "  ___"  "   _"   "  ___" ] H) ; first line of hats
         hat2     ([" _===_" " ....." "  /_\\" " (_*_)"] H) ; second line of hats
         nose     ([","      "."      "_"      " "     ] N)
         eye      ["."      "o"      "O"      "-"     ]
         left1    ([" "      "\\"     " "      " "     ] X) ; left arm, upper position
         left2    (["<"      " "      "/"      " "     ] X) ; left arm, lower position
         right1   ([""       "/"      ""       ""      ] Y) ; right arm, upper position
         right2   ([">"      ""       "\\"     ""      ] Y) ; right arm, lower position
         torso    ([" : "    "] ["    "> <"    "   "   ] T)
         base1    ([" : "    "   "    "___"    "   "   ] B) ; first line of base
         base2    ([""       "\" \""  ""       ""      ] B) ; second line of base
         nl       (str \newline) ]
    (str hat1 nl
         hat2 nl
         left1 "(" (eye L) nose (eye R) ")" right1 nl
         left2 "(" torso ")" right2 nl
         " (" base1 ")" nl
         "  " base2)))
```
Tests:
```
(println (a "33232124"))  ; waving guy with fez
(println (a "11114411"))  ; simple ASCII-art snowman
(println (a "34334442"))  ; mouse
(println (a "41214433"))  ; commissar with monocle
(println (a "41212243"))  ; commissar celebrating success of five-year plan
(println (a "41232243"))  ; commissar after too much vodka
```
My favorite:
34334442 - mouse
[Try it online!](https://tio.run/##bVBbT9swFH7nVxydaZI9rUNN/DKgSOteQEJMYjyAEityU4dm86WKnVbsz5djkz7AsBIdf@e7@Nit8X/GQR8ObK07B6oKkhkdq@oKbuEG7uABHuEelpL1LvpKMqu28InNEoTPXHznExE45xtWISJA0zSpQHME8or3xEGzWCxS81taiTxt6poqa740PKkcqb4iEpdkKG@5rhLyiL8QZyhNikHMrqx44JZaFxmeTp0hz0GIlnzkI8HLtE@u1Igp5IwMEkh4CRd5WpT3fHVkEsbjPVAu@Tpn1gg1vuYuecdCHKB2em96p7nMcAMd9PQbQEYX03DDwaV6xwE5wkCczVzMeCRMOoRVhgnQt6bXPDlh24Ee15BdAZZlURbzQiDnAOewV7vePcHT@Az7PtKp@h@8NcxpCTGfT4bQ263R8OP3z@vrmRoiBOf3Vrl3p4iyFEIUk8n6Mei3CjEvKLYsJ0Xrre1DUMPrGNY735oPLEUh/re02ujVoGK6SRjbVocAvoOu3@nZsybB1rwfkLLKD7NUF/UA0XuwY7uBnV//VYfDCw "Clojure – Try It Online")
[Answer]
# [Dart](https://www.dartlang.org/), 307 bytes
```
f(i,{r='.o0-',s=' : '}){i=i.split('').map((j)=>int.parse(j)-1).toList();return' ${['_===_',' ___ \n.....',' /_\\ ',' ___ \n (_*_)'][i[0]]}\n${' \\  '[i[4]]}(${r[i[2]]+',._ '[i[1]]+r[i[3]]})${' /  '[i[5]]}\n${'< /  '[i[4]]}(${[s,'] [','> <','  '][i[6]]})${'> \\ '[i[5]]}\n (${[s,'" "','___','   '][i[7]]})';}
```
[Try it online!](https://tio.run/##bZBBboMwEEX3PcUIIY3dECfYtJVKzAl6A0AWUhLJVWOQcbuxODu1CVGyyF8x/8@bb3HsrJvnM9GZtxJZv99iNkqET8CJei01G4cf7QgiZZduIOSbykobx4bOjqcwbXPKXP@lR0doaU/u1xqE1NeopJQKMwSlFDSGRcVxp5oG7j4Q9aootrWu9207NSb1CGEDMDhFcEjqbfjkbbvBjKnFz8MQTRFyGoHddf/tduFwc9YL9ZhhC3WoreAQy2FpfF/5KjbeD8BKJJCE3fDOhbgiHxHBcpr/en2ES6cNof4FYLDhr5AzSYTggue8SOgGG4O0fAxzHpXzp6HgRSGCnobFIvFATvM/ "Dart – Try It Online")
[Answer]
# Zsh, 247 bytes
[try it online!!](https://tio.run/##LY27bsMwDEV3fcWFQUBS0DhwnbaBIGbIlCFIlwB5KAJXbxk8FKjhb1dp15wuzuElf/uuFOeHI1thZukgIgb1NB2gERt5LtTJSrw1V7Z4AhYnrl/fa5z5rRYFd@Ub5ebGNmqyuCgJyEh7REyNB9u9dq05zKZCpYcnY2KMFWg4JvfThy54avJo6JroIzs6JWoznRO95ylvs6d7os9s6Pa/MFxCu3L0tW58aEdPj9lCxWEWu0VUZtQnrg/BN2MpZbvMHw)
```
(){H='_===_h ___
 .....h  _
  /_\h ___
 (_*_)'
W=' \  ' L=.oO- N=,._\  Y=' /  '
X='< / ' T=' : ] [> <   ' Z='> \ '
B=' : " "___   '
<<<" ${H[(ws:h:)$1]}
$W[$5]($L[$3]$N[$2]$L[$4])$Y[$6]
$X[$5](${T:3*($7-1):3})$Z[$6]
 (${B:3*($8-1):3})"
} ${(s::)1}
```
fav snowman:
```
43232122 Cossack dancer
  ___
 (_*_)
\(o_O)
 (] [)>
 (" ")
```
]


[Question]
      [
What general tips do you have for golfing in Python? I'm looking for ideas which can be applied to code-golf problems and which are also at least somewhat specific to Python (e.g. "remove comments" is not an answer).
Please post one tip per answer.

[Answer]
use `os.urandom()` as a random source instead of `random.randint()`
[Answer]
**Iterating over indices in a list**
Sometimes, you need to iterate over the indices of a list `l` in order to do something for each element that depends on its index. The obvious way is a clunky expression:
```
# 38 chars
for i in range(len(l)):DoStuff(i,l[i])
```
The Pythonic solution is to use `enumerate`:
```
# 36 chars
for i,x in enumerate(l):DoStuff(i,x)
```
But that nine-letter method is just too long for golfing.
Instead, just manually track the index yourself while iterating over the list.
```
# 32 chars
i=0
for x in l:DoStuff(i,x);i+=1
```
Here's some alternatives that are longer but might be situationally better
```
# 36 chars
# Consumes list
i=0
while l:DoStuff(i,l.pop(0));i+=1
# 36 chars
i=0
while l[i:]:DoStuff(i,l[i]);i+=1
```
[Answer]
# Leak variables to save on assignment
Combining with [this tip](https://codegolf.stackexchange.com/a/1020/21487), suppose you have a situation like
```
for _ in[0]*x:doSomething()
a="blah"
```
You can instead do:
```
for a in["blah"]*x:doSomething()
```
to skip out on a variable assignment. However, be aware that
```
exec"doSomething();"*x;a="blah"
```
in Python 2 is *just* shorter, so this only really saves in cases like assigning a char (via `"c"*x`) or in Python 3.
However, where things get fun is with Python 2 list comprehensions, where this idea still works due to a [quirk with list comprehension scope](https://stackoverflow.com/questions/4198906/python-list-comprehension-rebind-names-even-after-scope-of-comprehension-is-thi):
```
[doSomething()for a in["blah"]*x]
```
*(Credits to @xnor for expanding the former, and @Lembik for teaching me about the latter)*
[Answer]
# Use complex numbers to find the distance between two points
Say you have two 2-element tuples which represent points in the Euclidean plane, e.g. `x=(0, 0)` and `y=(3, 4)`, and you want to find the distance between them. The naïve way to do this is
```
d=((x[0]-y[0])**2+(x[1]-y[1])**2)**.5
```
Using complex numbers, this becomes:
```
c=complex;d=abs(c(*x)-c(*y))
```
If you have access to each coordinate individually, say `a=0, b=0, c=3, d=4`, then
```
abs(a-c+(b-d)*1j)
```
can be used instead.
[Answer]
# Use *f-strings*
Python 3.6 [introduces a new string literal](https://docs.python.org/3.6/reference/lexical_analysis.html#f-strings) that is vastly more byte-efficient at variable interpolation than using `%` or `.format()` in non-trivial cases. For example, you can write:
```
l='Python';b=40;print(f'{l}, {b} bytes')
```
instead of
```
l='Python';b=43;print('%s, %d bytes'%(l,b))
```
[Answer]
## Abuse `==` short circuiting
If you have:
* A function with a side effect (such as `print`);
* That you only want to run if some condition is (or is not) met.
Then you might be able to use `==` over `or`  to save a byte.
Here's printing all numbers `n` under 100 that have `f(n)` less than 2:
```
# Naive
for n in range(100):f(n)<2and print(n)
# Invert condition
for n in range(100):f(n)>1or print(n)
# Use ==
for n in range(100):f(n)<2==print(n)
```
[Answer]
# Avoid `list.insert`
Instead of `list.insert`, appending to a slice is shorter:
```
L.insert(i,x)
L[:i]+=x,
```
For example:
```
>>> L = [1, 2, 3, 4]
>>> L[:-2]+=5,
>>> L
[1, 2, 5, 3, 4]
>>> L[:0]+=6,
>>> L
[6, 1, 2, 5, 3, 4]
```
[Answer]
## Store 8-bit numbers compactly as a bytes object in Python 3
In Python 3, a *bytes object* is written as a string literal preceded by a `b`, like `b"golf"`. It acts much like a tuple of the `ord` values of its characters.
```
>>> l=b"golf"
>>> list(l)
[103, 111, 108, 102]
>>> l[2]
108
>>> 108 in l
True
>>> max(l)
111
>>> for x in l:print(x)
103
111
108
102
```
Python 2 also has bytes objects but they act as strings, so this only works in Python 3.
This gives a shorter way to express an explicit list of numbers between 0 to 255. Use this to hardcode data. It uses one byte per number, plus three bytes overhead for `b""`. For example, the list of the first 9 primes `[2,3,5,7,11,13,17,19,23]` compresses to 14 bytes rather than 24. (An extra byte is used for a workaround explained below for character 13.)
In many cases, your bytes object will contain non-printable characters such as `b"\x01x02\x03"` for `[1, 2, 3]`. These are written with hex escape characters, but [you may use them a single characters in your code](http://meta.codegolf.stackexchange.com/q/4922/20260) (unless the challenge says otherwise) even though SE will not display them. But, characters like the carriage return `b"\x0D"` will break your code, so you need to use the two-char escape sequence `"\r"`.
[Answer]
Use powers of the imaginary unit to calculate sines and cosines.
For example, given an angle `d` in degrees, you can calculate the sine and cosine as follows:
```
p=1j**(d/90.)
s=p.real
c=p.imag
```
This can also be used for related functions such as the side length of a unit `n`-gon:
```
l=abs(1-1j**(4./n))
```
[Answer]
# `0in` instead of `not all`
(or, under [DeMorgan's Law](https://en.wikipedia.org/wiki/De_Morgan%27s_laws), `any(not ...)`)
```
not all(...)
~-all(...)  # shorter than `not`, and with more forgiving precedence
0in(...)
```
```
not all map(f,a)
0in map(f,a)  # the reduction is more significant here because you can omit the parentheses
```
This only works if the falsey values in the `...` sequence are actually `False` (or `0`/`0.0`/etc.) (**not** `[]`/`""`/`{}` etc.).
# `1in` instead of `any`
This one isn't shorter with a comprehension:
```
any(f(x)for x in a)
1in(f(x)for x in a)
```
But it sometimes saves bytes with other kinds of expression by letting you omit the parentheses:
```
any(map(f,a))
1in map(f,a)
```
This has a similar truthiness-related caveat to the above, though.
---
# Notes
These might sometimes have less favourable precedence, because they use the `in` operator. However, if you're combining this with a comparison you may be able to make additional use of [this tip](https://codegolf.stackexchange.com/a/60 "wow, answer ID 60") about comparison condition chaining.
You can also use these if you want the entire `for`-comprehension in `any`/`all` to always be fully evaluated:
```
any([... for x in a])
1in[... for x in a]
```
---
This one's rare, but if you need to evaluate and discard an extra expression for every item in a comprehension, you could use a dictionary here at no extra cost:
```
1in[(condition,side_effect)[0]for x in a]
1in{condition:side_effect for x in a}
```
because `dict`'s `in` checks only the keys.
[Answer]
## Combine assignments of reused values with unused for-loop variables
If you need to loop a number of times but you don't care about the iteration variable, you can co-opt the loop to assign a variable.
```
r=reused;for _ in"_"*n:stuff
r=reused;exec("r;"*n)                          # [note 1]
r=reused;exec"r;"*n                            # [note 1]; Python 2 only
for r in[reused]*n:r
lambda args:((r:=reused)for _ in"_"*n)         # generally needs parentheses
lambda args,r=reused:(r for _ in"_"*n)         # only works with constants
lambda args:(r for r in[reused]*n)
```
This is generally a more versatile approach for assignment than the `:=` operator or using default arguments of functions, because it supports assigning to attributes `.x`, subscripts `[x]`, and unpacking with `*` or `,`.
```
(stuff+(a[0]:=value)for _ in"_"*n)                   # syntax error
(stuff+a[0]for a[0]in[value]*n)                      # works, and shorter!
(stuff+a+b for*a,b in[value]*n)                      # works!
```
The only pitfall is that scope inside comprehensions is sometimes quite confusing, because the body of the comprehension is compiled as a separate implicit function.
[Taken from @xnor's use of it here](https://codegolf.stackexchange.com/a/216302).
[note 1]: and longer if backslashes/quotes/newlines/... need to be escaped inside the string
---
*This is a bot account operated by pxeger. I'm posting this to get enough reputation to use chat.*
[Answer]
Abuse the fact that in case of an expression yielding `True` boolean operators return the first value that decides about the outcome of the expression instead of a boolean:
```
>>> False or 5
5
```
is pretty straightforward. For a more complex example:
```
>>> i = i or j and "a" or ""
```
i's value remains unchanged if it already had a value set, becomes "a" if j has a value or in any other case becomes an empty string (which can usually be omitted, as i most likely already was an empty string).
[Answer]
## Check if a number is a power of 2
Check whether a positive integer `n` is a perfect power of 2, that is one of `1, 2, 4, 8, 16, ...`, with any of these expressions:
```
n&~-n<1
n&-n==n
n^n-1>=n
2**n%n<1
```
The third expression also works for `n==0` giving `False`. The last is easy to modify to checking for, say, powers of 3.
[Answer]
Lets play with some list tricks
```
a=[5,5,5,5,5,5,5]
```
can be written as:
```
a=[5]*7
```
It can be expanded in this way. Lets, say we need to do something like
```
for i in range(0,100,3):a[i]=5
```
Now using the slicing trick we can simply do:
```
a[0:100:3]=[5]*(1+99//3)
```
[Answer]
If you are doing something small in a for loop whose only purpose is to invoke a side effect (`pop`, `print` in Python 3, `append`), it might be possible to translate it to a list-comprehension. For example, from Keith Randall's answer [here](https://codegolf.stackexchange.com/revisions/40297/1), in the middle of a function, hence the indent:
```
  if d>list('XXXXXXXXX'):
   for z in D:d.pop()
   c=['X']
```
Can be converted to:
```
  if d>list('XXXXXXXXX'):
   [d.pop()for z in D]
   c=['X']
```
Which then allows this golf:
```
  if d>list('XXXXXXXXX'):[d.pop()for z in D];c=['X']
```
An `if` within a `for` works just as well:
```
for i in range(10):
 if is_prime(i):d.pop()
```
can be written as
```
[d.pop()for i in range(10)if is_prime(i)]
```
[Answer]
## Use map for side effects
Usually you use `map` to transform a collection
```
>> map(ord,"abc")
[97, 98, 99]
```
But you can also use it to repeatedly act on object by a built-in method that modifies it.
```
>> L=[1,2,3,4,5]
>> map(L.remove,[4,2])
[None, None]
>> L
[1, 3, 5]
```
Be aware that the calls are done in order, so earlier ones might mess up later ones.
```
>> L=[1,2,3,4,5]
>> map(L.pop,[0,1])
[1, 3]
>> L
[2, 4, 5]
```
Here, we intended to extract the first two elements of `L`, but after extracting the first, the next second element is the original third one. We could sort the indices in descending order to avoid this.
An advantage of the evaluation-as-action is that it can be done inside of a `lambda`. Be careful in Python 3 though, where `map` objects are not evaluated immediately. You might need an expression like `[*map(...)]` or `*map(...),` to force evaluation.
[Answer]
## Logical short-circuiting in recursive functions
**A detailed guide**
I had worked with short-circuiting `and/or`'s for a while without really grasping how they work, just using `b and x or y` just as a template. I hope this detailed explanation will help you understand them and use them more flexibly.
---
Recursive named `lambda` functions are [often shorter](https://codegolf.stackexchange.com/a/61526/20260) than programs that loop. For evaluation to terminate, there must be control flow to prevent a recursive call for the base case. Python has a [ternary condition operator](https://stackoverflow.com/questions/394809/does-python-have-a-ternary-conditional-operator) that fits the bill.
```
f=lambda x:base_value if is_base_case else recursive_value
```
Note that [list selection](https://codegolf.stackexchange.com/a/62/20260) won't work because Python evaluates both options. Also, regular `if _:` isn't an option because we're in a `lambda`.
---
Python has another option to short-circuit, the logical operator keywords `and` and `or`. The idea is that
```
True or b == True
False and b == False
```
so Python can skip evaluate `b` in these cases because the result is known. Think of the evaluation of `a or b` as "Evaluate `a`. If it's True, output `a`. Otherwise, evaluate and output `b`." So, it's equivalent to write
```
a or b
a if a else b
```
It's the same for `a or b` except we stop if `a` is False.
```
a and b
a if (not a) else b
```
You might wonder why we didn't just write `False if (not a) else b`. The reason is that this works for non-Boolean `a`. Such values are [first converted to a Boolean](https://docs.python.org/2.4/lib/truth.html). The number `0`, `None`, and the empty list/tuple/set become `False`, and are so called "Falsey". The rest are "Truthy".
So, `a or b` and `a and b` always manages to produce either `a` or `b`, while forming a correct Boolean equation.
```
(0 or 0) == 0
(0 or 3) == 3
(2 or 0) == 2
(2 or 3) == 2
(0 and 0) == 0
(0 and 3) == 0
(2 and 0) == 0
(2 and 3) == 3
('' or 3) == 3
([] and [1]) == []
([0] or [1]) == [0]
```
---
Now that we understand Boolean short-circuiting, let's use it in recursive functions.
```
f=lambda x:base_value if is_base_case else recursive_value
```
The simplest and most common situation is when the base is something like `f("") = ""`, sending a Falsey value to itself. Here, it suffices to do `x and` with the argument.
For example, this function doubles each character in a string, `f("abc") == "aabbcc"`.
```
f=lambda s:s and s[0]*2+f(s[1:])
```
Or, this recursively sums the cubes of numbers `1 through n`, so `f(3)==36`.
```
f=lambda n:n and n**3+f(n-1)
```
Another common situation is for your function to take non-negative numbers to lists, with a base case of `0` giving the empty list. We need to transform the number to a list while preserving Truthiness. One way is `n*[5]`, where the list can be anything nonempty. This seems silly, but it works.
So, the following returns the list `[1..n]`.
```
f=lambda n:n*[5]and f(n-1)+[n]
```
Note that negative `n` will also give the empty list, which works here, but not always. For strings, it's similar with any non-empty string. If you've previously defined such a value, you can save chars by using it.
More generally, when your base value is an empty list, you can use the arithmetic values `True == 1` and `False == 0`  to do:
```
[5]*(is_not_base_case)and ...
```
TODO: Truthy base value
---
TODO: `and/or`
[Answer]
Cut out newlines wherever you can.
At the top-level, it doesn't matter.
```
a=1
b=9
```
Takes the same amount of characters as:
```
a=1;b=9
```
In the first case you have a newline instead of a `;`. But in function bodies, you save however deep the nesting level is:
```
def f():
 a=1;b=9
```
Actually in this case, you can have them all on one line:
```
def f():a=1;b=9
```
If you have an `if` or a `for`, you can likewise have everything on one line:
```
if h:a=1;b=9
for g in(1,2):a=1;b=9
```
But if you have a nesting of control structures (e.g. `if` in a `for`, or `if` in a `def`), then you need the newline:
```
if h:for g in(1,2):a=1;b=9 #ERROR
if h:
 for g in(1,2):a=1;b=9 # SAUL GOODMAN
```
[Answer]
## Use eval to iterate
Say you want to apply `f` composed `k` times to the number `1`, then print the result.
This can be done via an `exec` loop,
```
n=1
exec("n=f(n);"*k)
print(n)
```
which runs code like `n=1;n=f(n);n=f(n);n=f(n);n=f(n);n=f(n);print(n)`.
But, it's one character shorter to use `eval`
```
print(eval("f("*k+'1'+")"*k))
```
which evaluates code like `f(f(f(f(f(1)))))` and prints the result.
This does not save chars in Python 2 though, where `exec` doesn't need parens but `eval` still does. It does still help though when `f(n)` is an expression in which `n` appears only once as the first or last character, letting you use only one string multiplication.
[Answer]
One trick I have encountered concerns returning or printing Yes/No answers:
```
 print 'YNeos'[x::2]
```
x is the condition and can take value 0 or 1.
I found this rather brilliant.
[Answer]
A condition like
```
s = ''
if c:
    s = 'a'
```
can be written as
```
s = c*'a'
```
and there is possibly a need for parenthesis for condition.
This can also be combined with other conditions as (multiple ifs)
```
s = c1*'a' + c2*'b'
```
or (multiple elifs)
```
s = c1*'a' or c2*'b'
```
For example FizzBuzz problem's solution will be
```
for i in range(n):
    print((i%3<1)*"Fizz"+(i%5<1)*"Buzz" or i)
```
[Answer]
# Use Splat (`*`) to pass a bunch of single character strings into a function
For example:
```
a.replace("a","b")
a.replace(*"ab")    -2 bytes
some_function("a","b","c")
some_function(*"abc")       -5 bytes
```
In fact, if you have `n` single-character strings, you will save `3(n - 1) - 1` or `3n - 4` bytes by doing this (because each time, you remove the `","` for each one and add a constant `*`).
[Answer]
## Trig without imports
You can compute `cos` and `sin` without needing to `import math` by using complex arithmetic. For an angle of `d` degrees, its cosine is
```
(1j**(d/90)).real
```
and its sine is
```
(1j**(d/90)).imag
```
Here, `1j` is how Python writes the imaginary unit \$i\$. If your angle is `r` radians, you'll need to use `1j**(r/(pi/2))`, using a decimal approximation of `pi/2` if the challenge allows it.
If you're curious, this all works because of [Euler's formula](https://en.wikipedia.org/wiki/Euler%27s_formula):
$$i^x = (e^{i \pi /2})^x = e^{i \pi /2 \cdot x} = \cos(\pi/2 \cdot x) + i \sin(\pi /2 \cdot x)$$
[Answer]
`!=` can be replaced with `-`
here is a example
```
n=int(input())
if n!=69:
 print("thanks for being mature")
```
instead of using `!=` you can use `-`
after that it should look like this
```
n=int(input())
if n-69:
 print("thanks for being mature")
```
[Answer]
## Multiple **if** statements in comprehensions
If you need to keep multiple conditions inside comprehension, you can replace **and** with **if** to save a byte each time.
Works in Python 2 and 3.
```
[a for a in 'abc'if cond1()and cond2()or cond3()and cond4()and cond5()]
[a for a in 'abc'if cond1()if cond2()or cond3()if cond4()if cond5()]
```
[Try it online!](https://tio.run/##hZC9CgIxEIT7PMV20cLi/hpbQbCxshOLmOx5i7o5Yg706WMIGhTBlMPufDs748MPlusQDPagLZtqNl8KGB2xB7kaUJ@JT2lCnixDBQvYuQmlAId@cpyUeNvrgr2O9rW63D78SWZAUwA0P/flBtQV2HrAO@rJo5GZ1hZobSlOVwB0EbD9Ov0vlhB7Bb11oIDihjpqSbl2yg3GhVcVlN@gnOcQwhM "Python 2 – Try It Online")
[Answer]
## Build a string instead of joining
To concatenate strings or characters, it can be shorter to repeatedly append to the empty string than to `join`.
**23 chars**
```
s=""
for x in l:s+=f(x)
```
**25 chars**
```
s="".join(f(x)for x in l)
```
Assume here that `f(x)` stands for some expression in `x`, so you can't just `map`.
But, the `join` may be shorter if the result doesn't need saving to a variable or if the `for` takes newlines or indentation.
[Answer]
# String keys to dicts
For a dictionary with string keys which also happen to be valid Python variable names, you can get a saving if there's at least three items by using `dict`'s keyword arguments:
```
{'a':1,'e':4,'i':9}
dict(a=1,e=4,i=9)
```
The more string keys you have, the more quote characters you'll save, so this is particularly beneficial for large dictionaries (e.g. for a kolmogorov challenge).
[Answer]
When squaring single letter variables, it is shorter to times it by itself
```
>>> x=30
>>> x*x
900
```
Is one byte shorter than
```
>>> x=30
>>> x**2
900
```
[Answer]
When mapping a function on a list in Python 3, instead of doing `[f(x)for x in l]` or `list(map(f,l))`, do `[*map(f,l)]`.
It works for all other functions returning generators too (like `filter`).
The best solution is still switching to Python 2 though
[Answer]
## Iterate over adjacent pairs
It's common to want to iterate over adjacent pairs of items in a list or string, i.e.
```
"golf" -> [('g','o'), ('o','l'), ('l','f')]
```
There's a few methods, and which is shortest depends on specifics.
**Shift and zip**
```
## 47 bytes
l=input()
for x,y in zip(l,l[1:]):do_stuff(x,y)
```
Create a list of adjacent pairs, by removing the first element and zipping the original with the result. This is most useful in a list comprehension like
```
sum(abs(x-y)for x,y in zip(l,l[1:]))
```
You can also use `map` with a two-input function, though note that the original list is no longer truncated.
```
## Python 2
map(cmp,l[:-1],l[1:])
```
**Keep the previous**
```
## 41 bytes, Python 3
x,*l=input()
for y in l:do_stuff(x,y);x=y
```
Iterate over the elements of the list, remembering the element from a previous loop. This works best with Python 3's ability to unpack to input into the initial and remaining elements.
If there's an initial value of `x` that serves as a null operation in `do_stuff(x,y)`, you can iterate over the whole list.
```
## 39 bytes
x=''
for y in input():do_stuff(x,y);x=y
```
**Truncate from the front**
```
## 46 bytes
l=input()
while l[1:]:do_stuff(*l[:2]);l=l[1:]
```
Keep shortening the list and act on the first two elements. This works best when your operation is better-expressed on a length-two list or string than on two values.
---
I've written these all as loops, but they also lend to a recursive functions. You can also adjust to get cyclic pairs by putting the first element at the end of the list, or as the initial previous-value.
---
The Python 3.8 "walrus" [assignment expressions](https://codegolf.stackexchange.com/a/180041/20260) allow a short expression to give pairs, though with an extra initial element.
```
>>> p=''
>>> [(p,p:=c)for c in"golf"]
[('', 'g'), ('g', 'o'), ('o', 'l'), ('l', 'f')]
```
]


[Question]
      []


[Question]
      [
The [Vigenère cipher](http://en.wikipedia.org/wiki/Vigen%C3%A8re_cipher) is a substitution cipher where the encryption of each letter of the plaintext depends on a different character in a keyword. This stops you using simple methods of frequency analysis to guess the correct substitution. However, the keyword is repeated if it is shorter than the plaintext. This is a weakness. If the length of the keyword is known (n, say), however, and is much shorter than the message, then you can decompose the message into separate sections by taking every nth letter. You can then use frequency analysis on these.
The [Kasiski examination](http://en.wikipedia.org/wiki/Kasiski_examination) is a method to work out the most likely key lengths. It does this by considering identical substrings which happen to be a multiple of the key length apart. They are therefore encrypted in the same way. Turning this round, identical substrings in the ciphertext are likely to be a multiple of the key length apart. If you identify these distances, then the key length is likely to be a common factor of all these distances.
Your job is to write a function or program that can guess the most likely length of the keyword, given some encrypted text. To be precise, the function or program (just called function below) will satisfy the following:
* Inputs consist of a string representing the ciphertext and a positive integer (**len**, for the purposes of this spec) representing the shortest common substring to look at.
* The ciphertext will consist of upper case A-Z characters only. Any length is permitted.
* You can assume valid inputs without checking.
* The inputs may be passed in, or read from stdin.
* The function will identify all pairs of identical substrings in the ciphertext which have a length of *at least* **len**.
* Substrings in each pair may not overlap but substrings in different pairs can overlap.
* The function will return, or write to stdout, the highest common factor of the distances between the starts of these identical pairs.
* If there are no identical substrings then the function will return 0.
For example:
"AAAAAAAAAAAAAAAAAA", n returns 1 for any n from 1 to 8, 9 for n = 9 (as the only possible non-overlapping substrings of length 9 happen to be the same) and 0 otherwise.
"ABCDEFGHIJKL", n returns 0 for any n
"ABCDEABCDE", n returns 5 for n<=5 and 0 otherwise
"ABCABABCAB", 2 returns 1 because "AB" pairs are separated by 2,3,5 & 8
"ABCABABCAB", 3 returns 5
"**VHVS**SP*QUCE*MRVBVBBB**VHVS**URQGIBDUGRNICJ*QUCE*RVUAXSSR", 4 returns 6 because the repeating "VHVS" are 18 characters apart, while "QUCE" is separated by 30 characters
Naturally, lowest byte count wins and avoid standard loopholes.

[Answer]
# CJam, 67 bytes
Definitely still room for improvement, but I'll post what I have so far.
[Try it online](http://cjam.aditsu.net/#code=0r%3AT%2C%2Cri%3E%7BT%2CL(-%2C_m*%7B~%3AXT%3EL%3CT%40LX%2Be%3E%2C%7B0t%7D%2FX%3E%5C%23_W%3E%5C2%24%3F%7B%5C1%24_!%2B%25%7Dh%3B%7D%2F%7DfL)
```
0r:T,,ri>{T,L(-,_m*{~:XT>L<T@LX+e>,{0t}/X>\#_W>\2$?{\1$_!+%}h;}/}fL
```
[Answer]
# JavaScript (ES6) 117
```
F=(s,n,G=(a,b)=>b?G(b,a%b):a)=>(i=>{
  for(f=i;s[(j=i+n)-1];i++)
    for(;p=~s.indexOf(s.substr(i,n),j++);)
      f=G(~p-i,f)
})(0)|f
```
**Ungolfed**
```
F=(s,n)=>
{
  var G = (a,b) => b ? G(b,a%b) : a; // GCD function
  var p,w,i,j, f = 0; // f starting divisor
  for(i = 0; s[i + n - 1]; ++i) // scan s for each substring of lenght n
  {
     w = s.substr(i,n);
     for (j=i+n; (p = s.indexOf(w,j)) != -1; ++j) // find all occurrencies of substring in the rest f the string
        f = G(p - i, f); // p-i is the distance between pairs
  }
  return f
}
```
**Test** In Firefox/FireBug console
```
;["AAAAAAAAAAAAAAAAAA","ABCDEFGHIJKL","ABCDEABCDE","ABCABABCAB",
  "VHVSSPQUCEMRVBVBBBVHVSURQGIBDUGRNICJQUCERVUAXSSR"]
.forEach(s=>{
  for(o=[],i=1;i<=10;i++) o.push(i+':'+F(s,i));
  console.log(s+' '+o)
})
```
*Output*
```
AAAAAAAAAAAAAAAAAA 1:1,2:1,3:1,4:1,5:1,6:1,7:1,8:1,9:9,10:0
ABCDEFGHIJKL 1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0
ABCDEABCDE 1:5,2:5,3:5,4:5,5:5,6:0,7:0,8:0,9:0,10:0
ABCABABCAB 1:1,2:1,3:5,4:5,5:5,6:0,7:0,8:0,9:0,10:0
VHVSSPQUCEMRVBVBBBVHVSURQGIBDUGRNICJQUCERVUAXSSR 1:1,2:1,3:6,4:6,5:0,6:0,7:0,8:0,9:0,10:0
```
]