Compare Python and MiniScript

100 doors
PythonMiniScript
doors = [False] * 100
for i in range(100):
   for j in range(i, 100, i+1):
       doors[j] = not doors[j]
   print("Door %d:" % (i+1), 'open' if doors[i] else 'close')
d = {}
for p in range(1, 100)
    for t in range(p, 100, p)
        if d.hasIndex(t) then d.remove t else d.push t
    end for
end for

print d.indexes.sort
100 prisoners
PythonMiniScript
import random

def play_random(n):
    # using 0-99 instead of ranges 1-100
    pardoned = 0
    in_drawer = list(range(100))
    sampler = list(range(100))
    for _round in range(n):
        random.shuffle(in_drawer)
        found = False
        for prisoner in range(100):
            found = False
            for reveal in random.sample(sampler, 50):
                card = in_drawer[reveal]
                if card == prisoner:
                    found = True
                    break
            if not found:
                break
        if found:
            pardoned += 1
    return pardoned / n * 100   # %

def play_optimal(n):
    # using 0-99 instead of ranges 1-100
    pardoned = 0
    in_drawer = list(range(100))
    for _round in range(n):
        random.shuffle(in_drawer)
        for prisoner in range(100):
            reveal = prisoner
            found = False
            for go in range(50):
                card = in_drawer[reveal]
                if card == prisoner:
                    found = True
                    break
                reveal = card
            if not found:
                break
        if found:
            pardoned += 1
    return pardoned / n * 100   # %

if __name__ == '__main__':
    n = 100_000
    print(" Simulation count:", n)
    print(f" Random play wins: {play_random(n):4.1f}% of simulations")
    print(f"Optimal play wins: {play_optimal(n):4.1f}% of simulations")
playRandom = function(n)
    // using 0-99 instead of 1-100
    pardoned = 0
    numInDrawer = range(99)
    choiceOrder = range(99)
    for round in range(1, n)
        numInDrawer.shuffle
        choiceOrder.shuffle
        for prisoner in range(99)
            found = false
            for card in choiceOrder[:50]
                if card == prisoner then
                    found = true
                    break
                end if
            end for
            if not found then break
        end for
        if found then pardoned = pardoned + 1
    end for
    return pardoned / n * 100
end function

playOptimal = function(n)
    // using 0-99 instead of 1-100
    pardoned = 0
    numInDrawer = range(99)
    for round in range(1, n)
        numInDrawer.shuffle
        for prisoner in range(99)
            found = false
        drawer = prisoner
            for i in range(1,50)
                card = numInDrawer[drawer]
                if card == prisoner then
                    found = true
                    break
                end if
                drawer = card
            end for
            if not found then break
        end for
        if found then pardoned = pardoned + 1
    end for
    return pardoned / n * 100
end function

print "Random:  " + playRandom(10000) + "%"
print "Optimal: " + playOptimal(10000) + "%"
24 game
PythonMiniScript
'''
 The 24 Game

 Given any four digits in the range 1 to 9, which may have repetitions,
 Using just the +, -, *, and / operators; and the possible use of
 brackets, (), show how to make an answer of 24.

 An answer of "q" will quit the game.
 An answer of "!" will generate a new set of four digits.
 Otherwise you are repeatedly asked for an expression until it evaluates to 24

 Note: you cannot form multiple digit numbers from the supplied digits,
 so an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.

'''

from __future__ import division, print_function
import random, ast, re
import sys

if sys.version_info[0] < 3: input = raw_input

def choose4():
    'four random digits >0 as characters'
    return [str(random.randint(1,9)) for i in range(4)]

def welcome(digits):
    print (__doc__)
    print ("Your four digits: " + ' '.join(digits))

def check(answer, digits):
    allowed = set('() +-*/\t'+''.join(digits))
    ok = all(ch in allowed for ch in answer) and \
         all(digits.count(dig) == answer.count(dig) for dig in set(digits)) \
         and not re.search('\d\d', answer)
    if ok:
        try:
            ast.parse(answer)
        except:
            ok = False
    return ok

def main():    
    digits = choose4()
    welcome(digits)
    trial = 0
    answer = ''
    chk = ans = False
    while not (chk and ans == 24):
        trial +=1
        answer = input("Expression %i: " % trial)
        chk = check(answer, digits)
        if answer.lower() == 'q':
            break
        if answer == '!':
            digits = choose4()
            print ("New digits:", ' '.join(digits))
            continue
        if not chk:
            print ("The input '%s' was wonky!" % answer)
        else:
            ans = eval(answer)
            print (" = ", ans)
            if ans == 24:
                print ("Thats right!")
    print ("Thank you and goodbye")   

if __name__ == '__main__': main() 
evalAddSub = function()
    result = evalMultDiv
    while true
        if not tokens then return result
        op = tokens[0]
        if op != "+" and op != "-" then return result
        tokens.pull  // (discard operator)
        rhs = evalMultDiv
        if result == null or rhs == null then return null
        if op == "+" then result = result + rhs
        if op == "-" then result = result - rhs
    end while
end function

evalMultDiv = function()
    result = evalAtom
    while true
        if not tokens then return result
        op = tokens[0]
        if op != "*" and op != "/" then return result
        tokens.pull  // (discard operator)
        rhs = evalAtom
        if result == null or rhs == null then return null
        if op == "*" then result = result * rhs
        if op == "/" then result = result / rhs
    end while
end function
    
evalAtom = function()
    if tokens[0] == "(" then
        tokens.pull
        result = evalAddSub
        if not tokens or tokens.pull != ")" then
            print "Unbalanced parantheses"
            return null
        end if
        return result
    end if
    num = val(tokens.pull)
    idx = availableDigits.indexOf(num)
    if idx == null then
        print str(num) + " is not available"
        return null
    else
        availableDigits.remove idx
    end if
    return num
end function

choices = []
for i in range(1, 4)
    choices.push ceil(rnd*9)
end for
result = null
while result != 24
    availableDigits = choices[:]  // (clones the list)
    print "Using only the digits " + availableDigits + ","
    tokens = input("enter an expression that comes to 24: ").replace(" ","").values
    result = evalAddSub
    if availableDigits then
        print "You forgot to use: " + availableDigits
        result = null
    end if
    if result != null then print "That equals " + result + "."
end while
print "Great job!"
99 bottles of beer
PythonMiniScript
for i in range(99, 0, -1): b ='bottles of beer'; w = b + ' on the wall'; print(f'{i} {w}, {i}
{b}\nTake one down and pass it around, {i - 1} {w}.\n')
bottles = function(n)
    if n == 0 then return "no bottles"
    if n == 1 then return "1 bottle"
    return n + " bottles"
end function

verse = function(n)
    print bottles(n) + " of beer on the wall"
    print bottles(n) + " of beer"
    print "Take one down, pass it around"
    print bottles(n-1) + " of beer on the wall"
    print
end function

for i in range(99, 1)
    verse i
end for
A+B
PythonMiniScript
try: raw_input
except: raw_input = input

print(sum(map(int, raw_input().split())))
s = "  2    3  "
fields = s.split
for i in range(fields.len-1, 0)
    if fields[i] == "" then fields.remove i
end for
if fields.len < 2 then
    print "Not enough input"
else
    print val(fields[0]) + val(fields[1])
end if
Abbreviations, simple
PythonMiniScript

command_table_text = """add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2 
Clast 3
   compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate
   3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2
   forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load
   locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2
   msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3
   refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left
   2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1"""

user_words = "riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin"


def find_abbreviations_length(command_table_text):
    """ find the minimal abbreviation length for each word.
        a word that does not have minimum abbreviation length specified
        gets it's full lengths as the minimum.
    """
    command_table = dict()
    input_iter = iter(command_table_text.split())

    word = None
    try:
        while True:
            if word is None:
                word = next(input_iter)
            abbr_len = next(input_iter, len(word))
            try:
                command_table[word] = int(abbr_len)
                word = None
            except ValueError:
                command_table[word] = len(word)
                word = abbr_len
    except StopIteration:
        pass
    return command_table


def find_abbreviations(command_table):
    """ for each command insert all possible abbreviations"""
    abbreviations = dict()
    for command, min_abbr_len in command_table.items():
        for l in range(min_abbr_len, len(command)+1):
            abbr = command[:l].lower()
            abbreviations[abbr] = command.upper()
    return abbreviations


def parse_user_string(user_string, abbreviations):
    user_words = [word.lower() for word in user_string.split()]
    commands = [abbreviations.get(user_word, "*error*") for user_word in user_words]
    return " ".join(commands)


command_table = find_abbreviations_length(command_table_text)
abbreviations_table = find_abbreviations(command_table)

full_words = parse_user_string(user_words, abbreviations_table)

print("user words:", user_words)
print("full words:", full_words)
c = "add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2 Clast 3" +
 " compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate" +
 " 3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2" +
 " forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load" +
 " locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2" +
 " msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3" +
 " refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left" +
 " 2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1"
 
minLen = {}
lastItem = ""
for item in c.split
    if item == "" then continue
    item = item.upper
    if lastItem and item[0] >= "0" and item[0] <= "9" then
        minLen[lastItem] = val(item)
        lastItem = ""
    else
        minLen[item] = null
        lastItem = item
    end if
end for
 
check = function(word)
    word = word.upper
    for key in minLen.indexes
        if key[:word.len] != word then continue
        min = minLen[key]
        if min and word.len < min then continue
        return key
    end for
    return "*error*"
end function
 
input = "riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin"
 
output = []
for word in input.split
    if word == "" then continue
    output.push check(word)
end for
print output.join
ABC problem
PythonMiniScript
'''
Note that this code is broken, e.g., it won't work when 
blocks = [("A", "B"), ("A","C")] and the word is "AB", where the answer
should be True, but the code returns False.
'''
blocks = [("B", "O"),
          ("X", "K"),
          ("D", "Q"),
          ("C", "P"),
          ("N", "A"),
          ("G", "T"),
          ("R", "E"),
          ("T", "G"),
          ("Q", "D"),
          ("F", "S"),
          ("J", "W"),
          ("H", "U"),
          ("V", "I"),
          ("A", "N"),
          ("O", "B"),
          ("E", "R"),
          ("F", "S"),
          ("L", "Y"),
          ("P", "C"),
          ("Z", "M")]


def can_make_word(word, block_collection=blocks):
    """
    Return True if `word` can be made from the blocks in `block_collection`.

    >>> can_make_word("")
    False
    >>> can_make_word("a")
    True
    >>> can_make_word("bark")
    True
    >>> can_make_word("book")
    False
    >>> can_make_word("treat")
    True
    >>> can_make_word("common")
    False
    >>> can_make_word("squad")
    True
    >>> can_make_word("coNFused")
    True
    """
    if not word:
        return False

    blocks_remaining = block_collection[:]
    for char in word.upper():
        for block in blocks_remaining:
            if char in block:
                blocks_remaining.remove(block)
                break
        else:
            return False
    return True


if __name__ == "__main__":
    import doctest
    doctest.testmod()
    print(", ".join("'%s': %s" % (w, can_make_word(w)) for w in
                    ["", "a", "baRk", "booK", "treat", 
                     "COMMON", "squad", "Confused"]))
allBlocks = ["BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS", "JW", "HU", "VI", "AN",
"OB", "ER", "FS", "LY", "PC", "ZM"]
 
swap = function(list, index1, index2)
    tmp = list[index1]
    list[index1] = list[index2]
    list[index2] = tmp
end function
 
canMakeWord = function(str, blocks)
    if str == "" then return true
    c = str[0].upper
    for i in range(0, blocks.len - 1)
        bl = blocks[i]
        if c != bl[0] and c != bl[1] then continue
        swap blocks, 0, i
        if canMakeWord(str[1:], blocks[1:]) then return true
        swap blocks, 0, i
    end for
    return false
end function
 
for val in ["", "A", "BARK", "book", "Treat", "COMMON", "sQuAD", "CONFUSE"]
    out = """"""
    if val.len != 0 then out = val
    print out + ": " + canMakeWord(val, allBlocks)
end for
Ackermann function
PythonMiniScript
def ack1(M, N):
   return (N + 1) if M == 0 else (
      ack1(M-1, 1) if N == 0 else ack1(M-1, ack1(M, N-1)))
ackermann = function(m, n)
    if m == 0 then return n+1
    if n == 0 then return ackermann(m - 1, 1)
    return ackermann(m - 1, ackermann(m, n - 1))
end function
 
for m in range(0, 3)
    for n in range(0, 4)
        print "(" + m + ", " + n + "): " + ackermann(m, n)
    end for
end for
Add a variable to a class instance at runtime
PythonMiniScript
class empty(object):
    pass
e = empty()
empty = {}
empty.foo = 1
Animation
PythonMiniScript
#!/usr/bin/env python3
import sys

from PyQt5.QtCore import QBasicTimer, Qt
from PyQt5.QtGui import QFont
from PyQt5.QtWidgets import QApplication, QLabel


class Marquee(QLabel):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.right_to_left_direction = True
        self.initUI()
        self.timer = QBasicTimer()
        self.timer.start(80, self)

    def initUI(self):
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setAttribute(Qt.WA_TranslucentBackground)
        self.setText("Hello World! ")
        self.setFont(QFont(None, 50, QFont.Bold))
        # make more irritating for the authenticity with <marquee> element
        self.setStyleSheet("QLabel {color: cyan; }")

    def timerEvent(self, event):
        i = 1 if self.right_to_left_direction else -1
        self.setText(self.text()[i:] + self.text()[:i])  # rotate

    def mouseReleaseEvent(self, event):  # change direction on mouse release
        self.right_to_left_direction = not self.right_to_left_direction

    def keyPressEvent(self, event):  # exit on Esc
        if event.key() == Qt.Key_Escape:
            self.close()


app = QApplication(sys.argv)
w = Marquee()
# center widget on the screen
w.adjustSize()  # update w.rect() now
w.move(QApplication.instance().desktop().screen().rect().center()
       - w.rect().center())
w.show()
sys.exit(app.exec())
clear
text.inverse = true
s = "Hello World! "
while not key.available
    text.row = 12
    text.column = 15
    print " " + s + " "
    wait 0.1
    s = s[-1] + s[:-1]
end while
text.inverse = false
key.clear
Arithmetic evaluation
PythonMiniScript
import operator

class AstNode(object):
   def __init__( self, opr, left, right ):
      self.opr = opr
      self.l = left
      self.r = right

   def eval(self):
      return self.opr(self.l.eval(), self.r.eval())

class LeafNode(object):
   def __init__( self, valStrg ):
      self.v = int(valStrg)

   def eval(self):
      return self.v

class Yaccer(object):
   def __init__(self):
      self.operstak = []
      self.nodestak =[]
      self.__dict__.update(self.state1)

   def v1( self, valStrg ):
      # Value String
      self.nodestak.append( LeafNode(valStrg))
      self.__dict__.update(self.state2)
      #print 'push', valStrg

   def o2( self, operchar ):
      # Operator character or open paren in state1
      def openParen(a,b):
         return 0        # function should not be called

      opDict= { '+': ( operator.add, 2, 2 ),
         '-': (operator.sub, 2, 2 ),
         '*': (operator.mul, 3, 3 ),
         '/': (operator.div, 3, 3 ),
         '^': ( pow,         4, 5 ),  # right associative exponentiation for grins
         '(': ( openParen,   0, 8 )
         }
      operPrecidence = opDict[operchar][2]
      self.redeuce(operPrecidence)

      self.operstak.append(opDict[operchar])
      self.__dict__.update(self.state1)
      # print 'pushop', operchar

   def syntaxErr(self, char ):
      # Open Parenthesis 
      print 'parse error - near operator "%s"' %char

   def pc2( self,operchar ):
      # Close Parenthesis
      # reduce node until matching open paren found 
      self.redeuce( 1 )
      if len(self.operstak)>0:
         self.operstak.pop()        # pop off open parenthesis
      else:
         print 'Error - no open parenthesis matches close parens.'
      self.__dict__.update(self.state2)

   def end(self):
      self.redeuce(0)
      return self.nodestak.pop()

   def redeuce(self, precidence):
      while len(self.operstak)>0:
         tailOper = self.operstak[-1]
         if tailOper[1] < precidence: break

         tailOper = self.operstak.pop()
         vrgt = self.nodestak.pop()
         vlft= self.nodestak.pop()
         self.nodestak.append( AstNode(tailOper[0], vlft, vrgt))
         # print 'reduce'

   state1 = { 'v': v1, 'o':syntaxErr, 'po':o2, 'pc':syntaxErr }
   state2 = { 'v': syntaxErr, 'o':o2, 'po':syntaxErr, 'pc':pc2 }


def Lex( exprssn, p ):
   bgn = None
   cp = -1
   for c in exprssn:
      cp += 1
      if c in '+-/*^()':         # throw in exponentiation (^)for grins
         if bgn is not None:
            p.v(p, exprssn[bgn:cp])
            bgn = None
         if c=='(': p.po(p, c)
         elif c==')':p.pc(p, c)
         else: p.o(p, c)
      elif c in ' \t':
         if bgn is not None:
            p.v(p, exprssn[bgn:cp])
            bgn = None
      elif c in '0123456789':
         if bgn is None:
            bgn = cp
      else:
         print 'Invalid character in expression'
         if bgn is not None:
            p.v(p, exprssn[bgn:cp])
            bgn = None
         
   if bgn is not None:
      p.v(p, exprssn[bgn:cp+1])
      bgn = None
   return p.end()


expr = raw_input("Expression:")
astTree = Lex( expr, Yaccer())
print expr, '=',astTree.eval()
Expr = {}
Expr.eval = 0

BinaryExpr = new Expr
BinaryExpr.eval = function()
    if self.op == "+" then return self.lhs.eval + self.rhs.eval
    if self.op == "-" then return self.lhs.eval - self.rhs.eval
    if self.op == "*" then return self.lhs.eval * self.rhs.eval
    if self.op == "/" then return self.lhs.eval / self.rhs.eval
end function
binop = function(lhs, op, rhs)
    e = new BinaryExpr
    e.lhs = lhs
    e.op = op
    e.rhs = rhs
    return e
end function

parseAtom = function(inp)
    tok = inp.pull
    if tok >= "0" and tok <= "9" then
        e = new Expr
        e.eval = val(tok)
        while inp and inp[0] >= "0" and inp[0] <= "9"
            e.eval = e.eval * 10 + val(inp.pull)
        end while
    else if tok == "(" then
        e = parseAddSub(inp)
        inp.pull // swallow closing ")"
        return e
    else    
        print "Unexpected token: " + tok
        exit
    end if
    return e    
end function

parseMultDiv = function(inp)
    next = @parseAtom
    e = next(inp)
    while inp and (inp[0] == "*" or inp[0] == "/")
        e = binop(e, inp.pull, next(inp))
    end while
    return e
end function

parseAddSub = function(inp)
    next = @parseMultDiv
    e = next(inp)
    while inp and (inp[0] == "+" or inp[0] == "-")
        e = binop(e, inp.pull, next(inp))
    end while
    return e
end function

while true
    s = input("Enter expression: ").replace(" ","")
    if not s then break
    inp = split(s, "")
    ast = parseAddSub(inp)
    print ast.eval
end while
Array concatenation
PythonMiniScript
arr1 = [1, 2, 3]
arr2 = [4, 5, 6]
arr3 = [7, 8, 9]
arr4 = arr1 + arr2
assert arr4 == [1, 2, 3, 4, 5, 6]
arr4.extend(arr3)
assert arr4 == [1, 2, 3, 4, 5, 6, 7, 8, 9]
arrOne = [1, 2, 3]
arrTwo = [4, 5, 6]
print arrOne + arrTwo
Array length
PythonMiniScript
>>> print(len(['apple', 'orange']))
2
>>> 
fruits = ["apple", "orange"]
print fruits.len
Arrays
PythonMiniScript
array = []

array.append(1)
array.append(3)

array[0] = 2

print array[0]
arr = ["a", 1, 3]
print arr[0]

arr.push "x"
print arr.pop
Associative array/Creation
PythonMiniScript
hash = dict()  # 'dict' is the dictionary type.
hash = dict(red="FF0000", green="00FF00", blue="0000FF")
hash = { 'key1':1, 'key2':2, }
value = hash[key]
map = { 3: "test", "foo": 42 }

print map[3]
map[3] = "more tests"
print map[3]
print map["foo"]
print map.foo  // same as map["foo"] (only for string keys that are valid identifiers)
Associative array/Iteration
PythonMiniScript
myDict = { "hello": 13,
       "world": 31,
       "!"    : 71 }

# iterating over key-value pairs:
for key, value in myDict.items():
    print ("key = %s, value = %s" % (key, value))

# iterating over keys:
for key in myDict:
    print ("key = %s" % key)
# (is a shortcut for:)
for key in myDict.keys():
    print ("key = %s" % key)

# iterating over values:
for value in myDict.values():
    print ("value = %s" % value)
d = { 3: "test", "foo": 3 }

for keyVal in d
    print keyVal   // produces results like: { "key": 3, "value": "test" }
end for

for key in d.indexes
    print key
end for

for  val in d.values
    print val
end for
Associative array/Merging
PythonMiniScript
base = {"name":"Rocket Skates", "price":12.75, "color":"yellow"}
update = {"price":15.25, "color":"red", "year":1974}

result = {**base, **update}

print(result)
base = {"name":"Rocket Skates", "price":12.75, "color":"yellow"}
update = {"price":15.25, "color":"red", "year":1974}

result = base + update

print result
Averages/Arithmetic mean
PythonMiniScript
from math import fsum
def average(x):
    return fsum(x)/float(len(x)) if x else 0
print (average([0,0,3,1,4,1,5,9,0,0]))
print (average([1e20,-1e-20,3,1,4,1,5,9,-1e20,1e-20]))
arr = [ 1, 3, 7, 8, 9, 1 ]

avg = function(arr)
    avgNum = 0
    for num in arr
        avgNum = avgNum + num
    end for
    return avgNum / arr.len
end function

print avg(arr)
Averages/Median
PythonMiniScript
def median(aray):
    srtd = sorted(aray)
    alen = len(srtd)
    return 0.5*( srtd[(alen-1)//2] + srtd[alen//2])

a = (4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2)
print a, median(a)
a = (4.1, 7.2, 1.7, 9.3, 4.4, 3.2)
print a, median(a)
list.median = function()
    self.sort
    m = floor(self.len/2)
    if self.len % 2 then return self[m]
    return (self[m] + self[m-1]) * 0.5
end function
    
print [41, 56, 72, 17, 93, 44, 32].median
print [41, 72, 17, 93, 44, 32].median
Averages/Simple moving average
PythonMiniScript
from collections import deque

def simplemovingaverage(period):
    assert period == int(period) and period > 0, "Period must be an integer >0"
    
    summ = n = 0.0
    values = deque([0.0] * period)     # old value queue

    def sma(x):
        nonlocal summ, n
        
        values.append(x)
        summ += x - values.popleft()
        n = min(n+1, period)
        return summ / n

    return sma
SMA = {}
SMA.P = 5  // (a default; may be overridden)
SMA.buffer = null
SMA.next = function(n)
    if self.buffer == null then self.buffer = []
    self.buffer.push n
    if self.buffer.len > self.P then self.buffer.pull
    return self.buffer.sum / self.buffer.len
end function

sma3 = new SMA
sma3.P = 3
sma5 = new SMA

for i in range(10)
    num = round(rnd*100)
    print "num: " + num + "  sma3: " + sma3.next(num) + "  sma5: " + sma5.next(num)
end for
Babbage problem
PythonMiniScript
# Lines that start by # are a comments:
# they will be ignored by the machine

n=0 # n is a variable and its value is 0

# we will increase its value by one until
# its square ends in 269,696

while n**2 % 1000000 != 269696:

    # n**2 -> n squared
    # %    -> 'modulo' or remainer after division
    # !=   -> not equal to
    
    n += 1 # += -> increase by a certain number

print(n) # prints n

# short version
>>> [x for x in range(30000) if (x*x) % 1000000 == 269696] [0]
25264
// Lines that start with "//" are "comments" that are ignored
// by the computer.  We use them to explain the code.

// Start by finding the smallest number that could possibly
// square to 269696.  sqrt() returns the square root of a 
// number, and floor() truncates any fractional part.
k = floor(sqrt(269696))

// Since 269696 is even, we are only going to consider even
// roots.  We use the % (modulo) operator, which returns the
// remainder after division, to tell if k is odd; if so, we
// add 1 to make it even.
if k % 2 == 1 then k = k + 1

// Now we count up by 2 from k, until we find a number that,
// when squared, ends in 269696 (using % again).
while k^2 % 1000000 != 269696
    k = k + 2
end while

// The first such number we find is our answer.
print k + "^2 = " + k^2
Bacon cipher
PythonMiniScript
import string

sometext = """All children, except one, grow up. They soon know that they will grow
up, and the way Wendy knew was this. One day when she was two years old
she was playing in a garden, and she plucked another flower and ran with
it to her mother. I suppose she must have looked rather delightful, for
Mrs. Darling put her hand to her heart and cried, "Oh, why can't you
remain like this for ever!" This was all that passed between them on
the subject, but henceforth Wendy knew that she must grow up. You always
know after you are two. Two is the beginning of the end.

Of course they lived at 14 [their house number on their street], and
until Wendy came her mother was the chief one. She was a lovely lady,
with a romantic mind and such a sweet mocking mouth. Her romantic
mind was like the tiny boxes, one within the other, that come from the
puzzling East, however many you discover there is always one more; and
her sweet mocking mouth had one kiss on it that Wendy could never get,
though there it was, perfectly conspicuous in the right-hand corner.""".lower()

lc2bin = {ch: '{:05b}'.format(i) 
          for i, ch in enumerate(string.ascii_lowercase + ' .')}
bin2lc = {val: key for key, val in lc2bin.items()}

phrase = 'Rosetta code Bacon cipher example secret phrase to encode in the capitalisation of peter
pan'.lower()

def to_5binary(msg):
    return ( ch == '1' for ch in ''.join(lc2bin.get(ch, '') for ch in msg.lower()))

def encrypt(message, text):
    bin5 = to_5binary(message)
    textlist = list(text.lower())
    out = []
    for capitalise in bin5:
        while textlist:
            ch = textlist.pop(0)
            if ch.isalpha():
                if capitalise:
                    ch = ch.upper()
                out.append(ch)
                break
            else:
                out.append(ch)
        else:
            raise Exception('ERROR: Ran out of characters in sometext')
    return ''.join(out) + '...'


def  decrypt(bacontext):
    binary = []
    bin5 = []
    out = []
    for ch in bacontext:
        if ch.isalpha():
            binary.append('1' if ch.isupper() else '0')
            if len(binary) == 5:
                bin5 = ''.join(binary)
                out.append(bin2lc[bin5])
                binary = []
    return ''.join(out)
                

print('PLAINTEXT = \n%s\n' % phrase)
encrypted = encrypt(phrase, sometext)
print('ENCRYPTED = \n%s\n' % encrypted)
decrypted = decrypt(encrypted)
print('DECRYPTED = \n%s\n' % decrypted)
assert phrase == decrypted, 'Round-tripping error'
c = {}
c["a"] = "AAAAA"; c["b"] = "AAAAB"; c["c"] = "AAABA"; c["d"] = "AAABB"; c["e"] = "AABAA"; c["f"] =
"AABAB"; 
c["g"] = "AABBA"; c["h"] = "AABBB"; c["i"] = "ABAAA"; c["j"] = "ABAAB"; c["k"] = "ABABA"; c["l"] =
"ABABB"; 
c["m"] = "ABBAA"; c["n"] = "ABBAB"; c["o"] = "ABBBA"; c["p"] = "ABBBB"; c["q"] = "BAAAA"; c["r"] =
"BAAAB"; 
c["s"] = "BAABA"; c["t"] = "BAABB"; c["u"] = "BABAA"; c["v"] = "BABAB"; c["w"] = "BABBA"; c["x"] =
"BABBB"; 
c["y"] = "BBAAA"; c["z"] = "BBAAB"; c[" "] = "BBBAA";
codeMap = c  // (used "c" above just to make the lines shorter)
decodeMap = {}
for kv in codeMap
    decodeMap[kv.value] = kv.key
end for

message = "Computers are everywhere.  There are the obvious ones, like your smart phone or game
system. "
message = message + "There are less obvious ones, like in your microwave or your bedside clock.  And
then "
message = message + "there are the really invisible ones, like the 50 or so small computers in your
car."
message = message + "All these computers work in pretty much the same way."
message = message.values  // (convert to list)

encodeChar = function(ch)
    out = []
    for bit in codeMap[ch]
        while message[0].upper == message[0].lower
            out.push message.pull   // (not a letter we can use; pass through as-is)
        end while
        if bit == "A" then out.push message.pull.upper else out.push message.pull.lower
    end for
    return out
end function
    
encode = function(s)
    out = []
    for ch in s
        out = out + encodeChar(ch)
    end for
    return out.join("")
end function

decodeChar = function(encodedChar)
    code = ""
    for ch in encodedChar
        if ch == ch.upper then code = code + "A" else code = code + "B"
    end for
    if decodeMap.hasIndex(code) then return decodeMap[code]
    return "?"
end function

decode = function(s)
    // strip out all non-letters
    schars = s.values
    for i in range(schars.len-1, 0)
        if schars[i].lower == schars[i].upper then schars.remove i
    end for
    s = schars.join("")
    // now, decode using groups of 5 characters
    out = []
    for i in range(0, s.len-1, 5)
        out.push decodeChar(s[i:i+5])
    end for
    return out.join("")
end function

codedMsg = encode("the quick brown fox jumps over the lazy dog")
print codedMsg
print decode(codedMsg)
Balanced brackets
PythonMiniScript
>>> def gen(N):
...     txt = ['[', ']'] * N
...     random.shuffle( txt )
...     return ''.join(txt)
... 
>>> def balanced(txt):
...     braced = 0
...     for ch in txt:
...         if ch == '[': braced += 1
...         if ch == ']':
...             braced -= 1
...             if braced < 0: return False
...     return braced == 0
... 
>>> for txt in (gen(N) for N in range(10)):
...     print ("%-22r is%s balanced" % (txt, '' if balanced(txt) else ' not'))
... 
''                     is balanced
'[]'                   is balanced
'[][]'                 is balanced
'][[[]]'               is not balanced
'[]][[][]'             is not balanced
'[][[][]]]['           is not balanced
'][]][][[]][['         is not balanced
'[[]]]]][]][[[['       is not balanced
'[[[[]][]]][[][]]'     is balanced
'][[][[]]][]]][[[[]'   is not balanced
isBalanced = function(str) 
    level = 0
    for c in str
        if c == "[" then level = level + 1
        if c == "]" then level = level - 1
        if level < 0 then return false
    end for
    return level == 0
end function
Barnsley fern
PythonMiniScript

import random
from PIL import Image


class BarnsleyFern(object):
    def __init__(self, img_width, img_height, paint_color=(0, 150, 0),
                 bg_color=(255, 255, 255)):
        self.img_width, self.img_height = img_width, img_height
        self.paint_color = paint_color
        self.x, self.y = 0, 0
        self.age = 0

        self.fern = Image.new('RGB', (img_width, img_height), bg_color)
        self.pix = self.fern.load()
        self.pix[self.scale(0, 0)] = paint_color

    def scale(self, x, y):
        h = (x + 2.182)*(self.img_width - 1)/4.8378
        k = (9.9983 - y)*(self.img_height - 1)/9.9983
        return h, k

    def transform(self, x, y):
        rand = random.uniform(0, 100)
        if rand < 1:
            return 0, 0.16*y
        elif 1 <= rand < 86:
            return 0.85*x + 0.04*y, -0.04*x + 0.85*y + 1.6
        elif 86 <= rand < 93:
            return 0.2*x - 0.26*y, 0.23*x + 0.22*y + 1.6
        else:
            return -0.15*x + 0.28*y, 0.26*x + 0.24*y + 0.44

    def iterate(self, iterations):
        for _ in range(iterations):
            self.x, self.y = self.transform(self.x, self.y)
            self.pix[self.scale(self.x, self.y)] = self.paint_color
        self.age += iterations

fern = BarnsleyFern(500, 500)
fern.iterate(1000000)
fern.fern.show()
clear
x = 0
y = 0
for i in range(100000)
    gfx.setPixel 300 + 58 * x, 58 * y, color.green
    roll = rnd * 100
    xp = x
    if roll < 1 then
        x = 0
        y = 0.16 * y
    else if roll < 86 then
        x = 0.85 * x + 0.04 * y
        y = -0.04 * xp + 0.85 * y + 1.6
    else if roll < 93 then
        x = 0.2 * x - 0.26 * y
        y = 0.23 * xp + 0.22 * y + 1.6
    else
        x = -0.15 * x + 0.28 * y
        y = 0.26 * xp + 0.24 * y + 0.44
    end if
end for
Binary digits
PythonMiniScript
>>> for i in range(16): print('{0:b}'.format(i))

0
1
10
11
100
101
110
111
1000
1001
1010
1011
1100
1101
1110
1111
binary = function(n)
    result = ""
    while n
        result = str(n%2) + result
        n = floor(n/2)
    end while
    if not result then return "0"
    return result
end function
 
print binary(5)
print binary(50)
print binary(9000)
print binary(0)
Binary search
PythonMiniScript
def binary_search(l, value):
    low = 0
    high = len(l)-1
    while low <= high: 
        mid = (low+high)//2
        if l[mid] > value: high = mid-1
        elif l[mid] < value: low = mid+1
        else: return mid
    return -1
binarySearch = function(A, value, low, high)
    if high < low then return null
    mid = floor((low + high) / 2)
    if A[mid] > value then return binarySearch(A, value, low, mid-1)
    if A[mid] < value then return binarySearch(A, value, mid+1, high)
    return mid
end function
Boolean values
PythonMiniScript
>>> True
True
>>> not True
False
>>> # As numbers
>>> False + 0
0
>>> True + 0
1
>>> False + 0j
0j
>>> True * 3.141
3.141
>>> # Numbers as booleans
>>> not 0
True
>>> not not 0
False
>>> not 1234
False
>>> bool(0.0)
False
>>> bool(0j)
False
>>> bool(1+2j)
True
>>> # Collections as booleans
>>> bool([])
False
>>> bool([None])
True
>>> 'I contain something' if (None,) else 'I am empty'
'I contain something'
>>> bool({})
False
>>> bool("")
False
>>> bool("False")
True
boolTrue = true
boolFalse = false

if boolTrue then print "boolTrue is true, and its value is: " + boolTrue

if not boolFalse then print "boolFalse is not true, and its value is: " + boolFalse

mostlyTrue = 0.8
kindaTrue = 0.4
print "mostlyTrue AND kindaTrue: " + (mostlyTrue and kindaTrue)
print "mostlyTrue OR kindaTrue: " + (mostlyTrue or kindaTrue)
Bulls and cows
PythonMiniScript
'''
 Bulls and cows. A game pre-dating, and similar to, Mastermind.
'''

import random

digits = '123456789'
size = 4
chosen = ''.join(random.sample(digits,size))
#print chosen # Debug
print '''I have chosen a number from %s unique digits from 1 to 9 arranged in a random order.
You need to input a %i digit, unique digit number as a guess at what I have chosen''' % (size, size)
guesses = 0
while True:
    guesses += 1
    while True:
        # get a good guess
        guess = raw_input('\nNext guess [%i]: ' % guesses).strip()
        if len(guess) == size and \
           all(char in digits for char in guess) \
           and len(set(guess)) == size:
            break
        print "Problem, try again. You need to enter %i unique digits from 1 to 9" % size
    if guess == chosen:
        print '\nCongratulations you guessed correctly in',guesses,'attempts'
        break
    bulls = cows = 0
    for i in range(size):
        if guess[i] == chosen[i]:
            bulls += 1
        elif guess[i] in chosen:
            cows += 1
    print '  %i Bulls\n  %i Cows' % (bulls, cows)
secret = range(1,9)
secret.shuffle
secret = secret[:4].join("")

while true
    guess = input("Your guess? ").split("")
    if guess.len != 4 then
        print "Please enter 4 numbers, with no spaces."
        continue
    end if
    bulls = 0
    cows = 0
    for i in guess.indexes
        if secret[i] == guess[i] then
            bulls = bulls + 1
        else if secret.indexOf(guess[i]) != null then
            cows = cows + 1
        end if
    end for
    if bulls == 4 then
        print "You got it!  Great job!"
        break
    end if
    print "You score " + bulls + " bull" + "s"*(bulls!=1) + 
    " and " + cows + " cow" + "s"*(cows!=1) + "."
end while
Caesar cipher
PythonMiniScript
def caesar(s, k, decode = False):
    if decode: k = 26 - k
    return "".join([chr((ord(i) - 65 + k) % 26 + 65)
                for i in s.upper()
                if ord(i) >= 65 and ord(i) <= 90 ])

msg = "The quick brown fox jumped over the lazy dogs"
print msg
enc = caesar(msg, 11)
print enc
print caesar(enc, 11, decode = True)
caesar = function(s, key)
    chars = s.values
    for i in chars.indexes
        c = chars[i]
        if c >= "a" and c <= "z" then chars[i] = char(97 + (code(c)-97+key)%26)
        if c >= "A" and c <= "Z" then chars[i] = char(65 + (code(c)-65+key)%26)
    end for
    return chars.join("")
end function

print caesar("Hello world!", 7)
print caesar("Olssv dvysk!", 26-7)
Call an object method
PythonMiniScript
class MyClass(object):
    @classmethod
    def myClassMethod(self, x):
        pass
    @staticmethod
    def myStaticMethod(x):
        pass
    def myMethod(self, x):
        return 42 + x

myInstance = MyClass()

# Instance method
myInstance.myMethod(someParameter)
# A method can also be retrieved as an attribute from the class, and then explicitly called on an
instance:
MyClass.myMethod(myInstance, someParameter)


# Class or static methods
MyClass.myClassMethod(someParameter)
MyClass.myStaticMethod(someParameter)
# You can also call class or static methods on an instance, which will simply call it on the
instance's class
myInstance.myClassMethod(someParameter)
myInstance.myStaticMethod(someParameter)
Dog = {}
Dog.name = ""
Dog.help = function()
    print "This class represents dogs."
end function
Dog.speak = function()
    print self.name + " says Woof!"
end function

fido = new Dog
fido.name = "Fido"

Dog.help    // calling a "class method"
fido.speak  // calling an "instance method"
Case-sensitivity of identifiers
PythonMiniScript
>>> dog = 'Benjamin'; Dog = 'Samba'; DOG = 'Bernie'
>>> print ('The three dogs are named ',dog,', ',Dog,', and ',DOG)
The three dogs are named  Benjamin ,  Samba , and  Bernie
>>> 
dog = "Benjamin"
Dog = "Samba"
DOG = "Bernie"

print "There are three dogs named " + dog + ", " + Dog + " and " + DOG
Classes
PythonMiniScript
class MyClass:
    name2 = 2 # Class attribute

    def __init__(self):
        """
        Constructor  (Technically an initializer rather than a true "constructor")
        """
        self.name1 = 0 # Instance attribute
  
    def someMethod(self):
        """
        Method
        """
        self.name1 = 1
        MyClass.name2 = 3
  
  
myclass = MyClass() # class name, invoked as a function is the constructor syntax.

class MyOtherClass:
    count = 0  # Population of "MyOtherClass" objects
    def __init__(self, name, gender="Male", age=None):
        """
        One initializer required, others are optional (with different defaults)
        """
        MyOtherClass.count += 1
        self.name = name
        self.gender = gender
        if age is not None:
            self.age = age
    def __del__(self):
        MyOtherClass.count -= 1

person1 = MyOtherClass("John")
print person1.name, person1.gender  # "John Male"
print person1.age                   # Raises AttributeError exception!
person2 = MyOtherClass("Jane", "Female", 23)
print person2.name, person2.gender, person2.age  # "Jane Female 23"
// MiniScript is prototype based
Weapon = { "name": "Sword", "damage": 3 }
Weapon.slice = function()
    print "Did " + self.damage + " damage with " + self.name
end function

wep = new Weapon  // Same as: wep = { "__isa": Weapon }

wep.name = "Lance"

wep.slice
Collections
PythonMiniScript
collection = [0, '1']                 # Lists are mutable (editable) and can be sorted in place
x = collection[0]                     # accessing an item (which happens to be a numeric 0 (zero)
collection.append(2)                  # adding something to the end of the list
collection.insert(0, '-1')            # inserting a value into the beginning
y = collection[0]                     # now returns a string of "-1"
collection.extend([2,'3'])            # same as [collection.append(i) for i in [2,'3']] ... but
faster
collection += [2,'3']                 # same as previous line
collection[2:6]                       # a "slice" (collection of the list elements from the third up
to but not including the sixth)
len(collection)                       # get the length of (number of elements in) the collection
collection = (0, 1)                   # Tuples are immutable (not editable)
collection[:]                         # ... slices work on these too; and this is equivalent to
collection[0:len(collection)]
collection[-4:-1]                     # negative slices count from the end of the string
collection[::2]                       # slices can also specify a stride --- this returns all even
elements of the collection
collection="some string"              # strings are treated as sequences of characters
x = collection[::-1]                  # slice with negative step returns reversed sequence (string
in this case).
collection[::2] == "some string"[::2] # True, literal objects don't need to be bound to
name/variable to access slices or object methods
collection.__getitem__(slice(0,len(collection),2))  # same as previous expressions.
collection = {0: "zero", 1: "one"}    # Dictionaries (Hash)
collection['zero'] = 2                # Dictionary members accessed using same syntax as list/array
indexes.
collection = set([0, '1'])            # sets (Hash)
seq = [0, "foo", pi]
seq.push 42
seq = seq + [1, 2, 3]
print seq
Compound data type
PythonMiniScript
X, Y = 0, 1
p = (3, 4)
p = [3, 4]

print p[X]
Point = {}
Point.x = 0
Point.y = 0
Conditional structures
PythonMiniScript
if x == 0:
    foo()
elif x == 1:
    bar()
elif x == 2:
    baz()
else:
    boz()
x = 42
if x < 10 then
    print "small"
else if x < 20 then
    print "small-ish"
else if x > 100 then
    print "large"
else
    print "just right"
end if
Conway's Game of Life
PythonMiniScript
import random
from collections import defaultdict

printdead, printlive = '-#'
maxgenerations = 3
cellcount = 3,3
celltable = defaultdict(int, {
 (1, 2): 1,
 (1, 3): 1,
 (0, 3): 1,
 } ) # Only need to populate with the keys leading to life

##
## Start States
##
# blinker
u = universe = defaultdict(int)
u[(1,0)], u[(1,1)], u[(1,2)] = 1,1,1

## toad
#u = universe = defaultdict(int)
#u[(5,5)], u[(5,6)], u[(5,7)] = 1,1,1
#u[(6,6)], u[(6,7)], u[(6,8)] = 1,1,1

## glider
#u = universe = defaultdict(int)
#maxgenerations = 16
#u[(5,5)], u[(5,6)], u[(5,7)] = 1,1,1
#u[(6,5)] = 1
#u[(7,6)] = 1

## random start
#universe = defaultdict(int, 
#                       # array of random start values
#                       ( ((row, col), random.choice((0,1)))
#                         for col in range(cellcount[0])
#                         for row in range(cellcount[1])
#                       ) )  # returns 0 for out of bounds

for i in range(maxgenerations):
    print("\nGeneration %3i:" % ( i, ))
    for row in range(cellcount[1]):
        print("  ", ''.join(str(universe[(row,col)])
                            for col in range(cellcount[0])).replace(
                                '0', printdead).replace('1', printlive))
    nextgeneration = defaultdict(int)
    for row in range(cellcount[1]):
        for col in range(cellcount[0]):
            nextgeneration[(row,col)] = celltable[
                ( universe[(row,col)],
                  -universe[(row,col)] + sum(universe[(r,c)]
                                             for r in range(row-1,row+2)
                                             for c in range(col-1, col+2) )
                ) ]
    universe = nextgeneration
// Conway's Game of Life
clear
rows = 64; rowRange = range(0, rows-1)
cols = 96; colRange = range(0, cols-1)
// prepare two tile displays, in display layers 4 and 5
img = Image.create(2, 1); img.setPixel 1, 0, color.white
grids = []
for dispIdx in [4,5]
    display(dispIdx).mode = displayMode.tile
    td = display(dispIdx)
    td.cellSize = 10  // size of cells on screen
    td.extent = [cols, rows]
    td.overlap = -1   // adds a small gap between cells
    td.tileSet = img; td.tileSetTileSize = 1
    td.clear 0
    grids.push td
end for

// initialize to a random state
for x in colRange
    for y in rowRange
        td.setCell x, y, rnd > 0.5
    end for
end for

curIdx = 5
// main loop
while true
    yield
    td = grids[curIdx-4]
    newIdx = 4 + (curIdx == 4)
    newTd = grids[newIdx-4]
    for x in colRange
        for y in rowRange
            // get sum of neighboring states
            sum = 0
            for i in [x-1, x, x+1]
                if i < 0 or i >= cols then continue
                for j in [y-1, y, y+1]
                    if j < 0 or j >= rows then continue
                    if i==x and j==y then continue
                    sum = sum + td.cell(i,j)
                end for
            end for
            // Now, update the cell based on current state
            // and neighboring sum.
            if td.cell(x,y) then
                newTd.setCell x, y, (sum == 2 or sum == 3)
            else
                newTd.setCell x, y, sum == 3
            end if
        end for
    end for
    display(newIdx).mode = displayMode.tile
    display(curIdx).mode = displayMode.off
    curIdx = newIdx
end while
Copy a string
PythonMiniScript
>>> src = "hello"
>>> a = src
>>> b = src[:]
>>> import copy
>>> c = copy.copy(src)
>>> d = copy.deepcopy(src)
>>> src is a is b is c is d
True
phrase = "hi"
copy = phrase
print phrase
print copy
Count occurrences of a substring
PythonMiniScript
>>> "the three truths".count("th")
3
>>> "ababababab".count("abab")
2
string.count = function(s)
    return self.split(s).len - 1
end function

print "the three truths".count("th")
print "ababababab".count("abab")
Cumulative standard deviation
PythonMiniScript
>>> from math import sqrt
>>> def sd(x):
    sd.sum  += x
    sd.sum2 += x*x
    sd.n    += 1.0
    sum, sum2, n = sd.sum, sd.sum2, sd.n
    return sqrt(sum2/n - sum*sum/n/n)

>>> sd.sum = sd.sum2 = sd.n = 0
>>> for value in (2,4,4,4,5,5,7,9):
    print (value, sd(value))

    
(2, 0.0)
(4, 1.0)
(4, 0.94280904158206258)
(4, 0.8660254037844386)
(5, 0.97979589711327075)
(5, 1.0)
(7, 1.3997084244475311)
(9, 2.0)
>>>
StdDeviator = {}
StdDeviator.count = 0
StdDeviator.sum = 0
StdDeviator.sumOfSquares = 0

StdDeviator.add = function(x)
    self.count = self.count + 1
    self.sum = self.sum + x
    self.sumOfSquares = self.sumOfSquares + x*x
end function

StdDeviator.stddev = function()
    m = self.sum / self.count
    return sqrt(self.sumOfSquares / self.count - m*m)
end function

sd = new StdDeviator
for x in [2, 4, 4, 4, 5, 5, 7, 9]
    sd.add x
end for
print sd.stddev
Determine if a string is numeric
PythonMiniScript
def is_numeric(s):
    try:
        float(s)
        return True
    except (ValueError, TypeError):
        return False

is_numeric('123.0')
isNumeric = function(s)
    return s == "0" or s == "-0" or val(s) != 0
end function

print isNumeric("0")
print isNumeric("42")
print isNumeric("-3.14157")
print isNumeric("5@*#!")
print isNumeric("spam")
Draw a clock
PythonMiniScript
import time

def chunks(l, n=5):
    return [l[i:i+n] for i in range(0, len(l), n)]

def binary(n, digits=8):
    n=int(n)
    return '{0:0{1}b}'.format(n, digits)

def secs(n):
    n=int(n)
    h='x' * n
    return "|".join(chunks(h))

def bin_bit(h):
    h=h.replace("1","x")
    h=h.replace("0"," ")
    return "|".join(list(h))


x=str(time.ctime()).split()
y=x[3].split(":")

s=y[-1]
y=map(binary,y[:-1])

print bin_bit(y[0])
print
print bin_bit(y[1])
print
print secs(s)
// draw a clock hand, then copy it to an image
gfx.clear color.clear
gfx.fillPoly [[60,5], [64,10], [128,5], [64,0]], color.yellow
handImg = gfx.getImage(0,0, 128,10)

clear  // clear all displays

// prepare the face sprite
faceImg = file.loadImage("/sys/pics/shapes/CircleThinInv.png")
face = new Sprite
face.image = faceImg
face.scale = 2
face.x = 480; face.y = 320
display(4).sprites.push face

// prepare the hand sprite (from previously created image)
hand = new Sprite
hand.image = handImg
hand.x = face.x; hand.y = face.y
display(4).sprites.push hand

// main loop
while true
    hand.rotation = 90 - floor(time) % 60 * 6
    wait
end while
Entropy
PythonMiniScript
from __future__ import division
import math

def hist(source):
    hist = {}; l = 0;
    for e in source:
        l += 1
        if e not in hist:
            hist[e] = 0
        hist[e] += 1
    return (l,hist)

def entropy(hist,l):
    elist = []
    for v in hist.values():
        c = v / l
        elist.append(-c * math.log(c ,2))
    return sum(elist)

def printHist(h):
    flip = lambda (k,v) : (v,k)
    h = sorted(h.iteritems(), key = flip)
    print 'Sym\thi\tfi\tInf'
    for (k,v) in h:
        print '%s\t%f\t%f\t%f'%(k,v,v/l,-math.log(v/l, 2))
    
    

source = "1223334444"
(l,h) = hist(source);
print '.[Results].'
print 'Length',l
print 'Entropy:', entropy(h, l)
printHist(h)
entropy = function(s)
    count = {}
    for c in s
        if count.hasIndex(c) then count[c] = count[c]+1 else count[c] = 1
    end for
    sum = 0
    for x in count.values
        countOverN = x / s.len
        sum = sum + countOverN * log(countOverN, 2)
    end for
    return -sum
end function

print entropy("1223334444")
Even or odd
PythonMiniScript
>>> def is_odd(i): return bool(i & 1)

>>> def is_even(i): return not is_odd(i)

>>> [(j, is_odd(j)) for j in range(10)]
[(0, False), (1, True), (2, False), (3, True), (4, False), (5, True), (6, False), (7, True), (8,
False), (9, True)]
>>> [(j, is_even(j)) for j in range(10)]
[(0, True), (1, False), (2, True), (3, False), (4, True), (5, False), (6, True), (7, False), (8,
True), (9, False)]
>>> 
for i in range(-4, 4)
    if i % 2 == 0 then print i + " is even" else print i + " is odd"
end for
Execute HQ9+
PythonMiniScript

See [[RCHQ9+/Python]].

code = input("Enter HQ9+ program: ")

sing = function()
    for i in range(99,2)
        print i + " bottles of beer on the wall, " + i + " bottles of beer"
        print "Take one down, pass it around, " + (i-1) + " bottle" + "s"*(i>2) + " of beer on the
wall"
    end for
    print "1 bottle of beer on the wall, 1 bottle of beer"
    print "Take one down, pass it around, no bottles of beer on the wall!"
end function

accumulator = 0
for c in code
    c = c.lower
    if c == "h" then print "Hello World"
    if c == "q" then print code
    if c == "9" then sing
    if c == "+" then accumulator = accumulator + 1
end for
Factorial
PythonMiniScript
import math
math.factorial(n)
factorial = function(n)
    result = 1
    for i in range(2,n)
        result = result * i
    end for
    return result
end function

print factorial(10)
Factors of an integer
PythonMiniScript
>>> def factors(n):
      return [i for i in range(1, n + 1) if not n%i]
factors = function(n)
    result = [1]
    for i in range(2, n)
        if n % i == 0 then result.push i
    end for
    return result
end function

while true
    n = val(input("Number to factor (0 to quit)? "))
    if n <= 0 then break
    print factors(n)
end while
Fibonacci sequence
PythonMiniScript
from math import *

def analytic_fibonacci(n):
  sqrt_5 = sqrt(5);
  p = (1 + sqrt_5) / 2;
  q = 1/p;
  return int( (p**n + q**n) / sqrt_5 + 0.5 )

for i in range(1,31):
  print analytic_fibonacci(i),
fibonacci = function(n)
    if n < 2 then return n
    n1 = 0
    n2 = 1
    for i in range(n-1, 1)
        ans = n1 + n2
        n1 = n2
        n2 = ans
    end for
    return ans
end function

print fibonacci(6)
Filter
PythonMiniScript
values = range(10)
evens = [x for x in values if not x & 1]
ievens = (x for x in values if not x & 1) # lazy
# alternately but less idiomatic:
evens = filter(lambda x: not x & 1, values)
list.filter = function(f)
    result = []
    for item in self
        if f(item) then result.push item
    end for
    return result
end function

isEven = function(x)
    return x % 2 == 0
end function

nums = [1, 2, 3, 4, 5, 6, 7, 9, 12, 15, 18, 21]
print nums.filter(@isEven)
FizzBuzz
PythonMiniScript
for i in xrange(1, 101):
    if i % 15 == 0:
        print "FizzBuzz"
    elif i % 3 == 0:
        print "Fizz"
    elif i % 5 == 0:
        print "Buzz"
    else:
        print i
for i in range(1,100)
    if i % 15 == 0 then
        print "FizzBuzz"
    else if i % 3 == 0 then
        print "Fizz"
    else if i % 5 == 0 then
        print "Buzz"
    else
        print i
    end if
end for
Flipping bits game
PythonMiniScript
"""
Given a %i by %i sqare array of zeroes or ones in an initial
configuration, and a target configuration of zeroes and ones
The task is to transform one to the other in as few moves as 
possible by inverting whole numbered rows or whole lettered 
columns at once.
In an inversion any 1 becomes 0 and any 0 becomes 1 for that
whole row or column.

"""

from random import randrange
from copy import deepcopy
from string import ascii_lowercase


try:    # 2to3 fix
    input = raw_input
except:
    pass

N = 3   # N x N Square arrray

board  = [[0]* N for i in range(N)]

def setbits(board, count=1):
    for i in range(count):
        board[randrange(N)][randrange(N)] ^= 1

def shuffle(board, count=1):
    for i in range(count):
        if randrange(0, 2):
            fliprow(randrange(N))
        else:
            flipcol(randrange(N))


def pr(board, comment=''):
    print(str(comment))
    print('     ' + ' '.join(ascii_lowercase[i] for i in range(N)))
    print('  ' + '\n  '.join(' '.join(['%2s' % j] + [str(i) for i in line])
                             for j, line in enumerate(board, 1)))

def init(board):
    setbits(board, count=randrange(N)+1)
    target = deepcopy(board)
    while board == target:
        shuffle(board, count=2 * N)
    prompt = '  X, T, or 1-%i / %s-%s to flip: ' % (N, ascii_lowercase[0], 
                                                    ascii_lowercase[N-1])
    return target, prompt

def fliprow(i):
    board[i-1][:] = [x ^ 1 for x in board[i-1] ]
    
def flipcol(i):
    for row in board:
        row[i] ^= 1

if __name__ == '__main__':
    print(__doc__ % (N, N))
    target, prompt = init(board)
    pr(target, 'Target configuration is:')
    print('')
    turns = 0
    while board != target:
        turns += 1
        pr(board, '%i:' % turns)
        ans = input(prompt).strip()
        if (len(ans) == 1 
            and ans in ascii_lowercase and ascii_lowercase.index(ans) < N):
            flipcol(ascii_lowercase.index(ans))
        elif ans and all(ch in '0123456789' for ch in ans) and 1 <= int(ans) <= N:
            fliprow(int(ans))
        elif ans == 'T':
            pr(target, 'Target configuration is:')
            turns -= 1
        elif ans == 'X':
            break
        else:
            print("  I don't understand %r... Try again. "
                  "(X to exit or T to show target)\n" % ans[:9])
            turns -= 1
    else:
        print('\nWell done!\nBye.')
// Flipping Bits game.
// Transform a start grid to an end grid by flipping rows or columns.

size = 3

board = []
goal = []
for i in range(1,size)
    row = []
    for j in range(1,size)
        row.push (rnd > 0.5)
    end for
    board.push row
    goal.push row[0:]
end for

flipRow = function(n)
    for j in range(0, size-1)
        board[n-1][j] = not board[n-1][j]
    end for
end function

flipCol = function(n)
    for i in range(0, size-1)
        board[i][n-1] = not board[i][n-1]
    end for
end function

flipAny = function(s)
    s = s[0].upper
    if s >= "A" then flipCol s.code - 64 else flipRow val(s)
end function

for scramble in range(20)
    if rnd < 0.5 then flipRow ceil(rnd*size) else flipCol ceil(rnd*size)
end for

solved = function()
    for i in range(0, size-1)
        for j in range(0, size-1)
            if board[i][j] != goal[i][j] then return false
        end for
    end for
    return true
end function

moveCount = 0
while true
    print "  CURRENT:" + " "*(4+size*3) + "GOAL:"
    for i in range(1,size)
        s = i + " " + str(board[i-1])
        s = s + " "*(3+size*3) + str(goal[i-1])
        print s
    end for
    s = "   "
    for i in range(1,size)
        s = s + char(64+i) + "  "
    end for
    print s
    if solved then break
    moveCount = moveCount + 1
    inp = input("Move " + moveCount + "? ")
    flipAny(inp)
end while
print "You did it!"
Function composition
PythonMiniScript
compose = lambda f, g: lambda x: f( g(x) )
funcA = function(x)
    return x * 10
end function

funcB = function(x)
    return x + 5
end function

compose = function(f, g)
    return function(x)
        return f(g(x))
    end function
end function

f = compose(@funcA, @funcB)
print f(3)  // should be equal to (3+5)*10
Function definition
PythonMiniScript
def multiply(a, b):
    return a * b
multiply = function(x,y)
    return x*y
end function

print multiply(6, 7)
General FizzBuzz
PythonMiniScript
def genfizzbuzz(factorwords, numbers):
    # sort entries by factor
    factorwords.sort(key=lambda factor_and_word: factor_and_word[0])
    lines = []
    for num in numbers:
        words = ''.join(word for factor, word in factorwords if (num % factor) == 0)
        lines.append(words if words else str(num))
    return '\n'.join(lines)

if __name__ == '__main__':
    print(genfizzbuzz([(5, 'Buzz'), (3, 'Fizz'), (7, 'Baxx')], range(1, 21)))
factorWords = {}

maxNr = val(input("Max number? "))

while true
    factorInput = input("Factor? ")
    if factorInput == "" then break
    // Split input
    parts = factorInput.split(" ")
    factor = val(parts[0])
    word = parts[1]
    // Assign factor/word
    factorWords[factor] = word
end while

for nr in range(1,maxNr)
    matchingWords = ""
    for factor in factorWords.indexes
        if nr % factor == 0 then 
            matchingWords = matchingWords + factorWords[factor]
        end if
    end for
    if matchingWords then print matchingWords else print nr
end for
Generate Chess960 starting position
PythonMiniScript
>>> from itertools import permutations
>>> pieces = 'KQRrBbNN'
>>> starts = {''.join(p).upper() for p in permutations(pieces)
                     if p.index('B') % 2 != p.index('b') % 2         # Bishop constraint
                     and ( p.index('r') < p.index('K') < p.index('R')    # King constraint    
                           or p.index('R') < p.index('K') < p.index('r') ) }
>>> len(starts)
960
>>> starts.pop()
'QNBRNKRB'
>>>
// placeholder knights
rank = ["♘"] * 8

// function to get a random free space from a to b, inclusive
randFree = function(a, b)
    free = []
    for i in range(a, b)
        if rank[i] == "♘" then free.push i
    end for
    return free[rnd * free.len]
end function

// place the king
kingIdx = randFree(1, 6)
rank[kingIdx] = "♔"

// place rooks
rank[randFree(0, kingIdx - 1)] = "♖"
rank[randFree(kingIdx + 1, 7)] = "♖"

// place bishops
bishIdx = randFree(0, 7)
rank[bishIdx] = "♗"
while true
    i = randFree(0, 7)
    if i % 2 != bishIdx % 2 then break
end while
rank[i] = "♗"

// place queen
rank[randFree(0, 7)] = "♕"

print join(rank, " ")
Generate lower case ASCII alphabet
PythonMiniScript
# From the standard library:
from string import ascii_lowercase

# Generation:
lower = [chr(i) for i in range(ord('a'), ord('z') + 1)]
letters = []
for i in range(code("a"), code("z"))
    letters.push char(i)
end for

print letters
Generic swap
PythonMiniScript
a, b = b, a
swap = function(map, a, b)
    temp = map[a]
    map[a] = map[b]
    map[b] = temp
end function

x = 1
y = 2
print "BEFORE: x=" + x + ", y=" + y
swap(locals, "x", "y")
print "AFTER:  x=" + x + ", y=" + y
Greatest common divisor
PythonMiniScript
from fractions import gcd
gcd = function(a, b)
    while b
        temp = b
        b = a % b
        a = temp
    end while
    return abs(a)
end function

print gcd(18,12)
Greatest element of a list
PythonMiniScript
max(values)
list.max = function()
    if not self then return null
    result = self[0]
    for item in self
        if item > result then result = item
    end for
    return result
end function

print [47, 11, 42, 102, 13].max
Guess the number
PythonMiniScript
import random
t,g=random.randint(1,10),0
g=int(input("Guess a number that's between 1 and 10: "))
while t!=g:g=int(input("Guess again! "))
print("That's right!")
num = ceil(rnd*10)
while true
    x = val(input("Your guess?"))
    if x == num then
        print "Well guessed!"
        break
    end if
end while
Happy numbers
PythonMiniScript
>>> def happy(n):
    past = set()            
    while n != 1:
        n = sum(int(i)**2 for i in str(n))
        if n in past:
            return False
        past.add(n)
    return True

>>> [x for x in xrange(500) if happy(x)][:8]
[1, 7, 10, 13, 19, 23, 28, 31]
isHappy = function(x)
    while true
        if x == 89 then return false
        sum = 0
        while x > 0
            sum = sum + (x % 10)^2
            x = floor(x / 10)
        end while
        if sum == 1 then return true
        x = sum
    end while
end function

found = []
i = 1
while found.len < 8
    if isHappy(i) then found.push i
    i = i + 1
end while
print "First 8 happy numbers: " + found
Hash from two arrays
PythonMiniScript
keys = ['a', 'b', 'c']
values = [1, 2, 3]
hash = {key: value for key, value in zip(keys, values)}
keys = ["foo", "bar", "val"]
values = ["little", "miss", "muffet"]

d = {}
for i in range(keys.len-1)
    d[keys[i]] = values[i]
end for

print d
Hello world/Newbie
PythonMiniScript
print "Goodbye, World!"
print "Hello World!"
Hello world/Text
PythonMiniScript
print "Hello world!"
print "Hello world!"
Hofstadter Q sequence
PythonMiniScript
def q(n):
    if n < 1 or type(n) != int: raise ValueError("n must be an int >= 1")
    try:
        return q.seq[n]
    except IndexError:
        ans = q(n - q(n - 1)) + q(n - q(n - 2))
        q.seq.append(ans)
        return ans
q.seq = [None, 1, 1]

if __name__ == '__main__':
    first10 = [q(i) for i in range(1,11)]
    assert first10 == [1, 1, 2, 3, 3, 4, 5, 5, 6, 6], "Q() value error(s)"
    print("Q(n) for n = [1..10] is:", ', '.join(str(i) for i in first10))
    assert q(1000) == 502, "Q(1000) value error"
    print("Q(1000) =", q(1000))
cache = {1:1, 2:1}

Q = function(n)
    if not cache.hasIndex(n) then
        q = Q(n - Q(n-1)) + Q(n - Q(n-2))
        cache[n] = q
    end if
    return cache[n]
end function

for i in range(1,10)
    print "Q(" + i + ") = " + Q(i)
end for
print "Q(1000) = " + Q(1000)
Hunt the Wumpus
PythonMiniScript
import random

class WumpusGame(object):


    def __init__(self, edges=[]):
        
        # Create arbitrary caves from a list of edges (see the end of the script for example).
        if edges:
            cave = {}
            N = max([edges[i][0] for i in range(len(edges))])
            for i in range(N):
                exits = [edge[1] for edge in edges if edge[0] == i]
                cave[i] = exits

        # If no edges are specified, play in the standard cave: a dodecahedron.
        else:
            cave = {1: [2,3,4], 2: [1,5,6], 3: [1,7,8], 4: [1,9,10], 5:[2,9,11],
                6: [2,7,12], 7: [3,6,13], 8: [3,10,14], 9: [4,5,15], 10: [4,8,16], 
                11: [5,12,17], 12: [6,11,18], 13: [7,14,18], 14: [8,13,19], 
                15: [9,16,17], 16: [10,15,19], 17: [11,20,15], 18: [12,13,20], 
                19: [14,16,20], 20: [17,18,19]}

        self.cave = cave

        self.threats = {}

        self.arrows = 5

        self.arrow_travel_distance = 5        # As in the original game. I don't like this choice:
                                            # a bow should not cover a whole cave.
        self.player_pos = -1


    """
    HELPER: These methods wrap processes that are useful or called often.
    """


    def get_safe_rooms(self):
        """ Returns a list containing all numbers of rooms that
            do not contain any threats
        """
        return list(set(self.cave.keys()).difference(self.threats.keys()))


    def populate_cave(self):
        """ Drop player and threats into random rooms in the cave.
        """
        for threat in ['bat', 'bat', 'pit', 'pit', 'wumpus']:
            pos = random.choice(self.get_safe_rooms())
            self.threats[pos] = threat
        self.player_pos = random.choice(self.get_safe_rooms())


    def breadth_first_search(self, source, target, max_depth=5):
        """ The game board (whether custom or standard dodecahedron) is an undirected graph. 
            The rooms are the vertices and the tunnels are the edges of this graph. To find 
            out whether a target room can be reached from a source room using a given amount 
            of tunnels, one can do a breadth first search on the underlying undirected graph.

            BFS works like this: start with the source vertex, maybe it is already the target? 
            If not, then go a level deeper and find out, if one of the children (also called 
            successors) of the source vertex is the wanted target. If not, then for each child, 
            go a level deeper and find out if one of the grand-children is the wanted target. 
            If not, then for each grand-child go a level deeper and so on. 

            The following is a recursive implementation of BFS. You will not find any loops 
            (for, while). Instead you manage two lists. The first one ('stack') contains all 
            the vertices of the current depth-level (e.g. all grand children). The second 
            ('visited') contains all vertices that you already checked. Now there are three 
            possibilites: Either stack is empty, then all vertices have been checked unsuccessfully;
            or the target vertex is a member of the stack, then you are happy; or the target is 
            not a member of the stack, but there are still some vertices that you did not visit, 
            then you append to the stack, all successors of the members of the stack and the old 
            stack now belongs to the visited vertices.
        """
        # Set up some initial values.
        graph = self.cave
        depth = 0

        def search(stack, visited, target, depth):
            if stack == []:                    # The whole graph was searched, but target was not
found.
                return False, -1
            if target in stack:
                return True, depth
            visited = visited + stack
            stack = list(set([graph[v][i] for v in stack for i in
range(len(graph[v]))]).difference(visited))
            depth += 1
            if depth > max_depth:            # Target is too far away from the source.
                return False, depth
            else:                            # Visit all successors of vertices in the stack.
                return search(stack, visited, target, depth)

        return search([source], [], target, depth)


    """
    INPUT / OUTPUT: The player interacts with the game.
    """


    def print_warning(self, threat):
        """ Called when entering a new room. Shows threats in adjacent rooms.
        """
        if threat == 'bat':
            print("You hear a rustling.")
        elif threat == 'pit':
            print("You feel a cold wind blowing from a nearby cavern.")
        elif threat == 'wumpus':
            print("You smell something terrible nearby.")


    def get_players_input(self):
        """ Queries input until valid input is given.
        """
        while 1:                                # Query the action.

            inpt = input("Shoot or move (S-M)? ")
            try:                                # Ensure that the player choses a valid action
(shoot or move)
                mode = str(inpt).lower()
                assert mode in ['s', 'm', 'q']
                break
            except (ValueError, AssertionError):
                print("This is not a valid action: pick 'S' to shoot and 'M' to move.")

        if mode == 'q':                            # I added a 'quit-button' for convenience.
            return 'q', 0

        while 1:                                # Query the target of the action.

            inpt = input("Where to? ")
            try:                                # Ensure that the chosen target is convertable to an
integer.
                target = int(inpt)
            except ValueError:
                print("This is not even a real number.")
                continue                        # Restart the while loop, to get a valid integer as
target.

            if mode == 'm':
                try:                            # When walking, the target must be adjacent to the
current room.
                    assert target in self.cave[self.player_pos]
                    break
                except AssertionError:
                    print("You cannot walk that far. Please use one of the tunnels.")

            elif mode == 's':
                try:                            # When shooting, the target must be reachable within
5 tunnels.
                    bfs = self.breadth_first_search(self.player_pos, target)
                    assert bfs[0] == True
                    break
                except AssertionError:
                    if bfs[1] == -1:             # The target is outside cave.
                        print("There is no room with this number in the cave. Your arrow travels
randomly.")
                        target = random.choice(self.cave.keys())
                    if bfs[1] > self.arrow_travel_distance:                # The target is too far.
                        print("Arrows aren't that croocked.")

        return mode, target


    """
    CORE / GAME LOGIC
    """


    def enter_room(self, room_number):
        """ Controls the process of entering a new room.
        """    
        print("Entering room {}...".format(room_number))
        # Maybe a threat waits in the new room.    
        if self.threats.get(room_number) == 'bat':
            # The bat teleports the player to random empty room
            print("You encounter a bat, it transports you to a random empty room.")
            new_pos = random.choice(self.get_safe_rooms())
            return self.enter_room(new_pos)
        elif self.threats.get(room_number) == 'wumpus':
            print("Wumpus eats you.")
            return -1
        elif self.threats.get(room_number) == 'pit':
            print("You fall into a pit.")
            return -1

        # The room is safe; collect information about adjacent rooms.
        for i in self.cave[room_number]:
            self.print_warning(self.threats.get(i))

        # Only if nothing else happens, the player enters the room of his choice.
        return room_number


    def shoot_room(self, room_number):
        """ Controls the process of shooting in a room.
        """
        print("Shooting an arrow into room {}...".format(room_number))
        # Fire an arrow and see if something is hit by it.
        self.arrows -= 1
        threat = self.threats.get(room_number)
        if threat in ['bat', 'wumpus']:
            del self.threats[room_number]        
            if threat == 'wumpus':
                print("Hurra, you killed the wumpus!")
                return -1
            elif threat == 'bat':
                print("You killed a bat.")
        elif threat in ['pit', None]:
            print("This arrow is lost.")
        
        # If this was your last arrow and it did not hit the wumpus...
        if self.arrows < 1:        # This (or the updating of self.arrows) seems to be broken...
            print("Your quiver is empty.")
            return -1

        #  If you shoot into another room, the Wumpus has a 75% of chance of waking up and moving
into an adjacent room.
        if random.random() < 0.75:
            #print("DEBUG: Wumpus moved.")
            for room_number, threat in self.threats.items():
                if threat == 'wumpus':
                    wumpus_pos = room_number                    
            new_pos =
random.choice(list(set(self.cave[wumpus_pos]).difference(self.threats.keys())))
            del self.threats[room_number]
            self.threats[new_pos] = 'wumpus'            
            if new_pos == self.player_pos: # Wumpus entered players room.
                print("Wumpus enters your room and eats you!")
                return -1

        return self.player_pos

        
    def gameloop(self):

        print("HUNT THE WUMPUS")
        print("===============")
        print()
        self.populate_cave()
        self.enter_room(self.player_pos)

        while 1:

            #print("DEBUG: Your quiver holds {} arrows.".format(self.arrows))            
            #print("DEBUG: Rooms with no threats are: {}.".format(self.get_safe_rooms()))           
            #print("DEBUG: Threats are located in the following rooms: {}".format(self.threats))

            print("You are in room {}.".format(self.player_pos), end=" ")
            print("Tunnels lead to:  {0}  {1}  {2}".format(*self.cave[self.player_pos]))
            
            
            inpt = self.get_players_input()        # Player choses move or shoot.
            print()                                # Visual separation of rounds.
            if inpt[0] == 'm':                    # Move.
                target = inpt[1] 
                self.player_pos = self.enter_room(target)
            elif inpt[0] == 's':                # Shoot.
                target = inpt[1]
                self.player_pos = self.shoot_room(target)
            elif inpt[0] == 'q':                # Quit.
                self.player_pos = -1

            if self.player_pos == -1:            # E.g. Deadly threat, quiver empty, etc.
                break                            # If any of the game loosing conditions are True,
                                                # then player_pos will be -1. 

        print()
        print("Game over!")    
        

if __name__ == '__main__':                        
    # Only executed if you start this script as the main script,
    # i.e. you enter 'python path/to/wumpus.py' in a terminal.
    # Assuming you saved the script in the directory 'path/to' 
    # and named it 'wumpus.py'.

    # TODO: In the original game you can replay a dungeon (same positions of you and the threats)

    WG = WumpusGame()
    WG.gameloop()

exits = [[1,4,7], [0,2,9], [1,3,11], [2,4,13], [0,3,5],
  [4,6,14], [5,7,16], [0,6,8], [7,9,17], [1,8,10],
  [9,11,18], [2,10,12], [11,13,19], [3,12,14], [5,13,15],
  [14,16,19], [6,15,17], [8,16,18], [10,17,19], [12,15,18]]
hazard = [null] * 20
emptyRoom = function()
    while true
        room = floor(rnd * 20)
        if not hazard[room] then return room
    end while
end function
for i in range(1, 2)
    hazard[emptyRoom] = "bat"
    hazard[emptyRoom] = "pit"
end for
hazard[emptyRoom] = "wumpus"

print "*** HUNT THE WUMPUS ***"
print "-----------------------"
curRoom = emptyRoom
arrows = 5

checkWumpus = function()
    if hazard[curRoom] == "wumpus" then
        print "You find yourself face to face with the wumpus."
        print "It eats you whole."
        print "GAME OVER"; exit
    end if    
end function

while true
    print "You are in room " + curRoom + "."
    checkWumpus
    for r in exits[curRoom]
        if hazard[r] == "wumpus" then print "You smell something terrible nearby."
        if hazard[r] == "bat" then print "You hear a rustling."
        if hazard[r] == "pit" then print "You feel a cold wind blowing from a nearby cavern."
    end for
    print "Tunnels lead to: " + exits[curRoom].join(", ")
    print "You have " + arrows + " arrows."; print
    while true
        m = input("M)ove, S)hoot, or Q)uit? ").lower
        if m == "q" then exit
        if m != "m" and m != "s" then continue
        target = input("Which room? ").val
        if exits[curRoom].indexOf(target) == null then
            print "Cannot get there from here."
        else if m == "m" then
            curRoom = target
            if hazard[curRoom] == "bat" then
                print "You have entered the lair of a giant bat."
                curRoom = emptyRoom
                print "It picks you up and drops you in room " + curRoom + "."
            else if hazard[curRoom] == "pit" then
                print "The ground gives way beneath your feet."
                print "You fall into a deep abyss."
                print "GAME OVER"; exit
            end if
        else
            arrows = arrows - 1
            if hazard[target] == "wumpus" then
                print "Congratulations!  You shot the wumpus!"
                exit
            end if
            print "You missed."
            if rnd < 0.75 then
                print "The wumpus wakes from his slumber."
                hazard[hazard.indexOf("wumpus")] = null
                hazard[emptyRoom] = "wumpus"
                checkWumpus
            end if
            if arrows == 0 then
                print "As you grasp at your empty quiver, "
                print "you hear a large beast approaching..."
                hazard[curRoom] = "wumpus"
                checkWumpus
            end if
        end if
        break
    end while
end while
Idiomatically determine all the lowercase and uppercase letters
PythonMiniScript
classes = (str.isupper, str.islower, str.isalnum, str.isalpha, str.isdecimal,
           str.isdigit, str.isidentifier, str.isnumeric, str.isprintable,
           str.isspace, str.istitle)

for stringclass in classes:
    chars = ''.join(chr(i) for i in range(0x10FFFF+1) if stringclass(chr(i)))
    print('\nString class %s has %i characters the first of which are:\n  %r'
          % (stringclass.__name__, len(chars), chars[:100]))
toChars = function(seq)
    for i in seq.indexes
        seq[i] = char(seq[i])
    end for
    return seq.join("")
end function

print toChars(range(code("a"), code("z")))
print toChars(range(code("A"), code("Z")))
Infinity
PythonMiniScript
>>> float('infinity')
inf
posInfinity = 1/0
print posInfinity
Integer comparison
PythonMiniScript
#!/usr/bin/env python
a = input('Enter value of a: ')
b = input('Enter value of b: ')

if a < b:
    print 'a is less than b'
elif a > b:
    print 'a is greater than b'
elif a == b:
    print 'a is equal to b'
integer1 = input("Please Input Integer 1:").val
integer2 = input("Please Input Integer 2:").val
if integer1 < integer2 then print integer1 + " is less than " + integer2
if integer1 == integer2 then print integer1 + " is equal to " + integer2
if integer1 > integer2 then print integer1 + " is greater than " + integer2
Keyboard input/Flush the keyboard buffer
PythonMiniScript
def flush_input():
    try:
        import msvcrt
        while msvcrt.kbhit():
            msvcrt.getch()
    except ImportError:
        import sys, termios
        termios.tcflush(sys.stdin, termios.TCIOFLUSH)
key.clear
Keyboard input/Keypress check
PythonMiniScript
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, unicode_literals, print_function

import tty, termios
import sys
if sys.version_info.major < 3:
    import thread as _thread
else:
    import _thread
import time


try:
    from msvcrt import getch  # try to import Windows version
except ImportError:
    def getch():   # define non-Windows version
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
        try:
            tty.setraw(sys.stdin.fileno())
            ch = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        return ch

def keypress():
    global char
    char = getch()

def main():
    global char
    char = None
    _thread.start_new_thread(keypress, ())

    while True:
        if char is not None:
            try:
                print("Key pressed is " + char.decode('utf-8'))
            except UnicodeDecodeError:
                print("character can not be decoded, sorry!")
                char = None
            _thread.start_new_thread(keypress, ())
            if char == 'q' or char == '\x1b':  # x1b is ESC
                exit()
            char = None
        print("Program is running")
        time.sleep(1)

if __name__ == "__main__":
    main()
x = key.available
Keyboard input/Obtain a Y or N response
PythonMiniScript
#!/usr/bin/env python

try:
    from msvcrt import getch
except ImportError:
    def getch():
        import sys, tty, termios
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
        try:
            tty.setraw(sys.stdin.fileno())
            ch = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        return ch

print "Press Y or N to continue"
while True:
    char = getch()
    if char.lower() in ("y", "n"):
        print char
        break
// flush the keyboard
while key.available
    key.get
end while

// and now prompt and wait for Y or N
print "Press Y or N:"
k = ""
while k != "Y" and k != "N"
    k = key.get.upper
end while
print "You pressed: " + k
Leap year
PythonMiniScript
import calendar
calendar.isleap(year)
isLeapYear = function(year)
  return year%4==0 and (year % 100 or not year % 400)
end function
Least common multiple
PythonMiniScript
>>> import fractions
>>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0

>>> lcm(12, 18)
36
>>> lcm(-6, 14)
42
>>> assert lcm(0, 2) == lcm(2, 0) == 0
>>> 
gcd = function(a, b)
    while b
        temp = b
        b = a % b
        a = temp
    end while
    return abs(a)
end function

lcm = function(a,b)
    if not a and not b then return 0
    return abs(a * b) / gcd(a, b)
end function

print lcm(18,12)
Levenshtein distance
PythonMiniScript
def levenshteinDistance(str1, str2):
    m = len(str1)
    n = len(str2)
    d = [[i] for i in range(1, m + 1)]   # d matrix rows
    d.insert(0, list(range(0, n + 1)))   # d matrix columns
    for j in range(1, n + 1):
        for i in range(1, m + 1):
            if str1[i - 1] == str2[j - 1]:   # Python (string) is 0-based
                substitutionCost = 0
            else:
                substitutionCost = 1
            d[i].insert(j, min(d[i - 1][j] + 1,
                               d[i][j - 1] + 1,
                               d[i - 1][j - 1] + substitutionCost))
    return d[-1][-1]

print(levenshteinDistance("kitten","sitting"))
print(levenshteinDistance("rosettacode","raisethysword"))
import "stringUtil"
print "kitten".editDistance("sitting")
Longest common prefix
PythonMiniScript
import os.path

def lcp(*s):
    return os.path.commonprefix(s)

assert lcp("interspecies","interstellar","interstate") == "inters"
assert lcp("throne","throne") == "throne"
assert lcp("throne","dungeon") == ""
assert lcp("cheese") == "cheese"
assert lcp("") == ""
assert lcp("prefix","suffix") == ""
assert lcp("foo","foobar") == "foo"
lcp = function(strList)
    if not strList then return null
    // find the shortest and longest strings (without sorting!)
    shortest = strList[0]
    longest = strList[0]
    for s in strList
        if s.len < shortest.len then shortest = s
        if s.len > longest.len then longest = s
    end for
    if shortest.len < 1 then return ""
    // now find how much of the shortest matches the longest
    for i in range(0, shortest.len-1)
        if shortest[i] != longest[i] then return shortest[:i]
    end for
    return shortest
end function

print lcp(["interspecies","interstellar","interstate"])
print lcp(["throne","throne"])
print lcp(["throne","dungeon"])
print lcp(["throne", "", "throne"])
print lcp(["cheese"])
print lcp([])
print lcp(["foo","foobar"])
Look-and-say sequence
PythonMiniScript
def lookandsay(number):
    result = ""

    repeat = number[0]
    number = number[1:]+" "
    times = 1

    for actual in number:
        if actual != repeat:
            result += str(times)+repeat
            times = 1
            repeat = actual
        else:
            times += 1

    return result

num = "1"

for i in range(10):
    print num
    num = lookandsay(num)
// Look and Say Sequence
repeats = function(digit, string)
    count = 0
    for c in string
        if c != digit then break
        count = count + 1
    end for
    return str(count)
end function
 
numbers = "1"
print numbers
for i in range(1,10) // warning, loop size > 15 gets long numbers very quickly
    number = ""
    position = 0
    while position < numbers.len
        repeatCount = repeats(numbers[position], numbers[position:])
        number = number + repeatCount + numbers[position]
        position = position + repeatCount.val
    end while
    print number
    numbers = number
end for
Loops/Downward for
PythonMiniScript
for i in xrange(10, -1, -1):
    print i
for i in range(10, 0)
    print i
end for
Loops/For
PythonMiniScript
import sys
for i in xrange(5):
    for j in xrange(i+1):
        sys.stdout.write("*")
    print
for i in range(1,5)
    s = ""
    for j in range(1, i)
        s = s + "*"
    end for
    print s
end for
Loops/For with a specified step
PythonMiniScript
for i in xrange(2, 9, 2):
    print "%d," % i,
print "who do we appreciate?"
for i in range(1,20,4)
    print i
end for
Loops/Foreach
PythonMiniScript
for i in collection:
   print i
for i in collection
   print i
end
Loops/While
PythonMiniScript
n = 1024
while n > 0:
    print n
    n //= 2
i = 1024
while i > 0
    print i
    i = floor(i/2)
end while
Luhn test of credit card numbers
PythonMiniScript
>>> def luhn(n):
    r = [int(ch) for ch in str(n)][::-1]
    return (sum(r[0::2]) + sum(sum(divmod(d*2,10)) for d in r[1::2])) % 10 == 0

>>> for n in (49927398716, 49927398717, 1234567812345678, 1234567812345670):
    print(n, luhn(n))
isValid = function(s)
    sum = 0
    odd = true
    for i in range(s.len-1)
        d = val(s[i])
        sum = sum + d * (2 - odd)
        if not odd and d > 4 then sum = sum - 9
        odd = not odd
    end for
    return sum % 10 == 0
end function

test = function(s)
    if isValid(s) then print s + ": valid" else print s + ": invalid"
end function

test "49927398716"
test "49927398717"
test "1234567812345678"
test "1234567812345670"
Magic 8-ball
PythonMiniScript
import random

s = ('It is certain', 'It is decidedly so', 'Without a doubt', 'Yes, definitely',
 'You may rely on it', 'As I see it, yes', 'Most likely', 'Outlook good',
 'Signs point to yes', 'Yes', 'Reply hazy, try again', 'Ask again later',
 'Better not tell you now', 'Cannot predict now', 'Concentrate and ask again',
 "Don't bet on it", 'My reply is no', 'My sources say no', 'Outlook not so good',
 'Very doubtful')

q_and_a = {}

while True:
    question = input('Ask your question:')
    if len(question) == 0: break
        
    if question in q_and_a:
        print('Your question has already been answered')
    else:
        answer = random.choice(s)
        q_and_a[question] = answer
        print(answer)
answers = ["It is certain", "It is decidedly so", "Without a doubt",
        "Yes, definitely", "You may rely on it", "As I see it, yes",
        "Most likely", "Outlook good", "Signs point to yes", "Yes",
        "Reply hazy, try again", "Ask again later",
        "Better not tell you now", "Cannot predict now",
        "Concentrate and ask again", "Don't bet on it",
        "My reply is no", "My sources say no", "Outlook not so good",
        "Very doubtful"]
print "Ask your question and the Magic 8 Ball will give you the answer!"
input "What is your question?"
print answers[rnd * answers.len]
Mandelbrot set
PythonMiniScript
# Python 3.0+ and 2.5+
try:
    from functools import reduce
except:
    pass


def mandelbrot(a):
    return reduce(lambda z, _: z * z + a, range(50), 0)

def step(start, step, iterations):
    return (start + (i * step) for i in range(iterations))

rows = (("*" if abs(mandelbrot(complex(x, y))) < 2 else " "
        for x in step(-2.0, .0315, 80))
        for y in step(1, -.05, 41))

print("\n".join("".join(row) for row in rows))
ZOOM = 100
MAX_ITER = 40
gfx.clear color.black
for y in range(0,200)
    for x in range(0,300)
        zx = 0
        zy = 0
        cx = (x - 200) / ZOOM
        cy = (y - 100) / ZOOM
        for iter in range(MAX_ITER)
            if zx*zx + zy*zy > 4 then break
            tmp = zx * zx - zy * zy + cx
            zy = 2 * zx * zy + cy
            zx = tmp
        end for
        if iter then
            gfx.setPixel x, y, rgb(255-iter*6, 0, iter*6)
        end if
    end for
end for
Middle three digits
PythonMiniScript
>>> def middle_three_digits(i):
    s = str(abs(i))
    length = len(s)
    assert length >= 3 and length % 2 == 1, "Need odd and >= 3 digits"
    mid = length // 2
    return s[mid-1:mid+2]

>>> passing = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345]
>>> failing = [1, 2, -1, -10, 2002, -2002, 0]
>>> for x in passing + failing:
    try:
        answer = middle_three_digits(x)
    except AssertionError as error:
        answer = error
    print("middle_three_digits(%s) returned: %r" % (x, answer))

    
middle_three_digits(123) returned: '123'
middle_three_digits(12345) returned: '234'
middle_three_digits(1234567) returned: '345'
middle_three_digits(987654321) returned: '654'
middle_three_digits(10001) returned: '000'
middle_three_digits(-10001) returned: '000'
middle_three_digits(-123) returned: '123'
middle_three_digits(-100) returned: '100'
middle_three_digits(100) returned: '100'
middle_three_digits(-12345) returned: '234'
middle_three_digits(1) returned: AssertionError('Need odd and >= 3 digits',)
middle_three_digits(2) returned: AssertionError('Need odd and >= 3 digits',)
middle_three_digits(-1) returned: AssertionError('Need odd and >= 3 digits',)
middle_three_digits(-10) returned: AssertionError('Need odd and >= 3 digits',)
middle_three_digits(2002) returned: AssertionError('Need odd and >= 3 digits',)
middle_three_digits(-2002) returned: AssertionError('Need odd and >= 3 digits',)
middle_three_digits(0) returned: AssertionError('Need odd and >= 3 digits',)
>>> 
middle3 = function(num)
    if num < 0 then num = -num
    s = str(num)
    if s.len < 3 then return "Input too short"
    if s.len % 2 == 0 then return "Input length not odd"
    mid = (s.len + 1) / 2 - 1
    return s[mid-1:mid+2]
end function

for test in [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100,
 100, -12345, 1, 2, -1, -10, 2002, -2002, 0]
    print test + " --> " + middle3(test)
end for
Mouse position
PythonMiniScript
import Tkinter as tk

def showxy(event):
    xm, ym = event.x, event.y
    str1 = "mouse at x=%d  y=%d" % (xm, ym)
    # show cordinates in title
    root.title(str1)
    # switch color to red if mouse enters a set location range
    x,y, delta = 100, 100, 10
    frame.config(bg='red'
                 if abs(xm - x) < delta and abs(ym - y) < delta
                 else 'yellow')

root = tk.Tk()
frame = tk.Frame(root, bg= 'yellow', width=300, height=200)
frame.bind("<Motion>", showxy)
frame.pack()

root.mainloop()
print mouse.x, mouse.y
Multisplit
PythonMiniScript
>>> import re
>>> def ms2(txt="a!===b=!=c", sep=["==", "!=", "="]):
    if not txt or not sep:
        return []
    ans = m = []
    for m in re.finditer('(.*?)(?:' + '|'.join('('+re.escape(s)+')' for s in sep) + ')', txt):
        ans += [m.group(1), (m.lastindex-2, m.start(m.lastindex))]
    if m and txt[m.end(m.lastindex):]:
        ans += [txt[m.end(m.lastindex):]]
    return ans

>>> ms2()
['a', (1, 1), '', (0, 3), 'b', (2, 6), '', (1, 7), 'c']
>>> ms2(txt="a!===b=!=c", sep=["=", "!=", "=="])
['a', (1, 1), '', (0, 3), '', (0, 4), 'b', (0, 6), '', (1, 7), 'c']
parseSep = function(s, pats)
    result = []
    startPos = 0
    pos = 0
    while pos < s.len
        for pat in pats
            if s[pos : pos+pat.len] != pat then continue
            result.push s[startPos : pos]
            result.push "{" + pat + "}"
            startPos = pos + pat.len
            pos = startPos - 1
            break
        end for
        pos = pos + 1
    end while
    return result
end function

print parseSep("a!===b=!=c", ["==", "!=", "="])
Munching squares
PythonMiniScript
import Image, ImageDraw

image = Image.new("RGB", (256, 256))
drawingTool = ImageDraw.Draw(image)

for x in range(256):
    for y in range(256):
        drawingTool.point((x, y), (0, x^y, 0))

del drawingTool
image.save("xorpic.png", "PNG")
xor = function(a, b)
    result = 0
    bit = 1
    while a > 0 or b > 0
        if (a%2 == 0) != (b%2 == 0) then result = result + bit
        bit = bit * 2
        a = floor(a/2)
        b = floor(b/2)
    end while
    return result
end function

for x in range(0,255)
    for y in range(0,255)
        gfx.setPixel x, y, color.rgb(0, xor(x,y), 0)
    end for
end for
Mutual recursion
PythonMiniScript
def F(n): return 1 if n == 0 else n - M(F(n-1))
def M(n): return 0 if n == 0 else n - F(M(n-1))

print ([ F(n) for n in range(20) ])
print ([ M(n) for n in range(20) ])
f = function(n)
    if n > 0 then return n - m(f(n - 1))
    return 1
end function

m = function(n)
    if n > 0 then return n - f(m(n - 1))
    return 0
end function

print f(12)
print m(12)
N'th
PythonMiniScript
_suffix = ['th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th']

def nth(n):
    return "%i'%s" % (n, _suffix[n%10] if n % 100 <= 10 or n % 100 > 20 else 'th')

if __name__ == '__main__':
    for j in range(0,1001, 250):
        print(' '.join(nth(i) for i in list(range(j, j+25))))
ordinal = function(n)
    if n > 3 and n < 20 then return n + "th"
    if n % 10 == 1 then return n + "st"
    if n % 10 == 2 then return n + "nd"
    if n % 10 == 3 then return n + "rd"
    return n + "th"
end function

out = []
test = function(from, to)
    for i in range(from, to)
        out.push ordinal(i)
    end for
end function

test 0, 25
test 250, 265
test 1000, 1025
print out.join
Nested function
PythonMiniScript
def makeList(separator):
    counter = 1

    def makeItem(item):
        nonlocal counter
        result = str(counter) + separator + item + "\n"
        counter += 1
        return result

    return makeItem("first") + makeItem("second") + makeItem("third")

print(makeList(". "))
makeList = function(sep)
    counter = 0
    makeItem = function(item)
        outer.counter = counter + 1
        return counter + sep + item
    end function
    return [makeItem("first"), makeItem("second"), makeItem("third")]
end function
 
print makeList(". ")
Nim game
PythonMiniScript
print("Py Nim\n")

def getTokens(curTokens):
    global tokens
    
    print("How many tokens would you like to take? ", end='')
    take = int(input())
    
    if (take < 1 or take > 3):
        print("Number must be between 1 and 3.\n")
        getTokens(curTokens)
        return
    
    tokens = curTokens - take
    print(f'You take {take} tokens.')
    print(f'{tokens} tokens remaining.\n')

def compTurn(curTokens):
    global tokens
    
    take = curTokens % 4
    tokens = curTokens - take
    print (f'Computer takes {take} tokens.')
    print (f'{tokens} tokens remaining.\n')
    

tokens = 12
while (tokens > 0):
    getTokens(tokens)
    compTurn(tokens)

print("Computer wins!")
tokens = 12
 
print "Nim Game"
print "Starting with " + tokens + " tokens."
print
 
printRemaining = function()
    print tokens + " tokens remaining."
    print
end function
 
playerTurn = function(take)
    take = floor(val(take))
    if take < 1 or take > 3 then
        print "Take must be between 1 and 3."
        return false
    end if
 
    globals.tokens = tokens - take
 
    print "Player takes " + take + " tokens."
    printRemaining
    return true
end function
 
computerTurn = function()
    take = tokens % 4
    globals.tokens = tokens - take
 
    print "Computer takes " + take + " tokens."
    printRemaining
end function
 
while tokens > 0
    if playerTurn(input("How many tokens would you like to take? ")) then
        computerTurn
    end if
end while
 
print "Computer wins."
Number names
PythonMiniScript
TENS = [None, None, "twenty", "thirty", "forty",
        "fifty", "sixty", "seventy", "eighty", "ninety"]
SMALL = ["zero", "one", "two", "three", "four", "five",
         "six", "seven", "eight", "nine", "ten", "eleven",
         "twelve", "thirteen", "fourteen", "fifteen",
         "sixteen", "seventeen", "eighteen", "nineteen"]
HUGE = [None, None] + [h + "illion" 
                       for h in ("m", "b", "tr", "quadr", "quint", "sext", 
                                  "sept", "oct", "non", "dec")]

def nonzero(c, n, connect=''):
    return "" if n == 0 else connect + c + spell_integer(n)

def last_and(num):
    if ',' in num:
        pre, last = num.rsplit(',', 1)
        if ' and ' not in last:
            last = ' and' + last
        num = ''.join([pre, ',', last])
    return num
    
def big(e, n):
    if e == 0:
        return spell_integer(n)
    elif e == 1:
        return spell_integer(n) + " thousand"
    else:
        return spell_integer(n) + " " + HUGE[e]

def base1000_rev(n):
    # generates the value of the digits of n in base 1000
    # (i.e. 3-digit chunks), in reverse.
    while n != 0:
        n, r = divmod(n, 1000)
        yield r
 
def spell_integer(n):
    if n < 0:
        return "minus " + spell_integer(-n)
    elif n < 20:
        return SMALL[n]
    elif n < 100:
        a, b = divmod(n, 10)
        return TENS[a] + nonzero("-", b)
    elif n < 1000:
        a, b = divmod(n, 100)
        return SMALL[a] + " hundred" + nonzero(" ", b, ' and')
    else:
        num = ", ".join([big(e, x) for e, x in
                         enumerate(base1000_rev(n)) if x][::-1])
        return last_and(num)

if __name__ == '__main__':
    # examples
    for n in (0, -3, 5, -7, 11, -13, 17, -19, 23, -29):
        print('%+4i -> %s' % (n, spell_integer(n)))
    print('')  
    
    n = 201021002001
    while n:
        print('%-12i -> %s' % (n, spell_integer(n)))
        n //= -10
    print('%-12i -> %s' % (n, spell_integer(n)))
    print('')
singles = " one two three four five six seven eight nine ".split
teens = "ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen ".split
tys = "  twenty thirty forty fifty sixty seventy eighty ninety".split
ions = "thousand million billion".split

numberName = function(n)
    if n == 0 then return "zero"
    a = abs(n)
    r = ""  // (result)
    for u in ions
        h = a % 100
        if h > 0 and h < 10 then r = singles[h] + " " + r
        if h > 9 and h < 20 then r = teens[h-10] + " " + r
        if h > 19 and h < 100 then r = tys[h/10] + "-"*(h%10>0) + singles[h%10] + " " + r
        h = floor((a % 1000) / 100)
        if h then r = singles[h] + " hundred " + r
        a = floor(a / 1000)
        if a == 0 then break
        if a % 1000 > 0 then r = u + " " + r
    end for
    if n < 0 then r = "negative " + r
    return r
end function

// Test cases:
for n in [-1234, 0, 7, 42, 4325, 1000004, 214837564]
    print n + ": " + numberName(n)
end for
Palindrome detection
PythonMiniScript
def is_palindrome(s):
  return s == s[::-1]
isPalindrome = function(s)
    // convert to lowercase, and strip non-letters
    stripped = ""
    for c in s.lower
        if c >= "a" and c <= "z" then stripped = stripped + c
    end for

    // check palindromity
    mid = floor(stripped.len/2)
    for i in range(0, mid)
        if stripped[i] != stripped[-i - 1] then return false
    end for
    return true
end function

testStr = "Madam, I'm Adam"
answer = [testStr, "is"]
if not isPalindrome(testStr) then answer.push "NOT"
answer.push "a palindrome"
print answer.join
Pangram checker
PythonMiniScript
import string, sys
if sys.version_info[0] < 3:
    input = raw_input

def ispangram(sentence, alphabet=string.ascii_lowercase):
    alphaset = set(alphabet)
    return alphaset <= set(sentence.lower())

print ( ispangram(input('Sentence: ')) )
sentences = ["The quick brown fox jumps over the lazy dog.",
    "Peter Piper picked a peck of pickled peppers.",
    "Waltz job vexed quick frog nymphs."]

alphabet = "abcdefghijklmnopqrstuvwxyz"

pangram = function (toCheck)
    sentence = toCheck.lower
    fail = false
    for c in alphabet
        if sentence.indexOf(c) == null then return false
    end for
    return true
end function

for sentence in sentences
    if pangram(sentence) then
        print """" + sentence + """ is a Pangram"
    else
        print """" + sentence + """ is not a Pangram"
    end if
end for
Parsing/RPN calculator algorithm
PythonMiniScript
def op_pow(stack):
    b = stack.pop(); a = stack.pop()
    stack.append( a ** b )
def op_mul(stack):
    b = stack.pop(); a = stack.pop()
    stack.append( a * b )
def op_div(stack):
    b = stack.pop(); a = stack.pop()
    stack.append( a / b )
def op_add(stack):
    b = stack.pop(); a = stack.pop()
    stack.append( a + b )
def op_sub(stack):
    b = stack.pop(); a = stack.pop()
    stack.append( a - b )
def op_num(stack, num):
    stack.append( num )
    
ops = {
 '^': op_pow,
 '*': op_mul,
 '/': op_div,
 '+': op_add,
 '-': op_sub,
 }

def get_input(inp = None):
    'Inputs an expression and returns list of tokens'
    
    if inp is None:
        inp = input('expression: ')
    tokens = inp.strip().split()
    return tokens

def rpn_calc(tokens):
    stack = []
    table = ['TOKEN,ACTION,STACK'.split(',')]
    for token in tokens:
        if token in ops:
            action = 'Apply op to top of stack'
            ops[token](stack)
            table.append( (token, action, ' '.join(str(s) for s in stack)) )
        else:
            action = 'Push num onto top of stack'
            op_num(stack, eval(token))
            table.append( (token, action, ' '.join(str(s) for s in stack)) )
    return table

if __name__ == '__main__':
    rpn = '3 4 2 * 1 5 - 2 3 ^ ^ / +'
    print( 'For RPN expression: %r\n' % rpn )
    rp = rpn_calc(get_input(rpn))
    maxcolwidths = [max(len(y) for y in x) for x in zip(*rp)]
    row = rp[0]
    print( ' '.join('{cell:^{width}}'.format(width=width, cell=cell) for (width, cell) in
zip(maxcolwidths, row)))
    for row in rp[1:]:
        print( ' '.join('{cell:<{width}}'.format(width=width, cell=cell) for (width, cell) in
zip(maxcolwidths, row)))

    print('\n The final output value is: %r' % rp[-1][2])
RPN = function(inputText)
    tokens = inputText.split
    stack = []
    while tokens
        tok = tokens.pull
        if "+-*/^".indexOf(tok) != null then
            b = stack.pop
            a = stack.pop
            if tok == "+" then stack.push a + b
            if tok == "-" then stack.push a - b
            if tok == "*" then stack.push a * b
            if tok == "/" then stack.push a / b
            if tok == "^" then stack.push a ^ b
        else
            stack.push val(tok)
        end if
        print tok + " --> " + stack
    end while
    return stack[0]
end function

print RPN("3 4 2 * 1 5 - 2 3 ^ ^ / +")
Penney's game
PythonMiniScript
from __future__ import print_function
import random
from time import sleep

first = random.choice([True, False])

you = ''
if first:
    me = ''.join(random.sample('HT'*3, 3))
    print('I choose first and will win on first seeing {} in the list of tosses'.format(me))
    while len(you) != 3 or any(ch not in 'HT' for ch in you) or you == me:
        you = input('What sequence of three Heads/Tails will you win with: ')
else:
    while len(you) != 3 or any(ch not in 'HT' for ch in you):
        you = input('After you: What sequence of three Heads/Tails will you win with: ')
    me = ('H' if you[1] == 'T' else 'T') + you[:2]
    print('I win on first seeing {} in the list of tosses'.format(me))
    
print('Rolling:\n  ', end='')
rolled = ''
while True:
    rolled += random.choice('HT')
    print(rolled[-1], end='')
    if rolled.endswith(you):
        print('\n  You win!')
        break
    if rolled.endswith(me):
        print('\n  I win!')
        break
    sleep(1)    # For dramatic effect
randomTorH = function()
    if rnd < 0.5 then return "T" else return "H"
end function

if rnd < 0.5 then
    playerSeq = input("Input your sequence (e.g. HTH): ").upper
    if playerSeq[1] == "T" then compSeq = "H" else compSeq = "T"
    compSeq = compSeq + playerSeq[:2]
    print "I choose: " + compSeq
else
    compSeq = randomTorH + randomTorH + randomTorH
    print "I choose: " + compSeq
    playerSeq = input("Input your sequence (e.g. HTH): ").upper
end if

print "Here we go..."
seq = ""
while true
    flip = randomTorH
    print flip
    seq = seq + flip
    if seq[-3:] == playerSeq then
        print "You win!"
        break
    else if seq[-3:] == compSeq then
        print "I win!"
        break
    end if
    wait
end while
Phrase reversals
PythonMiniScript
>>> phrase = "rosetta code phrase reversal"
>>> phrase[::-1]                      # Reversed.
'lasrever esarhp edoc attesor'
>>> ' '.join(word[::-1] for word in phrase.split())      # Words reversed.
'attesor edoc esarhp lasrever'
>>> ' '.join(phrase.split()[::-1])                      # Word order reversed.
'reversal phrase code rosetta'
>>> 
phrase = "rosetta code phrase reversal"

// general sequence reversal function
reverse = function(seq)
    out = []
    for i in range(seq.len-1, 0)
        out.push seq[i]
    end for
    if seq isa string then return out.join("")
    return out
end function

// 1. Reverse the characters of the string.
print reverse(phrase)

// 2. Reverse the characters of each individual word in the string, maintaining original word order
within the string.
words = phrase.split
for i in words.indexes
    words[i] = reverse(words[i])
end for
print words.join

// 3. Reverse the order of each word of the string, maintaining the order of characters in each
word.
print reverse(phrase.split).join
Pig the dice game
PythonMiniScript
#!/usr/bin/python3

'''
See: http://en.wikipedia.org/wiki/Pig_(dice)

This program scores and throws the dice for a two player game of Pig

'''

from random import randint

playercount = 2
maxscore = 100
safescore = [0] * playercount
player = 0
score=0

while max(safescore) < maxscore:
    rolling = input("Player %i: (%i, %i) Rolling? (Y) "
                    % (player, safescore[player], score)).strip().lower() in {'yes', 'y', ''}
    if rolling:
        rolled = randint(1, 6)
        print('  Rolled %i' % rolled)
        if rolled == 1:
            print('  Bust! you lose %i but still keep your previous %i'
                  % (score, safescore[player]))
            score, player = 0, (player + 1) % playercount
        else:
            score += rolled
    else:
        safescore[player] += score
        if safescore[player] >= maxscore:
            break
        print('  Sticking with %i' % safescore[player])
        score, player = 0, (player + 1) % playercount
        
print('\nPlayer %i wins with a score of %i' %(player, safescore[player]))
// Pig the Dice for two players.
Player = {}
Player.score = 0
Player.doTurn = function()
    rolls = 0
    pot = 0
    print self.name + "'s Turn!"
    while true
        if self.score + pot >= goal then
            print "   " + self.name.upper + " WINS WITH " + (self.score + pot) + "!"
            inp = "H"
        else
            inp = input(self.name + ", you have " + pot + " in the pot.  [R]oll or Hold? ")
        end if
        if inp == "" or inp[0].upper == "R" then
            die = ceil(rnd*6)
            if die == 1 then
                print "   You roll a 1.  Busted!"
                return
            else
                print "   You roll a " + die + "."
                pot = pot + die
            end if
        else
            self.score = self.score + pot
            return
        end if
    end while
end function

p1 = new Player
p1.name = "Alice"
p2 = new Player
p2.name = "Bob"
goal = 100

while p1.score < goal and p2.score < goal
    for player in [p1, p2]
        print
        print p1.name + ": " + p1.score + "  |  " + p2.name + ": " + p2.score
        player.doTurn
        if player.score >= goal then break
    end for
end while
Playing cards
PythonMiniScript
import random

class Card(object):
    suits = ("Clubs","Hearts","Spades","Diamonds")
    pips = ("2","3","4","5","6","7","8","9","10","Jack","Queen","King","Ace")

    def __init__(self, pip,suit):
        self.pip=pip
        self.suit=suit

    def __str__(self):
        return "%s %s"%(self.pip,self.suit)

class Deck(object):
    def __init__(self):
        self.deck = [Card(pip,suit) for suit in Card.suits for pip in Card.pips]

    def __str__(self):
        return "[%s]"%", ".join( (str(card) for card in self.deck))

    def shuffle(self):
        random.shuffle(self.deck)

    def deal(self):
        self.shuffle()  # Can't tell what is next from self.deck
        return self.deck.pop(0)
suits = ["Spades", "Clubs", "Hearts", "Diamonds"]
pips = ["Ace","Two","Three","Four","Five","Six","Seven",
    "Eight","Nine","Ten","Jack","Queen","King"]

Card = {}
Card.str = function()
    return self.pip + " of " + self.suit + " (value: " + self.value + ")"
end function

//Build Deck
deck = []
for s in suits.indexes
    for p in pips.indexes
        card = new Card
        card.suit = suits[s]
        card.pip = pips[p]
        card.value = s * 100 + p
        deck.push card
    end for
end for
 
draw = function(count=7)
    hand = []
    for i in range(1, count)
        hand.push deck.pop
    end for
    return hand
end function
 
display = function(stack)
    for card in stack
        print card.str
    end for
end function
 
print "Deck created. Cards in Deck: " + deck.len
 
deck.shuffle
print "Deck Shuffled"
 
hand = draw
print "First hand: "
display hand

print
print deck.len + " cards left in deck:"
display deck
Polymorphic copy
PythonMiniScript
import copy

class T:
   def classname(self): 
      return self.__class__.__name__

   def __init__(self):
      self.myValue = "I'm a T."

   def speak(self):
      print self.classname(), 'Hello', self.myValue

   def clone(self):
      return copy.copy(self)

class S1(T):
   def speak(self):
      print self.classname(),"Meow", self.myValue

class S2(T):
   def speak(self):
      print self.classname(),"Woof", self.myValue


print "creating initial objects of types S1, S2, and T"
a = S1()
a.myValue = 'Green'
a.speak()

b = S2()
b.myValue = 'Blue'
b.speak()

u = T()
u.myValue = 'Purple'
u.speak()

print "Making copy of a as u, colors and types should match"
u = a.clone()
u.speak()
a.speak()
print "Assigning new color to u, A's color should be unchanged."
u.myValue = "Orange"
u.speak()
a.speak()

print "Assigning u to reference same object as b, colors and types should match"
u = b
u.speak()
b.speak()
print "Assigning new color to u. Since u,b references same object b's color changes as well"
u.myValue = "Yellow"
u.speak()
b.speak()
T = {}
T.foo = function()
    return "This is an instance of T"
end function

S = new T
S.foo = function()
    return "This is an S for sure"
end function

instance = new S
print "instance.foo: " + instance.foo

copy = {}
copy = copy + instance  // copies all elements
print "copy.foo: " + copy.foo

// And to prove this is a copy, and not a reference:
instance.bar = 1
copy.bar = 2
print "instance.bar: " + instance.bar
print "copy.bar: " + copy.bar
Quine
PythonMiniScript
w = "print('w = ' + chr(34) + w + chr(34) + chr(10) + w)"
print('w = ' + chr(34) + w + chr(34) + chr(10) + w)
s="s=;print s[:2]+char(34)+s+char(34)+s[2:]";print s[:2]+char(34)+s+char(34)+s[2:]
Random numbers
PythonMiniScript
>>> import random
>>> values = [random.gauss(1, .5) for i in range(1000)]
>>> 
randNormal = function(mean=0, stddev=1)
    return mean + sqrt(-2 * log(rnd,2.7182818284)) * cos(2*pi*rnd) * stddev
end function

x = []
for i in range(1,1000)
    x.push randNormal(1, 0.5)
end for
Range expansion
PythonMiniScript
def rangeexpand(txt):
    lst = []
    for r in txt.split(','):
        if '-' in r[1:]:
            r0, r1 = r[1:].split('-', 1)
            lst += range(int(r[0] + r0), int(r1) + 1)
        else:
            lst.append(int(r))
    return lst

print(rangeexpand('-6,-3--1,3-5,7-11,14,15,17-20'))
pullInt = function(chars)
    numstr = chars.pull
    while chars and chars[0] != "," and chars[0] != "-"
        numstr = numstr + chars.pull
    end while
    return val(numstr)
end function
    
expandRange = function(s)
    result = []
    chars = s.split("")
    while chars
        num = pullInt(chars)
        if not chars or chars.pull == "," then
            result.push num
        else
            result = result + range(num, pullInt(chars))
            chars.pull  // skip "," after range
        end if
    end while
    return result
end function

print expandRange("-6,-3--1,3-5,7-11,14,15,17-20")
Range extraction
PythonMiniScript
def range_extract(lst):
    'Yield 2-tuple ranges or 1-tuple single elements from list of increasing ints'
    lenlst = len(lst)
    i = 0
    while i< lenlst:
        low = lst[i]
        while i <lenlst-1 and lst[i]+1 == lst[i+1]: i +=1
        hi = lst[i]
        if   hi - low >= 2:
            yield (low, hi)
        elif hi - low == 1:
            yield (low,)
            yield (hi,)
        else:
            yield (low,)
        i += 1

def printr(ranges):
    print( ','.join( (('%i-%i' % r) if len(r) == 2 else '%i' % r)
                     for r in ranges ) )

if __name__ == '__main__':
    for lst in [[-8, -7, -6, -3, -2, -1, 0, 1, 3, 4, 5, 7,
                 8, 9, 10, 11, 14, 15, 17, 18, 19, 20],
                [0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22,
                 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39]]:
        #print(list(range_extract(lst)))
        printr(range_extract(lst))
extractRange = function(ints)
    result = []
    idx = 0
    while idx < ints.len
        runLen = 1
        while idx+runLen < ints.len and ints[idx+runLen] == ints[idx] + runLen
            runLen = runLen + 1
        end while
        if runLen > 2 then
            result.push ints[idx] + "-" + ints[idx+runLen-1]
            idx = idx + runLen
        else
            result.push ints[idx]
            idx = idx + 1
        end if
    end while
    return join(result, ",")
end function

test = [ 0,  1,  2,  4,  6,  7,  8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
   25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39]
print extractRange(test)
RCRPG
PythonMiniScript

See [[RCRPG/Python]].


See [[RCRPG/MiniScript]].

Remove duplicate elements
PythonMiniScript
items = [1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd']
unique = list(set(items))
items = [1, 2, 3, "a", "b", "c", 2, 3, 4, "b", "c", "d"]
d = {}
for i in items
    d.push i
end for
print d.indexes
Repeat
PythonMiniScript
#!/usr/bin/python
def repeat(f,n):
  for i in range(n):
    f();

def procedure():
  print("Example");

repeat(procedure,3); #prints "Example" (without quotes) three times, separated by newlines.
sayHi = function()
    print "Hi!"
end function

rep = function(f, n)
    for i in range(1, n)
        f
    end for
end function

rep @sayHi, 3
Repeat a string
PythonMiniScript
"ha" * 5  # ==> "hahahahaha"
str = "Lol"
print str * 5
Reverse a string
PythonMiniScript
input()[::-1]
str = "This is a string"
print "Forward: " + str
newStr = ""
for i in range(str.len-1, 0)
    newStr = newStr + str[i]
end for
print "Reversed: " + newStr
Reverse the gender of a string
PythonMiniScript
#!/usr/bin/env python
# -*- coding: utf-8 -*- #
 
import re
male2female=u"""maleS femaleS, maleness femaleness,
him her, himself herself, his her, his hers, he she,
Mr Mrs, Mister Missus, Ms Mr, Master Miss, Master Mistress,
uncleS auntS, nephewS nieceS, sonS daughterS, grandsonS granddaughterS,
brotherS sisterS, man woman, men women, boyS girlS, paternal maternal,
grandfatherS grandmotherS, GodfatherS GodmotherS, GodsonS GoddaughterS,
fiancéS fiancéeS, husband wife, husbands wives, fatherS motherS, 
bachelorS spinsterS, bridegroomS brideS, widowerS widowS,
KnightS DameS, Sir DameS, KingS QueenS, DukeS DuchessES, PrinceS PrincessES,
Lord Lady, Lords Ladies, MarquessES MarchionessES, EarlS CountessES, ViscountS ViscountessES,
ladS lassES, sir madam, gentleman lady, gentlemen ladies, BaronS BaronessES,
stallionS mareS, ramS eweS, coltS fillieS, billy nanny, billies nannies, bullS cowS,
godS goddessES, heroS heroineS, shirtS blouseS, undies nickers, sweat glow,
jackarooS jillarooS, gigoloS hookerS, landlord landlady, landlords landladies, 
manservantS maidservantS, actorS actressES, CountS CountessES, EmperorS EmpressES, 
giantS giantessES, heirS heiressES, hostS hostessES, lionS lionessES, managerS manageressES,
murdererS murderessES, priestS priestessES, poetS poetessES, shepherdS shepherdessES,
stewardS stewardessES, tigerS tigressES, waiterS waitressES,
cockS henS, dogS bitchES, drakeS henS, dogS vixenS,
tomS tibS, boarS sowS, buckS roeS, peacockS peahenS, 
gander goose, ganders geese, friarS nunS, monkS nunS, Adam Eve,
Aaron Erin, Adrian Adriana, Aidrian Aidriana, Alan Alaina, Albert Alberta,
Alex Alexa, Alex Alexis, Alexander Alaxandra, Alexander Alexandra,
Alexander Alexis, Alexandra Alexander, Alexei Alexis, Alfred Alfreda,
Andrew Andrea, Andrew Andrea, Angel Angelica, Anthony Antonia,
Antoine Antoinette, Ariel Arielle, Ashleigh Ashley, 
Barry Barrie, Benedict Benita, Benjamin Benjamine, Bert Bertha, 
Brandon Brandi, Brendan Brenda, Briana Brian, Brian Rianne, 
Caela Caesi, Caeleb Caeli, Carl Carla, Carl Carly, Carolus Caroline,
Charles Caroline, Charles Charlotte, Christian Christa, Christian Christiana,
Christian Christina, Christopher Christina, Christopher Christine,
Clarence Claire, Claude Claudia, Clement Clementine, Cory Cora,
Daniel Daniella, Daniel Danielle, David Davena, David Davida,
David Davina, Dean Deanna, Devin Devina,
Edward Edwina, Edwin Edwina, Emil Emilie, Emil Emily, Eric Erica, Erick Erica,
Erick Ericka, Ernest Ernestine, Ethan Etha, Ethan Ethel, Eugene Eugenie,
Fabian Fabia, Francesco Francesca, Frances Francesca, Francis Frances,
Francis Francine, Frederick Fredrica, Fred Freda, Fredrick Frederica,
Gabriel Gabriella, Gabriel Gabrielle, Gene Jean, George Georgia, george georgina,
George Georgina, Gerald Geraldine, Giovanni Giovanna, Glen Glenn,
Harry Harriet, Harry Harriette, Heather Heath, Henry Henrietta, Horace Horatia,
Ian Iana, Ilija Ilinka, Ivo Ivy, Ivan Ivy,
Jack Jackelyn, Jack Jackie, Jack Jaclyn, Jack Jacqueline, Jacob Jacobine,
James Jamesina, James Jamie, Jaun Jaunita, Jayda Jayden, Jesse Jessica, 
Jesse Jessie, Joe Johanna, Joel Joelle, John Jean, John Joan, 
John Johanna, Joleen Joseph, Jon Joane, Joseph Josephine, Joseph Josphine, 
Julian Julia, Julian Juliana, Julian Julianna, Justin Justine,
Karl Karly, Kendrick Kendra, Ken Kendra, Kian Kiana, Kyle Kylie,
Laurence Laura, Laurence Lauren, Laurence Laurencia, Leigh Leigha,
Leon Leona, Louis Louise, Lucas Lucia, Lucian Lucy, Luke Lucia, Lyle Lyla,
Maria Mario, Mario Maricela, Mark Marcia, Marshall Marsha, Martin martina,
Martin Martina, Martin Martine, Max Maxine, Michael Michaela, Michael Micheala,
Michael Michelle, Mitchell Michelle, Nadir Nadira, Nicholas Nicole, Nicholas Nicki,
Nicholas Nicole, Nicky Nikki, Nicolas Nicole, Nigel Nigella, Noel Noelle,
Oen Ioena, Oliver Olivia,
Patrick Patricia, Paul Paula, Phillip Phillipa, Phillip Pippa,
Quintin Quintina,
Reginald Regina, Richard Richardine, Robert Roberta, Robert Robyn, Ronald Rhonda,
Ryan Rhian, Ryan Ryanne,
Samantha Samuel, Samuel Samantha, Samuel Sammantha, Samuel Samuela,
Sean Sian, Sean Siana, Shaun Shauna, Sheldon Shelby, Sonny Sunny,
Stephan Stephanie, Stephen Stephanie, Steven Stephanie,
Terry Carol, Terry Carrol, Theodore Theadora, Theodore Theodora,
Theodore Theordora, Thomas Thomasina, Tristan Tricia, Tristen Tricia,
Ulric Ulrika, Valentin Valentina, Victor Victoria,
William Wilhelmina, William Willa, William Willamina,
Xavier Xaviera, Yarden Yardena, Zahi Zahira, Zion Ziona"""
 
re_nl=re.compile(r",[ \n]*")
m2f=[ tok.split(" ") for tok in re_nl.split(male2female) ]
 
switch={}
words=[]
 
 
re_plural=re.compile("E*S$")
re_ES=re.compile("ES$")
 
def gen_pluralize(m,f):
# do plurals first 
  yield re_plural.sub("",m),re_plural.sub("",f)
  yield re_ES.sub("es",m),re_ES.sub("es",f)
  yield re_plural.sub("s",m),re_plural.sub("s",f)
 
def gen_capitalize_pluralize(m,f):
  for m,f in gen_pluralize(m,f):
    yield m.capitalize(), f.capitalize()
    yield m,f
 
def gen_switch_role_capitalize_pluralize(m,f):
  for m,f in gen_capitalize_pluralize(m,f):
    yield m,f
    yield f,m
 
for m,f in m2f:
  for xy,xx in gen_switch_role_capitalize_pluralize(m,f):
    if xy not in switch: 
      switch[xy]=xx
      words.append(xy)
 
words="|".join(words)
 
re_word=re.compile(ur"\b("+words+ur")\b")
 
text=u'''When a new-hatched savage running wild about his native
woodlands in a grass clout, followed by the nibbling goats, as if
he were a green sapling; even then, in Queequeg's ambitious soul,
lurked a strong desire to see something more of Christendom than
a specimen whaler or two. His father was a High Chief, a King;
his uncle a High Priest; and on the maternal side he boasted aunts
who were the wives of unconquerable warriors. There was excellent
blood in his veins-royal stuff; though sadly vitiated, I fear,
by the cannibal propensity he nourished in his untutored youth.'''
 
 
def rev_gender(text):
  text=re_word.split(text)
  return "".join([ word+switch[gen] for word,gen in zip(text[::2],text[1::2])])+text[-1]
 
print rev_gender(text)
cap = function(w)   // (capitalize a word)
    return w[0].upper + w[1:]
end function

trans = {"she":"he", "her":"his", "hers":"his"}
trans = trans + {"he":"she", "his":"her", "him":"her"}

for k in trans.indexes
    trans[cap(k)] = cap(trans[k])
end for

reverseGender = function(s)
    s = s.replace(".", " .").replace(",", " ,").replace("?", " ?").replace("!", " !")
    words = s.split
    for i in words.indexes
        if trans.hasIndex(words[i]) then words[i] = trans[words[i]]
    end for
    s = words.join
    s = s.replace(" .", ".").replace(" ,", ",").replace(" ?", "?").replace(" !", "!")
    return s
end function

test = function(s)
    print "BEFORE: " + s
    print "AFTER:  " + reverseGender(s)
    print
end function

test "She was a soul stripper. She took his heart!"
test "He was a soul stripper. He took her heart!"
test "She wants what's hers, he wants her and she wants him!"
test "Her dog belongs to him but his dog is hers!"
Reverse words in a string
PythonMiniScript
 text = '''\
---------- Ice and Fire ------------

fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. favor who those with hold I

... elided paragraph last ...

Frost Robert -----------------------'''

for line in text.split('\n'): print(' '.join(line.split()[::-1]))
lines = ["==========================================",
    "|  ---------- Ice and Fire ------------  |",
    "|                                        |",
    "|  fire, in end will world the say Some  |",
    "|  ice. in say Some                      |",
    "|  desire of tasted I've what From       |",
    "|  fire. favor who those with hold I     |",
    "|                                        |",
    "|  ... elided paragraph last ...         |",
    "|                                        |",
    "|  Frost Robert -----------------------  |",
    "=========================================="]
    
for line in lines
    oldLine = line.split
    newLine = []
    while oldLine
// the line below line retains the outer box format
        newLine.push oldLine.pop
// alternate format, replace above line with below two lines below to strip all superfluous spaces
//    word = oldLine.pop
//    if word != "" then newLine.push word
    end while
    print newLine.join
end for
Roots of unity
PythonMiniScript
import cmath


class Complex(complex):
    def __repr__(self):
        rp = '%7.5f' % self.real if not self.pureImag() else ''
        ip = '%7.5fj' % self.imag if not self.pureReal() else ''
        conj = '' if (
            self.pureImag() or self.pureReal() or self.imag < 0.0
        ) else '+'
        return '0.0' if (
            self.pureImag() and self.pureReal()
        ) else rp + conj + ip

    def pureImag(self):
        return abs(self.real) < 0.000005

    def pureReal(self):
        return abs(self.imag) < 0.000005


def croots(n):
    if n <= 0:
        return None
    return (Complex(cmath.rect(1, 2 * k * cmath.pi / n)) for k in range(n))
    # in pre-Python 2.6:
    #   return (Complex(cmath.exp(2j*k*cmath.pi/n)) for k in range(n))


for nr in range(2, 11):
    print(nr, list(croots(nr)))
complexRoots = function(n)
    result = []
    for i in range(0, n-1)
        real = cos(2*pi * i/n)
        if abs(real) < 1e-6 then real = 0
        imag = sin(2*pi * i/n)
        if abs(imag) < 1e-6 then imag = 0
        result.push real + " " + "+" * (imag>=0) + imag + "i"
    end for
    return result
end function

for i in range(2,5)
    print i + ": " + complexRoots(i).join(", ")
end for
Rot-13
PythonMiniScript
>>> u'foo'.encode('rot13')
'sbb'
>>> 'sbb'.decode('rot13')
u'foo'
rot13 = function(s)
    chars = s.values
    for i in chars.indexes
        c = chars[i]
        if c >= "a" and c <= "z" then chars[i] = char(97 + (code(c)-97+13)%26)
        if c >= "A" and c <= "Z" then chars[i] = char(65 + (code(c)-65+13)%26)
    end for
    return chars.join("")
end function

print rot13("Hello world!")
print rot13("Uryyb jbeyq!")
RPG attributes generator
PythonMiniScript
import random
random.seed()
attributes_total = 0
count = 0

while attributes_total < 75 or count < 2:
    attributes = []

    for attribute in range(0, 6):
        rolls = []
        
        for roll in range(0, 4):
            result = random.randint(1, 6)
            rolls.append(result)
        
        sorted_rolls = sorted(rolls)
        largest_3 = sorted_rolls[1:]
        rolls_total = sum(largest_3)
        
        if rolls_total >= 15:
            count += 1
        
        attributes.append(rolls_total)

    attributes_total = sum(attributes)
    
print(attributes_total, attributes)
roll = function()
    results = []
    for i in range(0,3)
        results.push ceil(rnd * 6)
    end for
    results.sort
    results.remove 0
    return results.sum
end function
 
while true
    attributes = []
    gt15 = 0    // (how many attributes > 15)
    for i in range(0,5)
        attributes.push roll
        if attributes[i] > 15 then gt15 = gt15 + 1
    end for
 
    print "Attribute values: " + attributes.join(", ")
    print "Attributes total:  " + attributes.sum
 
    if attributes.sum >= 75 and gt15 >= 2 then break
    print "Attributes failed, rerolling"
    print
end while
print "Success!"
Self-describing numbers
PythonMiniScript
>>> def isSelfDescribing(n):
    s = str(n)
    return all(s.count(str(i)) == int(ch) for i, ch in enumerate(s))

>>> [x for x in range(4000000) if isSelfDescribing(x)]
[1210, 2020, 21200, 3211000]
>>> [(x, isSelfDescribing(x)) for x in (1210, 2020, 21200, 3211000, 42101000, 521001000,
6210001000)]
[(1210, True), (2020, True), (21200, True), (3211000, True), (42101000, True), (521001000, True),
(6210001000, True)]
numbers = [12, 1210, 1300, 2020, 21200, 5]
 
occurrences = function(test, values)
    count = 0
    for i in values
        if i.val == test then count = count + 1
    end for
    return count
end function
 
for number in numbers
    check = "" + number
    digits = check.values
    describing = true
    for digit in digits.indexes
        if digits[digit].val != occurrences(digit, digits) then
            describing = false
        end if
    end for
    if describing then
        print number + " is self describing"
    else
        print number + " is not self describing"
    end if
end for
Semiprime
PythonMiniScript
from prime_decomposition import decompose

def semiprime(n):
    d = decompose(n)
    try:
        return next(d) * next(d) == n
    except StopIteration:
        return False
isSemiprime = function(num)
    divisor = 2
    primes = 0
    while primes < 3 and num != 1
        if num % divisor == 0 then
            num = num / divisor;
            primes = primes + 1
        else
            divisor = divisor + 1
        end if
    end while
    return primes == 2
end function

print "Semiprimes up to 100:"
results = []
for i in range(2, 100)
    if isSemiprime(i) then results.push i
end for
print results
Shoelace formula for polygonal area
PythonMiniScript
>>> def area_by_shoelace(x, y):
    "Assumes x,y points go around the polygon in one direction"
    return abs( sum(i * j for i, j in zip(x,             y[1:] + y[:1]))
               -sum(i * j for i, j in zip(x[1:] + x[:1], y            ))) / 2

>>> points = [(3,4), (5,11), (12,8), (9,5), (5,6)]
>>> x, y = zip(*points)
>>> area_by_shoelace(x, y)
30.0
>>> 
shoelace = function(vertices)
    sum = 0
    points = vertices.len
    
    for i in range(0,points-2)
        sum = sum + vertices[i][0]*vertices[i+1][1]
    end for
    sum = sum + vertices[points-1][0]*vertices[0][1]
    
    for i in range(points-1,1)
        sum = sum - vertices[i][0]*vertices[i-1][1]
    end for
    sum = sum - vertices[0][0]*vertices[points-1][1]
    
    return abs(sum)/2
end function

verts = [[3,4],[5,11],[12,8],[9,5],[5,6]]

print "The polygon area is "  + shoelace(verts)
Show ASCII table
PythonMiniScript
for i in range(16):
    for j in range(32+i, 127+1, 16):
        if j == 32:
            k = 'Spc'
        elif j == 127:
            k = 'Del'
        else:
            k = chr(j)
        print("%3d : %-3s" % (j,k), end="")
    print()
// Prints ASCII table
// Note changing the values of startChar and endChar will print
// a flexible table in that range
 
startChar = 32
endChar = 127
characters = []
 
for i in range(startChar, endChar)
    addString = char(i) + "  "
    if i == 32 then addString = "SPC"
    if i == 127 then addString = "DEL"
    characters.push addString
end for
 
for i in characters.indexes
    iNum = i + startChar
    iChar = "     " + str(iNum)
    characters[i] = iChar[-5:] + " : " + characters[i]
end for
 
columns = 6
line = ""
col = 0
for out in characters
    col = col + 1
    line = line + out
    if col == columns then
        print line
        line = ""
        col = 0
    end if
end for
if line then print line // final check for odd incomplete line output
Singly-linked list/Traversal
PythonMiniScript
for node in lst:
    print node.value
myList = [2, 4, 6, 8]
for i in myList
    print i
end for
Spinning rod animation/Text
PythonMiniScript
from time import sleep
while True:
    for rod in r'\|/-':
        print(rod, end='\r')
        sleep(0.25)
print "Press control-C to exit..."
while true
    for c in "|/-\"
        text.setCell 0, 0, c
        wait 0.25
    end for
end while
Split a character string based on change of character
PythonMiniScript
from itertools import groupby

def splitter(text):
    return ', '.join(''.join(group) for key, group in groupby(text))

if __name__ == '__main__':
    txt = 'gHHH5YY++///\\'      # Note backslash is the Python escape char.
    print(f'Input: {txt}\nSplit: {splitter(txt)}')
s = "gHHH5YY++///\"
output = []
lastLetter = s[0]
for letter in s
    if letter != lastLetter then output.push ", "
    output.push letter
    lastLetter = letter
end for
print output.join("")
Square but not cube
PythonMiniScript
# nonCubeSquares :: Int -> [(Int, Bool)]
def nonCubeSquares(n):
    upto = enumFromTo(1)
    ns = upto(n)
    setCubes = set(x ** 3 for x in ns)
    ms = upto(n + len(set(x * x for x in ns).intersection(
        setCubes
    )))
    return list(tuple([x * x, x in setCubes]) for x in ms)


# squareListing :: [(Int, Bool)] -> [String]
def squareListing(xs):
    justifyIdx = justifyRight(len(str(1 + len(xs))))(' ')
    justifySqr = justifyRight(1 + len(str(xs[-1][0])))(' ')
    return list(
        '(' + str(1 + idx) + '^2 = ' + str(n) +
        ' = ' + str(round(n ** (1 / 3))) + '^3)' if bln else (
            justifyIdx(1 + idx) + ' ->' +
            justifySqr(n)
        )
        for idx, (n, bln) in enumerate(xs)
    )


def main():
    print(
        unlines(
            squareListing(
                nonCubeSquares(30)
            )
        )
    )


# GENERIC ------------------------------------------------------------------

# enumFromTo :: Int -> Int -> [Int]
def enumFromTo(m):
    return lambda n: list(range(m, 1 + n))


# justifyRight :: Int -> Char -> String -> String
def justifyRight(n):
    return lambda cFiller: lambda a: (
        ((n * cFiller) + str(a))[-n:]
    )


# unlines :: [String] -> String
def unlines(xs):
    return '\n'.join(xs)


main()
squares = []
tris = []
both = []
for i in range(1, 100)
    tris.push i*i*i
    if tris.indexOf(i*i) == null then
        squares.push i*i
    else
        both.push i*i
    end if
end for

print "Square but not cube:"
print squares[:30]
print "Both square and cube:"
print both[:3]
Stack
PythonMiniScript
from collections import deque
stack = deque()
stack.append(value) # pushing
value = stack.pop()
not stack # is empty?
// Note in Miniscript, a value of zero is false,
// and any other number is true.
// therefore the .len function works as the inverse of a .empty function
stack = [2, 4, 6]
stack.push 8
print "Stack is " + stack
print "Adding '9' to stack " + stack.push(9)
print "Top of stack is " + stack.pop
print "Stack is " + stack
if stack.len then
    print "Stack is not empty"
else
    print "Stack is empty"
end if
Statistics/Basic
PythonMiniScript
def sd1(numbers):
    if numbers:
        mean = sum(numbers) / len(numbers)
        sd = (sum((n - mean)**2 for n in numbers) / len(numbers))**0.5
        return sd, mean
    else:
        return 0, 0

def sd2(numbers):
    if numbers:
        sx = sxx = n = 0
        for x in numbers:
            sx += x
            sxx += x*x
            n += 1
        sd = (n * sxx - sx*sx)**0.5 / n
        return sd, sx / n
    else:
        return 0, 0

def histogram(numbers):
    h = [0] * 10
    maxwidth = 50 # characters
    for n in numbers:
        h[int(n*10)] += 1
    mx = max(h)
    print()
    for n, i in enumerate(h):
        print('%3.1f: %s' % (n / 10, '+' * int(i / mx * maxwidth)))
    print()

if __name__ == '__main__':
    import random
    for i in range(1, 6):
        n = [random.random() for j in range(10**i)]
        print("\n##\n## %i numbers\n##" % 10**i)
        print('  Naive  method: sd: %8.6f, mean: %8.6f' % sd1(n))
        print('  Second method: sd: %8.6f, mean: %8.6f' % sd2(n))
        histogram(n)
Stats = {}
Stats.count = 0
Stats.sum = 0
Stats.sumOfSquares = 0
Stats.histo = null

Stats.add = function(x)
    self.count = self.count + 1
    self.sum = self.sum + x
    self.sumOfSquares = self.sumOfSquares + x*x
    bin = floor(x*10)
    if not self.histo then self.histo = [0]*10
    self.histo[bin] = self.histo[bin] + 1
end function

Stats.mean = function()
    return self.sum / self.count
end function

Stats.stddev = function()
    m = self.sum / self.count
    return sqrt(self.sumOfSquares / self.count - m*m)
end function

Stats.histogram = function()
    for i in self.histo.indexes
        print "0." + i + ": " + "=" * (self.histo[i]/self.count * 200)
    end for
end function

for sampleSize in [100, 1000, 10000]
    print "Samples: " + sampleSize
    st = new Stats
    for i in range(sampleSize)
        st.add rnd
    end for
    print "Mean: " + st.mean + "  Standard Deviation: " + st.stddev
    st.histogram
end for
String case
PythonMiniScript
s = "alphaBETA"
print s.upper() # => "ALPHABETA"
print s.lower() # => "alphabeta"

print s.swapcase() # => "ALPHAbeta"

print "fOo bAR".capitalize() # => "Foo bar"
print "fOo bAR".title() # => "Foo Bar"

import string
print string.capwords("fOo bAR") # => "Foo Bar"
mixedString = "alphaBETA"
print "Upper Case of " + mixedString + " is " + mixedString.upper
print "Lower Case of " + mixedString + " is " + mixedString.lower
String comparison
PythonMiniScript
def compare(a, b):
    print("\n%r is of type %r and %r is of type %r"
          % (a, type(a), b, type(b)))
    if a <  b:      print('%r is strictly less than  %r' % (a, b))
    if a <= b:      print('%r is less than or equal to %r' % (a, b))
    if a >  b:      print('%r is strictly greater than  %r' % (a, b))
    if a >= b:      print('%r is greater than or equal to %r' % (a, b))
    if a == b:      print('%r is equal to %r' % (a, b))
    if a != b:      print('%r is not equal to %r' % (a, b))
    if a is b:      print('%r has object identity with %r' % (a, b))
    if a is not b:  print('%r has negated object identity with %r' % (a, b))

compare('YUP', 'YUP')
compare('BALL', 'BELL')
compare('24', '123')
compare(24, 123)
compare(5.0, 5)
string1 = input("Please enter a string.")
string2 = input("Please enter a second string.")

//Comparing two strings for exact equality

if string1 == string2 then
    print "Strings are equal."
end if

//Comparing two strings for inequality

if string1 != string2 then
    print "Strings are NOT equal."
end if

//Comparing two strings to see if one is lexically ordered before than the other

if string1 > string2 then
    print string1 + " is lexically ordered AFTER " + string2
    
//Comparing two strings to see if one is lexically ordered after than the other

else if string1 < string2 then
    print string1 + " is lexically ordered BEFORE " + string2
end if

//How to achieve case sensitive comparisons

//Comparing two strings for exact equality (case sensitive)
if string1 == string2 then
    print "Strings are equal. (case sensitive)"
end if

//Comparing two strings for inequality (case sensitive)
if string1 != string2 then
    print "Strings are NOT equal. (case sensitive)"
end if

//How to achieve case insensitive comparisons within the language

//Comparing two strings for exact equality (case insensitive)
if string1.lower == string2.lower then
    print "Strings are equal. (case insensitive)"
end if

//Comparing two strings for inequality (case insensitive)
if string1.lower != string2.lower then
    print "Strings are NOT equal. (case insensitive)"
end if
String concatenation
PythonMiniScript
s1 = "hello"
print s1 + " world"

s2 = s1 + " world"
print s2
s = "hello"
print s + " world!"
String matching
PythonMiniScript
"abcd".startswith("ab") #returns True
"abcd".endswith("zn") #returns False
"bb" in "abab" #returns False
"ab" in "abab" #returns True
loc = "abab".find("bb") #returns -1
loc = "abab".find("ab") #returns 0
loc = "abab".find("ab",loc+1) #returns 2
string.startsWith = function(s)
    return self.len >= s.len and s[:s.len] == s
end function

string.endsWith = function(s)
    return self.len >= s.len and s[-s.len:] == s
end function

string.findAll = function(s)
    result = []
    after = null
    while true
        foundPos = self.indexOf(s, after)
        if foundPos == null then return result
        result.push foundPos
        after = foundPos + s.len - 1
    end while
end function
    
first = "The brown dog jumped jumped and jumped"
second = "jumped"

firstQ = """" + first + """"  // (first string, in quotes)
secondQ = """" + second + """"
doesOrNot = [" does not ", " does "]

print firstQ + doesOrNot[first.startsWith(second)] + "start with " + secondQ
print

found = first.findAll(second)
if not found then
    print firstQ + " does not contain " + secondQ + " anywhere"
else
    for pos in found
        print firstQ + " is found at position " + pos + " in " + secondQ
    end for
end if
print

print firstQ + doesOrNot[first.endsWith(second)] + "end with " + secondQ
Strip comments from a string
PythonMiniScript
def remove_comments(line, sep):
    for s in sep:
        i = line.find(s)
        if i >= 0:
            line = line[:i]
    return line.strip()

# test
print remove_comments('apples ; pears # and bananas', ';#')
print remove_comments('apples ; pears # and bananas', '!')
strip = function(test)
    comment = test.indexOf("#")
    if comment == null then comment = test.indexOf(";")
    if comment then test = test[:comment]
    while test[-1] == " "
        test = test - " "
    end while
    return test
end function

print strip("This is a hash test    # a comment") + "."
print strip("This is a semicolon test   ;  a comment") + "."
print strip("This is a no comment test   ") + "."
Subleq
PythonMiniScript
import sys

def subleq(a):
    i = 0
    try:
        while i >= 0:
            if a[i] == -1:
                a[a[i + 1]] = ord(sys.stdin.read(1))
            elif a[i + 1] == -1:
                print(chr(a[a[i]]), end="")
            else:
                a[a[i + 1]] -= a[a[i]]
                if a[a[i + 1]] <= 0:
                    i = a[i + 2]
                    continue
            i += 3
    except (ValueError, IndexError, KeyboardInterrupt):
        print("abort")
        print(a)

subleq([15, 17, -1, 17, -1, -1, 16, 1, -1, 16, 3, -1, 15, 15,
        0, 0, -1, 72, 101, 108, 108, 111, 44, 32, 119, 111,
        114, 108, 100, 33, 10, 0])
memory = []
step = 3
currentAddress = 0
out = ""

process = function(address)
    A = memory[address].val
    B = memory[address + 1].val
    C = memory[address + 2].val
    nextAddress = address + step
    
    if A == -1 then
        memory[B] = input
    else if B == -1 then
        globals.out = globals.out + char(memory[A].val)
    else
        memory[B] = str(memory[B].val - memory[A].val)
        if memory[B] < 1 then nextAddress = C
    end if
    return nextAddress
end function

print
memory = input("Enter SUBLEQ program").split

print
print "Running Program"
print "-------------------"
processing = currentAddress < memory.len
while processing
    currentAddress = process(currentAddress)
    if currentAddress >= memory.len or currentAddress == -1 then
        processing = false
    end if
end while

print out
print "-------------------"
print "Execution Complete"
Substitution cipher
PythonMiniScript
from string import printable
import random

EXAMPLE_KEY = ''.join(sorted(printable, key=lambda _:random.random()))

def encode(plaintext, key):
    return ''.join(key[printable.index(char)] for char in plaintext)

def decode(plaintext, key):
    return ''.join(printable[key.index(char)] for char in plaintext)

original = "A simple example."
encoded = encode(original, EXAMPLE_KEY)
decoded = decode(encoded, EXAMPLE_KEY)
print("""The original is: {}
Encoding it with the key: {}
Gives: {}
Decoding it by the same key gives: {}""".format(
    original, EXAMPLE_KEY, encoded, decoded))
alphabet = "abcdefghijklmnopqrstuvwxyz".split("")
cipher = alphabet[0:]
cipher.shuffle
encode = {}
decode = {}
for i in alphabet.indexes
    encode[alphabet[i]] = cipher[i]
    decode[cipher[i]] = alphabet[i]
    encode[alphabet[i].upper] = cipher[i].upper
    decode[cipher[i].upper] = alphabet[i].upper
end for

apply = function(map, s)
    chars = s.split("")
    for i in chars.indexes
        if map.hasIndex(chars[i]) then chars[i] = map[chars[i]]
    end for
    return chars.join("")
end function

msg = "Now is the time for all good men (and women) to come together."
secretCode = apply(encode, msg)
print secretCode
print apply(decode, secretCode)
Substring/Top and tail
PythonMiniScript
print "knight"[1:]     # strip first character
print "socks"[:-1]     # strip last character
print "brooms"[1:-1]   # strip both first and last characters
test = "This thing"
print test[1:]
print test[:-1]
print test[1:-1]
Sum multiples of 3 and 5
PythonMiniScript
def sum35a(n):
    'Direct count'
    # note: ranges go to n-1
    return sum(x for x in range(n) if x%3==0 or x%5==0)

def sum35b(n): 
    "Count all the 3's; all the 5's; minus double-counted 3*5's"
    # note: ranges go to n-1
    return sum(range(3, n, 3)) + sum(range(5, n, 5)) - sum(range(15, n, 15))
    
def sum35c(n):
    'Sum the arithmetic progressions: sum3 + sum5 - sum15'
    consts = (3, 5, 15)
    # Note: stop at n-1
    divs = [(n-1) // c for c in consts]
    sums = [d*c*(1+d)/2 for d,c in zip(divs, consts)]
    return sums[0] + sums[1] - sums[2]

#test
for n in range(1001):
    sa, sb, sc = sum35a(n), sum35b(n), sum35c(n)
    assert sa == sb == sc  # python tests aren't like those of c.

print('For n = %7i -> %i\n' % (n, sc))

# Pretty patterns
for p in range(7):
    print('For n = %7i -> %i' % (10**p, sum35c(10**p)))

# Scalability 
p = 20
print('\nFor n = %20i -> %i' % (10**p, sum35c(10**p)))
// simple version:
sum35 = function(n)
    sum = 0
    for i in range(3, n-1, 3)
        sum = sum + i
    end for
    for i in range(5, n-1, 5)
        if i % 3 then sum = sum + i // (skip multiples of 3 here)
    end for
    return sum
end function

print sum35(1000)
Sum of a series
PythonMiniScript
print ( sum(1.0 / (x * x) for x in range(1, 1001)) )
zeta = function(num)
    return 1 / num^2
end function

sum = function(start, finish, formula)
    total = 0
    for i in range(start, finish)
        total = total + formula(i)
    end for
    return total
end function

print sum(1, 1000, @zeta)
Sum of squares
PythonMiniScript
sum(x * x for x in [1, 2, 3, 4, 5])
# or
sum(x ** 2 for x in [1, 2, 3, 4, 5])
# or
sum(pow(x, 2) for x in [1, 2, 3, 4, 5])
sumOfSquares = function(seq)
    sum = 0
    for item in seq
        sum = sum + item*item
    end for
    return sum
end function

print sumOfSquares([4, 8, 15, 16, 23, 42])
print sumOfSquares([1, 2, 3, 4, 5])
print sumOfSquares([])
Temperature conversion
PythonMiniScript
>>> while True:
    k = float(input('K ? '))
    print("%g Kelvin = %g Celsius = %g Fahrenheit = %g Rankine degrees."
          % (k, k - 273.15, k * 1.8 - 459.67, k * 1.8))

    
K ? 21.0
21 Kelvin = -252.15 Celsius = -421.87 Fahrenheit = 37.8 Rankine degrees.
K ? 222.2
222.2 Kelvin = -50.95 Celsius = -59.71 Fahrenheit = 399.96 Rankine degrees.
K ? 
fromKelvin = function(temp)
    print temp + " degrees in Kelvin is:"
    Celsius = temp - 273.15
    print Celsius + " degrees Celsius"
    Fahrenheit = round(Celsius  * 9/5 + 32,2)
    print Fahrenheit + " degrees Fahrenheit"
    Rankine = Fahrenheit + 459.67
    print Rankine + " degrees Rankine"
end function

temp = input("Enter a temperature in Kelvin: ")
fromKelvin temp.val
Text between
PythonMiniScript
#!/usr/bin/env python
from sys import argv

# textBetween in python
# Get the text between two delimiters
# Usage:
# python textBetween.py "hello Rosetta Code world" "hello " " world"

def textBetween( thisText, startString, endString ):
    try:
        if startString is 'start':
            startIndex = 0
        else:
            startIndex = thisText.index( startString ) 
        
        if not (startIndex >= 0):
            return 'Start delimiter not found'
        else:
            if startString is not 'start':
                startIndex = startIndex + len( startString )
        
        returnText = thisText[startIndex:]


        if endString is 'end':
            return returnText
        else:
            endIndex = returnText.index( endString )

        if not (endIndex >= 0):
            return 'End delimiter not found'
        else:
            returnText = returnText[:endIndex]

        return returnText
    except ValueError:
        return "Value error"

script, first, second, third = argv

thisText = first
startString = second
endString = third

print textBetween( thisText, startString, endString )
textBetween = function(s, startDelim, endDelim)
    startPos = s.indexOf(startDelim) + startDelim.len
    if startDelim == "start" then startPos = 0
    endPos = s.indexOf(endDelim, startPos)
    if endDelim == "end" then endDelim = null
    return s[startPos:endPos]
end function

print textBetween("Hello Rosetta Code world", "Hello ", " world")
print textBetween("Hello Rosetta Code world", "start", " world")
print textBetween("Hello Rosetta Code world", "Hello ", "end")
print textBetween("The quick brown fox jumps over the lazy other fox", "quick ", " fox")
print textBetween("FooBarBazFooBuxQuux", "Foo", "Foo")
Textonyms
PythonMiniScript
from collections import defaultdict
import urllib.request

CH2NUM = {ch: str(num) for num, chars in enumerate('abc def ghi jkl mno pqrs tuv wxyz'.split(), 2)
for ch in chars}
URL = 'http://www.puzzlers.org/pub/wordlists/unixdict.txt'


def getwords(url):
 return urllib.request.urlopen(url).read().decode("utf-8").lower().split()

def mapnum2words(words):
    number2words = defaultdict(list)
    reject = 0
    for word in words:
        try:
            number2words[''.join(CH2NUM[ch] for ch in word)].append(word)
        except KeyError:
            # Reject words with non a-z e.g. '10th'
            reject += 1
    return dict(number2words), reject

def interactiveconversions():
    global inp, ch, num
    while True:
        inp = input("\nType a number or a word to get the translation and textonyms:
").strip().lower()
        if inp:
            if all(ch in '23456789' for ch in inp):
                if inp in num2words:
                    print("  Number {0} has the following textonyms in the dictionary:
{1}".format(inp, ', '.join(
                        num2words[inp])))
                else:
                    print("  Number {0} has no textonyms in the dictionary.".format(inp))
            elif all(ch in CH2NUM for ch in inp):
                num = ''.join(CH2NUM[ch] for ch in inp)
                print("  Word {0} is{1} in the dictionary and is number {2} with textonyms:
{3}".format(
                    inp, ('' if inp in wordset else "n't"), num, ', '.join(num2words[num])))
            else:
                print("  I don't understand %r" % inp)
        else:
            print("Thank you")
            break


if __name__ == '__main__':
    words = getwords(URL)
    print("Read %i words from %r" % (len(words), URL))
    wordset = set(words)
    num2words, reject = mapnum2words(words)
    morethan1word = sum(1 for w in num2words if len(num2words[w]) > 1)
    maxwordpernum = max(len(values) for values in num2words.values())
    print("""
There are {0} words in {1} which can be represented by the Textonyms mapping.
They require {2} digit combinations to represent them.
{3} digit combinations represent Textonyms.\
""".format(len(words) - reject, URL, len(num2words), morethan1word))

    print("\nThe numbers mapping to the most words map to %i words each:" % maxwordpernum)
    maxwpn = sorted((key, val) for key, val in num2words.items() if len(val) == maxwordpernum)
    for num, wrds in maxwpn:
        print("  %s maps to: %s" % (num, ', '.join(wrds)))

    interactiveconversions()
import "listUtil"
import "mapUtil"

groups = "abc def ghi jkl mno pqrs tuv wxyz".split
charToNum = {}
for i in groups.indexes
    for ch in groups[i]
        charToNum[ch] = i + 2
    end for
end for

words = file.readLines("/sys/data/englishWords.txt")

wordToNum = function(word)
    parts = word.split("")
    parts.apply function(ch)
        return charToNum[ch]
    end function
    return parts.join("")
end function

numToWords = {}
moreThan1Word = 0
for word in words
    num = wordToNum(word.lower)
    if numToWords.hasIndex(num) then
        numToWords[num].push word
    else
        numToWords[num] = [word]
    end if
    if numToWords[num].len == 2 then moreThan1Word = moreThan1Word + 1
end for

print "There are " + words.len + " words in englishWords.txt which can be represented  by the digit
key mapping."
print "They require " + numToWords.len + " digit combinations to represent them."
print moreThan1Word + " digit combinations represent Textonyms."

while true
    print
    inp = input("Enter a word or digit combination: ")
    if not inp then break
    if val(inp) > 0 then
        print inp + " -> " + numToWords.get(inp)
    else
        num = wordToNum(inp.lower)
        print "Digit key combination for """ + inp + """ is: " + num
        print num + " -> " + numToWords.get(num)
    end if
end while
The Twelve Days of Christmas
PythonMiniScript
gifts = '''\
A partridge in a pear tree.
Two turtle doves
Three french hens
Four calling birds
Five golden rings
Six geese a-laying
Seven swans a-swimming
Eight maids a-milking
Nine ladies dancing
Ten lords a-leaping
Eleven pipers piping
Twelve drummers drumming'''.split('\n')

days = '''first second third fourth fifth
          sixth seventh eighth ninth tenth
          eleventh twelfth'''.split()

for n, day in enumerate(days, 1):
    g = gifts[:n][::-1]
    print(('\nOn the %s day of Christmas\nMy true love gave to me:\n' % day) +
          '\n'.join(g[:-1]) +
          (' and\n' + g[-1] if n > 1 else g[-1].capitalize()))
days = ["first","second","third", "fourth","fifth","sixth",
        "seventh","eigth","nineth","tenth","eleventh","twelfth"]
gifts = ["A partridge in a pear tree.","Two turtle doves, and",
        "Three French hens,","Four calling birds,",
        "Five gold rings,","Six geese a-laying,",
        "Seven swans a-swimming,","Eight maids a-milking,",
        "Nine ladies dancing,","Ten lords a-leaping,",
        "Eleven pipers piping,","Twelve drummers drumming,"]

for i in range(0,11)
    print "On the " + days[i] + " day of Christmas,"
    print "my true love gave to me,"
    for j in range(i,0)
        print " " + gifts[j]
    end for
    print "     ----------"
end for
Time a function
PythonMiniScript
import sys, timeit
def usec(function, arguments):
    modname, funcname = __name__, function.__name__
    timer = timeit.Timer(stmt='%(funcname)s(*args)' % vars(),
                         setup='from %(modname)s import %(funcname)s; args=%(arguments)r' % vars())
    try:
        t, N = 0, 1
        while t < 0.2:            
            t = min(timer.repeat(repeat=3, number=N))            
            N *= 10
        microseconds = round(10000000 * t / N, 1) # per loop
        return microseconds 
    except:
        timer.print_exc(file=sys.stderr)
        raise

from math import pow
def nothing(): pass
def identity(x): return x
start = time
for i in range(1,100000)
end for
duration = time - start
print "Process took " + duration + " seconds"
Tokenize a string
PythonMiniScript
text = "Hello,How,Are,You,Today"
tokens = text.split(',')
print ('.'.join(tokens))
tokens = "Hello,How,Are,You,Today".split(",")
print tokens.join(".")
Towers of Hanoi
PythonMiniScript
def hanoi(ndisks, startPeg=1, endPeg=3):
    if ndisks:
        hanoi(ndisks-1, startPeg, 6-startPeg-endPeg)
        print(f"Move disk {ndisks} from peg {startPeg} to peg {endPeg}")
        hanoi(ndisks-1, 6-startPeg-endPeg, endPeg)
 
hanoi(4)
moveDisc = function(n, A, C, B)
    if n == 0 then return
    moveDisc n-1, A, B, C
    print "Move disc " + n + " from pole " + A + " to pole " + C
    moveDisc n-1, B, C, A
end function

// Move disc 3 from pole 1 to pole 3, with pole 2 as spare
moveDisc 3, 1, 3, 2
Trigonometric functions
PythonMiniScript
Python 3.2.2 (default, Sep  4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> from math import degrees, radians, sin, cos, tan, asin, acos, atan, pi
>>> rad, deg = pi/4, 45.0
>>> print("Sine:", sin(rad), sin(radians(deg)))
Sine: 0.7071067811865475 0.7071067811865475
>>> print("Cosine:", cos(rad), cos(radians(deg)))
Cosine: 0.7071067811865476 0.7071067811865476
>>> print("Tangent:", tan(rad), tan(radians(deg)))
Tangent: 0.9999999999999999 0.9999999999999999
>>> arcsine = asin(sin(rad))
>>> print("Arcsine:", arcsine, degrees(arcsine))
Arcsine: 0.7853981633974482 44.99999999999999
>>> arccosine = acos(cos(rad))
>>> print("Arccosine:", arccosine, degrees(arccosine))
Arccosine: 0.7853981633974483 45.0
>>> arctangent = atan(tan(rad))
>>> print("Arctangent:", arctangent, degrees(arctangent))
Arctangent: 0.7853981633974483 45.0
>>> 
pi3 = pi/3
degToRad = pi/180
print "sin PI/3 radians = " + sin(pi3)
print "sin 60 degrees = " + sin(60*degToRad)
print "arcsin 0.5 in radians = " + asin(0.5)
print "arcsin 0.5 in degrees = " + asin(0.5)/degToRad
print "cos PI/3 radians = " + cos(pi3)
print "cos 60 degrees = " + cos(60*degToRad)
print "arccos 0.5 in radians = " + acos(0.5)
print "arccos 0.5 in degrees = " + acos(0.5)/degToRad
print "tan PI/3 radians = " + tan(pi3)
print "tan 60 degrees = " + tan(60*degToRad)
print "arctan 0.5 in radians = " + atan(0.5)
print "arctan 0.5 in degrees = " + atan(0.5)/degToRad
Two sum
PythonMiniScript
def two_sum(arr, num):
    i = 0
    j = len(arr) - 1
    while i < j:
        if arr[i] + arr[j] == num:
            return (i, j)
        if arr[i] + arr[j] < num:
            i += 1
        else:
            j -= 1
    return None


numbers = [0, 2, 11, 19, 90]
print(two_sum(numbers, 21))
print(two_sum(numbers, 25))
twoSum = function(numbers, sum)
    // Make a map of values to their indices in the numbers array
    // as we go, so we will know when we've found a match.
    map = {}
    for i in numbers.indexes
        key = sum - numbers[i]
        if map.hasIndex(key) then return [map[key], i]
        map[numbers[i]] = i
    end for
end function

print twoSum([0, 2, 11, 19, 90], 21)
Vector
PythonMiniScript
class Vector:
    def __init__(self,m,value):
        self.m = m
        self.value = value
        self.angle = math.degrees(math.atan(self.m))
        self.x = self.value * math.sin(math.radians(self.angle))
        self.y = self.value * math.cos(math.radians(self.angle))

    def __add__(self,vector):
        """
        >>> Vector(1,10) + Vector(1,2)
        Vector:
            - Angular coefficient: 1.0
            - Angle: 45.0 degrees
            - Value: 12.0
            - X component: 8.49
            - Y component: 8.49
        """
        final_x = self.x + vector.x
        final_y = self.y + vector.y
        final_value = pytagoras(final_x,final_y)
        final_m = final_y / final_x
        return Vector(final_m,final_value)

    def __neg__(self):
        return Vector(self.m,-self.value)

    def __sub__(self,vector):
        return self + (- vector)
        
    def __mul__(self,scalar):
        """
        >>> Vector(4,5) * 2
        Vector:
            - Angular coefficient: 4
            - Angle: 75.96 degrees
            - Value: 10
            - X component: 9.7
            - Y component: 2.43

        """
        return Vector(self.m,self.value*scalar)

    def __div__(self,scalar):
        return self * (1 / scalar)
    
    def __repr__(self):
        """
        Returns a nicely formatted list of the properties of the Vector.

        >>> Vector(1,10)
        Vector:
            - Angular coefficient: 1
            - Angle: 45.0 degrees
            - Value: 10
            - X component: 7.07
            - Y component: 7.07
        
        """
        return """Vector:
    - Angular coefficient: {}
    - Angle: {} degrees
    - Value: {}
    - X component: {}
    - Y component: {}""".format(self.m.__round__(2),
               self.angle.__round__(2),
               self.value.__round__(2),
               self.x.__round__(2),
               self.y.__round__(2))
vplus = function(v1, v2)
    return [v1[0]+v2[0],v1[1]+v2[1]]
end function

vminus = function (v1, v2)
    return [v1[0]-v2[0],v1[1]-v2[1]]
end function

vmult = function(v1, scalar)
    return [v1[0]*scalar, v1[1]*scalar]
end function

vdiv = function(v1, scalar)
    return [v1[0]/scalar, v1[1]/scalar]
end function

vector1 = [2,3]
vector2 = [4,5]

print vplus(vector1,vector2)
print vminus(vector2, vector1)
print vmult(vector1, 3)
print vdiv(vector2, 2)
Vector products
PythonMiniScript
def crossp(a, b):
    '''Cross product of two 3D vectors'''
    assert len(a) == len(b) == 3, 'For 3D vectors only'
    a1, a2, a3 = a
    b1, b2, b3 = b
    return (a2*b3 - a3*b2, a3*b1 - a1*b3, a1*b2 - a2*b1)
 
def dotp(a,b):
    '''Dot product of two eqi-dimensioned vectors'''
    assert len(a) == len(b), 'Vector sizes must match'
    return sum(aterm * bterm for aterm,bterm in zip(a, b))
 
def scalartriplep(a, b, c):
    '''Scalar triple product of three vectors: "a . (b x c)"'''
    return dotp(a, crossp(b, c))
 
def vectortriplep(a, b, c):
    '''Vector triple product of three vectors: "a x (b x c)"'''
    return crossp(a, crossp(b, c))
 
if __name__ == '__main__':
    a, b, c = (3, 4, 5), (4, 3, 5), (-5, -12, -13)
    print("a = %r;  b = %r;  c = %r" % (a, b, c))
    print("a . b = %r" % dotp(a,b))
    print("a x b = %r"  % (crossp(a,b),))
    print("a . (b x c) = %r" % scalartriplep(a, b, c))
    print("a x (b x c) = %r" % (vectortriplep(a, b, c),))
vectorA = [3, 4, 5]
vectorB = [4, 3, 5]
vectorC = [-5, -12, -13]

dotProduct = function(x, y)
    return x[0]*y[0] + x[1]*y[1] + x[2]*y[2]
end function

crossProduct = function(x, y)
    return [x[1]*y[2] - x[2]*y[1], x[2]*y[0] - x[0]*y[2], x[0]*y[1] - x[1]*y[0]]
end function

print "Dot Product = " + dotProduct(vectorA, vectorB)
print "Cross Product = " + crossProduct(vectorA, vectorB)
print "Scalar Triple Product = " + dotProduct(vectorA, crossProduct(vectorB,vectorC))
print "Vector Triple Product = " + crossProduct(vectorA, crossProduct(vectorB,vectorC))
Word wrap
PythonMiniScript
>>> import textwrap
>>> help(textwrap.fill)
Help on function fill in module textwrap:

fill(text, width=70, **kwargs)
    Fill a single paragraph of text, returning a new string.
    
    Reformat the single paragraph in 'text' to fit in lines of no more
    than 'width' columns, and return a new string containing the entire
    wrapped paragraph.  As with wrap(), tabs are expanded and other
    whitespace characters converted to space.  See TextWrapper class for
    available keyword args to customize wrapping behaviour.

>>> txt = '''\
Reformat the single paragraph in 'text' to fit in lines of no more
than 'width' columns, and return a new string containing the entire
wrapped paragraph.  As with wrap(), tabs are expanded and other
whitespace characters converted to space.  See TextWrapper class for
available keyword args to customize wrapping behaviour.'''
>>> print(textwrap.fill(txt, width=75))
Reformat the single paragraph in 'text' to fit in lines of no more than
'width' columns, and return a new string containing the entire wrapped
paragraph.  As with wrap(), tabs are expanded and other whitespace
characters converted to space.  See TextWrapper class for available keyword
args to customize wrapping behaviour.
>>> print(textwrap.fill(txt, width=45))
Reformat the single paragraph in 'text' to
fit in lines of no more than 'width' columns,
and return a new string containing the entire
wrapped paragraph.  As with wrap(), tabs are
expanded and other whitespace characters
converted to space.  See TextWrapper class
for available keyword args to customize
wrapping behaviour.
>>> print(textwrap.fill(txt, width=85))
Reformat the single paragraph in 'text' to fit in lines of no more than 'width'
columns, and return a new string containing the entire wrapped paragraph.  As with
wrap(), tabs are expanded and other whitespace characters converted to space.  See
TextWrapper class for available keyword args to customize wrapping behaviour.
>>> 
str = "one two three four five six seven eight nine ten eleven!"
width = 15
words = str.split
pos = 0
line = ""
for word in words
    pos = pos + word.len + 1
    if pos <= width then
        line = line + word + " "
    else
        print line[:-1]
        line = word + " "
        pos = word.len
    end if
end for
print line[:-1]
Write language name in 3D ASCII
PythonMiniScript
py = '''\
 ####   #   #  #####  #   #   ###   #   #
 #   #   # #     #    #   #  #   #  ##  #
 ####     #      #    #####  #   #  # # #
 #        #      #    #   #  #   #  #  ##
 #        #      #    #   #   ###   #   #'''

lines = py.replace('#', '<<<').replace(' ','X') \
        .replace('X', '   ').replace('\n', ' Y') \
        .replace('< ', '<>').split('Y')

for i, l in enumerate(lines): 
    print('  ' * (len(lines) - i) + l)
data = [
" ______  _____                       _________",
"|\     \/     \  ___  ________   ___|\   _____\ ________  ________  ___  ________  _________   ",
"\ \   _ \  _   \|\  \|\   ___  \|\  \ \  \____||\   ____\|\   ____\|\  \|\   __  \|\___   ___\ ",
" \ \  \\\__\ \  \ \  \ \  \\ \  \ \  \ \_____  \ \  \___|\ \  \___|\ \  \ \  \|\  \|___ \  \_| ",
"  \ \  \\|__| \  \ \  \ \  \\ \  \ \  \|____|\  \ \  \    \ \  \    \ \  \ \   ____\   \ \  \  ",
"   \ \  \    \ \  \ \  \ \  \\ \  \ \  \____\_\  \ \  \____\ \  \    \ \  \ \  \___|    \ \  \ ",
"    \ \__\    \ \__\ \__\ \__\\ \__\ \__\_________\ \_______\ \__\    \ \__\ \__\        \ \__\",
"     \|__|     \|__|\|__|\|__| \|__|\|__||________|\|_______|\|__|     \|__|\|__|         \|__|"]

for line in data
    print line
end for
Zero to the zero power
PythonMiniScript
from decimal import Decimal
from fractions import Fraction
from itertools import product

zeroes = [0, 0.0, 0j, Decimal(0), Fraction(0, 1), -0.0, -0.0j, Decimal(-0.0)]
for i, j in product(zeroes, repeat=2):
    try:
        ans = i**j
    except:
        ans = '<Exception raised>'
    print(f'{i!r:>15} ** {j!r:<15} = {ans!r}')
print "The result of zero to the zero power is " + 0^0