WeixiangYan/CodeTransOcean huggingface dataset:
Task: Strange numbers







Python: 



def isStrange(n):
    
    def test(a, b):
        return abs(a - b) in [2, 3, 5, 7]

    xs = digits(n)
    return all(map(test, xs, xs[1:]))




def main():
    

    xs = [
        n for n in range(100, 1 + 500)
        if isStrange(n)
    ]
    print('\nStrange numbers in range [100..500]\n')
    print('(Total: ' + str(len(xs)) + ')\n')
    print(
        '\n'.join(
            ' '.join(
                str(x) for x in row
            ) for row in chunksOf(10)(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 digits(n):
    
    return [int(c) for c in str(n)]



if __name__ == '__main__':
    main()





Ada: with Ada.Text_IO; use Ada.Text_IO;

procedure Strange_Numbers is

   function Is_Strange (A : Natural) return Boolean is
      Last     : Natural := A mod 10;
      Reminder : Natural := A / 10;
      Current  : Natural;
   begin
      while Reminder /= 0 loop
         Current := Reminder mod 10;
         exit when abs (Current - Last) not in 2 | 3 | 5 | 7;
         Last     := Current;
         Reminder := Reminder / 10;
      end loop;
      return Reminder = 0;
   end Is_Strange;

   Count : Natural := 0;
begin
   for A in 101 .. 499 loop
      if Is_Strange (A) then
         Put (A'Image);
         Count := Count + 1;
         if Count mod 10 = 0 then
            New_Line;
         end if;
      end if;
   end loop;
   New_Line;
   Put_Line ("Strange numbers in range 101 .. 499: " & Count'Image);
   New_Line;

   Count := 0;
   for A in 1_000_000_000 .. 1_999_999_999 loop
      if Is_Strange (A) then
         Count := Count + 1;
      end if;
   end loop;
   Put_Line ("Strange numbers in range 1_000_000_000 .. 1_999_999_999: " & Count'Image);
end Strange_Numbers;
Task: Hofstadter Q sequence







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





Ada: with Ada.Text_IO;

procedure Hofstadter_Q_Sequence is

   type Callback is access procedure(N: Positive);

   procedure Q(First, Last: Positive; Q_Proc: Callback) is
   
   

      Q_Store: array(1 .. Last) of Natural := (1 => 1, 2 => 1, others => 0);
      
      
      

      function Q(N: Positive) return Positive is
      begin
         if Q_Store(N) = 0 then
            Q_Store(N) := Q(N - Q(N-1)) + Q(N-Q(N-2));
         end if;
         return Q_Store(N);
      end Q;

   begin
      for I in First .. Last loop
         Q_Proc(Q(I));
      end loop;
   end Q;

   procedure Print(P: Positive) is
   begin
      Ada.Text_IO.Put(Positive'Image(P));
   end Print;

   Decrease_Counter: Natural := 0;
   Previous_Value: Positive := 1;

   procedure Decrease_Count(P: Positive) is
   begin
      if P < Previous_Value then
         Decrease_Counter := Decrease_Counter + 1;
      end if;
      Previous_Value := P;
   end Decrease_Count;

begin
   Q(1, 10, Print'Access);
   
   Ada.Text_IO.New_Line;

   Q(1000, 1000,  Print'Access);
   
   Ada.Text_IO.New_Line;

   Q(2, 100_000, Decrease_Count'Access);
   Ada.Text_IO.Put_Line(Integer'Image(Decrease_Counter));
   
   
end Hofstadter_Q_Sequence;
Task: Count occurrences of a substring







Python: >>> "the three truths".count("th")
3
>>> "ababababab".count("abab")
2





Ada: with Ada.Strings.Fixed, Ada.Integer_Text_IO;

procedure Substrings is
begin
   Ada.Integer_Text_IO.Put (Ada.Strings.Fixed.Count (Source  => "the three truths",
                                                     Pattern => "th"));
   Ada.Integer_Text_IO.Put (Ada.Strings.Fixed.Count (Source  => "ababababab",
                                                     Pattern => "abab"));
end Substrings;
Task: Append numbers at same position in strings







Python: list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
list2 = [10, 11, 12, 13, 14, 15, 16, 17, 18]
list3 = [19, 20, 21, 22, 23, 24, 25, 26, 27]

print([
    ''.join(str(n) for n in z) for z
    in zip(list1, list2, list3)
])





Ada: with Ada.Text_Io;
with Ada.Strings.Fixed;

procedure Append_Numbers is

   use Ada.Text_Io, Ada.Strings;

   type List_Type is array (Positive range <>) of Natural;

   procedure Put (List : List_Type) is
   begin
      Put ("[");
      for E of List loop
         Put (Natural'Image (E));
      end loop;
      Put ("]");
   end Put;

   List_1 : constant List_Type := ( 1,  2,  3,  4,  5,  6,  7,  8,  9);
   List_2 : constant List_Type := (10, 11, 12, 13, 14, 15, 16, 17, 18);
   List_3 : constant List_Type := (19, 20, 21, 22, 23, 24, 25, 26, 27);
   List   : List_Type (List_1'Range);
begin
   for A in List'Range loop
      List (A) := Natural'Value
        (Fixed.Trim (Natural'Image (List_1 (A)), Left) &
         Fixed.Trim (Natural'Image (List_2 (A)), Left) &
         Fixed.Trim (Natural'Image (List_3 (A)), Left));
   end loop;

   Put (List);  New_Line;
end Append_Numbers;
Task: User input_Graphical







Python: from javax.swing import JOptionPane

def to_int(n, default=0):
    try:
        return int(n)
    except ValueError:
        return default

number = to_int(JOptionPane.showInputDialog ("Enter an Integer")) 
println(number)

a_string = JOptionPane.showInputDialog ("Enter a String")
println(a_string)





Ada: with Gtk.Button;  use Gtk.Button;
with Gtk.GEntry;  use Gtk.GEntry;
with Gtk.Label;   use Gtk.Label;
with Gtk.Window;  use Gtk.Window;
with Gtk.Widget;  use Gtk.Widget;
with Gtk.Table;   use Gtk.Table;
 
with Gtk.Handlers;
with Gtk.Main;
 
procedure Graphic_Input is
   Window  : Gtk_Window;
   Grid    : Gtk_Tnetable;
   Label   : Gtk_Label;
   Message : Gtk_Label;
   Edit    : Gtk_GEntry;
   Button  : Gtk_Button;
 
   package Handlers is new Gtk.Handlers.Callback (Gtk_Widget_Record);
   package Return_Handlers is
      new Gtk.Handlers.Return_Callback (Gtk_Widget_Record, Boolean);
 
   function Delete_Event (Widget : access Gtk_Widget_Record'Class)
      return Boolean is
   begin
      return False;
   end Delete_Event;
 
   procedure Destroy (Widget : access Gtk_Widget_Record'Class) is
   begin
      Gtk.Main.Main_Quit;
   end Destroy;
 
   procedure Clicked (Widget : access Gtk_Widget_Record'Class) is
   begin
      if Get_Text (Label) = "Enter integer:" then
         Set_Text (Message, "Entered:" & Integer'Image (Integer'Value (Get_Text (Edit))));
         Set_Sensitive (Button, False);
      else
         Set_Text (Message, "Entered:" & Get_Text (Edit));
         Set_Text (Label, "Enter integer:");
      end if;
   exception
      when Constraint_Error =>
         Set_Text (Message, "Error integer input");
   end Clicked;
 
begin
   Gtk.Main.Init;
   Gtk.Window.Gtk_New (Window);
   Gtk_New (Grid, 2, 3, False);
   Add (Window, Grid);
   Gtk_New (Label, "Enter string:");
   Attach (Grid, Label, 0, 1, 0, 1);
   Gtk_New (Edit);   
   Attach (Grid, Edit, 1, 2, 0, 1);
   Gtk_New (Button, "OK");   
   Attach (Grid, Button, 2, 3, 0, 1);
   Gtk_New (Message);
   Attach (Grid, Message, 0, 3, 1, 2);
   Return_Handlers.Connect
   (  Window,
      "delete_event",
      Return_Handlers.To_Marshaller (Delete_Event'Access)
   );
   Handlers.Connect
   (  Window,
      "destroy",
      Handlers.To_Marshaller (Destroy'Access)
   );
   Handlers.Connect
   (  Button,
      "clicked",
      Handlers.To_Marshaller (Clicked'Access)
   );
   Show_All (Grid);
   Show (Window);
 
   Gtk.Main.Main;
end Graphic_Input;
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)))





Ada: with Ada.Text_IO, Miller_Rabin;

procedure Nemesis is

   type Number is range 0 .. 2**40-1; 

   function Is_Prime(N: Number) return Boolean is
      package MR is new Miller_Rabin(Number); use MR;
   begin
      return MR.Is_Prime(N) = Probably_Prime;
   end Is_Prime;

begin
   for P1 in Number(2) .. 61 loop
      if Is_Prime(P1) then
         for H3 in Number(1) .. P1 loop
            declare
               G: Number := H3 + P1;
               P2, P3: Number;
            begin
               Inner:
               for D in 1 .. G-1 loop
                  if ((H3+P1) * (P1-1)) mod D = 0 and then
                    (-(P1 * P1)) mod H3 = D mod H3
                  then
                     P2 := 1 + ((P1-1) * G / D);
                     P3 := 1 +(P1*P2/H3);
                     if Is_Prime(P2) and then Is_Prime(P3)
                       and then (P2*P3) mod (P1-1) = 1
                     then
                       Ada.Text_IO.Put_Line
                        ( Number'Image(P1) & " *"   & Number'Image(P2) & " *" &
                          Number'Image(P3) & "  = " & Number'Image(P1*P2*P3) );
                     end if;
                  end if;
               end loop Inner;
            end;
         end loop;
      end if;
   end loop;
end Nemesis;
Task: Find square difference







Python: import math
print("working...")
limit1 = 6000
limit2 = 1000
oldSquare = 0
newSquare = 0

for n in range(limit1):
    newSquare = n*n
    if (newSquare - oldSquare > limit2):
     print("Least number is = ", end = "");
     print(int(math.sqrt(newSquare)))
     break
    oldSquare = n*n

print("done...")
print()





Ada: with Ada.Text_IO; use Ada.Text_IO;

procedure Find_Square_Difference is
   Last   : Natural := 0;
   Square : Positive;
   Diff   : Positive;
begin
   for N in 1 .. Positive'Last loop
      Square := N ** 2;
      Diff   := Square - Last;
      Last   := Square;
      if Diff > 1000 then
         Put_Line (N'Image);
         exit;
      end if;
   end loop;
end Find_Square_Difference;
Task: Keyboard input_Flush the keyboard buffer







Python: def flush_input():
    try:
        import msvcrt
        while msvcrt.kbhit():
            msvcrt.getch()
    except ImportError:
        import sys, termios
        termios.tcflush(sys.stdin, termios.TCIOFLUSH)





Ada: with Ada.Text_IO;
procedure Flushtest is
   use Text_IO;
begin
   Put_Line ("Type anything for 2 s");
   delay 2.0;
Flush_Input:
   declare
      Ch   : Character;
      More : Boolean;
   begin
      loop
         Get_Immediate (Ch, More);
         exit when not More;
      end loop;
   end Flush_Input;
   New_Line;
   Put_Line ("Okay, thanks. Here is some input from you:");
   Put_Line (Get_Line);
end Flushtest;
Task: Fractal tree







Python: def setup():
    size(600, 600)
    background(0)
    stroke(255)
    drawTree(300, 550, 9)
    
def drawTree(x, y, depth):
    fork_ang = radians(20)
    base_len = 10
    if depth > 0:
        pushMatrix()
        translate(x, y - baseLen * depth)
        line(0, baseLen * depth, 0, 0)  
        rotate(fork_ang)
        drawTree(0, 0, depth - 1)  
        rotate(2 * -fork_ang)
        drawTree(0, 0, depth - 1) 
        popMatrix()





Ada: with Ada.Numerics.Elementary_Functions;

with SDL.Video.Windows.Makers;
with SDL.Video.Renderers.Makers;
with SDL.Video.Rectangles;
with SDL.Events.Events;

procedure Fractal_Tree is

   Width   : constant := 600;
   Height  : constant := 600;
   Level   : constant := 13;
   Length  : constant := 130.0;
   X_Start : constant := 475.0;
   Y_Start : constant := 580.0;
   A_Start : constant := -1.54;
   Angle_1 : constant := 0.10;
   Angle_2 : constant := 0.35;
   C_1     : constant := 0.71;
   C_2     : constant := 0.87;

   Window   : SDL.Video.Windows.Window;
   Renderer : SDL.Video.Renderers.Renderer;
   Event    : SDL.Events.Events.Events;

   procedure Draw_Tree (Level  : in Natural;
                        Length : in Float;
                        Angle  : in Float;
                        X, Y   : in Float)
   is
      use SDL;
      use Ada.Numerics.Elementary_Functions;
      Pi   : constant       := Ada.Numerics.Pi;
      X_2  : constant Float := X + Length * Cos (Angle, 2.0 * Pi);
      Y_2  : constant Float := Y + Length * Sin (Angle, 2.0 * Pi);
      Line : constant SDL.Video.Rectangles.Line_Segment
        := ((C.int (X), C.int (Y)), (C.int (X_2), C.int (Y_2)));
   begin
      if Level > 0 then
         Renderer.Set_Draw_Colour (Colour => (0, 220, 0, 255));
         Renderer.Draw (Line => Line);

         Draw_Tree (Level - 1, C_1 * Length, Angle + Angle_1, X_2, Y_2);
         Draw_Tree (Level - 1, C_2 * Length, Angle - Angle_2, X_2, Y_2);
      end if;
   end Draw_Tree;

   procedure Wait is
      use type SDL.Events.Event_Types;
   begin
      loop
         while SDL.Events.Events.Poll (Event) loop
            if Event.Common.Event_Type = SDL.Events.Quit then
               return;
            end if;
         end loop;
         delay 0.100;
      end loop;
   end Wait;

begin
   if not SDL.Initialise (Flags => SDL.Enable_Screen) then
      return;
   end if;

   SDL.Video.Windows.Makers.Create (Win      => Window,
                                    Title    => "Fractal tree",
                                    Position => SDL.Natural_Coordinates'(X => 10, Y => 10),
                                    Size     => SDL.Positive_Sizes'(Width, Height),
                                    Flags    => 0);
   SDL.Video.Renderers.Makers.Create (Renderer, Window.Get_Surface);
   Renderer.Set_Draw_Colour ((0, 0, 0, 255));
   Renderer.Fill (Rectangle => (0, 0, Width, Height));

   Draw_Tree (Level, Length, A_Start, X_Start, Y_Start);
   Window.Update_Surface;

   Wait;
   Window.Finalize;
   SDL.Finalise;
end Fractal_Tree;
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))





Ada: with Ada.Text_IO, Ada.Numerics.Generic_Elementary_Functions; 

procedure Benford is
   
   subtype Nonzero_Digit is Natural range 1 .. 9;
   function First_Digit(S: String) return Nonzero_Digit is
      (if S(S'First) in '1' .. '9' 
         then Nonzero_Digit'Value(S(S'First .. S'First))
         else First_Digit(S(S'First+1 .. S'Last)));
      
   package N_IO is new Ada.Text_IO.Integer_IO(Natural);  
      
   procedure Print(D: Nonzero_Digit; Counted, Sum: Natural) is
      package Math is new Ada.Numerics.Generic_Elementary_Functions(Float);
      package F_IO is new Ada.Text_IO.Float_IO(Float);
      Actual: constant Float := Float(Counted) / Float(Sum);
      Expected: constant Float := Math.Log(1.0 + 1.0 / Float(D), Base => 10.0);
      Deviation: constant Float := abs(Expected-Actual);
   begin
      N_IO.Put(D, 5);
      N_IO.Put(Counted, 14);
      F_IO.Put(Float(Sum)*Expected, Fore => 16, Aft => 1, Exp => 0);
      F_IO.Put(100.0*Actual, Fore => 9, Aft => 2, Exp => 0); 
      F_IO.Put(100.0*Expected, Fore => 11, Aft => 2, Exp => 0); 
      F_IO.Put(100.0*Deviation, Fore => 13, Aft => 2, Exp => 0);
   end Print;
   
   Cnt: array(Nonzero_Digit) of Natural := (1 .. 9 => 0);   
   D: Nonzero_Digit;
   Sum: Natural := 0;
   Counter: Positive;       
       
begin     
   while not Ada.Text_IO.End_Of_File loop
      
      N_IO.Get(Counter); 
        
      D := First_Digit(Ada.Text_IO.Get_Line); 
        
      Cnt(D) := Cnt(D)+1;
      Sum := Sum + 1;
   end loop;
   Ada.Text_IO.Put_Line(" Digit  Found[total]   Expected[total]    Found[%]" 
                                          & "   Expected[%]   Difference[%]");
   for I in Nonzero_Digit loop
      Print(I, Cnt(I), Sum);
      Ada.Text_IO.New_Line;
   end loop;
end Benford;
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))





Ada: with Ada.Text_IO;
with Ada.Numerics.Generic_Elementary_Functions;

procedure Almost_Integers is

   type Real is new Long_Long_Float;

   package Real_IO is
      new Ada.Text_IO.Float_IO (Real);
   package Integer_IO is
      new Ada.Text_IO.Integer_IO (Integer);

   function Faculty (N : in Long_Long_Integer) return Long_Long_Integer is
      (if N < 2 then N else N * Faculty (N - 1));

   function Hickerson (N : in Integer) return Real
   is
      package Math is
         new Ada.Numerics.Generic_Elementary_Functions (Real);
      LN2         : constant Real := Math.Log (2.0, Base => Ada.Numerics.E);
      Numerator   : constant Real := Real (Faculty (Long_Long_Integer (N)));
      Denominator : constant Real := 2.0 * LN2 ** (N + 1);
   begin
      return Numerator / Denominator;
   end Hickerson;

   function Is_Almost_Integer (N : Real) return Boolean is
      Image : String (1 .. 100);
   begin
      Real_IO.Put (Image, N, Exp => 0, Aft => 2);

      pragma Assert (Image (Image'Last - 2) = '.');
      case Image (Image'Last - 1) is
         when '0' | '9' =>  return True;
         when others    =>  return False;
      end case;
   end Is_Almost_Integer;

   use Ada.Text_IO;
   Placeholder : String := " n                         h(n)  almost";
   Image_N : String renames Placeholder ( 1 ..  2);
   Image_H : String renames Placeholder ( 4 .. 31);
   Image_A : String renames Placeholder (34 .. 39);
begin
   Put_Line (Placeholder);
   Image_N := (others => '-');
   Image_H := (others => '-');
   Image_A := (others => '-');
   Put_Line (Placeholder);

   for N in 1 .. 17 loop
      declare
         H : constant Real    := Hickerson (N);
         I : constant Boolean := Is_Almost_Integer (H);
      begin
         Integer_IO.Put (Image_N, N);
         Real_IO.Put (Image_H, H, Exp => 0, Aft => 4);
         Image_A := (if I then "TRUE " else "FALSE");
         Put_Line (Placeholder);
      end;
   end loop;
end Almost_Integers;
Task: Read a configuration file







Python: def readconf(fn):
    ret = {}
    with file(fn) as fp:
        for line in fp:
            
            line = line.strip()
            if not line or line.startswith('
            
            boolval = True
            
            if line.startswith(';'):
                
                line = line.lstrip(';')
                
                if len(line.split()) != 1: continue
                boolval = False
            
            bits = line.split(None, 1)
            if len(bits) == 1:
                
                k = bits[0]
                v = boolval
            else:
                
                k, v = bits
            ret[k.lower()] = v
    return ret


if __name__ == '__main__':
    import sys
    conf = readconf(sys.argv[1])
    for k, v in sorted(conf.items()):
        print k, '=', v





Ada: with Config; use Config;
with Ada.Text_IO; use Ada.Text_IO;

procedure Rosetta_Read_Cfg is
  cfg: Configuration:= Init("rosetta_read.cfg", Case_Sensitive => False, Variable_Terminator => ' ');
  fullname       : String  := cfg.Value_Of("*", "fullname");
  favouritefruit : String  := cfg.Value_Of("*", "favouritefruit");
  needspeeling   : Boolean := cfg.Is_Set("*", "needspeeling");
  seedsremoved   : Boolean := cfg.Is_Set("*", "seedsremoved");
  otherfamily    : String  := cfg.Value_Of("*", "otherfamily");
begin
  Put_Line("fullname = "       & fullname);
  Put_Line("favouritefruit = " & favouritefruit);
  Put_Line("needspeeling = "   & Boolean'Image(needspeeling));
  Put_Line("seedsremoved = "   & Boolean'Image(seedsremoved));
  Put_Line("otherfamily = "    & otherfamily);
end;