WeixiangYan/CodeTransOcean huggingface dataset:
Task: Smarandache prime-digital sequence





Java: public class SmarandachePrimeDigitalSequence {

    public static void main(String[] args) {
        long s = getNextSmarandache(7);
        System.out.printf("First 25 Smarandache prime-digital sequence numbers:%n2 3 5 7 ");
        for ( int count = 1 ; count <= 21 ; s = getNextSmarandache(s) ) {
            if ( isPrime(s) ) {
                System.out.printf("%d ", s);
                count++;
            }
        }
        System.out.printf("%n%n");
        for (int i = 2 ; i <=5 ; i++ ) {
            long n = (long) Math.pow(10, i);
            System.out.printf("%,dth Smarandache prime-digital sequence number = %d%n", n, getSmarandachePrime(n));
        }
    }
    
    private static final long getSmarandachePrime(long n) {
        if ( n < 10 ) {
            switch ((int) n) {
            case 1:  return 2;
            case 2:  return 3;
            case 3:  return 5;
            case 4:  return 7;
            }
        }
        long s = getNextSmarandache(7);
        long result = 0;
        for ( int count = 1 ; count <= n-4 ; s = getNextSmarandache(s) ) {
            if ( isPrime(s) ) {
                count++;
                result = s;
            }
        }
        return result;
    }
    
    private static final boolean isPrime(long test) {
        if ( test % 2 == 0 ) return false;
        for ( long i = 3 ; i <= Math.sqrt(test) ; i += 2 ) {
            if ( test % i == 0 ) {
                return false;
            }
        }
        return true;
    }

    private static long getNextSmarandache(long n) {
        
        if ( n % 10 == 3 ) {
            return n+4;
        }
        long retVal = n-4;
        
        
        int k = 0;
        while ( n % 10 == 7 ) {
            k++;
            n /= 10;
        }
        
        
        long digit = n % 10;

        
        long coeff = (digit == 2 ? 1 : 2);
        
        
        retVal += coeff * Math.pow(10, k);
        
        
        while ( k > 1 ) {
            retVal -= 5 * Math.pow(10, k-1);
            k--;
        }
        
        
        return retVal;
    }

}



Python: def divisors(n):
    divs = [1]
    for ii in range(2, int(n ** 0.5) + 3):
        if n % ii == 0:
            divs.append(ii)
            divs.append(int(n / ii))
    divs.append(n)
    return list(set(divs))


def is_prime(n):
    return len(divisors(n)) == 2


def digit_check(n):
    if len(str(n))<2:
        return True
    else:
        for digit in str(n):
            if not is_prime(int(digit)):
                return False
        return True


def sequence(max_n=None):
    ii = 0
    n = 0
    while True:
        ii += 1
        if is_prime(ii):
            if max_n is not None:
                if n>max_n:
                    break
            if digit_check(ii):
                n += 1
                yield ii


if __name__ == '__main__':
    generator = sequence(100)
    for index, item in zip(range(1, 16), generator):
        print(index, item)
    for index, item in zip(range(16, 100), generator):
        pass
    print(100, generator.__next__())
Task: Quickselect algorithm





Java: import java.util.Random;

public class QuickSelect {

	private static <E extends Comparable<? super E>> int partition(E[] arr, int left, int right, int pivot) {
		E pivotVal = arr[pivot];
		swap(arr, pivot, right);
		int storeIndex = left;
		for (int i = left; i < right; i++) {
			if (arr[i].compareTo(pivotVal) < 0) {
				swap(arr, i, storeIndex);
				storeIndex++;
			}
		}
		swap(arr, right, storeIndex);
		return storeIndex;
	}
	
	private static <E extends Comparable<? super E>> E select(E[] arr, int n) {
		int left = 0;
		int right = arr.length - 1;
		Random rand = new Random();
		while (right >= left) {
			int pivotIndex = partition(arr, left, right, rand.nextInt(right - left + 1) + left);
			if (pivotIndex == n) {
				return arr[pivotIndex];
			} else if (pivotIndex < n) {
				left = pivotIndex + 1;
			} else {
				right = pivotIndex - 1;
			}
		}
		return null;
	}
	
	private static void swap(Object[] arr, int i1, int i2) {
		if (i1 != i2) {
			Object temp = arr[i1];
			arr[i1] = arr[i2];
			arr[i2] = temp;
		}
	}
	
	public static void main(String[] args) {
		for (int i = 0; i < 10; i++) {
			Integer[] input = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};
			System.out.print(select(input, i));
			if (i < 9) System.out.print(", ");
		}
		System.out.println();
	}

}



Python: import random

def partition(vector, left, right, pivotIndex):
    pivotValue = vector[pivotIndex]
    vector[pivotIndex], vector[right] = vector[right], vector[pivotIndex]  
    storeIndex = left
    for i in range(left, right):
        if vector[i] < pivotValue:
            vector[storeIndex], vector[i] = vector[i], vector[storeIndex]
            storeIndex += 1
    vector[right], vector[storeIndex] = vector[storeIndex], vector[right]  
    return storeIndex

def _select(vector, left, right, k):
    "Returns the k-th smallest, (k >= 0), element of vector within vector[left:right+1] inclusive."
    while True:
        pivotIndex = random.randint(left, right)     
        pivotNewIndex = partition(vector, left, right, pivotIndex)
        pivotDist = pivotNewIndex - left
        if pivotDist == k:
            return vector[pivotNewIndex]
        elif k < pivotDist:
            right = pivotNewIndex - 1
        else:
            k -= pivotDist + 1
            left = pivotNewIndex + 1

def select(vector, k, left=None, right=None):
    
    if left is None:
        left = 0
    lv1 = len(vector) - 1
    if right is None:
        right = lv1
    assert vector and k >= 0, "Either null vector or k < 0 "
    assert 0 <= left <= lv1, "left is out of range"
    assert left <= right <= lv1, "right is out of range"
    return _select(vector, left, right, k)

if __name__ == '__main__':
    v = [9, 8, 7, 6, 5, 0, 1, 2, 3, 4]
    print([select(v, i) for i in range(10)])
Task: Non-decimal radices_Convert





Java: public static long backToTen(String num, int oldBase){
   return Long.parseLong(num, oldBase); 
}

public static String tenToBase(long num, int newBase){
   return Long.toString(num, newBase);
}



Python: i = int('1a',16)
Task: Walk a directory_Recursively





Java: import java.io.File;

public class MainEntry {
    public static void main(String[] args) {
        walkin(new File("/home/user")); 
    }
    
    
    public static void walkin(File dir) {
        String pattern = ".mp3";
        
        File listFile[] = dir.listFiles();
        if (listFile != null) {
            for (int i=0; i<listFile.length; i++) {
                if (listFile[i].isDirectory()) {
                    walkin(listFile[i]);
                } else {
                    if (listFile[i].getName().endsWith(pattern)) {
                        System.out.println(listFile[i].getPath());
                    }
                }
            }
        }
    }
}



Python: from pathlib import Path

for path in Path('.').rglob('*.*'):
    print(path)
Task: CRC-32





Java: import java.util.zip.* ;

public class CRCMaker {
   public static void main( String[ ] args ) {
      String toBeEncoded = new String( "The quick brown fox jumps over the lazy dog" ) ;
      CRC32 myCRC = new CRC32( ) ;
      myCRC.update( toBeEncoded.getBytes( ) ) ;
      System.out.println( "The CRC-32 value is : " + Long.toHexString( myCRC.getValue( ) ) + " !" ) ;
   }
}



Python: >>> s = 'The quick brown fox jumps over the lazy dog'
>>> import zlib
>>> hex(zlib.crc32(s))
'0x414fa339'

>>> import binascii
>>> hex(binascii.crc32(s))
'0x414fa339'
Task: CSV to HTML translation





Java: 

grammar csv2html;
dialog : {System.out.println("<HTML><Table>");}header body+{System.out.println("</Table></HTML>");} ;
header : {System.out.println("<THEAD align=\"center\"><TR bgcolor=\"blue\">");}row{System.out.println("</TR></THEAD");};
body   : {System.out.println("<TBODY><TR>");}row{System.out.println("</TR></TBODY");};
row    : field ',' field '\r'? '\n';
field  : Field{System.out.println("<TD>" + $Field.text.replace("<","&lt;").replace(">","&gt;") + "</TD>");};
Field  : ~[,\n\r]+;



Python: csvtxt = 

from cgi import escape

def _row2tr(row, attr=None):
    cols = escape(row).split(',')
    return ('<TR>'
            + ''.join('<TD>%s</TD>' % data for data in cols)
            + '</TR>')

def csv2html(txt):
    htmltxt = '<TABLE summary="csv2html program output">\n'
    for rownum, row in enumerate(txt.split('\n')):
        htmlrow = _row2tr(row)
        htmlrow = '  <TBODY>%s</TBODY>\n' % htmlrow
        htmltxt += htmlrow
    htmltxt += '</TABLE>\n'
    return htmltxt

htmltxt = csv2html(csvtxt)
print(htmltxt)
Task: Classes





Java: public class MyClass{

  
  private int variable;  

  
  public MyClass(){
    
  }

  
  public void someMethod(){
   this.variable = 1;
  }
}



Python: class MyClass:
    name2 = 2 

    def __init__(self):
        
        self.name1 = 0 
  
    def someMethod(self):
        
        self.name1 = 1
        MyClass.name2 = 3
  
  
myclass = MyClass() 

class MyOtherClass:
    count = 0  
    def __init__(self, name, gender="Male", age=None):
        
        MyOtherClass.count += 1
        self.name = name
        self.gender = gender
        if age is not None:
            self.age = age
    def __del__(self):
        MyOtherClass.count -= 1

person1 = MyOtherClass("John")
print person1.name, person1.gender  
print person1.age                   
person2 = MyOtherClass("Jane", "Female", 23)
print person2.name, person2.gender, person2.age
Task: Kaprekar numbers





Java: public class Kaprekar {
    private static String[] splitAt(String str, int idx){
        String[] ans = new String[2];
        ans[0] = str.substring(0, idx);
        if(ans[0].equals("")) ans[0] = "0"; 
        ans[1] = str.substring(idx);
        return ans;
    }
        
    public static void main(String[] args){
        int count = 0;
        int base = (args.length > 0) ? Integer.parseInt(args[0]) : 10;
        for(long i = 1; i <= 1000000; i++){
            String sqrStr = Long.toString(i * i, base);
            for(int j = 0; j < sqrStr.length() / 2 + 1; j++){
                String[] parts = splitAt(sqrStr, j);
                long firstNum = Long.parseLong(parts[0], base);
                long secNum = Long.parseLong(parts[1], base);
                
                if(secNum == 0) break;
                if(firstNum + secNum == i){
                    System.out.println(i + "\t" + Long.toString(i, base) +
                            "\t" + sqrStr + "\t" + parts[0] + " + " + parts[1]);
                    count++;
                    break;
                }
            }
        }
        System.out.println(count + " Kaprekar numbers < 1000000 (base 10) in base "+base);
    }
}



Python: >>> def k(n):
	n2 = str(n**2)
	for i in range(len(n2)):
		a, b = int(n2[:i] or 0), int(n2[i:])
		if b and a + b == n:
			return n
			

		
>>> [x for x in range(1,10000) if k(x)]
[1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999]
>>> len([x for x in range(1,1000000) if k(x)])
54
>>>
Task: Hofstadter Figure-Figure sequences





Java: import java.util.*;

class Hofstadter
{
  private static List<Integer> getSequence(int rlistSize, int slistSize)
  {
    List<Integer> rlist = new ArrayList<Integer>();
    List<Integer> slist = new ArrayList<Integer>();
    Collections.addAll(rlist, 1, 3, 7);
    Collections.addAll(slist, 2, 4, 5, 6);
    List<Integer> list = (rlistSize > 0) ? rlist : slist;
    int targetSize = (rlistSize > 0) ? rlistSize : slistSize;
    while (list.size() > targetSize)
      list.remove(list.size() - 1);
    while (list.size() < targetSize)
    {
      int lastIndex = rlist.size() - 1;
      int lastr = rlist.get(lastIndex).intValue();
      int r = lastr + slist.get(lastIndex).intValue();
      rlist.add(Integer.valueOf(r));
      for (int s = lastr + 1; (s < r) && (list.size() < targetSize); s++)
        slist.add(Integer.valueOf(s));
    }
    return list;
  }
  
  public static int ffr(int n)
  {  return getSequence(n, 0).get(n - 1).intValue();  }
  
  public static int ffs(int n)
  {  return getSequence(0, n).get(n - 1).intValue();  }
  
  public static void main(String[] args)
  {
    System.out.print("R():");
    for (int n = 1; n <= 10; n++)
      System.out.print(" " + ffr(n));
    System.out.println();
    
    Set<Integer> first40R = new HashSet<Integer>();
    for (int n = 1; n <= 40; n++)
      first40R.add(Integer.valueOf(ffr(n)));
      
    Set<Integer> first960S = new HashSet<Integer>();
    for (int n = 1; n <= 960; n++)
      first960S.add(Integer.valueOf(ffs(n)));
    
    for (int i = 1; i <= 1000; i++)
    {
      Integer n = Integer.valueOf(i);
      if (first40R.contains(n) == first960S.contains(n))
        System.out.println("Integer " + i + " either in both or neither set");
    }
    System.out.println("Done");
  }
}



Python: def ffr(n):
    if n < 1 or type(n) != int: raise ValueError("n must be an int >= 1")
    try:
        return ffr.r[n]
    except IndexError:
        r, s = ffr.r, ffs.s
        ffr_n_1 = ffr(n-1)
        lastr = r[-1]
        
        s += list(range(s[-1] + 1, lastr))
        if s[-1] < lastr: s += [lastr + 1]
        
        len_s = len(s)
        ffs_n_1 = s[n-1] if len_s > n else (n - len_s) + s[-1]
        ans = ffr_n_1 + ffs_n_1
        r.append(ans)
        return ans
ffr.r = [None, 1]

def ffs(n):
    if n < 1 or type(n) != int: raise ValueError("n must be an int >= 1")
    try:
        return ffs.s[n]
    except IndexError:
        r, s = ffr.r, ffs.s
        for i in range(len(r), n+2):
            ffr(i)
            if len(s) > n:
                return s[n]
        raise Exception("Whoops!")
ffs.s = [None, 2]

if __name__ == '__main__':
    first10 = [ffr(i) for i in range(1,11)]
    assert first10 == [1, 3, 7, 12, 18, 26, 35, 45, 56, 69], "ffr() value error(s)"
    print("ffr(n) for n = [1..10] is", first10)
    
    bin = [None] + [0]*1000
    for i in range(40, 0, -1):
        bin[ffr(i)] += 1
    for i in range(960, 0, -1):
        bin[ffs(i)] += 1
    if all(b == 1 for b in bin[1:1000]):
        print("All Integers 1..1000 found OK")
    else:
        print("All Integers 1..1000 NOT found only once: ERROR")
Task: Magic squares of odd order





Java: public class MagicSquare {

    public static void main(String[] args) {
        int n = 5;
        for (int[] row : magicSquareOdd(n)) {
            for (int x : row)
                System.out.format("%2s ", x);
            System.out.println();
        }
        System.out.printf("\nMagic constant: %d ", (n * n + 1) * n / 2);
    }

    public static int[][] magicSquareOdd(final int base) {
        if (base % 2 == 0 || base < 3)
            throw new IllegalArgumentException("base must be odd and > 2");

        int[][] grid = new int[base][base];
        int r = 0, number = 0;
        int size = base * base;

        int c = base / 2;
        while (number++ < size) {
            grid[r][c] = number;
            if (r == 0) {
                if (c == base - 1) {
                    r++;
                } else {
                    r = base - 1;
                    c++;
                }
            } else {
                if (c == base - 1) {
                    r--;
                    c = 0;
                } else {
                    if (grid[r - 1][c + 1] == 0) {
                        r--;
                        c++;
                    } else {
                        r++;
                    }
                }
            }
        }
        return grid;
    }
}



Python: >>> def magic(n):
    for row in range(1, n + 1):
        print(' '.join('%*i' % (len(str(n**2)), cell) for cell in
                       (n * ((row + col - 1 + n // 2) % n) +
                       ((row + 2 * col - 2) % n) + 1
                       for col in range(1, n + 1))))
    print('\nAll sum to magic number %i' % ((n * n + 1) * n // 2))

    
>>> for n in (5, 3, 7):
	print('\nOrder %i\n=======' % n)
	magic(n)

	

Order 5
=======
17 24  1  8 15
23  5  7 14 16
 4  6 13 20 22
10 12 19 21  3
11 18 25  2  9

All sum to magic number 65

Order 3
=======
8 1 6
3 5 7
4 9 2

All sum to magic number 15

Order 7
=======
30 39 48  1 10 19 28
38 47  7  9 18 27 29
46  6  8 17 26 35 37
 5 14 16 25 34 36 45
13 15 24 33 42 44  4
21 23 32 41 43  3 12
22 31 40 49  2 11 20

All sum to magic number 175
>>>
Task: Order by pair comparisons





Java: import java.util.*;

public class SortComp1 {
    public static void main(String[] args) {
        List<String> items = Arrays.asList("violet", "red", "green", "indigo", "blue", "yellow", "orange");
        List<String> sortedItems = new ArrayList<>();
        Comparator<String> interactiveCompare = new Comparator<String>() {
                int count = 0;
                Scanner s = new Scanner(System.in);
                public int compare(String s1, String s2) {
                    System.out.printf("(%d) Is %s <, =, or > %s. Answer -1, 0, or 1: ", ++count, s1, s2);
                    return s.nextInt();
                }
            };
        for (String item : items) {
            System.out.printf("Inserting '%s' into %s\n", item, sortedItems);
            int spotToInsert = Collections.binarySearch(sortedItems, item, interactiveCompare);
            
            
            if (spotToInsert < 0) spotToInsert = ~spotToInsert;
            sortedItems.add(spotToInsert, item);
        }
        System.out.println(sortedItems);
    }
}



Python: def _insort_right(a, x, q):
    

    lo, hi = 0, len(a)
    while lo < hi:
        mid = (lo+hi)//2
        q += 1
        less = input(f"{q:2}: IS {x:>6} LESS-THAN {a[mid]:>6} ? y/n: ").strip().lower() == 'y'
        if less: hi = mid
        else: lo = mid+1
    a.insert(lo, x)
    return q

def order(items):
    ordered, q = [], 0
    for item in items:
        q = _insort_right(ordered, item, q)
    return ordered, q

if __name__ == '__main__':
    items = 'violet red green indigo blue yellow orange'.split()
    ans, questions = order(items)
    print('\n' + ' '.join(ans))
Task: Benford's law





Java: import java.math.BigInteger;
import java.util.Locale;

public class BenfordsLaw {

    private static BigInteger[] generateFibonacci(int n) {
        BigInteger[] fib = new BigInteger[n];
        fib[0] = BigInteger.ONE;
        fib[1] = BigInteger.ONE;
        for (int i = 2; i < fib.length; i++) {
            fib[i] = fib[i - 2].add(fib[i - 1]);
        }
        return fib;
    }

    public static void main(String[] args) {
        BigInteger[] numbers = generateFibonacci(1000);

        int[] firstDigits = new int[10];
        for (BigInteger number : numbers) {
            firstDigits[Integer.valueOf(number.toString().substring(0, 1))]++;
        }

        for (int i = 1; i < firstDigits.length; i++) {
            System.out.printf(Locale.ROOT, "%d %10.6f %10.6f%n",
                    i, (double) firstDigits[i] / numbers.length, Math.log10(1.0 + 1.0 / i));
        }
    }
}



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))
Task: Nautical bell





Java: import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.TimeZone;

public class NauticalBell extends Thread {

    public static void main(String[] args) {
        NauticalBell bells = new NauticalBell();
        bells.setDaemon(true);
        bells.start();
        try {
            bells.join();
        } catch (InterruptedException e) {
            System.out.println(e);
        }
    }

    @Override
    public void run() {
        DateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

        int numBells = 0;
        long time = System.currentTimeMillis();
        long next = time - (time % (24 * 60 * 60 * 1000)); 

        while (next < time) {
            next += 30 * 60 * 1000; 
            numBells = 1 + (numBells % 8);
        }

        while (true) {
            long wait = 100L;
            time = System.currentTimeMillis();
            if (time - next >= 0) {
                String bells = numBells == 1 ? "bell" : "bells";
                String timeString = sdf.format(time);
                System.out.printf("%s : %d %s\n", timeString, numBells, bells);
                next += 30 * 60 * 1000;
                wait = next - time;
                numBells = 1 + (numBells % 8);
            }
            try {
                Thread.sleep(wait);
            } catch (InterruptedException e) {
                return;
            }
        }
    }
}



Python: import time, calendar, sched, winsound

duration = 750      
freq = 1280         
bellchar = "\u2407"
watches = 'Middle,Morning,Forenoon,Afternoon,First/Last dog,First'.split(',')

def gap(n=1):
    time.sleep(n * duration / 1000)
off = gap
 
def on(n=1):
    winsound.Beep(freq, n * duration)
 
def bong():
    on(); off(0.5)

def bongs(m):
    for i in range(m):
        print(bellchar, end=' ')
        bong()
        if i % 2:
            print('  ', end='')
            off(0.5)
    print('')
        
scheds =  sched.scheduler(time.time, time.sleep)

def ships_bell(now=None):
    def adjust_to_half_hour(atime):
        atime[4] = (atime[4] // 30) * 30
        atime[5] = 0
        return atime

    debug = now is not None
    rightnow = time.gmtime()
    if not debug:
        now = adjust_to_half_hour( list(rightnow) )
    then = now[::]
    then[4] += 30
    hr, mn = now[3:5]
    watch, b = divmod(int(2 * hr + mn // 30 - 1), 8)
    b += 1
    bells = '%i bell%s' % (b, 's' if b > 1 else ' ')
    if debug:
        print("%02i:%02i, %-20s %s" % (now[3], now[4], watches[watch] + ' watch', bells), end=' ')
    else:
        print("%02i:%02i, %-20s %s" % (rightnow[3], rightnow[4], watches[watch] + ' watch', bells), end=' ')
    bongs(b)
    if not debug:
        scheds.enterabs(calendar.timegm(then), 0, ships_bell)
        
        scheds.run()

def dbg_tester():
    for h in range(24):
        for m in (0, 30):
            if (h,m) == (24,30): break
            ships_bell( [2013, 3, 2, h, m, 15, 5, 61, 0] )
        
    
if __name__ == '__main__':
    ships_bell()
Task: Anonymous recursion





Java: public static long fib(int n) {
    if (n < 0)
        throw new IllegalArgumentException("n can not be a negative number");

    return new Object() {
        private long fibInner(int n) {
            return (n < 2) ? n : (fibInner(n - 1) + fibInner(n - 2));
        }
    }.fibInner(n);
}



Python: >>> Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args)))
>>> fib = lambda f: lambda n: None if n < 0 else (0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2)))
>>> [ Y(fib)(i) for i in range(-2, 10) ]
[None, None, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Task: Substring_Top and tail





Java: String strOrig = 'brooms';
String str1 = strOrig.substring(1, strOrig.length());
system.debug(str1);
String str2 = strOrig.substring(0, strOrig.length()-1);
system.debug(str2);
String str3 = strOrig.substring(1, strOrig.length()-1);
system.debug(str3);


String strOrig = 'brooms';
String str1 = strOrig.replaceAll( '^.', '' );
system.debug(str1);
String str2 = strOrig.replaceAll( '.$', '' ) ;
system.debug(str2);
String str3 = strOrig.replaceAll( '^.|.$', '' );
system.debug(str3);



Python: print "knight"[1:]     
print "socks"[:-1]     
print "brooms"[1:-1]