WeixiangYan/CodeTransOcean huggingface dataset:
Task: Run as a daemon or service




Go: package main

import (
    "fmt"
    "github.com/sevlyar/go-daemon"
    "log"
    "os"
    "time"
)

func work() {
    f, err := os.Create("daemon_output.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer f.Close()
    ticker := time.NewTicker(time.Second)
    go func() {
        for t := range ticker.C {
            fmt.Fprintln(f, t) 
        }
    }()
    time.Sleep(60 * time.Second) 
    ticker.Stop()
    log.Print("ticker stopped")
}

func main() {
    cntxt := &daemon.Context{
        PidFileName: "pid",
        PidFilePerm: 0644,
        LogFileName: "log",
        LogFilePerm: 0640,
        WorkDir:     "./",
        Umask:       027,
        Args:        []string{"[Rosetta Code daemon example]"},
    }

    d, err := cntxt.Reborn()
    if err != nil {
        log.Fatal("Unable to run: ", err)
    }
    if d != nil {
        return
    }
    defer cntxt.Release()

    log.Print("- - - - - - - - - - - - - - -")
    log.Print("daemon started")

    work()
}
Task: Process SMIL directives in XML data




Go: package main

import (
    "fmt"
    "github.com/beevik/etree"
    "log"
    "os"
    "strconv"
    "strings"
)

type animData struct {
    element *etree.Element
    attrib  string
    from    string
    to      string
    begin   float64
    dur     float64
}

func check(err error) {
    if err != nil {
        log.Fatal(err)
    }
}

func (ad *animData) AtTime(t float64) string {
    beg := ad.begin
    end := beg + ad.dur
    if t < beg || t > end {
        log.Fatalf("time must be in interval [%g, %g]", beg, end)
    }
    fromSplit := strings.Fields(ad.from)
    toSplit := strings.Fields(ad.to)
    le := len(fromSplit)
    interSplit := make([]string, le)
    for i := 0; i < le; i++ {
        fromF, err := strconv.ParseFloat(fromSplit[i], 64)
        check(err)
        toF, err := strconv.ParseFloat(toSplit[i], 64)
        check(err)
        interF := (fromF*(end-t) + toF*(t-beg)) / ad.dur
        interSplit[i] = fmt.Sprintf("%.2f", interF)
    }
    return strings.Join(interSplit, " ")
}

func main() {
    doc := etree.NewDocument()
    check(doc.ReadFromFile("smil.xml"))
    smil := doc.SelectElement("smil")
    if smil == nil {
        log.Fatal("'smil' element not found")
    }
    x3d := smil.SelectElement("X3D")
    if x3d == nil {
        log.Fatal("'X3D' element not found")
    }
    doc.SetRoot(x3d) 
    var ads []*animData
    for _, a := range doc.FindElements("
        attrib := a.SelectAttrValue("attributeName", "?")
        from := a.SelectAttrValue("from", "?")
        to := a.SelectAttrValue("to", "?")
        beginS := a.SelectAttrValue("begin", "?")
        durS := a.SelectAttrValue("dur", "?")
        if attrib == "?" || from == "?" || to == "?" ||
            beginS == "?" || durS == "?" {
            log.Fatal("an animate element has missing attribute(s)")
        }
        begin, err := strconv.ParseFloat(beginS[:len(beginS)-1], 64)
        check(err)
        dur, err := strconv.ParseFloat(durS[:len(durS)-1], 64)
        check(err)
        p := a.Parent()
        if p == nil {
            log.Fatal("an animate element has no parent")
        }
        pattrib := p.SelectAttrValue(attrib, "?")
        if pattrib == "?" {
            log.Fatal("an animate element's parent has missing attribute")
        }
        ads = append(ads, &animData{p, attrib, from, to, begin, dur})
        p.RemoveChild(a) 
    }
    ts := []float64{0, 2}
    for _, t := range ts {
        for _, ad := range ads {
            s := ad.AtTime(t)
            ad.element.CreateAttr(ad.attrib, s)
        }
        doc.Indent(2)
        fmt.Printf("At time = %g seconds:\n\n", t)
        doc.WriteTo(os.Stdout)
        fmt.Println()
    }
}
Task: IPC via named pipe




Go: package main

import (
        "fmt"
        "io"
        "log"
        "os"
        "sync/atomic"
        "syscall"
)

const (
        inputFifo  = "/tmp/in.fifo"
        outputFifo = "/tmp/out.fifo"
        readsize   = 64 << 10
)

func openFifo(path string, oflag int) (f *os.File, err error) {
        err = syscall.Mkfifo(path, 0660)
        
        if err != nil && !os.IsExist(err) {
                return
        }
        f, err = os.OpenFile(path, oflag, 0660)
        if err != nil {
                return
        }
        
        fi, err := f.Stat()
        if err != nil {
                f.Close()
                return nil, err
        }
        if fi.Mode()&os.ModeType != os.ModeNamedPipe {
                f.Close()
                return nil, os.ErrExist
        }
        return
}

func main() {
        var byteCount int64
        go func() {
                var delta int
                var err error
                buf := make([]byte, readsize)
                for {
                        input, err := openFifo(inputFifo, os.O_RDONLY)
                        if err != nil {
                                break
                        }
                        for err == nil {
                                delta, err = input.Read(buf)
                                atomic.AddInt64(&byteCount, int64(delta))
                        }
                        input.Close()
                        if err != io.EOF {
                                break
                        }
                }
                log.Fatal(err)
        }()

        for {
                output, err := openFifo(outputFifo, os.O_WRONLY)
                if err != nil {
                        log.Fatal(err)
                }
                cnt := atomic.LoadInt64(&byteCount)
                fmt.Fprintln(output, cnt)
                output.Close()
        }
}
Task: Remote agent_Agent logic




Go: package agent

import (
    "log"
    "math/rand"
    "time"

    "ra/ifc"
)






var sectorColor, sectorBall, agentBall byte


var stream ifc.Streamer

func Agent(s ifc.Streamer) {
    stream = s
    
    rand.Seed(time.Now().Unix())
    
    hs := stream.Rec()
    if hs != ifc.Handshake {
        log.Fatal("agent: thats no handshake")
    }
    stream.Send(ifc.Handshake)
    
    for gameOver := false; !gameOver; {
        findMisplaced()
        get()
        findMatching()
        gameOver = drop()
    }
}



const noColor byte = '-'





func move() {
    for {
        
        
        switch rand.Intn(4) {
        case 0:
            stream.Send(ifc.CmdLeft)
            for stream.Rec() != ifc.EvStop {
            }
            continue
        case 1:
            stream.Send(ifc.CmdRight)
            for stream.Rec() != ifc.EvStop {
            }
            continue
        }
        stream.Send(ifc.CmdForward)
        bump := false
        sectorColor = noColor
        sectorBall = noColor
    events:
        for {
            switch ev := stream.Rec(); ev {
            case ifc.EvBump:
                bump = true
            case ifc.EvColorRed, ifc.EvColorGreen,
                ifc.EvColorYellow, ifc.EvColorBlue:
                sectorColor = ev
            case ifc.EvBallRed, ifc.EvBallGreen,
                ifc.EvBallYellow, ifc.EvBallBlue:
                sectorBall = ev
            case ifc.EvStop:
                break events
            }
        }
        if bump {
            continue
        }
        if sectorColor == noColor {
            log.Fatal("agent: expected color event after move")
        }
        return
    }
}


func findMisplaced() {
    for {
        move()
        
        switch sectorBall {
        case ifc.EvBallRed, ifc.EvBallGreen,
            ifc.EvBallYellow, ifc.EvBallBlue:
            if sectorBall != sectorColor+32 {
                return
            }
        }
    }
}


func get() {
    stream.Send(ifc.CmdGet)
    for {
        switch stream.Rec() {
        case ifc.EvStop:
            
            agentBall = sectorBall
            sectorBall = noColor
            return
        case ifc.EvNoBallInSector, ifc.EvAgentFull:
            log.Fatal("agent: expected get to succeed")
        }
    }
}














func findMatching() {
    for sectorColor+32 != agentBall || agentBall == sectorBall {
        move()
    }
}





func drop() (gameOver bool) {
    for sectorBall != noColor {
        move()
    }
    
    stream.Send(ifc.CmdDrop)
ev:
    for {
        switch stream.Rec() {
        case ifc.EvGameOver:
            gameOver = true
        case ifc.EvStop:
            break ev
        case ifc.EvNoBallInAgent, ifc.EvSectorFull:
            log.Fatal("expected drop to succeed")
        }
    }
    sectorBall = agentBall
    agentBall = noColor
    return
}
Task: Draw pixel 2







Python: import Tkinter,random
def draw_pixel_2 ( sizex=640,sizey=480 ):
    pos  = random.randint( 0,sizex-1 ),random.randint( 0,sizey-1 )
    root = Tkinter.Tk()
    can  = Tkinter.Canvas( root,width=sizex,height=sizey,bg='black' )
    can.create_rectangle( pos*2,outline='yellow' )
    can.pack()
    root.title('press ESCAPE to quit')
    root.bind('<Escape>',lambda e : root.quit())
    root.mainloop()

draw_pixel_2()
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)
Task: Longest common suffix







Python: 

from itertools import takewhile
from functools import reduce



def longestCommonSuffix(xs):
    
    def allSame(cs):
        h = cs[0]
        return all(h == c for c in cs[1:])

    def firstCharPrepended(s, cs):
        return cs[0] + s
    return reduce(
        firstCharPrepended,
        takewhile(
            allSame,
            zip(*(reversed(x) for x in xs))
        ),
        ''
    )




def main():
    

    samples = [
        [
            "Sunday", "Monday", "Tuesday", "Wednesday",
            "Thursday", "Friday", "Saturday"
        ], [
            "Sondag", "Maandag", "Dinsdag", "Woensdag",
            "Donderdag", "Vrydag", "Saterdag"
        ]
    ]
    for xs in samples:
        print(
            longestCommonSuffix(xs)
        )



if __name__ == '__main__':
    main()
Task: Distinct power numbers







Python: from itertools import product
print(sorted(set(a**b for (a,b) in product(range(2,6), range(2,6)))))
Task: Unique characters







Python: 

from itertools import chain, groupby



def uniques(xs):
    
    return [
        h for h, (_, *tail) in
        groupby(sorted(chain(*xs)))
        if not tail
    ]




def main():
    
    print(
        uniques([
            "133252abcdeeffd",
            "a6789798st",
            "yxcdfgxcyz"
        ])
    )



if __name__ == '__main__':
    main()
Task: Day of the week of Christmas and New Year







Python: import datetime

weekDays = ("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday")
thisXMas  = datetime.date(2021,12,25)
thisXMasDay = thisXMas.weekday()
thisXMasDayAsString = weekDays[thisXMasDay]
print("This year's Christmas is on a {}".format(thisXMasDayAsString))

nextNewYear = datetime.date(2022,1,1)
nextNewYearDay = nextNewYear.weekday()
nextNewYearDayAsString = weekDays[nextNewYearDay]
print("Next new year is on a {}".format(nextNewYearDayAsString))
Task: Abelian sandpile model_Identity







Python: from itertools import product
from collections import defaultdict


class Sandpile():
    def __init__(self, gridtext):
        array = [int(x) for x in gridtext.strip().split()]
        self.grid = defaultdict(int,
                                {(i //3, i % 3): x 
                                 for i, x in enumerate(array)})

    _border = set((r, c) 
                  for r, c in product(range(-1, 4), repeat=2) 
                  if not 0 <= r <= 2 or not 0 <= c <= 2
                  )
    _cell_coords = list(product(range(3), repeat=2))
    
    def topple(self):
        g = self.grid
        for r, c in self._cell_coords:
            if g[(r, c)] >= 4:
                g[(r - 1, c)] += 1
                g[(r + 1, c)] += 1
                g[(r, c - 1)] += 1
                g[(r, c + 1)] += 1
                g[(r, c)] -= 4
                return True
        return False
    
    def stabilise(self):
        while self.topple():
            pass
        
        g = self.grid
        for row_col in self._border.intersection(g.keys()):
            del g[row_col]
        return self
    
    __pos__ = stabilise     
    
    def __eq__(self, other):
        g = self.grid
        return all(g[row_col] == other.grid[row_col]
                   for row_col in self._cell_coords)

    def __add__(self, other):
        g = self.grid
        ans = Sandpile("")
        for row_col in self._cell_coords:
            ans.grid[row_col] = g[row_col] + other.grid[row_col]
        return ans.stabilise()
       
    def __str__(self):
        g, txt = self.grid, []
        for row in range(3):
            txt.append(' '.join(str(g[(row, col)]) 
                                for col in range(3)))
        return '\n'.join(txt)
    
    def __repr__(self):
        return f'{self.__class__.__name__}()'
        

unstable = Sandpile()
s1 = Sandpile()
s2 = Sandpile()
s3 = Sandpile("3 3 3  3 3 3  3 3 3")
s3_id = Sandpile("2 1 2  1 0 1  2 1 2")
Task: Base 16 numbers needing a to f







Python: 



def p(n):
    
    return 9 < n and (9 < n % 16 or p(n // 16))




def main():
    
    xs = [
        str(n) for n in range(1, 1 + 500)
        if p(n)
    ]
    print(f'{len(xs)} matches for the predicate:\n')
    print(
        table(6)(xs)
    )





def chunksOf(n):
    
    def go(xs):
        return (
            xs[i:n + i] for i in range(0, len(xs), n)
        ) if 0 < n else None
    return go



def table(n):
    
    def go(xs):
        w = len(xs[-1])
        return '\n'.join(
            ' '.join(row) for row in chunksOf(n)([
                s.rjust(w, ' ') for s in xs
            ])
        )
    return go



if __name__ == '__main__':
    main()
Task: Juggler sequence







Python: from math import isqrt

def juggler(k, countdig=True, maxiters=1000):
    m, maxj, maxjpos = k, k, 0
    for i in range(1, maxiters):
        m = isqrt(m) if m % 2 == 0 else isqrt(m * m * m)
        if m >= maxj:
            maxj, maxjpos  = m, i
        if m == 1:
            print(f"{k: 9}{i: 6,}{maxjpos: 6}{len(str(maxj)) if countdig else maxj: 20,}{' digits' if countdig else ''}")
            return i

    print("ERROR: Juggler series starting with $k did not converge in $maxiters iterations")


print("       n    l(n)  i(n)       h(n) or d(n)\n-------------------------------------------")
for k in range(20, 40):
    juggler(k, False)

for k in [113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443, 275485, 1267909]:
    juggler(k)
Task: Find words whose first and last three letters are equal







Python: import urllib.request
urllib.request.urlretrieve("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt", "unixdict.txt")

dictionary = open("unixdict.txt","r")

wordList = dictionary.read().split('\n')

dictionary.close()

for word in wordList:
    if len(word)>5 and word[:3].lower()==word[-3:].lower():
        print(word)
Task: Find words which contain the most consonants







Python: print('\n'.join((f'{x[0]}: {" ".join(sorted(x[1]))}' if len(x[1]) < 30 else f'{x[0]}: {len(x[1])} words' for x in
      (x for x in ((n, [x[1] for x in l if x[0] == n]) for n in range(maxlen, -1, -1)) if x[1]))) if (maxlen := max(l := [(len(c), w)
      for w in [l for l in [l.rstrip() for l in open('unixdict.txt')] if len(l) > 10 and all(c >= 'a' and c <= 'z' for c in l)]
      if sorted(c := w.replace('a', '').replace('e', '').replace('i', '').replace('o', '').replace('u', '')) == sorted(set(c))])[0]) else None)
Task: Odd words







Python: 

import urllib.request
urllib.request.urlretrieve("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt", "unixdict.txt")

dictionary = open("unixdict.txt","r")

wordList = dictionary.read().split('\n')

dictionary.close()

oddWordSet = set({})

for word in wordList:
    if len(word)>=9 and word[::2] in wordList:
        oddWordSet.add(word[::2])

[print(i) for i in sorted(oddWordSet)]
Task: Modified random distribution







Python: import random
from typing import List, Callable, Optional


def modifier(x: float) -> float:
    
    return 2*(.5 - x) if x < 0.5 else 2*(x - .5)


def modified_random_distribution(modifier: Callable[[float], float],
                                 n: int) -> List[float]:
    
    d: List[float] = []
    while len(d) < n:
        r1 = prob = random.random()
        if random.random() < modifier(prob):
            d.append(r1)
    return d


if __name__ == '__main__':
    from collections import Counter

    data = modified_random_distribution(modifier, 50_000)
    bins = 15
    counts = Counter(d // (1 / bins) for d in data)
    
    mx = max(counts.values())
    print("   BIN, COUNTS, DELTA: HISTOGRAM\n")
    last: Optional[float] = None
    for b, count in sorted(counts.items()):
        delta = 'N/A' if last is None else str(count - last)
        print(f"  {b / bins:5.2f},  {count:4},  {delta:>4}: "
              f"{'
        last = count
Task: Deming's funnel







Python: import math 

dxs = [-0.533, 0.27, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275, 1.251,
       -0.231, -0.401, 0.269, 0.491, 0.951, 1.15, 0.001, -0.382, 0.161, 0.915,
       2.08, -2.337, 0.034, -0.126, 0.014, 0.709, 0.129, -1.093, -0.483, -1.193, 
       0.02, -0.051, 0.047, -0.095, 0.695, 0.34, -0.182, 0.287, 0.213, -0.423,
       -0.021, -0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315, 0.201, 
       0.034, 0.097, -0.17, 0.054, -0.553, -0.024, -0.181, -0.7, -0.361, -0.789,
       0.279, -0.174, -0.009, -0.323, -0.658, 0.348, -0.528, 0.881, 0.021, -0.853,
       0.157, 0.648, 1.774, -1.043, 0.051, 0.021, 0.247, -0.31, 0.171, 0.0, 0.106,
       0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017, 0.281, -0.749,
       -0.149, -2.436, -0.909, 0.394, -0.113, -0.598, 0.443, -0.521, -0.799, 
       0.087]

dys = [0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395, 0.49, -0.682,
       -0.065, 0.242, -0.288, 0.658, 0.459, 0.0, 0.426, 0.205, -0.765, -2.188, 
       -0.742, -0.01, 0.089, 0.208, 0.585, 0.633, -0.444, -0.351, -1.087, 0.199,
       0.701, 0.096, -0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007, 
       0.009, 0.508, -0.79, 0.723, 0.881, -0.508, 0.393, -0.226, 0.71, 0.038, 
       -0.217, 0.831, 0.48, 0.407, 0.447, -0.295, 1.126, 0.38, 0.549, -0.445, 
       -0.046, 0.428, -0.074, 0.217, -0.822, 0.491, 1.347, -0.141, 1.23, -0.044, 
       0.079, 0.219, 0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104, 
       -0.729, 0.65, -1.103, 0.154, -1.72, 0.051, -0.385, 0.477, 1.537, -0.901, 
       0.939, -0.411, 0.341, -0.411, 0.106, 0.224, -0.947, -1.424, -0.542, -1.032]

def funnel(dxs, rule):
    x, rxs = 0, []
    for dx in dxs:
        rxs.append(x + dx)
        x = rule(x, dx)
    return rxs

def mean(xs): return sum(xs) / len(xs)

def stddev(xs):
    m = mean(xs)
    return math.sqrt(sum((x-m)**2 for x in xs) / len(xs))

def experiment(label, rule):
    rxs, rys = funnel(dxs, rule), funnel(dys, rule)
    print label
    print 'Mean x, y    : %.4f, %.4f' % (mean(rxs), mean(rys))
    print 'Std dev x, y : %.4f, %.4f' % (stddev(rxs), stddev(rys))
    print


experiment('Rule 1:', lambda z, dz: 0)
experiment('Rule 2:', lambda z, dz: -dz)
experiment('Rule 3:', lambda z, dz: -(z+dz))
experiment('Rule 4:', lambda z, dz: z+dz)
Task: Exponentiation with infix operators in (or operating on) the base







Python: from itertools import product

xx = '-5 +5'.split()
pp = '2 3'.split()
texts = '-x**p -(x)**p (-x)**p -(x**p)'.split()

print('Integer variable exponentiation')
for x, p in product(xx, pp):
    print(f'  x,p = {x:2},{p}; ', end=' ')
    x, p = int(x), int(p)
    print('; '.join(f"{t} =={eval(t):4}" for t in texts))

print('\nBonus integer literal exponentiation')
X, P = 'xp'
xx.insert(0, ' 5')
texts.insert(0, 'x**p')
for x, p in product(xx, pp):
    texts2 = [t.replace(X, x).replace(P, p) for t in texts]
    print(' ', '; '.join(f"{t2} =={eval(t2):4}" for t2 in texts2))
Task: Set right-adjacent bits







Python: from operator import or_
from functools import reduce

def set_right_adjacent_bits(n: int, b: int) -> int:
    return reduce(or_, (b >> x for x in range(n+1)), 0)


if __name__ == "__main__":
    print("SAME n & Width.\n")
    n = 2  
    bits = "1000 0100 0010 0000"
    first = True
    for b_str in bits.split():
        b = int(b_str, 2)
        e = len(b_str)
        if first:
            first = False
            print(f"n = {n}; Width e = {e}:\n")
        result = set_right_adjacent_bits(n, b)
        print(f"     Input b: {b:0{e}b}")
        print(f"      Result: {result:0{e}b}\n")
        
    print("SAME Input & Width.\n")
    
    bits = '01' + '1'.join('0'*x for x in range(10, 0, -1))
    for n in range(4):
        first = True
        for b_str in bits.split():
            b = int(b_str, 2)
            e = len(b_str)
            if first:
                first = False
                print(f"n = {n}; Width e = {e}:\n")
            result = set_right_adjacent_bits(n, b)
            print(f"     Input b: {b:0{e}b}")
            print(f"      Result: {result:0{e}b}\n")
Task: Bioinformatics_Subsequence







Python:  
from random import choice
import regex as re 
import time

def generate_sequence(n: int ) -> str:
    return "".join([ choice(['A','C','G','T']) for _ in range(n) ])

def dna_findall(needle: str, haystack: str) -> None:

    if sum(1 for _ in re.finditer(needle, haystack, overlapped=True)) == 0:
        print("No matches found")
    else:
        print(f"Found {needle} at the following indices: ")
        for match in re.finditer(needle, haystack, overlapped=True):
            print(f"{match.start()}:{match.end()} ")

dna_seq = generate_sequence(200)
sample_seq = generate_sequence(4)

c = 1
for i in dna_seq:
    print(i, end="") if c % 20 != 0 else print(f"{i}")
    c += 1
print(f"\nSearch Sample: {sample_seq}")

dna_findall(sample_seq, dna_seq)
Task: Reverse the order of lines in a text file while preserving the contents of each line







Python: 

import sys

if len(sys.argv)!=2:
    print("Usage : python " + sys.argv[0] + " <filename>")
    exit()

dataFile = open(sys.argv[1],"r")

fileData = dataFile.read().split('\n')

dataFile.close()

[print(i) for i in fileData[::-1]]
Task: Positive decimal integers with the digit 1 occurring exactly twice







Python: 

from itertools import permutations

for i in range(0,10):
    if i!=1:
        baseList = [1,1]
        baseList.append(i)
        [print(int(''.join(map(str,j)))) for j in sorted(set(permutations(baseList)))]
Task: Unique characters in each string







Python: LIST = ["1a3c52debeffd", "2b6178c97a938stf", "3ycxdb1fgxa2yz"]

print(sorted([ch for ch in set([c for c in ''.join(LIST)]) if all(w.count(ch) == 1 for w in LIST)]))
Task: Jacobsthal numbers







Python: 
from math import floor, pow

def isPrime(n):
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:
            return False        
    return True

def odd(n):
    return n and 1 != 0
    
def jacobsthal(n):
    return floor((pow(2,n)+odd(n))/3)

def jacobsthal_lucas(n):
    return int(pow(2,n)+pow(-1,n))

def jacobsthal_oblong(n):
    return jacobsthal(n)*jacobsthal(n+1)


if __name__ == '__main__':
    print("First 30 Jacobsthal numbers:")
    for j in range(0, 30):
        print(jacobsthal(j), end="  ")

    print("\n\nFirst 30 Jacobsthal-Lucas numbers: ")
    for j in range(0, 30):
        print(jacobsthal_lucas(j), end = '\t')

    print("\n\nFirst 20 Jacobsthal oblong numbers: ")
    for j in range(0, 20):
        print(jacobsthal_oblong(j), end="  ")

    print("\n\nFirst 10 Jacobsthal primes: ")
    for j in range(3, 33):
        if isPrime(jacobsthal(j)):
            print(jacobsthal(j))