WeixiangYan/CodeTransOcean huggingface dataset:
Task: Topswops







Python: >>> from itertools import permutations
>>> def f1(p):
	i = 0
	while True:
		p0  = p[0]
		if p0 == 1: break
		p[:p0] = p[:p0][::-1]
		i  += 1
	return i

>>> def fannkuch(n):
	return max(f1(list(p)) for p in permutations(range(1, n+1)))

>>> for n in range(1, 11): print(n,fannkuch(n))

1 0
2 1
3 2
4 4
5 7
6 10
7 16
8 22
9 30
10 38
>>>




Fortran: module top
implicit none
contains 
recursive function f(x) result(m)
  integer :: n, m, x(:),y(size(x)), fst
  fst = x(1)
  if (fst == 1) then
    m = 0
  else
    y(1:fst) = x(fst:1:-1)
    y(fst+1:) = x(fst+1:)
    m = 1 + f(y)
  end if
end function

recursive function perms(x) result(p)
integer, pointer     :: p(:,:), q(:,:)
integer              :: x(:), n, k, i
n = size(x)
if (n == 1) then
  allocate(p(1,1))
  p(1,:) = x
else
  q => perms(x(2:n))
  k = ubound(q,1)
  allocate(p(k*n,n))
  p = 0
  do i = 1,n
    p(1+k*(i-1):k*i,1:i-1) = q(:,1:i-1)
    p(1+k*(i-1):k*i,i) = x(1)
    p(1+k*(i-1):k*i,i+1:) = q(:,i:)
  end do
end if
end function
end module

program topswort
use top
implicit none
integer :: x(10)
integer, pointer  :: p(:,:)
integer :: i, j, m

forall(i=1:10)
  x(i) = i
end forall

do i = 1,10
  p=>perms(x(1:i))
  m = 0
  do j = 1, ubound(p,1)
    m = max(m, f(p(j,:)))
  end do
  print "(i3,a,i3)", i,": ",m
end do  
end program
Task: Odd word problem







Python: from sys import stdin, stdout

def char_in(): return stdin.read(1)
def char_out(c): stdout.write(c)

def odd(prev = lambda: None):
	a = char_in()
	if not a.isalpha():
		prev()
		char_out(a)
		return a != '.'

	
	def clos():
		char_out(a)
		prev()

	return odd(clos)

def even():
	while True:
		c = char_in()
		char_out(c)
		if not c.isalpha(): return c != '.'

e = False
while odd() if e else even():
	e = not e




Fortran:       MODULE ELUDOM	
       INTEGER MSG,INF	
       LOGICAL DEFER	
       CONTAINS
        CHARACTER*1 RECURSIVE FUNCTION GET(IN)	
         INTEGER IN	
         CHARACTER*1 C	
          READ (IN,1,ADVANCE="NO",EOR=3,END=4) C	
    1     FORMAT (A1,$)	
    2     IF (("A"<=C .AND. C<="Z").OR.("a"<=C .AND. C<="z")) THEN	
            IF (DEFER) THEN	
              GET = GET(IN)	
              WRITE (MSG,1) C	
              RETURN		
            END IF		
           ELSE		
            DEFER = .NOT. DEFER	
          END IF	
    3     GET = C	
          RETURN	
    4     GET = CHAR(0)	
        END FUNCTION GET
      END MODULE ELUDOM	

      PROGRAM CONFUSED	
      USE ELUDOM	
      CHARACTER*1 C	
      MSG = 6	
      INF = 10	
      OPEN (INF,NAME = "Confused.txt",STATUS="OLD",ACTION="READ")	

Chew through the input. A full stop marks the end.
   10 DEFER = .FALSE.	
   11 C = GET(INF)		
      IF (ICHAR(C).LE.0) STOP		
      IF (C.NE." ") WRITE (MSG,12) C	
   12 FORMAT (A1,$)			
      IF (C.NE.".") GO TO 11	
      WRITE (MSG,"('')")	
      GO TO 10		
      END
Task: Memory layout of a data structure







Python: from ctypes import Structure, c_int

rs232_9pin  = "_0 CD RD TD DTR SG DSR RTS CTS RI".split()
rs232_25pin = ( "_0  PG  TD  RD  RTS CTS DSR SG  CD  pos neg"
                "_11 SCD SCS STD TC  SRD RC"
                "_18 SRS DTR SQD RI DRS XTC" ).split()

class RS232_9pin(Structure):
    _fields_ = [(__, c_int, 1) for __ in rs232_9pin]

	
class RS232_25pin(Structure):
    _fields_ = [(__, c_int, 1) for __ in rs232_25pin]




Fortran:        TYPE RS232PIN9
        LOGICAL CARRIER_DETECT		
        LOGICAL RECEIVED_DATA		
        LOGICAL TRANSMITTED_DATA	
        LOGICAL DATA_TERMINAL_READY	
        LOGICAL SIGNAL_GROUND		
        LOGICAL DATA_SET_READY		
        LOGICAL REQUEST_TO_SEND		
        LOGICAL CLEAR_TO_SEND		
        LOGICAL RING_INDICATOR		
       END TYPE RS232PIN9
Task: Largest proper divisor of n







Python: def lpd(n):
    for i in range(n-1,0,-1):
        if n%i==0: return i
    return 1

for i in range(1,101):
    print("{:3}".format(lpd(i)), end=i%10==0 and '\n' or '')




Fortran:        program LargestProperDivisors
       implicit none
       integer i, lpd
       do 10 i=1, 100
           write (*,'(I3)',advance='no') lpd(i)
 10        if (i/10*10 .eq. i) write (*,*)       
       end program
       
       integer function lpd(n)
       implicit none
       integer n, i
       if (n .le. 1) then
           lpd = 1
       else
           do 10 i=n-1, 1, -1
 10            if (n/i*i .eq. n) goto 20
 20        lpd = i
       end if
       end function
Task: Numbers with equal rises and falls







Python: import itertools

def riseEqFall(num):
    
    height = 0
    d1 = num % 10
    num //= 10
    while num:
        d2 = num % 10
        height += (d1<d2) - (d1>d2)
        d1 = d2
        num //= 10
    return height == 0
    
def sequence(start, fn):
    
    num=start-1
    while True:
        num += 1
        while not fn(num): num += 1
        yield num

a296712 = sequence(1, riseEqFall)


print("The first 200 numbers are:")
print(*itertools.islice(a296712, 200))


print("The 10,000,000th number is:")
print(*itertools.islice(a296712, 10000000-200-1, 10000000-200))






Fortran:       PROGRAM A296712
          INTEGER IDX, NUM, I
*         Index and number start out at zero
          IDX = 0
          NUM = 0 
*         Find and write the first 200 numbers
          WRITE (*,'(A)') 'The first 200 numbers are: '
          DO 100 I = 1, 200
              CALL NEXT NUM(IDX, NUM)
              WRITE (*,'(I4)',ADVANCE='NO') NUM
              IF (MOD(I,20).EQ.0) WRITE (*,*)
  100     CONTINUE
*         Find the 10,000,000th number
          WRITE (*,*)
          WRITE (*,'(A)',ADVANCE='NO') 'The 10,000,000th number is: '
  200     CALL NEXT NUM(IDX, NUM)
          IF (IDX.NE.10000000) GOTO 200
          WRITE (*,'(I8)') NUM
          STOP
      END    

*     Given index and current number, retrieve the next number
*     in the sequence.
      SUBROUTINE NEXT NUM(IDX, NUM) 
          INTEGER IDX, NUM
          LOGICAL IN SEQ
  100     NUM = NUM + 1
          IF (.NOT. IN SEQ(NUM)) GOTO 100
          IDX = IDX + 1           
      END
    
*     See whether N is in the sequence
      LOGICAL FUNCTION IN SEQ(N)
          INTEGER N, DL, DR, VAL, HEIGHT
*         Get first digit and divide value by 10
          DL = MOD(N, 10)
          VAL = N / 10
          HEIGHT = 0
  100     IF (VAL.NE.0) THEN
*             Retrieve digits by modulo and division
              DR = DL
              DL = MOD(VAL, 10)
              VAL = VAL / 10
*             Record rise or fall
              IF (DL.LT.DR) HEIGHT = HEIGHT + 1
              IF (DL.GT.DR) HEIGHT = HEIGHT - 1
              GOTO 100
          END IF
*         N is in the sequence if the final height is 0
          IN SEQ = HEIGHT.EQ.0
          RETURN
      END
Task: Length of an arc between two angles







Python: import math

def arc_length(r, angleA, angleB):
    return (360.0 - abs(angleB - angleA)) * math.pi * r / 180.0




Fortran: *-----------------------------------------------------------------------
* given:  polar coordinates of two points on a circle of known radius
* find:  length of the major arc between these points
*
*___Name_____Type___I/O___Description___________________________________
*   RAD      Real   In    Radius of circle, any unit of measure
*   ANG1     Real   In    Angle of first point, degrees
*   ANG2     Real   In    Angle of second point, degrees
*   MAJARC   Real   Out   Length of major arc, same units as RAD
*-----------------------------------------------------------------------
      FUNCTION MAJARC (RAD, ANG1, ANG2)
       IMPLICIT NONE
       REAL RAD, ANG1, ANG2, MAJARC

       REAL FACT                          
       PARAMETER (FACT = 3.1415926536 / 180.)
       REAL DIF

*       Begin
       MAJARC = 0.
       IF (RAD .LE. 0.) RETURN
       DIF = MOD(ABS(ANG1 - ANG2), 360.)   
       DIF = MAX(DIF, 360. - DIF)          
       MAJARC = RAD * DIF * FACT           
       RETURN
      END  

*-----------------------------------------------------------------------
      PROGRAM TMA
       IMPLICIT NONE
       INTEGER J
       REAL ANG1, ANG2, RAD, MAJARC, ALENG
       REAL DATARR(3,3)     
       DATA DATARR / 120.,  10., 10.,
     $                10., 120., 10.,
     $               180., 270., 10. /

       DO J = 1, 3
         ANG1 = DATARR(1,J)
         ANG2 = DATARR(2,J)
         RAD = DATARR(3,J)
         ALENG = MAJARC (RAD, ANG1, ANG2)        
         PRINT *, 'first angle: ', ANG1, ' second angle: ', ANG2, 
     $     ' radius: ', RAD, ' Length of major arc: ', ALENG
       END DO
      END
Task: Matrix with two diagonals







Python: 



def twoDiagonalMatrix(n):
    
    return matrix(
        n, n, lambda row, col: int(
            row in (col, 1 + (n - col))
        )
    )




def main():
    
    for n in [7, 8]:
        print(
            showMatrix(
                twoDiagonalMatrix(n)
            ) + '\n'
        )





def matrix(nRows, nCols, f):
    
    return [
        [f(y, x) for x in range(1, 1 + nCols)]
        for y in range(1, 1 + nRows)
    ]



def showMatrix(rows):
    
    return '\n'.join([
        ' '.join([str(x) for x in y]) for y in rows
    ])



if __name__ == '__main__':
    main()




Fortran: program prog

    dimension a(100, 100)

    n = 7
	
    j1 = 1
    j2 = n
    do i = 1, n
        do j = 1, n
            a(i, j) = 0.
        end do
        a(i, j1) = 1
        a(i, j2) = 1
        j1 = j1 + 1
        j2 = j2 - 1
    end do

    do i = 1, n
        print *, (a(i, j), j=1,n)
    end do

end
Task: Words containing _the_ substring







Python: import urllib.request as request

with request.urlopen("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt") as f:
    a = f.read().decode("ASCII").split()

for s in a:
    if len(s) > 11 and "the" in s:
        print(s)




Fortran: program main
implicit none
integer :: lun
character(len=256) :: line
integer :: ios
   open(file='unixdict.txt',newunit=lun)
   do
      read(lun,'(a)',iostat=ios)line
      if(ios /= 0)exit
      if( index(line,'the') /= 0 .and. len_trim(line) > 11 ) then
         write(*,'(a)')trim(line)
      endif
   enddo
end program main
Task: Here document







Python: print()




Fortran:       INTEGER I         
      CHARACTER*666 I AM    
      I AM =                                                           "<col72
C              111111111122222222223333333333444444444455555555556666666666
C     123456789012345678901234567890123456789012345678901234567890123456789
     1                                                                  <col72
     2              I AM                                                <col72
     3                                                                  <col72
     4           THAT I AM                                              <col72
     5"

Chug through the text blob.
      DO I = 0,600,66   
        WRITE (6,1) I AM(I + 1:I + 66)  
    1   FORMAT (A66)            
      END DO                
      END
Task: Address of a variable







Python: var num = 12
var pointer = ptr(num) 

print pointer 

@unsafe 
pointer.addr = 0xFFFE 




Fortran: program test_loc
  implicit none

  integer :: i
  real    :: r

  i = loc(r)
  print *, i
end program
Task: Determinant and permanent







Python: from itertools import permutations
from operator import mul
from math import fsum
from spermutations import spermutations

def prod(lst):
    return reduce(mul, lst, 1)

def perm(a):
    n = len(a)
    r = range(n)
    s = permutations(r)
    return fsum(prod(a[i][sigma[i]] for i in r) for sigma in s)

def det(a):
    n = len(a)
    r = range(n)
    s = spermutations(n)
    return fsum(sign * prod(a[i][sigma[i]] for i in r)
                for sigma, sign in s)

if __name__ == '__main__':
    from pprint import pprint as pp

    for a in ( 
            [
             [1, 2], 
             [3, 4]], 

            [
             [1, 2, 3, 4],
             [4, 5, 6, 7],
             [7, 8, 9, 10],
             [10, 11, 12, 13]],        

            [
             [ 0,  1,  2,  3,  4],
             [ 5,  6,  7,  8,  9],
             [10, 11, 12, 13, 14],
             [15, 16, 17, 18, 19],
             [20, 21, 22, 23, 24]],
        ):
        print('')
        pp(a)
        print('Perm: %s Det: %s' % (perm(a), det(a)))




Fortran: 



































program f
  implicit none
  real, dimension(3,3) :: j, m
  data j/ 2,-1, 1,-1,-2, 1,-1,-1,-1/
  data m/2, 9, 4, 7, 5, 3, 6, 1, 8/
  write(6,*) 'j example, determinant: ',det(j,3,-1)
  write(6,*) 'j example, permanent:   ',det(j,3,1)
  write(6,*) 'maxima, determinant:    ',det(m,3,-1)
  write(6,*) 'maxima, permanent:      ',det(m,3,1)

contains

  recursive function det(a,n,permanent) result(accumulation)
    
    
    real, dimension(n,n), intent(in) :: a
    integer, intent(in) :: n, permanent
    real, dimension(n-1, n-1) :: b
    real :: accumulation
    integer :: i, sgn
    if (n .eq. 1) then
      accumulation = a(1,1)
    else
      accumulation = 0
      sgn = 1
      do i=1, n
        b(:, :(i-1)) = a(2:, :i-1)
        b(:, i:) = a(2:, i+1:)
        accumulation = accumulation + sgn * a(1, i) * det(b, n-1, permanent)
        sgn = sgn * permanent
      enddo
    endif
  end function det

end program f
Task: Sum of divisors







Python: def factorize(n):
    assert(isinstance(n, int))
    if n < 0: 
        n = -n 
    if n < 2: 
        return 
    k = 0 
    while 0 == n%2: 
        k += 1 
        n //= 2 
    if 0 < k: 
        yield (2,k) 
    p = 3 
    while p*p <= n: 
        k = 0 
        while 0 == n%p: 
            k += 1 
            n //= p 
        if 0 < k: 
            yield (p,k)
        p += 2 
    if 1 < n: 
        yield (n,1) 

def sum_of_divisors(n): 
    assert(n != 0) 
    ans = 1 
    for (p,k) in factorize(n): 
        ans *= (pow(p,k+1) - 1)//(p-1) 
    return ans 
    
if __name__ == "__main__":
    print([sum_of_divisors(n) for n in range(1,101)])




Fortran:        program DivSum
       implicit none
       integer i, j, col, divs(100)
       
       do 10 i=1, 100, 1
 10        divs(i) = 1
 
       do 20 i=2, 100, 1
           do 20 j=i, 100, i
 20            divs(j) = divs(j) + i
 
       col = 0
       do 30 i=1, 100, 1
           write (*,'(I4)',advance='no') divs(i)
           col = col + 1
           if (col .eq. 10) then
               col = 0
               write (*,*)
           end if
 30    continue
       end program
Task: Sorting algorithms_Bead sort







Python: 
from itertools import zip_longest


def beadsort(l):
    return list(map(sum, zip_longest(*[[1] * e for e in l], fillvalue=0)))



print(beadsort([5,3,1,7,4,1,1]))




Fortran: program BeadSortTest
  use iso_fortran_env 
  
  
  
  

  integer, dimension(7) :: a = (/ 7, 3, 5, 1, 2, 1, 20 /)

  call beadsort(a)
  print *, a

contains

  subroutine beadsort(a)
    integer, dimension(:), intent(inout) :: a

    integer, dimension(maxval(a), maxval(a)) :: t
    integer, dimension(maxval(a)) :: s
    integer :: i, m

    m = maxval(a)
    
    if ( any(a < 0) ) then
       write(ERROR_UNIT,*) "can't sort"
       return
    end if

    t = 0
    forall(i=1:size(a)) t(i, 1:a(i)) = 1  
    forall(i=1:m)             
       s(i) = sum(t(:, i))    
       t(:, i) = 0            
       t(1:s(i), i) = 1       
    end forall
    
    forall(i=1:size(a)) a(i) = sum(t(i,:))
    
  end subroutine beadsort

end program BeadSortTest
Task: Möbius function







Python: 













 


def isPrime(n) :
 
    if (n < 2) :
        return False
    for i in range(2, n + 1) :
        if (i * i <= n and n % i == 0) :
            return False
    return True
 
def mobius(N) :
     
    
    if (N == 1) :
        return 1
 
    
    
    
    p = 0
    for i in range(1, N + 1) :
        if (N % i == 0 and
                isPrime(i)) :
 
            
            
            if (N % (i * i) == 0) :
                return 0
            else :
 
                
                
                p = p + 1
 
    
    
    
    
    if(p % 2 != 0) :
        return -1
    else :
        return 1
 

print("Mobius numbers from 1..99:")
      
for i in range(1, 100):
  print(f"{mobius(i):>4}", end = '')

  if i % 20 == 0: print()






Fortran: program moebius
    use iso_fortran_env, only: output_unit

    integer, parameter          :: mu_max=1000000, line_break=20
    integer, parameter          :: sqroot=int(sqrt(real(mu_max)))
    integer                     :: i, j
    integer, dimension(mu_max)  :: mu

    mu = 1

    do i = 2, sqroot
        if (mu(i) == 1) then
            do j = i, mu_max, i
                mu(j) = mu(j) * (-i)
            end do

            do j = i**2, mu_max, i**2
                mu(j) = 0
            end do
        end if
    end do

    do i = 2, mu_max
        if (mu(i) == i) then
            mu(i) = 1
        else if (mu(i) == -i) then
            mu(i) = -1
        else if (mu(i) < 0) then
            mu(i) = 1
        else if (mu(i) > 0) then
            mu(i) = -1
        end if
    end do

    write(output_unit,*) "The first 199 terms of the Möbius sequence are:"
    write(output_unit,'(3x)', advance="no") 
    do i = 1, 199
        write(output_unit,'(I2,x)', advance="no") mu(i)
        if (modulo(i+1, line_break) == 0) write(output_unit,*)
    end do
end program moebius
Task: Mertens function







Python: def mertens(count):
    
    m = [None, 1]
    for n in range(2, count+1):
        m.append(1)
        for k in range(2, n+1):
            m[n] -= m[n//k]
    return m
    

ms = mertens(1000)

print("The first 99 Mertens numbers are:")
print("  ", end=' ')
col = 1
for n in ms[1:100]:
    print("{:2d}".format(n), end=' ')
    col += 1
    if col == 10:
        print()
        col = 0
        
zeroes = sum(x==0 for x in ms)
crosses = sum(a!=0 and b==0 for a,b in zip(ms, ms[1:]))
print("M(N) equals zero {} times.".format(zeroes))
print("M(N) crosses zero {} times.".format(crosses))




Fortran:       program Mertens
      implicit none
      integer M(1000), n, k, zero, cross
       
C     Generate Mertens numbers       
      M(1) = 1
      do 10 n=2, 1000
          M(n) = 1
          do 10 k=2, n
              M(n) = M(n) - M(n/k)
 10   continue 

C     Print table
      write (*,"('The first 99 Mertens numbers are:')")
      write (*,"('   ')",advance='no')
      k = 9
      do 20 n=1, 99
          write (*,'(I3)',advance='no') M(n)
          k = k-1
          if (k .EQ. 0) then
              k=10
              write (*,*)
          end if
 20   continue
 
C     Calculate zeroes and crossings
      zero = 0
      cross = 0
      do 30 n=2, 1000
          if (M(n) .EQ. 0) then
              zero = zero + 1
              if (M(n-1) .NE. 0) cross = cross+1
          end if    
 30   continue 
 
 40   format("M(N) is zero ",I2," times.")
      write (*,40) zero
 50   format("M(N) crosses zero ",I2," times.")
      write (*,50) cross
      end program
Task: Product of divisors







Python: def product_of_divisors(n):
    assert(isinstance(n, int) and 0 < n)
    ans = i = j = 1
    while i*i <= n:
        if 0 == n%i:
            ans *= i
            j = n//i
            if j != i:
                ans *= j
        i += 1
    return ans
    
if __name__ == "__main__":
    print([product_of_divisors(n) for n in range(1,51)])




Fortran:        program divprod
       implicit none
       integer divis(50), i, j
       do 10 i=1, 50
 10        divis(i) = 1
       do 20 i=1, 50
           do 20 j=i, 50, i
 20            divis(j) = divis(j)*i
       do 30 i=1, 50
           write (*,'(I10)',advance='no') divis(i)
 30        if (i/5 .ne. (i-1)/5) write (*,*)            
       end program
Task: Playing cards







Python: 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()  
        return self.deck.pop(0)




Fortran: MODULE Cards

IMPLICIT NONE

  TYPE Card
    CHARACTER(5) :: value
    CHARACTER(8) :: suit
  END TYPE Card

  TYPE(Card) :: deck(52), hand(52)
  TYPE(Card) :: temp

  CHARACTER(5) :: pip(13) = (/"Two  ", "Three", "Four ", "Five ", "Six  ", "Seven", "Eight", "Nine ", "Ten  ", &
                              "Jack ", "Queen", "King ", "Ace  "/)
  CHARACTER(8) :: suits(4) = (/"Clubs   ", "Diamonds", "Hearts  ", "Spades  "/)
  INTEGER :: i, j, n, rand, dealt = 0
  REAL :: x

CONTAINS
 
  SUBROUTINE Init_deck
  
    DO i = 1, 4
      DO j = 1, 13
        deck((i-1)*13+j) = Card(pip(j), suits(i))
      END DO
    END DO
  END SUBROUTINE Init_deck
 
  SUBROUTINE Shuffle_deck
  
    DO i = 52-dealt, 1, -1
      CALL RANDOM_NUMBER(x)
      rand = INT(x * i) + 1
      temp = deck(rand)
      deck(rand) = deck(i)
      deck(i) = temp
    END DO
  END SUBROUTINE Shuffle_deck

  SUBROUTINE Deal_hand(number)
  
    INTEGER :: number
    DO i = 1, number
      hand(i) = deck(dealt+1)
      dealt = dealt + 1
    END DO
  END SUBROUTINE

  SUBROUTINE Print_hand
  
    DO i = 1, dealt
      WRITE (*, "(3A)") TRIM(deck(i)%value), " of ", TRIM(deck(i)%suit)
    END DO
    WRITE(*,*)
  END SUBROUTINE Print_hand
 
  SUBROUTINE Print_deck
  
    DO i = dealt+1, 52
      WRITE (*, "(3A)") TRIM(deck(i)%value), " of ", TRIM(deck(i)%suit)
    END DO
    WRITE(*,*)
  END SUBROUTINE Print_deck

END MODULE Cards
Task: Two sum







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




Fortran: program twosum
  implicit none

  integer, parameter, dimension(5) :: list = (/ 0, 2, 11, 19, 90/)
  integer, parameter :: target_val = 21
  integer :: nelem
  integer :: i, j
  logical :: success = .false.

  nelem = size(list)
  outer:do i = 1,nelem
     do j = i+1,nelem
        success = list(i) + list(j) == target_val
        if (success) exit outer
     end do
  end do outer

  if (success) then
     
     print('("(",2(i3.1,1X),")",3(A1,i3.1))'), i,j, ":", list(i), "+", list(j), "=", target_val
  else
     print*, "Failed"
  end if

end program twosum
Task: Find the last Sunday of each month







Python: import sys
import calendar

year = 2013
if len(sys.argv) > 1:
    try:
        year = int(sys.argv[-1])
    except ValueError:
        pass

for month in range(1, 13):
    last_sunday = max(week[-1] for week in calendar.monthcalendar(year, month))
    print('{}-{}-{:2}'.format(year, calendar.month_abbr[month], last_sunday))




Fortran:       D = DAYNUM(Y,M,D)    
      DAYNUM(Y,M,D) = D
Task: Comments







Python: 

var x = 0 

var y = 0 


There are also multi-line comments
Everything inside of 
]



discard 




Fortran: C     This would be some kind of comment
C     Usually one would avoid columns 2-6 even in a comment.