WeixiangYan/CodeTransOcean huggingface dataset:
Task: Carmichael 3 strong pseudoprimes







Python: class Isprime():
    
    multiples = {2}
    primes = [2]
    nmax = 2
    
    def __init__(self, nmax):
        if nmax > self.nmax:
            self.check(nmax)

    def check(self, n):
        if type(n) == float:
            if not n.is_integer(): return False
            n = int(n)
        multiples = self.multiples
        if n <= self.nmax:
            return n not in multiples
        else:
            
            primes, nmax = self.primes, self.nmax
            newmax = max(nmax*2, n)
            for p in primes:
                multiples.update(range(p*((nmax + p + 1) // p), newmax+1, p))
            for i in range(nmax+1, newmax+1):
                if i not in multiples:
                    primes.append(i)
                    multiples.update(range(i*2, newmax+1, i))
            self.nmax = newmax
            return n not in multiples

    __call__ = check
            
        
def carmichael(p1):
    ans = []
    if isprime(p1):
        for h3 in range(2, p1):
            g = h3 + p1
            for d in range(1, g):
                if (g * (p1 - 1)) % d == 0 and (-p1 * p1) % h3 == d % h3:
                    p2 = 1 + ((p1 - 1)* g // d)
                    if isprime(p2):
                        p3 = 1 + (p1 * p2 // h3)
                        if isprime(p3):
                            if (p2 * p3) % (p1 - 1) == 1:
                                
                                ans += [tuple(sorted((p1, p2, p3)))]
    return ans
                
isprime = Isprime(2)
 
ans = sorted(sum((carmichael(n) for n in range(62) if isprime(n)), []))
print(',\n'.join(repr(ans[i:i+5])[1:-1] for i in range(0, len(ans)+1, 5)))




Fortran:       LOGICAL FUNCTION ISPRIME(N)	
       INTEGER N			
       INTEGER F			
        ISPRIME = .FALSE.		
        DO F = 2,SQRT(DFLOAT(N))	
          IF (MOD(N,F).EQ.0) RETURN	
        END DO				
        ISPRIME = .TRUE.		
      END FUNCTION ISPRIME		

      PROGRAM CHASE
      INTEGER P1,P2,P3	
      INTEGER H3,D	
      INTEGER MSG	
      MSG = 6		
      WRITE (MSG,1)	
    1 FORMAT ("Carmichael numbers that are the product of three primes:"
     & /"    P1  x P2  x P3 =",9X,"C")
      DO P1 = 2,61	
        IF (ISPRIME(P1)) THEN	
          DO H3 = 2,P1 - 1		
            DO D = 1,H3 + P1 - 1		
              IF (MOD((H3 + P1)*(P1 - 1),D).EQ.0	
     &        .AND. (MOD(H3 + MOD(-P1**2,H3),H3) .EQ. MOD(D,H3))) THEN	
                P2 = 1 + (P1 - 1)*(H3 + P1)/D	
                IF (ISPRIME(P2)) THEN		
                  P3 = 1 + P1*P2/H3			
                  IF (ISPRIME(P3)) THEN			
                    IF (MOD(P2*P3,P1 - 1).EQ.1) THEN		
                      WRITE (MSG,2) P1,P2,P3, INT8(P1)*P2*P3		
    2                 FORMAT (3I6,I12)
                    END IF
                  END IF
                END IF
              END IF
            END DO
          END DO
        END IF
      END DO
      END
Task: Rock-paper-scissors







Python: from random import choice

rules = {'rock': 'paper', 'scissors': 'rock', 'paper': 'scissors'}
previous = ['rock', 'paper', 'scissors']

while True:
    human = input('\nchoose your weapon: ')
    computer = rules[choice(previous)]  

    if human in ('quit', 'exit'): break

    elif human in rules:
        previous.append(human)
        print('the computer played', computer, end='; ')

        if rules[computer] == human:  
            print('yay you win!')
        elif rules[human] == computer:  
            print('the computer beat you... :(')
        else: print("it's a tie!")

    else: print("that's not a valid choice")




Fortran: 


















program rpsgame

  integer, parameter :: COMPUTER=1, HAPLESSUSER=2
  integer, dimension(3) :: rps = (/1,1,1/)
  real, dimension(3) :: p
  character :: answer, cc 
  integer :: exhaustion, i
  real, dimension(2) :: score = (/0, 0/)
  character(len=8), dimension(3) :: choices = (/'rock    ','paper   ','scissors'/)
  real :: harvest
  do exhaustion = 1, 30
    p = rps/real(sum(rps))
    p(2) = p(2) + p(1)
    p(3) = p(3) + p(2)
    call random_number(harvest)
    i = sum(merge(1,0,harvest.le.p)) 
    cc = 'rsp'(i:i)
    write(6, "(2(A,', '),A,'?  ')", advance='no')(trim(choices(i)),i=1,size(choices))
    read(5, *) answer
    write(6, "('scoring computer choice (',A,') and your choice (',A,')')")cc,answer
    if (answer.eq.cc) then
      score = score + 0.5
    else
      i = HAPLESSUSER
      if (answer.eq.'r') then
        if (cc.eq.'p') i = COMPUTER
      else if (answer.eq.'p') then
        if (cc.eq.'s') i = COMPUTER
      else if (answer.eq.'s') then
        if (cc.eq.'r') i = COMPUTER
      else
        exit
      endif
      score(i) = score(i) + 1
    end if
    i = scan('rps',answer)
    rps(i) = rps(i) + 1
  end do
  if (25 .lt. exhaustion) write(6, *) "I'm bored out of my skull"
  write(6, *)"Who's keeping score anyway???"
  write(6, '(2f5.1)') score
  if (score(COMPUTER) .lt. score(HAPLESSUSER)) print*,'you won
end program rpsgame
Task: Benford's law







Python: from __future__ import division
from itertools import islice, count
from collections import Counter
from math import log10
from random import randint

expected = [log10(1+1/d) for d in range(1,10)]

def fib():
    a,b = 1,1
    while True:
        yield a
        a,b = b,a+b


def power_of_threes():
    return (3**k for k in count(0))

def heads(s):
    for a in s: yield int(str(a)[0])

def show_dist(title, s):
    c = Counter(s)
    size = sum(c.values())
    res = [c[d]/size for d in range(1,10)]

    print("\n%s Benfords deviation" % title)
    for r, e in zip(res, expected):
        print("%5.1f%% %5.1f%%  %5.1f%%" % (r*100., e*100., abs(r - e)*100.))

def rand1000():
    while True: yield randint(1,9999)

if __name__ == '__main__':
    show_dist("fibbed", islice(heads(fib()), 1000))
    show_dist("threes", islice(heads(power_of_threes()), 1000))

    
    show_dist("random", islice(heads(rand1000()), 10000))




Fortran: -*- mode: compilation; default-directory: "/tmp/" -*-
Compilation started at Sat May 18 01:13:00

a=./f && make $a && $a
f95 -Wall -ffree-form f.F -o f
  0.301030010      0.176091254      0.124938756       9.69100147E-02   7.91812614E-02   6.69467747E-02   5.79919666E-02   5.11525236E-02   4.57575098E-02 THE LAW
  0.300999999      0.177000001      0.125000000       9.60000008E-02   7.99999982E-02   6.70000017E-02   5.70000000E-02   5.29999994E-02   4.50000018E-02 LEADING FIBONACCI DIGIT

Compilation finished at Sat May 18 01:13:00
Task: Hickerson series of almost integers







Python: from decimal import Decimal
import math

def h(n):
    'Simple, reduced precision calculation'
    return math.factorial(n) / (2 * math.log(2) ** (n + 1))
    
def h2(n):
    'Extended precision Hickerson function'
    return Decimal(math.factorial(n)) / (2 * Decimal(2).ln() ** (n + 1))

for n in range(18):
    x = h2(n)
    norm = str(x.normalize())
    almostinteger = (' Nearly integer' 
                     if 'E' not in norm and ('.0' in norm or '.9' in norm) 
                     else ' NOT nearly integer!')
    print('n:%2i h:%s%s' % (n, norm, almostinteger))




Fortran: program hickerson
    implicit none
    integer, parameter :: q = selected_real_kind(30)
    integer, parameter :: l = selected_int_kind(15)
    real(q) :: s, l2
    integer :: i, n, k

    l2 = log(2.0_q)
    do n = 1, 17
        s = 0.5_q / l2
        do i = 1, n
            s = (s * i) / l2
        end do

        k = floor((s - floor(s, l)) * 10)
        if (k == 0 .or. k == 9) then
            print 1, n, s, ""
        else
            print 1, n, s, " NOT"
        endif
    end do
  1 format('h(',I2,') = ',F23.3,' is',A,' an almost-integer')
end program
Task: Case-sensitivity of identifiers







Python: >>> 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
>>>




Fortran: program Example
  implicit none

  character(8) :: dog, Dog, DOG

  dog = "Benjamin"
  Dog = "Samba"
  DOG = "Bernie"

  if (dog == DOG) then
    write(*,*) "There is just one dog named ", dog
  else
    write(*,*) "The three dogs are named ", dog, Dog, " and ", DOG
  end if

end program Example
Task: Sorting algorithms_Stooge sort







Python: >>> data = [1, 4, 5, 3, -6, 3, 7, 10, -2, -5, 7, 5, 9, -3, 7]
>>> def stoogesort(L, i=0, j=None):
	if j is None:
		j = len(L) - 1
	if L[j] < L[i]:
		L[i], L[j] = L[j], L[i]
	if j - i > 1:
		t = (j - i + 1) // 3
		stoogesort(L, i  , j-t)
		stoogesort(L, i+t, j  )
		stoogesort(L, i  , j-t)
	return L

>>> stoogesort(data)
[-6, -5, -3, -2, 1, 3, 3, 4, 5, 5, 7, 7, 7, 9, 10]




Fortran: program Stooge
  implicit none

  integer :: i
  integer :: array(50) = (/ (i, i = 50, 1, -1) /) 
  
  call Stoogesort(array)
  write(*,"(10i5)") array

contains

recursive subroutine Stoogesort(a)
  integer, intent(in out) :: a(:)
  integer :: j, t, temp
 
   j = size(a)
   if(a(j) < a(1)) then
     temp = a(j)
     a(j) = a(1)
     a(1) = temp
   end if

  if(j > 2) then
    t = j / 3
    call Stoogesort(a(1:j-t))
    call Stoogesort(a(1+t:j))
    call Stoogesort(a(1:j-t)) 
  end if

end subroutine
end program
Task: Truncate a file







Python: def truncate_file(name, length):
    if not os.path.isfile(name):
        return False
    if length >= os.path.getsize(name):
        return False
    with open(name, 'ab') as f:
        f.truncate(length)
    return True




Fortran:       SUBROUTINE CROAK(GASP)	
       CHARACTER*(*) GASP	
        WRITE (6,*) "Oh dear. ",GASP	
        STOP "++ungood."	
      END			

      SUBROUTINE FILEHACK(FNAME,NB)
       CHARACTER*(*) FNAME	
       INTEGER NB		
       INTEGER L		
       INTEGER F,T		
       PARAMETER (F=66,T=67)	
       LOGICAL EXIST		
       CHARACTER*1 B		
        IF (FNAME.EQ."") CALL CROAK("Blank file name
        IF (NB.LE.0)     CALL CROAK("Chop must be positive
        INQUIRE(FILE = FNAME, EXIST = EXIST)	
        IF (.NOT.EXIST) CALL CROAK("Can't find a file called "//FNAME)	
        OPEN (F,FILE=FNAME,STATUS="OLD",ACTION="READWRITE",	
     1   FORM="UNFORMATTED",RECL=1,ACCESS="DIRECT")		
        OPEN (T,STATUS="SCRATCH",FORM="UNFORMATTED",RECL=1)	

Copy the desired "records" to the temporary file.
   10   DO L = 1,NB	
          READ  (F,REC = L,ERR = 20) B	
          WRITE (T) B			
        END DO		
   20   IF (L.LE.NB) CALL CROAK("Short file
Convert from input to output...
        REWIND T		
        CLOSE(F)		
        OPEN (F,FILE=FNAME,FORM="FORMATTED",	
     1   ACTION="WRITE",STATUS="REPLACE")	
Copy from the temporary file.
        DO L = 1,NB	
          READ  (T) B		
          WRITE (F,"(A1,$)") B	
        END DO		
Completed.
   30   CLOSE(T)	
        CLOSE(F)	
      END		

      PROGRAM CHOPPER
       CALL FILEHACK("foobar.txt",12)
      END
Task: Sorting algorithms_Shell sort







Python: def shell(seq):
    inc = len(seq) // 2
    while inc:
        for i, el in enumerate(seq[inc:], inc):
            while i >= inc and seq[i - inc] > el:
                seq[i] = seq[i - inc]
                i -= inc
            seq[i] = el
        inc = 1 if inc == 2 else inc * 5 // 11




Fortran: MODULE sort

CONTAINS

SUBROUTINE Shell_Sort(a)

  IMPLICIT NONE
  INTEGER :: i, j, increment
  REAL :: temp
  REAL, INTENT(in out) :: a(:)
	
  increment = SIZE(a) / 2
  DO WHILE (increment > 0)
      DO i = increment+1, SIZE(a)
         j = i
         temp = a(i)
         DO WHILE (j >= increment+1 .AND. a(j-increment) > temp)
            a(j) = a(j-increment)
            j = j - increment
         END DO
         a(j) = temp
      END DO
      IF (increment == 2) THEN
   	  increment = 1
      ELSE
         increment = increment * 5 / 11
      END IF      
  END DO
 
END SUBROUTINE Shell_Sort

END MODULE sort

PROGRAM Shellsort

USE sort

  IMPLICIT NONE
  REAL :: array(1000)
     
  CALL RANDOM_SEED
  CALL RANDOM_NUMBER(array)
 
  WRITE (*,*) "Unsorted array"
  WRITE (*,*) array
  WRITE (*,*) 
  CALL Shell_Sort(array)
  WRITE (*,*) "Sorted array"
  WRITE (*,*) array
  
END PROGRAM Shellsort
Task: Deconvolution_1D







Python: def ToReducedRowEchelonForm( M ):
    if not M: return
    lead = 0
    rowCount = len(M)
    columnCount = len(M[0])
    for r in range(rowCount):
        if lead >= columnCount:
            return
        i = r
        while M[i][lead] == 0:
            i += 1
            if i == rowCount:
                i = r
                lead += 1
                if columnCount == lead:
                    return
        M[i],M[r] = M[r],M[i]
        lv = M[r][lead]
        M[r] = [ mrx / lv for mrx in M[r]]
        for i in range(rowCount):
            if i != r:
                lv = M[i][lead]
                M[i] = [ iv - lv*rv for rv,iv in zip(M[r],M[i])]
        lead += 1
    return M
 
def pmtx(mtx):
    print ('\n'.join(''.join(' %4s' % col for col in row) for row in mtx))
 
def convolve(f, h):
    g = [0] * (len(f) + len(h) - 1)
    for hindex, hval in enumerate(h):
        for findex, fval in enumerate(f):
            g[hindex + findex] += fval * hval
    return g

def deconvolve(g, f):
    lenh = len(g) - len(f) + 1
    mtx = [[0 for x in range(lenh+1)] for y in g]
    for hindex in range(lenh):
        for findex, fval in enumerate(f):
            gindex = hindex + findex
            mtx[gindex][hindex] = fval
    for gindex, gval in enumerate(g):        
        mtx[gindex][lenh] = gval
    ToReducedRowEchelonForm( mtx )
    return [mtx[i][lenh] for i in range(lenh)]  

if __name__ == '__main__':
    h = [-8,-9,-3,-1,-6,7]
    f = [-3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1]
    g = [24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7]
    assert convolve(f,h) == g
    assert deconvolve(g, f) == h




Fortran: 



program deconv
  
  use mkl95_lapack, only : gelsd

  implicit none
  real(8), allocatable :: g(:), href(:), A(:,:), f(:)
  real(8), pointer     :: h(:), r(:)
  integer              :: N
  character(len=16)    :: cbuff
  integer              :: i
  intrinsic            :: nint

  
  allocate(g(21),f(16))
  g = [24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7]
  f = [-3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1]

  
  h => deco(f, g)

  
  N = size(h)
  allocate(href(N))
  href = [-8,-9,-3,-1,-6,7]
  cbuff = ' '
  write(cbuff,'(a,i0,a)') '(a,',N,'(i0,a),i0)'
  if (any(abs(h-href) > 1.0d-4)) then
     write(*,'(a)') 'deconv(f, g) - FAILED'
  else
     write(*,cbuff) 'deconv(f, g) = ',(nint(h(i)),', ',i=1,N-1),nint(h(N))
  end if

  
  r => deco(h, g)

  cbuff = ' '
  N = size(r)
  write(cbuff,'(a,i0,a)') '(a,',N,'(i0,a),i0)'
  if (any(abs(r-f) > 1.0d-4)) then
     write(*,'(a)') 'deconv(h, g) - FAILED'
  else
     write(*,cbuff) 'deconv(h, g) = ',(nint(r(i)),', ',i=1,N-1),nint(r(N))
  end if

contains
  function deco(p, q)
    real(8), pointer    :: deco(:)
    real(8), intent(in) :: p(:), q(:)

    real(8), allocatable, target :: r(:)
    real(8), allocatable         :: A(:,:)
    integer :: N

    
    N = size(q) - size(p) + 1
    allocate(A(size(q),N),r(size(q)))
    A = 0.0d0
    do i=1,N
       A(i:i+size(p)-1,i) = p
    end do
    
    
    r = q
    call gelsd(A, r)

    deco => r(1:N)
  end function deco

end program deconv
Task: Inverted syntax







Python: x = truevalue if condition else falsevalue




Fortran:       INQUIRE(FILE = FILENAME(1:L), EXIST = MAYBE, ERR = 666, IOSTAT = RESULT)
Task: LU decomposition







Python: from pprint import pprint

def matrixMul(A, B):
    TB = zip(*B)
    return [[sum(ea*eb for ea,eb in zip(a,b)) for b in TB] for a in A]

def pivotize(m):
    
    n = len(m)
    ID = [[float(i == j) for i in xrange(n)] for j in xrange(n)]
    for j in xrange(n):
        row = max(xrange(j, n), key=lambda i: abs(m[i][j]))
        if j != row:
            ID[j], ID[row] = ID[row], ID[j]
    return ID

def lu(A):
    
    n = len(A)
    L = [[0.0] * n for i in xrange(n)]
    U = [[0.0] * n for i in xrange(n)]
    P = pivotize(A)
    A2 = matrixMul(P, A)
    for j in xrange(n):
        L[j][j] = 1.0
        for i in xrange(j+1):
            s1 = sum(U[k][j] * L[i][k] for k in xrange(i))
            U[i][j] = A2[i][j] - s1
        for i in xrange(j, n):
            s2 = sum(U[k][j] * L[i][k] for k in xrange(j))
            L[i][j] = (A2[i][j] - s2) / U[j][j]
    return (L, U, P)

a = [[1, 3, 5], [2, 4, 7], [1, 1, 0]]
for part in lu(a):
    pprint(part, width=19)
    print
print
b = [[11,9,24,2],[1,5,2,6],[3,17,18,1],[2,5,7,1]]
for part in lu(b):
    pprint(part)
    print




Fortran: program lu1
  implicit none
  call check( reshape([real(8)::1,2,1,3,4,1,5,7,0                  ],[3,3]) )
  call check( reshape([real(8)::11,1,3,2,9,5,17,5,24,2,18,7,2,6,1,1],[4,4]) )
 
contains
 
  subroutine check(a)
    real(8), intent(in)   :: a(:,:)
    integer               :: i,j,n
    real(8), allocatable  :: aa(:,:),l(:,:),u(:,:)
    integer, allocatable  :: p(:,:)
    integer, allocatable  :: ipiv(:)
    n = size(a,1)
    allocate(aa(n,n),l(n,n),u(n,n),p(n,n),ipiv(n))
    forall (j=1:n,i=1:n)
      aa(i,j) = a(i,j)
      u (i,j) = 0d0
      p (i,j) = merge(1  ,0  ,i.eq.j)
      l (i,j) = merge(1d0,0d0,i.eq.j)
    end forall
    call lu(aa, ipiv)
    do i = 1,n
       l(i, :i-1) = aa(i, :i-1)
       u(i,i:   ) = aa(i,i:   )
    end do
    p(ipiv,:) = p
    call mat_print('a',a)
    call mat_print('p',p)
    call mat_print('l',l)
    call mat_print('u',u)
    print *, "residual"
    print *, "|| P.A - L.U || =  ", maxval(abs(matmul(p,a)-matmul(l,u)))
  end subroutine
 
  subroutine lu(a,p)

    real(8), intent(inout) :: a(:,:)
    integer, intent(out  ) :: p(:)
    integer                :: n, i,j,k,kmax
    n = size(a,1)
    p = [ ( i, i=1,n ) ]
    do k = 1,n-1
        kmax = maxloc(abs(a(p(k:),k)),1) + k-1
        if (kmax /= k ) then
            p([k, kmax]) = p([kmax, k])
            a([k, kmax],:) = a([kmax, k],:)
        end if
        a(k+1:,k) = a(k+1:,k) / a(k,k)
        forall (j=k+1:n) a(k+1:,j) = a(k+1:,j) - a(k,j)*a(k+1:,k)
    end do
  end subroutine

  subroutine mat_print(amsg,a)
    character(*), intent(in) :: amsg
    class    (*), intent(in) :: a(:,:)
    integer                  :: i
    print*,' '
    print*,amsg
    do i=1,size(a,1)
      select type (a)
        type is (real(8)) ; print'(100f8.2)',a(i,:)
        type is (integer) ; print'(100i8  )',a(i,:)
      end select
    end do
    print*,' '
  end subroutine

end program
Task: Optional parameters







Python: >>> def printtable(data):
    for row in data:
        print ' '.join('%-5s' % ('"%s"' % cell) for cell in row)

        
>>> import operator
>>> def sorttable(table, ordering=None, column=0, reverse=False):
    return sorted(table, cmp=ordering, key=operator.itemgetter(column), reverse=reverse)

>>> data = [["a", "b", "c"], ["", "q", "z"], ["zap", "zip", "Zot"]]
>>> printtable(data)
"a"   "b"   "c"  
""    "q"   "z"  
"zap" "zip" "Zot"
>>> printtable( sorttable(data) )
""    "q"   "z"  
"a"   "b"   "c"  
"zap" "zip" "Zot"
>>> printtable( sorttable(data, column=2) )
"zap" "zip" "Zot"
"a"   "b"   "c"  
""    "q"   "z"  
>>> printtable( sorttable(data, column=1) )
"a"   "b"   "c"  
""    "q"   "z"  
"zap" "zip" "Zot"
>>> printtable( sorttable(data, column=1, reverse=True) )
"zap" "zip" "Zot"
""    "q"   "z"  
"a"   "b"   "c"  
>>> printtable( sorttable(data, ordering=lambda a,b: cmp(len(b),len(a))) )
"zap" "zip" "Zot"
"a"   "b"   "c"  
""    "q"   "z"  
>>>




Fortran: module ExampleOptionalParameter
  
  
  implicit none
contains

  subroutine sort_table(table, ordering, column, reverse)
    type(table_type), intent(inout) :: table
    integer, optional :: column
    logical, optional :: reverse
    optional :: ordering
    interface
       integer function ordering(a, b)
         type(table_element), intent(in) :: a, b
       end function ordering
    end interface

    integer :: the_column, i
    logical :: reversing
    type(table_row) :: rowA, rowB

    if ( present(column) ) then
       if ( column > get_num_of_columns(table) ) then
          
       else
          the_column = column
       end if
    else
       the_column = 1   
    end if

    reversing = .false.  
    if ( present(reverse) ) reversing = reverse

    do
       
       
       
       
       ea = get_element(rowA, the_column)
       eb = get_element(rowB, the_column)
       if ( present(ordering) ) then
          if ( .not. reversing ) then
             if ( ordering(ea, eb) > 0 ) then
                
             end if
          else   
             if ( ordering(ea, eb) < 0 ) then
                
             end if
          end if
       else
          if ( .not. reversing ) then
             if ( lexinternal(ea, eb) > 0 ) then
                
             end if
          else   
             if ( lexinternal(ea, eb) < 0 ) then
                
             end if
          end if
       end if
       
       
    end do

  end subroutine sort_table

end module ExampleOptionalParameter
Task: Trabb Pardo–Knuth algorithm







Python: 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.
>>> def f(x): return abs(x) ** 0.5 + 5 * x**3

>>> print(', '.join('%s:%s' % (x, v if v<=400 else "TOO LARGE!")
	           for x,v in ((y, f(float(y))) for y in input('\nnumbers: ').strip().split()[:11][::-1])))

11 numbers: 1 2 3 4 5 6 7 8 9 10 11
11:TOO LARGE!, 10:TOO LARGE!, 9:TOO LARGE!, 8:TOO LARGE!, 7:TOO LARGE!, 6:TOO LARGE!, 5:TOO LARGE!, 4:322.0, 3:136.73205080756887, 2:41.41421356237309, 1:6.0
>>>




Fortran: program tpk
  implicit none
  
  real, parameter :: overflow = 400.0
  real :: a(11), res
  integer :: i
 
  write(*,*) "Input eleven numbers:"
  read(*,*) a
 
  a = a(11:1:-1)
  do i = 1, 11
    res = f(a(i))
    write(*, "(a, f0.3, a)", advance = "no") "f(", a(i), ") = "
    if(res > overflow) then
      write(*, "(a)") "overflow
    else
       write(*, "(f0.3)") res
    end if
  end do  
      
contains

real function f(x)
  real, intent(in) :: x
  
  f = sqrt(abs(x)) + 5.0*x**3

end function  
end program
Task: Rate counter







Python: import subprocess
import time

class Tlogger(object):
    def __init__(self):
        self.counts = 0
        self.tottime = 0.0
        self.laststart = 0.0
        self.lastreport = time.time()

    def logstart(self):
        self.laststart = time.time()

    def logend(self):
        self.counts +=1
        self.tottime += (time.time()-self.laststart)
        if (time.time()-self.lastreport)>5.0:   
           self.report()

    def report(self):
        if ( self.counts > 4*self.tottime):
            print "Subtask execution rate: %f times/second"% (self.counts/self.tottime);
        else:
            print "Average execution time: %f seconds"%(self.tottime/self.counts);
        self.lastreport = time.time()


def taskTimer( n, subproc_args ):
    logger = Tlogger()

    for x in range(n):
        logger.logstart()
        p = subprocess.Popen(subproc_args)
        p.wait()
        logger.logend()
    logger.report()


import timeit
import sys

def main( ):

    
    s = 
    timer = timeit.Timer(s)
    rzlts = timer.repeat(5, 5000)
    for t in rzlts:
        print "Time for 5000 executions of statement = ",t
    
    
    print "
    print "Command:",sys.argv[2:]
    print ""
    for k in range(3):
       taskTimer( int(sys.argv[1]), sys.argv[2:])

main()




Fortran:       DO I = FIRST,LAST
        IF (PROGRESSNOTE((I - FIRST)/(LAST - FIRST + 1.0))) WRITE (6,*) "Reached ",I,", towards ",LAST
        ...much computation...
      END DO