text:
Simple Printing Arrows
For golfing practice, I have been doing the assignments in my girlfriend's Intro to Python class. I found that for this assignment, there were multiple strategies that came very close in character count, and I'm sure people here can find even better ways. Although I am most interested in ways to do this in Python, I would like to know the most golfed this program can get, therefore this is code golf and shortest answer wins.
The Rules:
The assignment is outlined below. The user should be asked to input twice, although the prompts don't have to say anything, and can be in a different order.
Standard loopholes apply.

Assignment 3: Arrows
Write a program that prompts the user for a number of columns, and them prints the pattern as seen below. You can assume that the user will supply positive numbers. Your program should handle both left and right arrows. Here are a few sample runnings:
How many columns? 3
Direction? (l)eft or (r)ight: r
*
 *
  *
 *
*
How many columns? 5
Direction? (l)eft or (r)ight: l
    *
   *
  *
 *
*
 *
  *
   *
    *

This looks like homewo... oh, nevermind.

Are trailing spaces on each line permitted?

@ThomasKwa yes.

Can we use control characters to move the cursor, as in this question?

@ThomasKwa Sure... although I'm honestly not sure what that means and I'm interested in seeing it in action.

Are functions allowed?

@Vɪʜᴀɴ of course... Why would they not be?

Can the number of columns be larger than 9? (i.e. more than one digit)

@ThomasKwa For future reference, by default, yes.

Pyth, 23 bytes
May or may not be valid, based on the answer to this comment. Regardless, I found this neat, and, if it is invalid, the other Pyth answers are also invalid. ;) Well, it's valid, because I apparently missed the blatantly obvious. :/
EDIT: I WON!!!! YESSS!!!! First time ever! :D
j+_J_Wqz\r.e+*dkb*\*QtJ

Live demo.

m+*\ d\*Q instead of that enumerate thingy. Saves 2 bytes.

Pyth, 27
j<tQ_Wqz\l++Jm+*\ d\*Q_PJtJ

Try it online
The basic idea here is to build one string that, for say 5, looks like this:
*
 *
  *
   *
    *
   *
  *
 *
*
 *
  *
   *
    *

And then flip it upside down if we get l as our input. Then we take all but the last input-1 lines of this string and print it out.

Python 2, 81 79 bytes
c=input()
r=1
l=0
exec"print' '*(%sabs(c-r))+'*';r+=1;"%("c+~"*input())*(2*c-1)

Might still be golfable, but we'll see :)

Nice idea with having the inputs be variables l and r. I hadn't realized the input is eval'ed in the same environment as the code.

Pyth, 30 28 27 bytes
VtyQ+*+*tQJqz\r_WJ.a-hNQd\*

Try it online.
Apparently I'm currently tied with FryAmTheEggman with a completely different approach. (I think that one is ingenious.)
Example
$ python pyth.py spa.p
r
3
*
 *
  *
 *
*

$ python pyth.py spa.p
l
5
    *
   *
  *
 *
*
 *
  *
   *
    *

Explanation
 tyQ                              (columns * 2) - 1
V                               loop N through range(the above)
        tQ                                columns - 1 (maximum number of spaces)
       *                                multiplied by
           qz\r                           1 if direction == "r" else 0
          J                               also save that 1 or 0 to J
      +                               plus
                  .a-hNQ                    abs(N - columns + 1)
               _WJ                      negate that if direction == "r"
     *                  d           that many spaces
    +                    \*       add the star and print

@Pietu1998 I still am interested in a basic description of what you're doing.  I see you only have 1 loop and no map or lambda...

@aks. I added an explanation.

PowerShell, 91 85 102 Bytes
$c=(Read-Host)-1;if(!$c){"*";exit}(@(0..$c+($c-1)..0),@($c..0+1..$c))[(Read-Host)-eq'l']|%{" "*$_+"*"}

Gets the columns, stores it in $c. We subtract one because each column also has an * and we're only interested in how many spaces are required.
If the entered value was a 1, print * and exit - rest of the script doesn't make a difference.+
The next section first gets the direction and tests whether it's -equal to l, then creates an array based on indexing into an array of dynamically generated arrays based on the value of $c. Magic. Essentially, this is how many spaces per line we need.
For example, for 5 r this collection would hold (0,1,2,3,4,3,2,1,0).
Takes the array and pipes it into a Foreach-Object % loop, where we output a string of X number of spaces, then the *

Example usage:
PS C:\Tools\Scripts\golfing> .\simple-printing-arrows.ps1
6
r
*
 *
  *
   *
    *
     *
    *
   *
  *
 *
*

Edit - removed variable $e by piping the collection directly
Edit2 - correctly accounts for 1 column, now
+ If it's still mandatory to take input for direction for 1-column arrows (I contend it is not), we can swap the positioning of the Read-Host and lose a couple more bytes by re-introducing the $d variable, for 106:
$c=(Read-Host)-1;$d=Read-Host;if(!$c){"*";exit}(@(0..$c+($c-1)..0),@($c..0+1..$c))[$d-eq'l']|%{" "*$_+"*"}

Try putting 1 column, and left - you get a 2-column right arrow. Try putting 1 column and right - you get a 'Specified argument out of the range of valid values' error.  I thought your 85 would be possible to beat by avoiding the doubled-up-ranges. But I can't even get close. Accounting for a 1 column arrow, I'm currently at 112 chars. >_<

@TessellatingHeckler Thanks - corrected.

That's pushed yours up to 102 and mine is down to 102.  I can't bare to stare at this any longer, but there must be one more I can delete... :D

TI-BASIC, 75 65 57 54 50 47 Bytes
Thanks to @ThomasKwa for the correct byte calculation and golfing 10 bytes.
Tested on my TI-84+ Silver Edition.
First TI-BASIC submission, golfing suggestions welcome (I don't know many tricks yet). If name plays a factor in memory shown, this one's was 3 characters instead of 1 (I looked at the byte count on my calculator itself). This program is limited by the output function's restrictions (I think to arrows of length 4), but I could probably switch to text, which displays graphically if that is too low of a length.
Prompt L,Str1
Str1="R
For(I,1,2L-1
Output(I,(1-2Ans)abs(I-L)+AnsL+1,"*
End

Note that this also doesn't clear the screen or pause it.
I really feel like the equation I'm using can be golfed more. It also feels so wrong to exclude the ending quotation mark.

@ThomasKwa Thanks! I'll do that now.

Second: Ans is free, because you don't use it for input and Output( doesn't modify Ans. Use it, and get rid of the variable A. You can assign using -2(Str1="R; no need for a conditional.

@ThomasKwa thanks for the tips, looks like I've got a ways to go in TI-BASIC.

Third: There's really no need to multiply the value by -2. Just do Str1="R for the second line. That makes the fourth line Output(I,(1-2Ans)abs(I-L)+AL+1,"*, which nets you 4 more bytes. But wait, there's an idiom for (1-2Ans)—it's cos(πAns), which saves one byte, plus one more because we get the open parenthesis for free!

Becoming proficient in golfing in any language requires only practice; you'll get there.

Yeah, I implemented that but forgot to change that part specially in my answer.

Python 2, 111 109 104 bytes
Pretty simple solution. I'm sure it can be golfed more. For those who don't know, ~x+n is the same as n-1-x.
n=input()
r=range(n)
r+=r[-2::-1]
for i in[r,[~x+n for x in r]]['r'>raw_input()]:print"*".rjust(i+1," ")

Try it online
Edit: This was golfed into the last line:
if'r'>d:r=[~x+n for x in r]
for i in r:print"*".rjust(i+1," ")

Perl, 85 bytes
($-,$_)=<>;$,=$/;@}=map$"x$_.'*',0..--$-;@}=reverse@}if/l/;print@},map$}[$--$_],1..$-

Usage:
perl 59874.pl <<< '6
r'

I like how you name your scripts something you'll recognize them by later...

@mbomb007 haha! You know, I don't actually name my scripts that, but I thought it was best to name something simple for usage instructions... simplearrows2.pl doesn't seem as good! :P

Python 2, 89 bytes
c=input()-1
d=raw_input()>'l'
for j in range(2*c+1):print' '*(d*c-(2*d-1)*abs(c-j))+'*'

Works almost identically to my Pyth answer, just calculating the correct number of spaces on the fly.

Matlab, 109 105 96 bytes
Thanks to @beaker for saving me 9 bytes.
x=eye(input(''));if(input('','s')<114),x=fliplr(x);end
x=x*10+32;disp(char([x;x(end-1:-1:1,:)]))

You can save 9 bytes if you replace the two lines inserting the ascii codes with x=x*10+32;

@beaker Very clever, thanks!

Python 2, 98 89 bytes
f=[' '*n+'*'for n in range(input())]
if'l'==input():f=f[::-1]
print'\n'.join(f+f[-2::-1])

A little more lengthy.

Usage
$ python2 test.py
3
"l"
  *
 *
*
 *
  *

Also apparently broken. NameError: name 'l' is not defined, NameError: name 'd' is not defined.

Check the usage. @TessellatingHeckler

Ahh, clever. But your 1-column arrows have two arrow heads. (I think you could golf it further by not storing i and d at all, just using range(P()) and if P()=='l'...)

Thanks for the suggestions! I also fixed the double arrow heads. @TessellatingHeckler

Can't test atm, but you could probably do something like f=[...][::2*('r'>input())-1] actually

Pinching an idea from another Python2 answer, you might be able to golf -1 with if'd'<input()

PowerShell, 104 102 97 bytes
# 97 version:
$o=@(($c=(read-host)-1))[(read-host)-eq'l'];($j=2*$c)..0|%{' '*[Math]::Abs($o++%($j+!$j)-$c)+'*'}

3
r
*
 *
  *
 *
*

# Previous 102 version:
$o=@(($c=(read-host)-1))[(read-host)-eq'l'];(2*$c)..0|%{
' '*[Math]::Abs($o++%(2*($c+(!$c+0)))-$c)+'*'}

NB. if you want to run it again, open a new PowerShell, or rv o to reset the variable state.
Compared to how terse the others are, this hurts. [Hurts less at 97 than it did at 122]. Two parts to it, neither of them very surprising; reads a number of columns, uses an array-index-ternary-operator-substitute  to get an offset, and runs through a wave function starting at the offset (and a tweak so it doesn't fall over doing mod 0).
(And ouch did I spend ages on that wave function, unable to spot my misunderstanding, and typing all the it's-not-LISP-,honest parens).

That's bloody brilliant.

PHP, 156 Bytes
<?for($c=1+fgets(STDIN);--$c;$s[-$c]=$t[]=sprintf("%{$c}s","*"));arsort($s);$a=fgetc(STDIN)==r?$s+$t:$t+$s;array_splice($a,count($a)/2,1)?><?=join("
",$a);

Creates two arrays, like this:
$t = [
    0 => "  *"
    1 => " *"
    2 => "*"
]
$s = [
    -1 => "*"
    -2 => " *"
    -3 => "  *"
]

then uses array union $s+$t or $t+$s to combine them and array_splice to remove the element in the middle. Finally output using <?=join()

with CLI arguments instead of STDIN my code would be 8 bytes shorter ;)

Vyxal j, 14 bytes
ƛ×⁰\l=[↲¹]↳;øm

Try it Online!
11 if 1/0 is allowed
ƛ          ;   # Map to...
 ×             # Asterisk
  ⁰\l=[  ]     # If left...
       ↲¹      # Left justify, then push size to right-just by
          ↳    # Right-justify
            øm # Palindromise

Ruby, 118 bytes
2.times{l,d=gets.split;l=l.to_i;a=(d=="r"?(0..l-1):(l-1).downto(0)).to_a;(a+a[0..-2].reverse).each{|x| puts "#{' '*x}*"}}

2.times{ -- twice, of course...
l,d=gets.split; -- get the input
l=l.to_i; -- change length to an integer
a=(d=="r"?(0..l-1):(l-1).downto(0)).to_a; -- create an array from the range of 0 to the length
(a+a[0..-2].reverse).each{|x| puts "#{' '*x}*"} -- iterate, turn into the strings to make the arrows
Not exactly the greatest golf ever, but, hey.

PowerShell, 98 94 Bytes
$c=(Read-Host)-1;$d=Read-Host;if($c){$c..0+1..$c|%{if($d-eq'r'){$_=$c-$_}' '*$_+'*'}}else{'*'}

If I could find a way to put the Read-Host for direction inside the foreach-object loop but only prompt for it once I might be able to save a few bytes.
Edit: 94 bytes.  Instead of testing for left, test for right (simplifies the loop).
Original 98 byte:
$c=(Read-Host)-1;$d=Read-Host;if($c){0..$c+($c-1)..0|%{if($d-eq'l'){$_=$c-$_}' '*$_+'*'}}else{'*'}

Resetting the $_ variable -- tricksy Hobbit. Very clever, and I learned something today.

@TimmyD Very tricksy.  And then switch the if statement to save even more.

Jelly, 15 bytes
=”ro⁹ạŒḄ}⁶ẋp”*Y

Try it online!
If we can use any values instead of l and r, then this 11 byte program works for 1 being to the right and 0 to the left.
If we can use any character rather than *, we can reduce the programs to 14 and 10 bytes
How it works
=”ro⁹ạŒḄ}⁶ẋp”*Y - Main link. Takes C on the left and n on the right
 ”r             - "r"
=               - Is C = "r"?
    ⁹           - Yield n
   o            - If C ≠ "r", yield n else 1
        }       - To n:
      ŒḄ        -   Bounce; Yield [1, 2, ..., n, ..., 2, 1]
     ạ          - Absolute difference

                  If C = "r", this yields [0, 1, ..., n-1, ..., 1, 0]
                  If C ≠ "r", this yields [n-1, n-2, ..., 0, ..., n-2, n-1]
                  Call the result B

         ⁶      - Yield a space
          ẋ     - For each element k in B, repeat a space k times
            ”*  - Yield "*"
           p    - Cartesian product; This appends "*" to each element in B
              Y - Join on newlines

><>, 60 bytes
i"1l"i=&-:&*&:?!\:1-:}c0.
~/?:<-$?&::&;!?l<oao"*"
1/  \o" "-

2 wasted bytes on the bottom line, how irritating!
Due to how input works in ><>, it's not possible to 'wait' for input - the i command checks if an input character is available on STDIN. If there is, it pushes the ASCII value of that character, and pushes -1 if not.
This means that, in order to use this program, the number and direction must already be ready on STDIN, e.g. 3r for a size 3 arrow pointing to the right. I'm not sure if that disqualifies this entry, let me know your thoughts :o)
I'll also write up a description if anyone wants one.

In a sense it does wait for input if you try to run it in a shell, so I think that's fine. I'm more concerned with the fact that this expects the input to be a single digit though (unless I'm meant to input : for 10?)

An excellent point, I hadn't thought about input over 9. Back to the drawing board!

I've left a comment on the main question for a clarification, just in case

PHP, 154 bytes
It looks really repetitive, but it does the desired:
$c=$argv[1];$b=l==$argv[2]?1:0;$a=$b?$c:-1;function a($a){echo strrev(str_pad('*',$a))."\n";}while($b?--$a:++$a<$c)a($a+1);while($b?++$a<=$c:1<$a--)a($a);

Runs from command line like:
php arrow.php 5 l
php arrow.php 5 r

Japt -R, 14 bytes
Could save at least 3 bytes with looser I/O requirements.
õ@'*ùXÃê zVèÊÑ

Try it
11 bytes
Takes 0/1 as input for r/l and uses 1 instead of *
oç mÄ ê zVÑ

Try it
õ@'*ùXÃê zVèÊÑ     :Implicit input of integer U & string V
õ                  :Range [1,U]
 @                 :Map each X
  '*               :  Literal "*"
    ùX             :  Left pad with spaces to length X
      Ã            :End map
       ê           :Palindromise
         z         :Rotate clockwise 90° this many times ...
          Vè       :  Count the occurrences in U of
            Ê      :    "l"
             Ñ     :  Multiply by 2
                   :Implicit output joined with newlines

oç mÄ ê zVÑ     :Implicit input of integers U & V
o               :Range [0,U)
 ç              :For each, repeat space that many times
   m            :Map
    Ä           :  Append 1
      ê         :Palindromise
        zVÑ     :Rotate clockwise 90° V*2 times
                :Implicit output joined with newlines


text:
Monday Mini-Golf #3: Anagram distance
Monday Mini-Golf: A series of short code-golf challenges, posted (hopefully!) every Monday.
(Sorry this one's a little late.)
I'm sure most of you folks have heard of Levenshtein distance, an algorithm for calculating the distance between two strings. Well, this challenge is about implementing a similar algorithm of my own invention*, called anagram distance. The main difference is that the order of the characters doesn't matter; instead, only the characters that are unique to one string or the other are measured.
Challenge
The goal of the challenge is to write a program or function that takes in two strings and returns the anagram distance between them. The main way to do this is to use the following logic:

Convert both strings to lowercase and (optionally) sort each one's characters alphabetically.
While the strings contain at least one equal character, remove the first instance of this character from each string.
Add the lengths of the remaining strings and return/output the result.

Example
If the inputs are:
Hello, world!
Code golf!

Then, lowercased and sorted, these become: (by JS's default sort; note the leading spaces)
 !,dehllloorw
 !cdefgloo

Removing all of the characters that are in both strings, we end up with:
,hllrw
cfg

Thus, the anagram distance between the original two strings = 6 + 3 = 9.
Details

The strings may be taken in any sensible format.
The strings will consist only of printable ASCII.
The strings themselves will not contain any whitespace other than regular spaces. (No tabs, newlines, etc.)
You need not use this exact algorithm, as long as the results are the same.

Test-cases
Input 1:
Hello, world!
Code golf!

Output 1:
9

Input 2:
12345 This is some text.
.txet emos si sihT 54321

Output 2:
0

Input 3:
All unique characters here!
Bdfgjkmopvwxyz?

Output 3:
42

Input 4:
This is not exactly like Levenshtein distance,
but you'll notice it is quite similar.

Output 4:
30

Input 5:
all lowercase.
ALL UPPERCASE!

Output 5:
8

Scoring
This is code-golf, so shortest valid code in bytes wins. Tiebreaker goes to submission that reached its final byte count first. The winner will be chosen next Monday, Oct 12. Good luck!
Edit: Congrats to the winner, @isaacg, using Pyth (again) for an astounding 12 bytes!
*If this algorithm has been used elsewhere and/or given another name, please let me know! I wasn't able to find it with a 20-minute search.

Describing the task as “write a program […] that [does stuff] using the following logic” to later add “You need not use this exact algorithm […]” is a tad contradictory.

@Édouard True; thanks for pointing that out. I believe it's better now.

It's already Tuesday again. ;)

@MartinBüttner It's kinda hard to write a challenge while you're on the road without wi-fi. ;) Don't worry, I'll have a new one ready in a little bit.

Pyth, 12 bytes
ls.-M.prR0.z

Test suite
The operation in question is equivalent to Pyth's bagwise subtraction operator, .-, applied in both directions. You could call it bagwise xor, I suppose.
The solution is:
.z: get input as list of 2 strings.
rR0: convert both to lowercase.
.p: Form all permutations, i.e. normal and reversed.
.-M: Map the .- operation over each ordering.
s: Concatenate the results.
l: Print the length.

And I thought all answers might be overly long.... Well done!

JavaScript (ES7), 92 bytes
Defines an anonymous function.
To test, run the snippet below. You can edit the code and click 'Test' to compare its output with the original. (Leave a comment if you find an improvement!) Input is like "Hello, world!", "Code golf!" in the input box.
Thanks to @ETHproductions for saving 6 bytes!

(a,b)=>[for(v of a[t="toLowerCase"]())if((b=b[t]())==(b=b.replace(v,"")))v][l="length"]+b[l]

Code:
<textarea id="textbox" style="margin-top:5px; margin-bottom:5px"></textarea>

Input:
<textarea id="inputbox" style="margin-top:5px; margin-bottom:5px"></textarea>
<button id="testbtn">Test!</button><button id="resetbtn">Reset</button>

Original Code Output:

New Code Output:

More about the test suite

How it works
//Define function w/ paramters a, b
(a,b)=>
     //lowercase a
     //for each character v in a:
     [for(v of a[t="toLowerCase"]())
          //lowercase b
          //remove the first instance of v in b
          //if b before removal equals b after removal (if nothing was removed):
          if((b=b[t]())==(b=b.replace(v,"")))
               //keep v in the array of a's values to keep
               v]
     //get the length of the computed array
     [l="length"]
     //add b's length
     +b[l]
     //implicitly return the sum

I'd been working on an array-based ES6 answer for an hour, and had only been able to get it down to 122. Seems I was looking in the wrong direction! +1

BTW, you could replace .join("")+b with .join``+b with no effect.

Wow, where on earth did you get that test suite? It's brilliant! I wish I could +1 three or four more times....

@ETHproductions Thank you! :D I made the test suite myself, actually. Check out my meta post!

I +1'ed over there, hope it makes up for not being able to +5 here. ;)

I was able to get one using the Map object to 118, and another one with eval and split to 108, but couldn't top yours. Very nice!

I modified this version using ES7's array comprehensions and got 93: (a,b)=>([for(v of a[t="toLowerCase"]())if((b=b[t]())==(b=b.replace(v,"")))v].join``+b).length

@ETHproductions Thanks! Didn't know about that ES7 feature.

CJam, 23 19 bytes
2{'¡,lelfe=}*.-:z:+

Try it online in the CJam interpreter.
How it works
2{         }*        Do the following twice:
  '¡,                  Push the string of the first 161 Unicode charcters.
     lel               Read a line from STDIN and convert it to lowercase.
        fe=            Count the number of occurrences of each of the 160
                       characters in the lowercased line.
             .-      Vectorized subtraction; push the differences of the
                     occurrences of all 161 characters.
               :z    Apply absolute value to each difference.
                 :+  Push the sum of all results.

Ruby, 62
#!ruby -naF|
gets
p$F.count{|c|!$_.sub!(/#{Regexp.escape c}/i){}}+~/$/

There has to be a better way.
Edit: 57 chars thanks to iamnotmaynard investigating a path I was too lazy to.
#!ruby -naF|
gets.upcase!
p$F.count{|c|!$_.sub!(c.upcase){}}+~/$/

sub can take strings. Couldn't you use c.downcase instead of /#{Regexp.escape c}/i ?

I'd have to downcase both strings (or upcase, equivalently.)

Ah, of course. (Though it looks to me that doing so would still save you a couple bytes.)

Python, 90 87 81 80 79 bytes
lambda a,b,s=str.lower:sum(abs(s(a).count(c)-s(b).count(c)))for c in{*s(a+b)}))

Python <3.5 version, 80 bytes
lambda a,b,s=str.lower:sum(abs(s(a).count(c)-s(b).count(c))for c in set(s(a+b)))

Explanation
For each character in a or b, count up the number of occurrences in each string, and add the (positive) difference.
Edit: Re-read rules, realized anonymous functions are acceptable, improved answer by getting rid of raw_input. First golf, please be gentle!
Thanks to sp3000 for the improvement of redefining str.lower and making me realize print was unnecessary. Also spaces. Still learning.
Using python >=3.5, there's a shorter way of defining sets, so a byte can be saved over previous versions.

Retina, 40 20 bytes
20 bytes saved thanks to Martin Büttner.
Place each line in its own file and replace the \n with a literal newline.
+i`(.)(.*\n.*)\1
$2
.

pb, 648 bytes
^w[B!0]{t[B]vb[T]^>}vb[-1]w[X!0]{<t[64]w[T!0]{w[B!0]{b[B-1]v}^[Y]t[T-1]}}w[B!-1]{w[B=0]{b[27]}t[26]w[T!0]{w[B!0]{b[B-1]v}^[Y]t[T-1]}>}b[0]w[X!0]{<w[B!0]{b[1]v}^[Y]w[B=0]{b[32]}w[B=1]{b[0]}}^w[B!0]{t[B]vb[B+T]^>}vb[1]<w[B!9]{t[B]b[0]vv<[X]w[B!0]{>}b[T]^^<[X]w[B!0]{>}<}b[0]<w[X!-1]{t[B]vb[1]^w[B!1]{>}vvw[X!-1]{w[B=T]{b[0]<[X]^w[B!1]{>}^b[0]vt[2]}<}^[Y]vw[B!1]{>}b[0]^<}t[0]w[B!1]{w[B!0]{t[T+1]b[0]}>}b[0]vvw[X!-1]{w[B!0]{t[T+1]b[0]}<}>b[11]^b[T]w[B!0]{vw[B!11]{>}t[B]b[0]>b[T]<[X]^t[B]b[0]vw[B!11]{>}<w[T!0]{t[T-1]b[B+1]w[B=11]{b[0]^<[X]b[B+1]vw[B!11]{>}<}}^<[X]}vw[B!11]{b[B+48]>}b[0]<w[B!0]{w[B!0]{>}<t[B]^^<[X]w[B!0]{>}b[T]<[X]vvw[B!0]{>}<b[0]<}

Takes input with a tab character separating the two strings.
This one was a doozy. Actually implementing the algorithm wasn't the hard part, that came relatively easily. But I had to do two things that are difficult to do in pb: Case insensitivity and itoa. I happened to have a program for converting to lowercase just lying around (itself 211 bytes long) and everything else was tacked onto the end to do the work for this challenge specifically.
You can watch this program run on YouTube! There are a couple things you should keep in mind if you do:

This version of the program is slightly modified, weighing in at 650 bytes. The only difference is that 255 is used as a flag value instead of -1, because trying to print chr(-1) crashes the interpreter when running in watch mode.
The input in that video is Hello, world! and Code golf.. This is slightly different than one of the example inputs in the challenge; I used it because it was short but modified it so the correct output would be 10 instead of 9. This is just to show off that the number is printed correctly even if it's multiple digits, which is hard in pb.
The interpreter is awful, and it shows here. Notably, the tab character throws off the spacing so things aren't lined up for large portions of the video, whenever a byte is set to 10 it shows a line break even though the language still considers it to be one "line", and the fact that it just moves the cursor to the start instead of clearing the screen means that there are occasionally a number of characters in the video that aren't even really there, they just never went away from when they were there. There are some protections against this in pbi but the fact that chr(10) isn't handled properly makes them largely useless here. All that being said, I think it's almost kind of beautiful to watch. It's a huge mess of horrible code interpreting other horrible code, pieces of it breaking down in front of your eyes, and yet everything works just enough to get the right answer. It looks like garbage is being printed but if you watch closely enough with knowledge of the source you can make out what it's doing and why at any point. I feel like Cypher when I watch this video: I... I don’t even see the code. All I see is blonde, brunette, red-head.

Without further ado, here's the code ungolfed.
### UNTIL FURTHER NOTICE, ALL CODE YOU SEE HERE   ###
### IS JUST A SIMPLE LOWERCASE PROGRAM. ALL INPUT ###
### IS PRINTED UNALTERED UNLESS ITS ASCII CODE IS ###
### IN [65, 90], IN WHICH CASE IT IS PRINTED WITH ###
### 32 ADDED TO IT.                               ###

^w[B!0]{t[B]vb[T]^>}    # Copy entire input to Y=0
                        # (If the program ended here, it would be cat!)
vb[-1]                  # Leave a flag at the end of the copy (important later)

# Next, this program will set each of those bytes to 0 or 32, then add the input again.
# A byte needs to be set to 32 iff it's in [65, 90].
# pb can't test > or <, only == and !=.
# A workaround:

# Set each byte to max((byte - 64), 0)

w[X!0]{<        # For each byte:
    t[64]         # Set T to 64 as a loop variable
    w[T!0]{       # While T != 0:
        w[B!0]{     # While the current byte not 0:
            b[B-1]v   # Subtract one from the current cell, then go down one
                      # (guaranteed to be 0 and kill the loop)
        }
        ^[Y]        # Brush is at Y=0 or Y=1 and needs to be at Y=0.
                    # ^[Y] always brings brush to Y=0
        t[T-1]      # T--
    }
}

# Bytes that are currently 0 need to be 0.
# Bytes that are currently in [27, inf) need to be 0.
# Bytes in [1, 26] need to be 32.

# Set bytes that are equal to 0 to 27
# The only groups that have to be worried about are >26 and =<26.

# Then set each byte to max((byte - 26), 0)

w[B!-1]{         # Until we hit the flag:
    w[B=0]{b[27]}   # Set any 0 bytes to 27
    t[26]           # T as loop variable again
    w[T!0]{         # While T != 0:
        w[B!0]{       # While the current byte not 0:
            b[B-1]v     # Subtract one from the current cell, then go down one
                        # (guaranteed to be 0 and kill the loop)
        }
        ^[Y]          # Brush is at Y=0 or Y=1 and needs to be at Y=0.
                      # ^[Y] always brings brush to Y=0
        t[T-1]        # T--
    }
>}
b[0]              # Clear the flag

# Set bytes that are equal to 0 to 32
# All others to 0

w[X!0]{<          # For each byte:
    w[B!0]{       # While the current byte not 0:
        b[1]v       # Set it to 1, then go down one
                    # (guaranteed to be 0 and kill the loop)
    }
    ^[Y]          # Back to Y=0 no matter what
    w[B=0]{b[32]} # Set 0 bytes to 32
    w[B=1]{b[0]}  # Set 1 bytes to 0
}

# Any byte that had a capital letter is now 32. All others are 0.
# Add the original values to the current values to finish.

^w[B!0]{          # For each byte OF ORIGINAL INPUT:
    t[B]vb[B+T]^>   # Add it to the space below
}

### ABOVE IS THE ENTIRE LOWERCASE PROGRAM. THE    ###
### REST OF THE CODE IMPLEMENTS THE ALGORITHM.    ###

vb[1]            # Leave a flag after the end, guaranteed to be further right
                 # than anything else

<w[B!9]{         # Starting from the end, until hitting a tab:
    t[B]b[0]        # Store the last byte and erase it
    vv<[X]          # Go down two columns and all the way to the left
    w[B!0]{>}       # Go right until reaching an empty space
    b[T]            # Print the stored byte
    ^^<[X]w[B!0]{>} # Go back to the end of the first line
    <
}

b[0]              # Erase the tab
<w[X!-1]{         # For each byte in the first line:
    t[B]            # Store that byte
    vb[1]           # Mark that byte to be found later
    ^w[B!1]{>}      # Find the flag at the end
    vvw[X!-1]{      # For everything in the other line:
        w[B=T]{       # If the current byte is the same as the saved byte:
            b[0]        # Set it to 0
            <[X]^       # Go to the beginning of line 2
            w[B!1]{>}   # Find the marker for where the program is working in line 1
            ^b[0]v      # Set that byte that the program is working on to 0
            t[2]        # Stay on line 2 and start looking for a 2 (will never appear)
                        # (If this block was entered, it basically breaks the outer loop.)
        }
        <
    }
    ^[Y]v           # Ensure that the brush is on Y=1
    w[B!1]{>}       # Find the marker for where the program is working in line 1
    b[0]^<          # Erase the marker and start working on the next byte
}

t[0]              # Set T to 0. It's going to be used for counting the remaining bytes.

w[B!1]{           # Until hitting the flag at the very right:
    w[B!0]{         # If the current byte is not 0:
        t[T+1]        # Add 1 to T
        b[0]          # Set the current byte to 0
    }
    >
}
b[0]              # Clear the flag

vvw[X!-1]{        # Same as above, but for Y=2
    w[B!0]{
        t[T+1]
        b[0]
    }
    <
}

# T now contains the number that needs to be printed!!
# Now, to print out a number in decimal...

>b[11]            # A flag that shows the end of the number
                  # (so 0 digits aren't confused for other empty spaces on the canvas)
^b[T]             # The number to be converted to digits
w[B!0]{           # While the number to be converted is not 0:
    vw[B!11]{>}     # Go to the flag
    t[B]b[0]>b[T]   # Move it right
    <[X]^t[B]b[0]   # Store the number to be converted to digits to T and clear its space on the canvas
    vw[B!11]{>}<    # Go to the left of the flag
    w[T!0]{         # While T is not 0:
        t[T-1]        # T--
        b[B+1]        # B++
        w[B=11]{      # If B is 10:
            b[0]        # Set it back to 0
            ^<[X]b[B+1]   # Add 1 to a counter to be converted after
            vw[B!11]{>}<  # Go back to continue converting T
        }
    }
^<[X]}

vw[B!11]{         # Add 48 to all digits to get correct ASCII value
    b[B+48]>
}

b[0]              # Clear the flag value, 0s now appear as 48 instead of 0 so it is unnecessary

<w[B!0]{          # While there are digits on Y=2:
    w[B!0]{>}<      # Go to the last one
    t[B]            # Save it to T
    ^^<[X]          # Go to (0, 0)
    w[B!0]{>}       # Go right until finding an empty space
    b[T]            # Print the digit in T
    <[X]vvw[B!0]{>} # Go to the end of Y=2
    <b[0]           # Erase it
    <               # Repeat until finished. :)
}

C++ 199 bytes
Uses an array to store the count of each character in the first string, minis the count in the second string. Next it finds the sum of the absolute values of the elements of the array: this is the distance.
Golfed:
#define L(c) c<91&c>64?c+32:c
int d(char*a,char*b){int l[128];int i=128,s=0;for(;i-->0;)l[i]=0;for(;a[++i];)l[L(a[i])]++;for(i=-1;b[++i];)l[L(b[i])]--;for(i=0;++i<128;)s+=i[l]>0?i[l]:-i[l];return s;}

Ungolfed:
#define L(c) (c<='Z' && c>='A' ? c+'a'-'A':c)
//convert to lower case
int dist(char a[],char b[]){
  int l[128];
  int i = 128, s = 0;

  for(;i-->0;)
    l[i]=0;

  for(;a[++i]!='\0';)
    l[L(a[i])]++;

  for(i=-1;b[++i]!='\0';)
    l[L(b[i])]--;

  for(i=0;++i<128;)
    s+=i[l]>0?i[l]:-i[l];

  return s;
}

PowerShell, 79 bytes
param($a,$b)$a=[char[]]$a.ToLower();$b=[char[]]$b.ToLower();(diff $a $b).Length

Almost the exact same code as my answer on Anagram Code Golf ... but ... I'm getting some weird behavior if I just snip off the -eq0 from that answer, so I wound up needing to explicitly .ToLower() and recast outside of the param declaration.+
Explanation also (mostly) copied from that answer --
Takes the two string inputs, makes them lowercase, and re-casts them as char-arrays. The diff function (an alias for Compare-Object) takes the two arrays and returns items that are different between the two. We leverage that by re-casting the return as an array with (), and then checking its length.
+For example, I was getting bogus results with param([char[]]$a,[char[]]$b)(diff $a $b).length on the all lowercase./ALL UPPERCASE! test. If I manually separated out the arrays (e.g., ran (diff ('a','l','l'...), it worked fine, but would fail every time there were capital/lowercase overlap with the casting. Everything I can read on the documentation states that diff is case-insensitive by default, so ... shrug???

Very odd.  It isn't needed for any of the other cases (even with different case-sensitivity).

Bash, 68 67 bytes
f()(fold -w1<<<"$1"|sort)
diff -i <(f "$1") <(f "$2")|grep -c ^.\

I think this works. Note the trailing space on the second line.
Test cases
$ ./anagram "Hello, world!" "Code golf!"
9
$ ./anagram "12345 This is some text." ".txet emos si sihT 54321"
0
$ ./anagram "All unique characters here!" "Bdfgjkmopvwxyz?"
42
$ ./anagram "This is not exactly like Levenshtein distance," "but you'll notice it is quite similar."
30
$ ./anagram "all lowercase." "ALL UPPERCASE!"
8

Perl, 52 46 bytes + 3 switches (a,F,n) = 55 49 bytes
# 49 bytes (prefix 'x' to all characters so that values() could be removed)
perl -naF -E 'END{$c+=abs for%a;say$c}$a{x.lc}+=2*$.-3 for@F'

# 55 bytes
perl -naF -E 'END{$c+=abs for values%a;say$c}$a{+lc}+=2*$.-3 for@F'

Takes input from STDIN with the input strings in their own lines, terminated by EOF.
Switches:
-aF splits each input line into characters and stores this into @F
-n  loop over all input lines
-E  Execute the script from the next arg

Code:
# %a is the hash counting the occurances of the lowercase characters
# $. has the line number. Thus, 2*$.-3 is -1 for line 1 and +1 for line 2
$a{+lc}+=2*$.-3 for @F

# In the end (assuming 2 lines have been read), sum up the absolute values
# from the hash %a. Note that if a character occured more times in string 1
# its value be negative, if more in string 2 then positive, otherwise 0.
END {
    $c+=abs for values %a;
    say $c
}

Bash + GNU utils, 53
S(){ sed 's/./\L&\n/g'|sort;};S>1;S|comm -3 1 -|wc -l

sed transforms to lowercase and splits the string into lines for sort.  Since we need to do this twice I put it into a function.  comm3 -3 filters out the relevant lines and wc -l produces the number.
Input is via STDIN; since two commands read sequentially, you have to send EOF (Ctrl-D) twice, between the strings and at the end.  Overwrites file 1, if present.

Matlab, 91 bytes
function r=f(s,t)
s=lower(s);t=lower(t);u=unique([s t]);r=sum(abs(histc(s,u)-histc(t,u)));

Try it online.
This works as follows:

Converts the strings to lower case.
Finds the unique characters of the two strings together. That is, determines all characters that ever appear in the strings.
Computes the histogram of each string. That is, for each string finds how many times each of the characters obtained in step 2 appears.
Subtracts the histograms and takes the absolute value of the differences. This represents how many times a character appears in one string more than in the other.
The result is the sum of those absolute differences.

This seems way too long-- are you sure it's optimal?

@ThomasKwa No, not at all :-)

Jelly, 6 bytes
Œlœ^/L

Try it online!

F#, 134 126 bytes
let g=Seq.countBy Char.ToLower>>List.ofSeq
let f a b=g a@g b|>Seq.groupBy fst|>Seq.sumBy(snd>>Seq.map snd>>Seq.reduce(-)>>abs)

Explanation:

Count the number of times each (lowercased) character appears in a and b separately.
Group the counts together by their common character
Reduce each group with the - operator, which has the following effect:

If only one value is found (i.e. the character appeared in only one input), that value is returned.
If two values are found (i.e. the character appeared in both inputs) subtract the second value from the first.

Sum the absolute value of the values from the previous step.

Scala, 134 81 bytes
Thanks @ASCII-only for their work.
(s,t)=>{var k::l::_=List(s,t)map(_.toLowerCase.toBuffer)
((k--l)++(l--k)).length}

Try it online!

quick golf (just doing the more obvious golfs first), 118

81

ew, I missed that, I have things to learn in scalagolf

Haha, I probably have more things to learn. The first being Scala :P

those tricks were nice though.

Yeah, golfing in other languages helps :P

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Integer Percentify
Write a function which takes in a list of positive integers and returns a list of integers approximating the percent of total for the corresponding integer in the same position.
All integers in the return list must exactly add up to 100. You can assume the sum of integers passed in is greater than 0.  How you want to round or truncate decimals is up to you as long as any single resulting integer returned as a percentage is off by no more than 1 in either direction.
p([1,0,2])      ->  [33,0,67] or [34,0,66]
p([1000,1000])  ->  [50,50] or [49,51] or [51,49]
p([1,1,2,4])    ->  [12,12,25,51] or [13,12,25,50] or [12,13,25,50] or [13,13,25,49] or [13,12,26,49] or [12,13,26,49] or [12,12,26,50]
p([0,0,0,5,0])  ->  [0,0,0,100,0]

This is code-golf, so shortest code in bytes wins!

Must our algorithm be deterministic? Must it always terminate within a bounded time?

We already had some rounding problem similar but more general

Related http://codegolf.stackexchange.com/q/45701/21348 (but this new one is far simpler)

I assume that [13,13,25,49] is also ok for the third example.

Can we return our answer separated by new lines (ie. [0, 1] => 0\n100)?

I suggest that you add another test case: p([2,2,2,2,2,3]). It has many possible legal answers, but not all 2's can be mapped to the same value. This eliminates many overly-simple algorithms that work on all the previous test cases because the rounding isn't too bad.

Can p([1000,1000])  ->  [49,51]?

@l4m2 It seems wrong, but both the results are off by 1 and no more, so it follows the spec

Dyalog APL, 21 19 16 bytes
+\⍣¯1∘⌊100×+\÷+/

The above is a train equivalent of
{+\⍣¯1⌊100×+\⍵÷+/⍵}

Try it online.
How it works
                 ⍝ Sample input: 1 1 2 4
           +\    ⍝ Cumulative sum of input. (1 2 4 8)
              +/ ⍝ Sum of input. (8)
             ÷   ⍝ Divide the first result by the second. (0.125 0.25 0.5 1)
       100×      ⍝ Multiply each quotient by 100. (12.5 25 50 100)
      ⌊          ⍝ Round the products down to the nearest integer... (12 25 50 100)
     ∘           ⍝ and ...
  ⍣¯1            ⍝ apply the inverse of...
+\               ⍝ the cumulative sum. (12 13 25 50)

If only Fermat could have taken golf lessons from you.

@TessellatingHeckler I see what you did there. Maybe then he'd have enough room in the margins for his proof. :)

TI-BASIC, 26 23 16 bytes
For TI-83+/84+ series calculators.
ΔList(augment({0},int(cumSum(ᴇ2Ans/sum(Ans

Thanks to @Dennis for a beautiful algorithm! We take the cumulative sum of the list after converting to percents, then floor, tack a 0 onto the front, and take differences. ᴇ2 is one byte shorter than 100.
At the same byte count is:
ΔList(augment({0},int(cumSum(Ans/sum(Ans%

Fun fact: % is a two-byte token that multiplies a number by .01—but there's no way to type it into the calculator! You need to either edit the source outside or use an assembly program.
Old code:
int(ᴇ2Ans/sum(Ans
Ans+(ᴇ2-sum(Ans)≥cumSum(1 or Ans

The first line calculates all floored percents, then the second line adds 1 to the first N elements, where N is the percentage left over. cumSum( stands for "cumulative sum".
Example with {1,1,2,4}:
          sum(Ans                  ; 8
int(ᴇ2Ans/                         ; {12,12,25,50}

                        1 or Ans   ; {1,1,1,1}
                 cumSum(           ; {1,2,3,4}
     ᴇ2-sum(Ans)                   ; 1
                ≥                  ; {1,0,0,0}
Ans+                               ; {13,12,25,50}

We won't have N>dim([list], because no percentage is decreased by more than 1 in flooring.

Not sure how you counting the bytes here, it looks awfully longer than 23 to me

@DavidArenburg This is just the human-readable form. All tokens (int(, sum(, Ans, etc.) occupy only one byte.

+1 This is one of the most impressive TI-BASIC golfs I've seen on this site.

Thomas this answer is stunning!

Are you sure there's no way to enter the % symbol? I would've thought it could be found in the symbol catalog... Also, I should get out my TI-84+ Silver. I haven't used it in a while. Block Dude is awesome.

@mbomb007 It's not in the catalog of either my 84+ or my SE. I don't know why TI decided to exclude it.

CJam, 25 23 22 bytes
{_:e2\:+f/_:+100-Xb.+}

Thanks to @Sp3000 for 25 → 24.
Try it online.
How it works
_                   e# Push a copy of the input.
 :e2                e# Apply e2 to each integer, i.e., multiply by 100.
    \               e# Swap the result with the original.
     :+             e# Add all integers from input.
       f/           e# Divide the product by the sum. (integer division)
        _:+         e# Push the sum of copy.
           100-     e# Subtract 100. Let's call the result d.
               Xb   e# Convert to base 1, i.e., push an array of |d| 1's.
                 .+ e# Vectorized sum; increment the first |d| integers.

J (8.04 beta), 59 bytes (30 stolen bytes)
30 byte literal J-port of Dennis's APL answer:
    f=.3 :'+/\^:_1<.100*(+/\%+/)y'

    f 1 1 2 4
12 13 25 50

59 bytes answer, best I could do myself:
f=.3 :0
p=.<.100*y%+/y
r=.100-+/p
p+((r$1),(#p-r)$0)/:\:p
)

(Based on the remainder having to go to the highest values, no more than +1 each, split over multiple values in the case of a remainder > 1 or a tie for highest value).
e.g.
   f 1 0 2
33 0 67

   f 1000 1000
50 50

   f 1 1 2 4
12 12 25 51

   f 0 0 0 5 0
0 0 0 100 0

   f 16 16 16 16 16 16
17 17 17 17 16 16

   f 0 100 5 0 7 1
0 89 4 0 7 0

Explanation

f=.3 : 0 - 'f' is a variable, which is a verb type (3), defined below (:0):
p=. variable 'p', built from:

y is a list of numbers 1 0 2
+/y is '+' put between each value '/', the sum of the list  3
y % (+/y) is original y values divided by the sum: 0.333333 0 0.666667
100 * (y%+/y) is 100x those values: 33.33.. 0 0.66... to get the percentages.
<. (100*y%+/y) is the floor operator applied to the percentages: 33 0 66

r=. variable 'r', built from:

+/p is the sum of the floored percentages: 99
100 - (+/p) is 100 - the sum, or the remaining percentage points needed to make the percentages sum to 100.

result, not stored:

r $ 1 is a list of 1s, as long as the number of items we need to increment: 1 [1 1 ..]
#p is the length of the percentage list
(#p - r) is the count of items that won't be incremented
(#p-r) $ 0 is a list of 0s as long as that count: 0 0 [0 ..]
((r$1) , (#p-r)$0) is the 1s list followed by the 0s list:  1 0 0
\: p is a list of indexes to take from p to put it in descending order.
/: (\:p) is a list of indexes to take from \:p to put that in ascending order
((r$1),(#p-r)$0)/:\:p is taking the elements from the 1 1 .. 0 0 .. mask list and sorting so there are 1s in the positions of the biggest percentages, one for each number we need to increment, and 0s for other numbers: 0 0 1.
p + ((r$1),(#p-r)$0)/:\:p is the percentages + the mask, to make the result list which sums to 100%, which is the function return value.

e.g.
33 0 66 sums to 99
100 - 99 = 1
1x1 , (3-1)x0 = 1, 0 0
sorted mask   = 0 0 1

33 0 66
 0 0  1
-------
33 0 67

and

) end of definition.

I'm not very experienced with J; I wouldn't be too surprised if there's a "turn list into percentages of the total" operation built in, and a cleaner way to "increment n biggest values" too. (This is 11 bytes less than my first attempt).

Very cool.  I have a python solution but it's a lot longer than this one.  Nice work!

If you haven't noticed, the rules have changed, so you should be able to shorten this considerably.

@DaveAlger thanks! @ThomasKwa I noticed, I'm not sure it helps me considerably - first attempt I can get -2 characters. I would need to change the list[0:100-n] + list[:-100-n] approach - and I haven't thought of another way to approach it.

Mathematica, 41 bytes
(s=Floor[100#/Tr@#];s[[;;100-Tr@s]]++;s)&

Wait, what happens here?

@Seeq The algorithm is like the old code in the TI-BASIC answer. It calculates all floored percents, then adds 1 to the first N elements, where N is the percentage left over.

Jelly, 7 bytes
-2 thanks to Dennis, reminding me to use another new feature (Ä) and using : instead of what I initially had.
ŻÄ×³:SI

Try it online!
Jelly, 11 bytes
0;+\÷S×ȷ2ḞI

Try it online!
Done alongside caird coinheringaahing and user202729 in chat.
How it works

0;+\÷S×ȷ2ḞI - Full program.

0;          - Prepend a 0.
  +\        - Cumulative sum.
    ÷S      - Divided by the sum of the input.
      ×ȷ2   - Times 100. Replaced by ×³ in the monadic link version.
         ḞI - Floor each, compute the increments (deltas, differences).

JavaScript (ES6), 81 bytes
a=>(e=0,a.map(c=>((e+=(f=c/a.reduce((c,d)=>c+d)*100)%1),f+(e>.999?(e--,1):0)|0)))

That "must equal 100" condition (rather than rounding and adding up) nearly doubled my code (from 44 to 81). The trick was to add an pot for decimal values that, once it reaches 1, takes 1 from itself and adds it to the current number. Problem then was floating points, which means something like [1,1,1] leaves a remainder of .9999999999999858. So I changed the check to be greater than .999, and decided to call that precise enough.

Haskell, 42 27 bytes
p a=[div(100*x)$sum a|x<-a]

Pretty much the trivial method in Haskell, with a few spaces removed for golfing.
Console (brackets included to be consistent with example):
*Main> p([1,0,2])
[33,0,66]
*Main> p([1000,1000])
[50,50]
*Main> p([1,1,2,4])
[12,12,25,50]
*Main> p([0,0,0,5,0])
[0,0,0,100,0]

Edit: practised my putting, made some obvious replacements.
Original:
p xs=[div(x*100)tot|x<-xs]where tot=sum xs

The sum of the list should be 100. In your first example, it is 99

Haskell, 63 56 55 bytes
p l=tail>>=zipWith(-)$[100*x`div`sum l|x<-0:scanl1(+)l]

JavaScript (ES6) 60 63 95
Adapted and simplified from  my (wrong) answer to another challenge
Thk to @l4m2 for discovering that this was wrong too
Fixed saving 1 byte (and 2 byte less, not counting the name F=)
v=>v.map(x=>(x=r+x*100,r=x%f,x/f|0),f=eval(v.join`+`),r=f/2)

Test running the snippet below in any EcmaScript 6 compliant browser

F=
v=>v.map(x=>(x=r+x*100,r=x%f,x/f|0),f=eval(v.join`+`),r=f/2)

console.log('[1,0,2] (exp [33,0,67] [34,0,66])-> '+F([1,0,2]))
console.log('[1000,1000] (exp [50,50])-> '+F([1000,1000]))
console.log('[1,1,2,4] (exp[12,12,25,51] [13,12,25,50] [12,13,25,50] [12,12,26,50])-> '+F([1,1,2,4]))
console.log('[0,0,0,5,0] (exp [0,0,0,100,0])-> '+F([0,0,0,5,0]))
console.log('[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,980] -> '+F([1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,980]))
console.log('[2,2,2,2,2,3] -> ' + F([2,2,2,2,2,3]))

Failed on [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,980]

@l4m2 failed why? The sum is 100 and any single resulting integer returned as a percentage is off by no more than 1 in either direction.

The last one should be at most one off by 98, but it's 100

@l4m2 uh, right, thanks.Time to think again

@l4m2 should be fixed now

Perl, 42 bytes
Based on Dennis's algorithm
Includes +1 for -p
Run with the list of numbers on STDIN, e.g.
perl -p percent.pl <<< "1 0 2"

percent.pl:
s%\d+%-$-+($-=$a+=$&*100/eval y/ /+/r)%eg

Brain-Flak, 150 bytes
((([]){[{}]({}<>)<>([])}{})[()])<>([]){{}<>([{}()]({}<([()])>)<>(((((({})({})({})){}){}){}{}){}){}(<()>))<>{(({}<({}())>)){({}[()])<>}{}}{}([])}<>{}{}

Try it online!
Starting from the end and working backward, this code ensures at each step that the sum of the output numbers so far is equal to the total percentage encountered, rounded down.
(

  # Compute and push sum of numbers
  (([]){[{}]({}<>)<>([])}{})

# And push sum-1 above it (simulating a zero result from the mod function)
[()])

<>

# While elements remain
([]){{}

  # Finish computation of modulo from previous step
  <>([{}()]({}

    # Push -1 below sum (initial value of quotient in divmod)
    <([()])>

  # Add to 100*current number, and push zero below it
  )<>(((((({})({})({})){}){}){}{}){}){}(<()>))

  # Compute divmod
  <>{(({}<({}())>)){({}[()])<>}{}}{}

([])}

# Move to result stack and remove values left over from mod
<>{}{}

Husk, 14 bytes
Ẋ-Θmȯ⌊*100/Σ¹∫

Try it online! or Verify all test cases
Algorithm from Dennis' answer.
Explanation
Ẋ-Θmȯ⌊*100/Σ¹∫
             ∫ cumulative sums
   mȯ          map to the follwing 4 functions
          /Σ¹  divide by sum of input
      *100     times 100
     ⌊         floored
  Θ            prepend a zero
Ẋ-             fold consecutive pairs with subtraction

@KevinCruijssen think it's correct now.

Octave, 40 bytes
@(x)diff(ceil([0,cumsum(100*x/sum(x))]))

Python 2, 89 bytes
def f(L):
 p=[int(x/0.01/sum(L))for x in L]
 for i in range(100-sum(p)):p[i]+=1
 return p

print f([16,16,16,16,16,16])
print f([1,0,2])

->

[17, 17, 17, 17, 16, 16]
[34, 0, 66]

JavaScript, 48 bytes

F=

x=>x.map(t=>s+=t,y=s=0).map(t=>-y+(y=100*t/s|0))

// Test
console.log=x=>O.innerHTML+=x+'\n';

console.log('[1,0,2] (exp [33,0,67] [34,0,66])-> '+F([1,0,2]))
console.log('[1000,1000] (exp [50,50])-> '+F([1000,1000]))
console.log('[1,1,2,4] (exp[12,12,25,51] [13,12,25,50] [12,13,25,50] [12,12,26,50])-> '+F([1,1,2,4]))
console.log('[0,0,0,5,0] (exp [0,0,0,100,0])-> '+F([0,0,0,5,0]))

05AB1E, 9 bytes
.¥IO/т*ï¥

Try it online!
+3 for a bugfix

You can remove the leading D, because input will be used implicitly.

Although I'm not 100% sure it's valid. The challenge states percentages can be off by 1, but must always sum to 100. But an input like [1,1,1] would result in [33,33,33]. Although I'm pretty sure halve the other answers are incorrect for similar reasons. Here a straight-forward fix at the cost of 3 bytes.

Vyxal, 12 bytes
∑/₁*ṙ:∑₁$-Þ…

Try it Online!
Explained
∑/₁*ṙ:∑₁$-Þ…
∑             # sum(input)
 /            # input ÷ ↑         # get the weight of each number
  ₁*          # ↑ * 100           # and make it a percentage
    ṙ         # map(round, ↑)     # rounding each number
     :∑       # ↑, sum(↑)         # now sum the above
       ₁$-    # 100 - ↑           # and subtract from 100. The result represents any potential round errors that need correction
          Þ…  # distribute(↑, ↑↑) # spread ↑ over the rounded list evenly

Rust, 85 bytes
This uses vectors instead of arrays because as far as I am aware there is no way to accept arrays of multiple different lengths.
let a=|c:Vec<_>|c.iter().map(|m|m*100/c.iter().fold(0,|a,x|a+x)).collect::<Vec<_>>();

Japt v2.0a0, 13 bytes
å+ mzUx÷L)änT

Try it

Jq 1.5, 46 bytes
add as$s|.[1:]|map(100*./$s|floor)|[100-add]+.

Expanded
  add as $s               # compute sum of array elements
| .[1:]                   # \ compute percentage for all elements
| map(100*./$s|floor)     # / after the first element
| [100-add] + .           # compute first element as remaining percentage

Try it online!

PHP, 82 bytes
for(;++$i<$argc-1;$s+=$x)echo$x=$argv[$i]/array_sum($argv)*100+.5|0,_;echo 100-$s;

takes input from command line arguments, prints percentages delimited by underscore.
Run with -nr or try it online.

This outputs 15_15_15_15_15_25 when given the input [2,2,2,2,3], which isn't right because 3/13 ~= 23.1%

@SophiaLechner Which of the answers does that correctly?

Most do, actually. The correct answers so far seem to be built around one of two algorithms; the first rounds off the percentages of cumulative sums and takes the difference; the second calculates the floors of the percentages and then increments enough distinct percentages to bring the total to 100.

@SophiaLechner I didn´t mean I wouldn´t look into it; but I´ll do later. Thanks for noticing.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Print out all IPv6 addresses

This reminds me when a few years ago someone uploaded a torrent "Hacker tool: complete list of all IP addresses". This was, of course, just a generated list of the ~4 billion IPv4 addresses, but thousands of "h4xx0rz" downloaded it. Look mum, imahacker!

This was then, but nowadays everybody has switched to IPv6. (Right?)
Your task is to write a program that prints out all IPv6 addresses.
You should write a full program that takes no input and prints IPv6 addresses, one per line, and no other output. Your program must print all 2128 possible addresses, including invalid ones. Each address must be printed exactly once. You may print the addresses in any order.
Each address may be printed in full, with 8 groups of 4 hexadecimal digits separated by colons, e.g.
2001:0db8:85a3:0000:0000:8a2e:0370:7334

You may, at your discretion, use any of the standard abbreviations from RFC 5952:

Leading zeros in a group may be omitted, except that 0 cannot be abbreviated further.
:: may be used at most once per address to abbreviate a sequence of one or more all-zero groups.
The hexadecimal digits may use lowercase or uppercase.

If you achieve the representation recommendation from RFC 5952 (lowercase letters only, shortest possible representation, with :: used as early as possible if there are multiple places where it can be used), you get a -20% bonus.
Due to the size of the output, your program is not expected to finish while we're sitting there. Your program may be interrupted by external means at some point (Ctrl+C, pulling out the power, …). Your program must produce output as a stream, so that after a “reasonable” wait, it will have produced some lines. Basically, building a giant string in memory only to print it at the end is not allowed. Any program that would run out of memory on a “standard” PC is disqualified. (Nonetheless, if your program was left to run for sufficiently long, it must print all IPv6 addresses and then exit.)
(If this condition is a problem for web interpreters that run the program until completion and then let you see the output, and you don't have a hosted interpreter, test your program on a smaller version of the problem, and then carefully adjust it to the full 2128.)
Your score is your program's length in bytes, multiplied by 0.8 if you get the bonus. It's code golf, so the lowest score wins.

This is 5.445*10¹⁵ yottabytes. To store all of that data, you need at least 15 Earth-sized datacenters containing nothing but hard drives packed in as tightly as possible. That's one big torrent.....

@Mew I'm wondering how small the file would be compressed (using some generic compression like gzip) though.

@SztupY: apparently the output can be compressed to 25 bytes  (Decompression algorithm = a Pyth interpreter, compression algorithm = posting to PPCG)  From lurking on this site, it seems that Pyth is a rather generic compressed format.

In my experience, @Gilles is a real SO heavyweight!  Glad to see you bringing questions to our little PPCG corner of SO!  Also fun for me to see networking-related questions.

This reminds me of that "iterate over all possible GUIDs" question on SO.

Should consider additional bonuses if someone wants to use the representation described in rfc 1924... or as another challenge.

Can a Verilog solution on FPGA hardware be accepted? Could the output format then be parallel ASCII?

@hexafraction Um, I don't know. I guess so? I can't find an applicable meta policy.

@BenVoigt Now you just need to write a compression algorithm. :)

You know, this idea of a generated file suggests another challenge: Make a function that generates a requested byte range from a file containing all ipv6 addresses.

@BenVoigt there's a long running AI/compression challenge based on handing in (their dataset compressed + your decompresser), on the idea that identifying patterns is linked to intelligence, more intelligence == better compression, and you can't cheat by handing in 1 byte + hide the data in the decompresser. CodeGolf is just like that, except with human compressers and we can offload everything possible into the interpreter. It would be a bit of a different site if we scored (code size + interpreter/compiler size).

@TessellatingHeckler: Meta question related to that: http://meta.codegolf.stackexchange.com/q/7104/11335

What is this "IPv6" you speak of?

Pyth, 21 bytes
KJ^8CdWJj\:ct.H+K=tJ4

Uses a while loop with J as the iterator variable. Initializes the maximum using 8^chr(' '). Pads by adding that initial value, converting to hex, then removing the first character.

That code looks like somebody sneezed on their keyboard, then tried to clean it.

@darksky That's golflangs for you :P

Python 3, 65 bytes · 0.8 = 52.0
from ipaddress import*
n=4**64
while n:n-=1;print(IPv6Address(n))

Dang python! It always has the right methods! :D

ipaddress is python3 only.

@Hurricane996, yeah, I had been using it in Python 2 from PyPI without realizing that it only entered the standard library in Python 3. So I’ve switched this to Python 3 at the expense of one byte.

@MDXF Python doesn't have ++ or -- operators

Pyth, 27 25 24 bytes
Note: the code had a bug previously, fixing it saved 1 byte
J^4 64WJj\:c%"%032x"=tJ4

Prints the addresses like
ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff
ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffe
ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffd
ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffc
...
0000:0000:0000:0000:0000:0000:0000:0003
0000:0000:0000:0000:0000:0000:0000:0002
0000:0000:0000:0000:0000:0000:0000:0001
0000:0000:0000:0000:0000:0000:0000:0000

Previous (more complicated) version using the pad operator (also 24 bytes):
J^4 64WJj\:c.[\032.H=tJ4

Explanation
J^4 64                  set J to 2^128
WJ                     while J is not 0:
            =tJ               decrement J
    %"%032x"                 format to length-32 hex string
   c           4            split every 4 chars
j\:                        join by : and print

Pyth, 21 bytes (invalid)
jmj\:c.[\032.Hd4^4 64

This can't be run since 1) it would consume at least 2132 bytes (252 yobibytes) of memory and 2) the interpreter doesn't like it (2128 doesn't fit in ssize_t, so no lists of that size). It would print the addresses in lexicographical order. You can try out the algorithm by changing the number(s) in the end to something usable.

What about ... "Any program that would run out of memory on a “standard” PC is disqualified." ?

@TessellatingHeckler The first one won't, as it runs iteratively. The second one I have clearly marked as invalid.

C (with GCC extensions), 76 bytes * 0.8 = 60.8
__uint128_t i;main(){char s[50];for(;inet_ntop(10,&i,s,49),puts(s),++i>0;);}

This uses the 128-bit integers GCC extension to simply count up from :: to ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff.  inet_ntop() correctly formats each address so the -20% bonus can be claimed.
Output
Using sed to output every millionth line up to 10 million:
$ ./ipv6all | sed -n '1~1000000p;10000000q'
::
4042:f00::
8084:1e00::
c0c6:2d00::
9:3d00::
404b:4c00::
808d:5b00::
c0cf:6a00::
12:7a00::
4054:8900::
$

Note I am using a little-endian x86_64 machine, and that network addresses are typically always in network-order (big-endian), so the endianness is effectively swapped by using inet_ntop().  This does not matter - all addresses will still (eventually) be displayed.

__int128_t i;s[];main(){for(;inet_ntop(10,&i,s,49),puts(s),++i;);} is 66 bytes, you can always make s[] -> s[50] for +2 bytes just to be sure, but this works

CJam, 36 27 bytes
G32#{(_"%032x"e%4/':*oNo}h;

-9 bytes thanks to @Dennis (I forgot that CJam has string formatting). Prints the addresses lowercase and descending.
For obvious reasons, use the Java interpreter, not the online one. You can replace G32# with something smaller for testing online though, e.g. here's the last 100.
Explanation
G32#             16^32 = 2^128. Call this n
{ ... }h;        While loop. The final ; is to pop n at the end
 (               Decrement n
 _               Copy n
 "%032x"e%       String format to hex, padded to 32 digits
 4/              Split into groups of 4
 ':*             Join with colons
 oNo             Output with newline

What's kind of interesting is that the online interpreter, beyond not being able to handle the size of course, also prints the result wrong. If you remove the loop, and only print the first value, it prints 0000:0000:0000:0000:0000:0000:ffff:ffff. Looks like the string formatting might work differently online. I confirmed that it works fine with the offline version.

n is the same as oNo in TIO.

Python 2.7, 67 bytes
n=4**64
while n:n-=1;s='%032x'%n;exec"s=s[4:]+':'+s[:4];"*7;print s

As a side effect of the method used to insert the colons, the addresses are printed with the rightmost column appearing at the left:
ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff
fffe:ffff:ffff:ffff:ffff:ffff:ffff:ffff
fffc:ffff:ffff:ffff:ffff:ffff:ffff:ffff
...
0003:0000:0000:0000:0000:0000:0000:0000
0002:0000:0000:0000:0000:0000:0000:0000
0001:0000:0000:0000:0000:0000:0000:0000

The rotating is really neat! Also belated, but welcome from anarchy :)

If you say the rightmost column is at the left, it's printing invalid IPv6 addresses, but if the columns are in the correct places, then it's [printing] the addresses in any order. ;)

Cinnamon Gum, 16 bytes
0000000: 678b 36d0 b54c d44d 8bc5 455b 8d0c 0500  g.6..L.M..E[....                               .

Try it online. (TIO limits output)
Explanation
The g mode puts Cinnamon Gum in generate mode. The rest of the string decompresses to this regex:
[0-9a-f][0-9a-f][0-9a-f][0-9a-f]:[0-9a-f][0-9a-f][0-9a-f][0-9a-f]:[0-9a-f][0-9a-f][0-9a-f][0-9a-f]:[0-9a-f][0-9a-f][0-9a-f][0-9a-f]:[0-9a-f][0-9a-f][0-9a-f][0-9a-f]:[0-9a-f][0-9a-f][0-9a-f][0-9a-f]:[0-9a-f][0-9a-f][0-9a-f][0-9a-f]:[0-9a-f][0-9a-f][0-9a-f][0-9a-f]

It then creates a generator of all possible strings that match the regex and iterates through it, printing out each one.
Somewhat amusingly, the golfier regex ([0-9a-f]{4,4}:){7,7}[0-9a-f]{4,4} actually compresses to a longer string than the regex above.

Verilog, 335
My first Verilog submission, probably could use more golfing but I don't have the energy to do so right now. c is clock, o is ASCII output. Does not qualify for formatting bonus due to zero-padding instead of abbreviating.
module b(output[0:38]o,input c);reg[127:0]a;wire[0:39]d;assign o=d[0:38];always @(posedge c) a<=a+(~(&a));genvar i,j;generate for(i=0;i<8;i=i+1) begin:q for(j=0;j<4;j=j+1) begin:r assign d[5*i+j]=a[16*i+4*j:16*i+4*j+7]>9?{4'h6,a[16*i+4*j:16*i+4*j+7]-9}:{4'h3,a[16*i+4*j:16*i+4*j+7]};end assign d[5*i+4]=8'h3A; end endgenerate endmodule

This is a simple iteration followed by some bit-twiddling to make the output ASCII. I chop the colon after the last group with a small hack. Synthesizes and appears to work for xc3s500e-4ft256-4 on ISE 13.7 lin64.

C, 91-126 bytes
My original version, 119 bytes.
long a[9],i;
f(long*x){if(65536&++*x)*x=0,f(x+1);}
main(){for(;!a[8];f(a))for(i=7;i+1;i--)printf(i?"%lx:":"%lx\n",a[i]);}

Best golfed portable-ish version, 103 bytes (thanks @Dennis for some of these concepts)
long*p,a[9];
main(i){while(!a[8]){
for(i=8;i--;printf(i?"%lx:":"%lx\n",a[i]));
for(p=a;++*p>>16;*p++=0);}}

Explanation: The algorithm itself is reasonably straightforward. I used long rather than unsigned int because it's shorter. Declaring them at the file level means everything's preinitialized with zeros. The f function is a simple increment with carry that operates on the low 16 bits of each word. The loop ends when it carries into the 129th bit.
Iterating backwards for the printf means that we print the addresses in the "proper" order and also the check for printing a newline is a few characters shorter.
This does use some non-portable constructs. It's best regarded as a K&R dialect of C, since it uses implicit int return types and does not include stdio.h. And my use of long was informed by this - on most modern systems int is sufficient because it's 32 bits. This could probably run unmodified on PDP-11 Unix.
However, it can be shorter. If we assume that we can use int (either as a type wider than 16 bits, or a type of exactly 16 bits with various properties that happen to be true on many systems such as twos complement and arithmetic rollover), we can get rid of the stuff related to using long.
Version for int wider than 16 bits, 97 bytes.
a[9],*p;main(i){while(!a[8]){
for(i=8;i--;printf(i?"%x:":"%x\n",a[i]));
for(p=a;++*p>>16;*p++=0);}}

Version for 16-bit systems, 91 bytes.
a[9],*p;main(i){while(!a[8]){
for(i=8;i--;printf(i?"%x:":"%x\n",a[i]));
for(p=a;!++*p;p++);}}

Oddly enough, though, the original K&R compiler didn't actually support the declaration without int (it compiles fine, but treats the variables as external and therefore undefined at link time), so an additional three bytes are needed to change the declaration to int*p,a[9]; for a total of 94.
Also, if the assumption that it is interrupted before completing output were a hard constraint, we could remove the end check, saving five bytes.
Bonus: fully ANSI portable version, 126 bytes:
#include<stdio.h>
long*p,i,a[9];
int main(){while(!a[8]){
for(i=8;i--;printf(i?"%lx:":"%lx\n",a[i]));
for(p=a;++*p>>16;*p++=0);}}

Newlines in all versions are inserted for readability and in locations where whitespace is not required, and are excluded from the byte count, except for the newline after the #include line in the ANSI version.
All versions except the ANSI version fall through at the end of main and therefore may return a spurious exit code to the operating system.

Portability usually isn't a concern here. This works on my machine: a[9];f(int*x){if(++*x>>16)*x=f(x+1);}main(i){for(;!a[8];f(a))for(i=8;i--;)printf(i?"%x:":"%x\n",a[i]);}

You are clearly much better at this than me. Some of those I am very surprised works ,but I should really have thought of the i-- condition check.

When you tested this, did you run it all the way until the carry? My machine puts a random value in a[0] after rolling over in your version.

Yes. The first 6,553,601 IP addresses are printed correctly on my machine.

Ideone doesn't like it either, but it works on codepad: wrap in a[0] and wrap in a[1]

You do need the end check. Good point, I shouldn't have written “assume” — the program is supposed to be correct if not interrupted, and useful (fsvo useful) if interrupted. I've clarified the question (fortunately nobody tried to exploit this loophole), thanks.

Oops, my browser didn't show your edit before I posted my last comment...  p=a;while(!++*p) -> for(p=a;!++*p;) still works though.

AutoIt3, 142 231 Bytes
For $a=0 To 2^32-1
For $b=0 To 2^32-1
For $c=0 To 2^32-1
For $d=0 To 2^32-1
$s=StringFormat("%08x%08x%08x%08x",$a,$b,$c,$d)
For $j=0 To 8
ConsoleWrite(StringMid($s,$j*4+1,4)&($j<7?":":""))
Next
ConsoleWrite(@LF)
Next
Next
Next
Next

Explanation

For $a=0 To 2^32-1: Iterate 4 times over 0-2^32 ((2^32)^4=2^128) possible combinations.
$s=StringFormat("%08x%08x%08x%08x",$a,$b,$c,$d): Convert the numbers to a hexadecimal string with a length of 32 (4*32).
For $j=0 To 8: Iterate over all 8 sections of the string.
ConsoleWrite(StringMid($s,$j*4+1,4)&($j<7?":":"")): Extract the next 4 characters from the string and add a colon (:) at the end, if we haven't reached the last section, then output everything to the console
Next: End the inner for-loop
ConsoleWrite(@LF): Add a line-feed at the end of the line
Next: End the outer for-loops

Expected output size: (One line (39 bytes) + line-feed) (=40 bytes) * 2^128 = 1.361* 10^16 YB  (yottabytes)

Don’t you mean 4^64 - 1?

@AndersKaseorg apparently I need to even use 4 loops up to 2^32-1, because AutoIt can parse large values like 4^64, but can't store them for use in a loop, because integers only go up to 2^32-1 in AutoIt.

Commodore BASIC 2.0, 339 bytes
In order to get lower-case hex digits, this program is written in "shifted mode" (press <SHIFT>+<C=>)
1k=65535:a=0
2fOb=0tok:fOc=0tok:fOd=0tok:fOe=0tok:fOf=0tok:fOg=0tok:fOh=0tok
3x=a:goS6:?":";:x=b:goS6:?":";:x=c:goS6:?":";:x=d:goS6:?":";:x=e:goS6:?":";:x=f
4goS6:?":";:x=g:goS6:?":";:x=h:goS6:?
5nE:nE:nE:nE:nE:nE:nE:nE:a=a+1:ifa<65536tH2
6y=x/4096:goS7:y=x/256aN15:goS7:y=x/16aN15:goS7:y=xaN15:goS7:reT
7?mI("0123456789abcdef",y+1,1);:reT

Simply making this work on the Commodore 64 was a challenge, because of memory, screen size, data size, and other limitations.  I considered implementing the abbreviated representation, but other limitations (such as the undocumented inability to use array elements as loop indices) meant it would increase the length of the program by an estimated 1000 bytes.
Line 7 is an implementation of HEX$(), which Commodore BASIC 2.0 is lacking.  I can't use a DEF FN for this because those can only return numbers, not strings.  Line 6 is a subroutine that applies it to a group of four digits, which would have been considerably shorter if functions could return strings.
Lines 2 and 5 are eight nested loops, implemented as seven "for" loops and a conditional goto because eight "for" loops, when combined with the two "gosubs" for printing out the address, will overflow the C64's tiny stack.
A C64 can print out about 1.2 addresses per second, for an estimated runtime of 1.3*10^31 years.

PowerShell (v4), 193 166 162 145 103 bytes
TimmyD's no-bonus version at 103 bytes:
$i=[bigint]::Pow(4,64);while($i-gt0){('{0:X32}'-f($i-=1)-replace'0(?=.{32})'-replace'.{4}(?!$)','$0:')}

Previous with-bonus version at 145 * 0.8 = 116 bytes
With help from TimmyD and tomkandy, who points out that 0 -eq $false but ([bigint]0) -eq $true. So all my previous versions won't terminate.
$i=[bigint]::Pow(4,64);while($i-gt0){$i-=1;[IPAddress]::Parse((('{0:X32}'-f$i
)-replace'0(?=.{32})'-replace'.{4}(?!$)','$0:')).IPAddressToString}

Previously at 162, before some regex changes:
$i=[bigint]::Pow(4,64)
while($i){$i-=1;if(($x='{0:X32}'-f$i).Length-eq33){$x=$x.Substring(1)}
[IPAddress]::Parse(($x-replace'.{4}(?!$)','$0:')).IPAddressToString}

"A challenge where PowerShell ought to be reasonably competetive!" - me, before I tried it.
Explanation
# PowerShell (PS) has no IP address arithmetic, e.g. IP + 1
#- PS has no 128 bit integers
#- PS has no automatic bignums

# Start from the top, with the BigInteger specialised Power()
$i = [BigInt]::pow(4,64)

# Loop 4**64 through 1, work with $i-1 for ff... -> ::0
while ($i) {
    # PS has no decrement operator for bignums
    # (no using $i-- in the while loop test)
    $i-=1

    # The Net.IPAddress class can't turn a BigInteger
    # into an IPv6 address directly. And because it mashes
    # IPv4 and IPv6 into one class, there's no obvious way
    # to make a small number always cast to an IPv6 address.
    # Format the bignum as a string of 32 hex digits.
    $x = '{0:X32}' -f $i

    # The BigInteger often formats as /33/ hex digits,
    # with a leading zero (to avoid unintentional +/- sign bits)
    # ( https://msdn.microsoft.com/library/dd268287 )
    # So remove the leading 0, if there is one
    if (($x).Length-eq33){$x=$x.Substring(1)}

    # I can't always remove the leading zero, because it
    # can't parse FFFFF... into an address without colons
    # and this regex replace into groups of 4 with colons
    # would go wrong at length 31. No : after the last group
    # This is still better than split/join ... because there
    # isn't a split-into-groups-of-N that I know of.
    $x = ($x -replace '.{4}(?!$)', '$1:'

    # Woo! * 0.8 bonus! 45 characters to save 38! :D
    [IPAddress]::Parse($x).IPAddressToString

}

95 without bonus. Thanks to you two for introducing me to [bigint], that's rather handy (for things I oughtn't to be doing in posh in the first place...) for($g=[bigint]::pow(2,128);$g;$g-=1){'{0:X32}'-f$g-replace'(?=(.{4})+$)',':'-replace'^0+:',''}

Sorry should be for($g=[bigint]::pow(2,120);$g;$g-=1){'{0:X32}'-f$g-replace'(?=(.{4})+$)',':'-replace'^0*:',''}

for($g=[bigint]::pow(2,128);$g-gt0;$g-=1){'{0:X32}'-f$g-replace'(?=(.{4})+$)',':'-replace'^\d*:',''} Yes, the first address is wrong but it's not repeated at the end. Also note that while($i) in yours won't stop at zero - [boolean][bigint]0 evaluates as true

@tomkandy oh wow, I must have only ever tested the end by setting $i=5 as an int.  (Complex 0 isn't $false either ... and nor is empty string. I should pay more attention to "it's not Python"). Thanks!   (And this script of yours doesn't get rid of the leading 0: anymore :/ )

@TessellatingHeckler Not going for the bonus is sadly 13 bytes shorter -- $i=[bigint]::Pow(4,64);while($i-gt0){('{0:X32}'-f($i-=1)-replace'0(?=.{32})'-replace'.{4}(?!$)','$0:')} at 103...

@TimmyD wasn't much of a bonus if it didn't end up shorter afterwards, eh; I've edited it in because it's shorter, it ought to be there.

AutoIt3, 137 Bytes
For $i=0 To 4^64
$s=StringFormat("%032x",$i)
For $j=0 To 7
ConsoleWrite(StringMid($s,$j*4+1,4)&($j<7?':':''))
Next
ConsoleWrite(@LF)
Next

I know that but I'm new here :(

Just making sure you know. Thanks.

Don’t you mean 4^64 - 1?

Regenerate -a, 24 bytes
(($3:!)[0-9a-f]{4}()){8}

Attempt This Online!
(
    # Match ":" iff we're not on the first iteration
    (
        $3        # Match iff we're not on the first iteration
        :         # Match ":"
    !             # Short-circuiting alternation - only try matching the below
                  # if it was impossible for the above to match.
                  # Do nothing
    )
    [0-9a-f]{4}   # Match 4 hexadecimal digits
    ()            # $3 = signal that we're not on the first iteration anymore
)
{8}               # Repeat the above 8 times

Alternative 24 bytes:
(({#1}:!)[0-9a-f]{4}){8}

Attempt This Online!
It might not be intended that this is possible, but Regenerate allows a quantifier to be preceded by nothing. This is what's happening with {#1} - it's impossible for it to match on the first iteration because $1 hasn't been captured yet and doesn't have a length. On subsequent iterations, a match of nothing gets repeated 4 times (the length of $1).

Ruby 75
x=->s,n{n>0?65536.times{|m|x.(s+?:*(8<=>n)+m.to_s(16),n-1)}: p(s)};x.('',8)

This is a recursive solution that takes a each prefix and finds every possible suffix. Recursively.

Get shorter function definitions with lambdas: x=->s,n{...};x['',8]

Haskell 111
s[]=[[]]
s(a:b)=[y:z|z<-s b,y<-a]
r=replicate
main=mapM putStrLn$s$tail$concat$r 8$":":r 4"0123456789abcdef"

With my own sequence function s it no longer leaks memory, but does not feel golfed any more.

How do you compile it so that it doesn't run out of memory? With my ghc v7.10.2 and std. compile options it leaks memory.

Python 2, 95 bytes
def i(p=0):
 while p<4**64:print':'.join(hex(p)[2:].zfill(32)[4*s:4*s+4]for s in range(8));p+=1

Simply goes through every number from 0 to 2^128. First it converts the current number to hexadecimal string, then strips off the '0x' that that function gives. Next it adjusts the string to have 32 zeros in the front and then breaks it up into groups of four. Finally it joins the groups of four with colons, prints that out and adds 1 to the current number. Has the added bonus that you can start it at any value if you give it one, but no input is needed.

If your answer is a function, you don't need to call it :)

@BetaDecay Then that was my misunderstanding. Fixed! Thanks.

CBM BASIC v7.0 (166 characters)
a=65535
fOi=0toa:fOj=0toa:fOk=0toa:fOl=0toa:fOm=0toa:fOn=0toa:fOo=0toa:fOp=0toa:?hE(i)":"hE(j)":"hE(k)":"hE(l)":"hE(m)":"hE(n)":"hE(o)":"hE(p):nE:nE:nE:nE:nE:nE:nE:nE

Mark's answer is for the Commodore 64's BASIC 2.0, which lacks a built-in command for printing numbers in hexadecimal.  However, thanks to the HEX$() function in BASIC 7.0, the Commodore 128 version is much shorter.  It doesn't fit on a single logical line (which on the C128 is limited to 160 characters) but can still be entered as two separate lines in direct mode.

It looks like you're missing half your loops.  An IPv6 address is 128 bits, not 64 bits.

@Mark: Thanks for pointing this out! I've fixed the problem.

Zsh -P, 60 bytes
x=({0..9} {a..f})
eval for\ {1..8}' ($x$x$x$x)<<<${(j/:/)@}'

Attempt This Online! (Warning: if you don't click the kill button fairly quickly, your browser will run out of memory and crash)
eval for\ {1..8} creates 8 nested loops using the loop variables $1, $2, ..., $8. These numbered variables can then be referred to implicitly using $@ (here, they're joined with colons using ${(j/:/)}).
The <<<${...} section is actually repeated for each level of nested loop as well, but (apart from the last one) they all do nothing, because they feed into the next loop, which ignores its input.
The -P option enables an implicit cartesian product on the adjacent expansions $x$x$x$x. This is the shortest way I could find to count up to 0xffff in hex without needing to convert each loop variable to hex individually.

Vyxal, 21 bytes
₇E(nk6τ₅32ε\0*p4ẇ\:j,

Try it Online!
Ugh, we really need a zfill builtin.

Go, \$243 \times 0.8 = \$ 194.4 bytes
import(."fmt";."net/netip")
func F(){for a,M:=0,1<<32-1;a<M;a++{for b:=0;b<M;b++{for c:=0;c<M;c++{for d:=0;d<M;d++{s:=""
for n,k:=0,Sprintf("%08x%08x%08x%08x",a,b,c,d);n<8;n++{s+=k[4*n:4*(n+1)]+":"}
A,_:=ParseAddr(s[:len(s)-1])
Println(A)}}}}}

Attempt This Online!
Prints to STDOUT. Uses the netip.Addr type from the Golang standard library to do the formatting for me.
Explanation
import(."fmt";."net/netip")
func F(){
for a,M:=0,1<<32-1;a<M;a++{ // first 8 digits
for b:=0;b<M;b++{           // next  8 digits
for c:=0;c<M;c++{           // next  8 digits
for d:=0;d<M;d++{           // final 8 digits
k:=Sprintf("%08x%08x%08x%08x",a,b,c,d)  // join the numbers into a single string
s:=""
for n:=0;n<8;n++{s+=k[4*n:4*(n+1)]+":"} // split into 8 groups of 4, split by colons
A,_:=ParseAddr(s[:len(s)-1])            // parse the address
Println(A)}}}}}                         // print using the default String() method, which formats the address

Tcl 341 318 301
proc ip6 {p c} {
    set s %x:%x:%x:%x:%x:%x:%x:%x
    set p [scan $p $s]
    while {[set d 7]} {
        $c [format [string map {x 04x} $s] {*}$p]
        while {[set i [lindex $p $d]]==0xFFFF} {
            lset p $d 0
            if {!$d} return
            incr d -1
        }
        lset p $d [incr i]
    }
}
ip6 fFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:0000 puts


text:
Why? To please the rich programmer!
Have you ever wanted to ask the compiler "Why?" Most of us have been frustrated when the code isn't working as it should. Mathworks has therefore implemented a nice little function, why, that answers the question. To give a few examples from MATLAB:
why
The programmer suggested it.

why
To fool the tall good and smart system manager.

why(2)
You insisted on it.

why(46)
Bill insisted on it.

Your task is to implement the why function in your language. The function should work with and without an input argument (alternatively use input 0 or -1). The function must be named why (or, writing why(n) in STDIN should result in the appropriate string being printed).
If no argument is given, or the argument is zero or negative, the output string should be a random, valid phrase.  So, there should be a function why, why(), why(0) or why(-1) that returns a random sentence.
If an input argument, n is given (function argument, not STDIN), the output should be the n'th string (defined below). So, why(1) should always output (print/display) the same result.
The sentences are built up as follows (Type 1, Type 2 and Special). All sentences end with !.
"Person" "ending" !
"Verb" "adjective" "Person" !
A list of special cases

The list of persons:
Stewie
Peter
Homer
The programmer
The system manager
You

The list of endings:
suggested it
insisted on it
did it

The list of verbs are:
To fool
To satisfy
To please

The list of adjectives:
the smart
the bald
the tall
the rich
the stupid

The list of special cases:
How should I know?
Stop asking!
Don't ask!

The way to select a numbered one is:
Type of sentences:
Odd number => Type 1
Even number => Type 2
n % 7 = 0 => Type 3 (% is the modulus operator)

Names: The nth name is defined using modulus (%).
n = 1:   1 % 7  => Stewie
n = 2:   2 % 7  => Peter
...
n = 6:   6 % 7  => You
n = 7:   7 % 7  => How should I know?
n = 11:  11 % 7 => The programmer
n = 14:  14 % 7 => Stop asking!
n = 21:  21 % 7 => Don't ask!

Endings: The nth ending is also defined using the modulus. Assume the endings (1, 2 and 3) are listed like (1 2 2 3). As the numbers are always odd, use ((n+1)/2 % 4)
n = 1:    ((1+1)/2 % 4)  => suggested it
n = 3:    ((3+1)/2 % 4)  => insisted on it
n = 13:   ((13+1)/2 % 4) => did it

Adjectives: The nth adjective is defined using the modulus. As the numbers are always even, use: (n % 10)/2
n = 2:   (2 % 10)/2 => Smart
n = 6:   (6 % 10)/2 => The tall
...

Verbs: The nth verb is also defined using the modulus. Assume the verbs (1, 2 and 3) are listed like (1 2 2 3) As the numbers are always even for verbs, use (n % 8) / 2
n = 2:   (2 % 8)/2 => To fool
n = 4:   (4 % 8)/2 => To satisfy
n = 6:   (6 % 8)/2 => To satisfy
n = 8:   (8 % 8)/2 => To please

Now, the way to create a random one should be fairly simple, simply select a random n.
Some examples:
why
You suggested it!

why
To fool the tall Homer!

why
Don't ask!

why(1)
Stewie suggested it!

why(14)
Stop asking!

why(8)
To please the rich Stewie!

Standard code golf rules apply. A winner will be selected one week from the day the challenge was posted.

writing why in the stdin should return the string I might be able to work with that. Does it have to be lowercase why or would WHY be acceptable?

Lower and upper case are both fine.

Also the Endings should not need /2 to work.  That gives fractional values. 13 should also be insisted (14/2=7 %4 = 3 = 2nd of insisted).

Does it matter if you end up with cases like the rich The programmer due to the specified the?

@StewieGriffin The words The and To in your lists should probably be lowercase to match your examples...

@Jonathan: i'm on my cell and won't have my laptop available the coming hours. You're most welcome to fix the aparently wrong examples in the question text. Thanks for noting it!

Still weird ... endings should be 1:suggested 3,5:insisted 7:(did)special 9:suggested 11,13:insisted 15:did

@edc65 Crap, forgot my own (1 2 2 3) order. Again, away from my laptop, so i can't fix it. (I have blocked codegolf on my work computer. I ended up having to work on a saturday because i used some of my working hours trying to solve / golf a challenge on a friday).

:) I should do the same

Could we get why(4) added to the examples?  I think that will clarify a lot of the above questions.

@DLosc, because I screwed up, To satisfy the bald The programmer is technically a valid sentence for why(4). No bonus (too late for that), but a pat on the back and happy times if you manage to do as edc65, and remove the the where it doesn't fit.

JavaScript (ES6) 345
Not sure about the numbers, but here is my attempt.
Test running the snippet below in an EcmaScript compliant browser.

why=n=>(n<1?n=Math.random()*840|0:0,s="suggested,insisted on,did,fool,satisfy,please,stupid,smart,bald,tall,rich,Don't ask!,How should I know?,Stop asking!,Stewie,Peter,Homer,programmer,system manager,You".split`,`,n%7?(p=s[n%7+13],n&1?(p>'a'?'The ':'')+p+` ${s['2011'[-~n/2%4]]} it!`:`To ${s['5344'[n%8/2]]} the ${s[n/2%5+6]} ${p}!`):s[11+n%3])

for(o='',i=0;++i<1e3;)o+=i+':'+why(i)+'\n';O.innerHTML=o

function test() { R.innerHTML=why(+I.value) }

// Less golfed

WHY=n=>(
  n=n<1?Math.random()*999|0:n,
  s=["suggested", "insisted on", "did", "fool", "satisfy", "please",
     "stupid", "smart", "bald", "tall", "rich",
     "Don't ask!", "How should I know?", "Stop asking!",
     "Stewie", "Peter", "Homer", "programmer", "system manager", "You"],
  n%7
    ? ( p=s[n%7+13],
        n&1
        ? (p>'a'?'The ':'')+p+` ${s['2011'[-~n/2%4]]} it!`
        : `To ${s['5344'[n%8/2]]} the ${s[n/2%5+6]} ${p}!`)
    : s[11+n%3]
)
#O { height:300px; width:50%; overflow:auto }
#I { width:2em }
Why(<input id=I>)<button onclick=test()>-></button>

Nice answer! Can't speak authoritatively on the number validity, but you can save 1 byte (!) using 0 as your string delimiter instead of ,!

@DomHastings I think that trick is no more needed with template strings. split(0) is the same length of split',' (pretend these are backticks)

Ahhh, sorry, I was thinking you could lose the brackets, this isn't coffeescript! :)

C#, 502 bytes
This project needs to have the AssemblyName set to why which will produce an executable with the correct name.
Fully golfed:
using System;class W{static void Main(string[]i)int n=i.Length>0?int.Parse(i[0]):new Random().Next();string[]s={"Don't ask!","How should I know?","Stop asking!"},v={"To please ","To fool ","To satisfy ",null},a={"the stupid","the smart","the bald","the tall","the rich"},p={"","Stewie","Peter","Homer","The programmer","The system manager","You"},e={"suggested it!","insisted on it!",null,"did it!"};Console.Write(n%7<1?s[n%3]:n%2<1?(v[n%8/2]??v[2])+a[n%10/2]+" {0}!":"{0} "+(e[n/2%4]??e[1]),p[n%7]);}}

Indentation and new lines for clarity:
using System;
class W{
    static void Main(string[]i)
        int n=i.Length>0
            ?int.Parse(i[0])
            :new Random().Next();
        string[]
            s={"Don't ask!","How should I know?","Stop asking!"},
            v={"To please ","To fool ","To satisfy ",null},
            a={"the stupid","the smart","the bald","the tall","the rich"},
            p={"","Stewie","Peter","Homer","The programmer","The system manager","You"},
            e={"suggested it!","insisted on it!",null,"did it!"};
        Console.Write(
            n%7<1
                ?s[n%3]
                :n%2<1
                    ?(v[n%8/2]??v[2])+a[n%10/2]+" {0}!"
                    :"{0} "+(e[n/2%4]??e[1]),
            p[n%7]
        );
    }
}

Example input/output:
>Why
To fool the bald Homer!
>Why 1
Stewie suggested it!

Powershell 437 461 453 Bytes
Edit: Missed the duplicated verbs
Splitting between the corpus and the calculations for byte-count

267 Bytes = Pre-coded text (excluding to,the,it and ! since they have fixed places).
186 Bytes = calculation

Sets default argument to 0 if not specified.  If argument is <1 then it gets a random number <99 fn:1 and reruns.  Technically this means -50 will work as well, being treated as a random case.
function why{param($b=0)$p=@('Stewie','Peter','Homer','The programmer','The system manager','You');$e=@('did','suggested','insisted on','insisted on');$v=@('please','fool','satisfy','satisfy');$a=@('stupid','smart','bald','tall','rich');$s=@("Don't ask!",'How should I know?','Stop asking!');if($b-le0){why(Get-Random 99)}elseif(!($b%7)){$s[$b/7%3]}else{$n=$p[$b%7-1];if($b%2){"$n $($e[($b+1)/2%4]) it!"}else{"To $($v[$b%8/2]) the $($a[$b%10/2]) $n!"}}}

Explanation:
# Any -1 in calculations is to account for arrays starting at index 0
# Final key placed in position 0 for indexing (4%4 = 0)
# Powershell 1 = True, 0 = False
if($b-le0){why(Get-Random 99)}          # If not positive, choose random number
elseif(!($b%7))                         # $b%7 means special so use that
  {$s[$b/7%3]}                          # Divide by 7 and find modulo, use that phrase.
else{$n=$p[$b%7-1]                      # Get the correct person (Used in both types). 6 max
if($b%2){"$n $($e[($b+1)/2%4]) it!"}    # Create type 1 sentence
else{"To $($v[$b%8/2]) the $($a[$b%10/2]) $n!"} # Type 2

fn:1 99 Chosen to save a byte.  If there are more than 99 possible sentences above (did not calculate) increase to 999 or 9999 as applicable (+1/2 bytes)

MUMPS, 379 bytes
f(s,i) s:'i i=$L(s,"^") q $P(s,"^",i)
why(n) s:'n n=$R(840) s p="Stewie^Peter^Homer^The programmer^The system manager^You",e="suggested^insisted on^did",v="fool^satisfy^please",a="smart^bald^tall^rich^stupid",s="How should I know?^Stop asking!^Don't ask!" q:n#7=0 $$f(s,n#3) q:n#2 $$f(p,n#7)_" "_$$f(e,n+1/2#4)_" it!" q "To "_$$f(v,n#8/2)_" the "_$$f(a,n#10/2)_" "_$$f(p,n#7)_"!"

When no input is given, a random number in 0..839 is generated.
Usage:
>w $$why(15)
Stewie did it!
>w $$why()
Don't ask!

MUMPS's left-to-right evaluation strategy saves a good few bytes on parentheses here.
Side note: see those strings that look like "foo^bar^baz^qux"? Those are so-called "delimited strings", and are the standard way of storing lists that fit within the maximum string size limit, since MUMPS does not actually have lists/arrays (or, indeed, any data structures besides trees). For lists too large to fit in a single string, we instead use trees of depth 1 and put the values on the leaves of the tree. Fun!

+1: MUMPS, of all languages, really needs a why function. ;)

Emacs Lisp 473 Bytes
(defun why(n)(if(and n(> n 0))(let*((p'(t"Stewie""Peter""Homer""The programmer""The system manager""You"))(e'("did""suggested""insisted on""insisted on"))(v'("please""fool""satisfy""satisfy"))(a'("stupid""smart""bald""tall""rich"))(s'("Don't ask!""How should I know?""Stop asking!"))(q(nth(% n 7)p)))(cond((=(% n 7)0)(nth(%(/ n 7)3)s))((=(% n 2)1)(format"%s %s it!"q(nth(%(/(1+ n)2)4)e)))(t(format"To %s the %s %s!"(nth(/(% n 8)2)v)(nth(/(% n 10)2)a)q))))(why(random 99))))

Largest 'waste' is probably the format,%s... sections. If variables could be inlined into the strings without the specification it would save 10 bytes on %s and another 12 on format

Ruby 396 378 372 bytes
I'm sure this is not golfed to the max.
p=%w[a Stewie Peter Homer The\ programmer The\ system\ manager You]
why=->n{n<1 ? why[rand(99)+1]:n%7<1 ? $><<%w[a How\ should\ I\ know? Stop\ asking! Don't\ ask!][n/7]:n%2<1 ? $><<'To '+%w[fool satisfy satisfy please][n%8/2-1]+' the '+%w[smart bald tall rich stupid][n%10/2-1]+' '+p[n%7]+?!:$><
=i:A7md{;A2%{S["suggested""insisted on""did"]A2/=+" it"+}{"To "["fool""satisfy"_"please"]A(2/:B=" the "["smart""bald""tall""rich""stupid"]B=SM}?[M"Stewie""Peter""Homer""The programmer""The system manager""You"]A=\'!}{["How should I know?""Stop asking!""Don't ask!"]\(=}?

Permalink
Haven't used CJam before, so I'll take any tips. I'm sure there's a lot of tricks I don't know!
(I couldn't figure out how to name this as a function called "why" - it appears that functions don't exist in CJam - so I'm not sure if a CJam answer is okay or not...)

Functions do exist, but there are only 26 valid function names (A to Z).

Lua 5.3.0, 452 460 446 bytes
This is my first attempt at a code golf, so please correct me if I did something wrong!
a={"Stewie","Peter","Homer","The Programmer","The system manager","You"}b={"fool ","satisfy ",n,"please "}b[3]=b[2]why=function(n)pcall(math.randomseed,n and n>0 and n)n=math.random(1e9)q=n>>4r=n>>8return 1>n&7 and({"How should I Know?","Stop asking!","Don't ask!"})[q%3+1]or 0<n%2 and a[q%6+1]..({" suggested"," insisted on"," did"})[r%3+1].." it"or"To "..b[q%4+1].."the "..({"smart ","bald ","tall ","rich ","stupid "})[r%5+1]..a[(r>>4)%6+1]end

Ungolfed:
a={
    "Stewie",
    "Peter",
    "Homer",
    "The Programmer",
    "The system manager",
    "You"
}
b={
    "fool ",
    "satisfy ",
    n,
    "please "
}
b[3]=b[2]
why=function(n)
    pcall(math.randomseed,n and n>0 and n)
    n=math.random(1e9)
    q=n>>4
    r=n>>8
    return
            1>n&7 and
                ({"How should I Know?","Stop asking!","Don't ask!"})[q%3+1]
            or 0<n%2 and
                a[q%6+1]..({" suggested"," insisted on"," did"})[r%3+1].." it"
            or
                "To "..b[q%4+1].."the "..({"smart ","bald ","tall ","rich ","stupid "})[r%5+1]..a[(r>>4)%6+1]
end

Python (2), 692 bytes
I’m still learning, so please be gentle! :)
from sys import argv,maxint
import random
def why(*O):
 P=["You","Stewie","Peter","Homer","programmer","system manager"];E=["did","suggested","insisted on","insisted on"];I=["please","fool","satisfy","satisfy"];Q=["stupid","smart","bald","tall","rich"];S=["Don't ask!","How should I know?","Stop asking!"]
 if len(argv)>1:A=O[0]
 else:A=random.randint(-maxint-1,maxint)
 if A%7==0:print S[A%3]
 else:
  M=P[A%6]
  if A%11==0:
   M=P[4]
  if A%2==0:
   if M==P[0]:M="you"
   U=I[(A%8)/2];Z=Q[(A%10)/2];print"To %s the %s %s!"%(U,Z,M)
  if A%2==1:
   if M==P[4]:M="The %s"%P[4]
   if M==P[5]:M="The %s"%P[5]
   C=E[((A+1)/2)%4];print"%s %s it!"%(M,C)
if len(argv)>1:why(int(argv[1]))
else:why()

Works with or without an int as a command line argument.
I tried to emphasise code correctness as much as possible, as with generating random numbers from -sys.maxint - 1 to sys.maxint and displaying sentences in the right case.
The code relies very heavily of if-statements that I’m sure could be replaced with something more place efficient.
Feedback is very welcome!
Ungolfed (1341 bytes)
from sys import argv, maxint
import random

def Why(*Optional):
    Persons = ["You", "Stewie", "Peter", "Homer", "programmer", "system manager"]
    Endings = ["did it", "suggested it", "insisted on it", "insisted on it"]
    Verbs = ["please", "fool", "satisfy", "satisfy"]
    Adjectives = ["stupid", "smart", "bald", "tall", "rich"]
    SpecialCases = ["Don't ask!", "How should I know?", "Stop asking!"]

    if len(argv) > 1:
        Argument = Optional[0]
    else:
        Argument = random.randint(-maxint - 1, maxint)

    if Argument % 7 is 0:
        print SpecialCases[Argument % 3]
    else:
        Person = Persons[(Argument) % 6]
        if Argument % 11 is 0:
            Person = "programmer"
        if Argument % 2 is 0:
            if Person is "You":
                Person = "you"
            Verb = Verbs[(Argument % 8) / 2]
            Adjective = Adjectives[(Argument % 10) / 2]
            print "To %s the %s %s!" % (Verb, Adjective, Person)
        if Argument % 2 is 1:
            if Person is "programmer":
                Person = "The programmer"
            if Person is "system manager":
                Person = "The system manager"
            Ending = Endings[((Argument + 1) / 2) % 4]
            print "%s %s!" % (Person, Ending)

if len(argv) > 1:
    Why(int(argv[1]))
else:
    Why()

I suggest you read [http://codegolf.stackexchange.com/questions/54/tips-for-golfing-in-python]—in particular, you can save many bytes by using the first tip on that page. You can also index from the back of the verb list so you only need one "satisfy": use argument%8/2-1 and remove the second one. You can also replace ==0 with <1.


text:
Returning the range of a number as a palindrome
I like to do programming challenges in my free time to teach myself and keep fresh, this one I can't seem to optimize though and it's driving me insane.
The goal is essentially, "Given a number, return the numbers leading up to it as a palindrome."
For example if you are given the input 5 the answer your program should return is: 123454321
The catch? You have to solve it in as few characters as possible. The minimum needed seems to be 41 characters and I can't condense it past 76.
I have tried all sorts of solutions, here are a few:
# Note: "Palindromic_Number" is required. "def P(N):" will not work.
def Palindromic_Number(N):
    a = ''
    for x in range(1,N+1):
        a += str(x)
    return a + a[::-1][1:]

def Palindromic_Number(N):
    a = ''.join(map(str, range(1,N+1)))
    return a + a[::-1][1:]

def Palindromic_Number(N):
    a = ''.join([str(x) for x in range(1, N+1)])
    return a + a[::-1][1:]

# This one uses Python 2.7
Palindromic_Number = lambda N: ''.join(map(str, range(1,N+1) + range(1,N+1)[::-1][1:]))

Does anyone have any ideas as to how I could shorten my code? I'm just looking for a point in the right direction where to look as this point.

range(1,N)+range(N,0,-1) should be shorter than using a+a[::-1][1:] afterwards as it allows you to not define a at all.

Forget it, it won't be so usefull. You can't add ranges in python 3. Only in python 2 where the builtin returns a list.

What's the input range? 1 to 9? 0 to 9?

You could try:
def Palindromic_Number(N):
    return int('1'*N)**2

just preforms 11111 * 11111 which equals 123454321
47 chars.

Or, as a lambda:
Palindromic_Number=lambda N:int('1'*N)**2

41 chars.

41 as a lambda, the apparent minimum, so I dare say you've nailed it :) (assuming input from 1-9)

@Sp3000 thank you! added to answer.

In the last solution (that takes advantage of Python 2 style ranges) you could reduce this
range(1,N+1) + range(1,N+1)[::-1][1:]

in a couple of ways:

Instead of slicing the second range, create the reversed range directly as range(N-1,0,-1)
Making N come out of the second range allows changing N+1 and N-1 to N and N:
range(1,N) + range(N,0,-1)

Slicing with [-2::-1] is shorter than [::-1][1:] by two bytes/chars. You can also remove the spaces on either side of the plus sign.

Python 2, 40 bytes
Palindromic_Number=lambda n:(10**n/9)**2

Try it online! (Includes test code to actually run the program.)
I know that you claimed that 41 is the minimum, but it's actually possible to do it in 40.
This uses the same strategy seen in the other answers, of squaring a repunit (a number made out of repetitions of the digit 1). However, instead of using string operations to produce the repunit (and thus having to pay for int to convert string to integer), it generates the palindrome entirely arithmetically.
The basic idea here is that 10n is a 1 followed by n 0s; if we subtract 1 we therefore get n 9s, and dividing by 9 gives us n 1s. Because Python 2 rounds integer arithmetic downwards, we can omit the subtraction of 1 (as it'll leave the answer higher by ⅑ than it should, which is a fraction that will disappear in the rounding), and we'll still get the correct answer.

range is a rather long name; with lambda N,r=range:/def ...(N,r=range): you can shave off a few characters if you also remove all unnecessary whitespace.

Since this question migrated from Code Review I'm not sure whether it'll ping, but in any case aliasing range (5 chars) doesn't save any bytes when it's only used twice (compare range;range vs r=range;r;r)

It pings. I can't delete the answer, but I'm removing that part at least.