Thursday, December 1, 2016


Stateless versus Stateful APIs:
Stateless API:
  def cmd_execute(cmds):
        import shlex, subprocess
        from threading import Timer
        from subprocess import Popen, PIPE
        args = shlex.split(cmds[0])
        print(args)
        process = subprocess.Popen(args, stdin = subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        kill_proc = lambda p: p.kill()
        timer = Timer(10, kill_proc, [process])
        output = ''
        try:
          timer.start()
          for i in range (1,len(cmds)):
             process.stdin.write(str.encode(cmds[i]))
          output, stderr = process.communicate()
          output = output.decode('utf-8')
        finally:
          timer.cancel()
        return output
Stateful API:
import pexpect
global c
c = None
def cmd_execute(cmds):
    global c
    if  c == None:
        c = pexpect.spawn ('/usr/bin/python')
        c.expect('>>>')
    count = 0
    output = ''
    for cmd in cmds:
        #print('cmd='+cmd)
        c.sendline(cmd)
        c.expect ('.+')
        print(c.after)
        output += c.after
    c.sendline()
    c.expect('.+')
    print(c.after)
    return output
output = cmd_execute(["a='hello'", "a"])
#print(output)
print('c='+repr(c))
output = cmd_execute(["b='world'", "b"])
#print(output)
print('c='+repr(c))
output = cmd_execute(["c=a+b", "c"])
#print(output)
print('c='+repr(c))
"""

a='hello'
>>>
a
'hello'
>>>
c=<pexpect.pty_spawn.spawn object at 0x7f0728dbbcd0>

>>>
b='world'
>>>
b
'world'
>>>

c=<pexpect.pty_spawn.spawn object at 0x7f0728dbbcd0>
>>> c=a+b

>>> c

'helloworld'
>>>

c=<pexpect.pty_spawn.spawn object at 0x7f0728dbbcd0>

"""

#codingexercise
Find the lexicographic minimum rotation of a string
The trick is that for most rotations we just concatenate the string with itself to find all possible rotations as substrings Then we can linearly search for the minimum.
String MinRotation(String input)
{
String min = input;
var concatenated = input + input;
for (int i = 0; i < input.Length; i++)
     var select = input.substring(i,n);
     if (select < min)
         min = select;
return min;
}
Finding the maximum is similarly straightforwardly linear with greater than comparision
if we were to group different rotations by their occurence then  we can use a hashtable
Also a few more exercises: https://1drv.ms/w/s!Ashlm-Nw-wnWljZZqmcHRUZNx9PF
int fib(int n)
{
if (n <= 0) return 0;
if (n == 1) return 1;
if (n == 2) return 1;
return fib(n-1) +fib(n-2);
}

No comments:

Post a Comment