Recently I was looking for libraries to write to the serial port on Linux machines so that I could simulate a KVM switch. The PySerial package comes very useful here.
Some examples borrowed from online tutorials and reposted here:
also we can optimize the above by removing the inner iterations because they are already sorted and cmax or rmax can be picked and compared.
Some examples borrowed from online tutorials and reposted here:
import time
import serial
# configure the serial connections (the parameters differs on the device you are connecting to)
ser = serial.Serial(
port='/dev/ttyUSB1',
baudrate=9600,
parity=serial.PARITY_ODD,
stopbits=serial.STOPBITS_TWO,
bytesize=serial.SEVENBITS
)
ser.isOpen()
print 'Enter your commands below.\r\nInsert "exit" to leave the application.'
input=1
while 1 :
# get keyboard input
input = raw_input(">> ")
if input == 'exit':
ser.close()
exit()
else:
ser.write(input + '\r\n')
out = ''
time.sleep(1)
while ser.inWaiting() > 0:
out += ser.read(1)
if out != '':
print ">>" + out
We could also talk to a DRAC card.
#codingexercise:
static int GetKthLargest(int[,] A, int row, int col, int k)
{
int r = row-1;
int c = col-1;
int prev = r * col + c;
if (k <= 0 || k > prev) return -1;
if (k <= 0 || k > prev) return -1;
int count = 0;
while ( count < k)
{
// compare left and top and increment r or c
// the idea is that the k largest elements will be a contiguous block
// and the next element for inclusion will be either to the left of this block or
// on the top of this block
// we just need to propagate the front on all rows one cell at a time.
int m = r;
int n = c;
int rselected = r*col + c; // position of selected on top
int cselected = r*col + c; // position of selected at left
if (count + 1 == k) return A[r,c];
int rmax = Int16.MinValue; // max value on top
int cmax = Int16.MinValue; // max value at left
for (int j = n ; j < col && m > 0; j++ )
{
if ( A[m-1, j] > cmax){
rselected = (m-1)*col+j;
cmax = A[m-1,j];
}else break;
}
for (int i = row-1; i >= m && n > 0; i--)
{
if ( A[i, n-1] > rmax){
cselected = i*col+n-1;
rmax = A[i, n-1];
}else break;
}
if (cmax > rmax)
{
r = rselected/col;
c = rselected%col;
}else{
r = cselected/col;
c = cselected%col;
}
if ((r+1)*col + c == prev)
{
prev = r*col + c;
row--;
}
count++;
}
return A[r,c];
}
class Program { static void Main(string[] args)
{
var A = new int [4, 4] {{10, 13, 15, 19 }, {21, 23, 24, 27}, {29, 31, 33, 37}, {41, 43, 45, 47}};
for (int k = 1; k < 17; k++)
{
Console.WriteLine("K={0},Value={1}", k, GetKthLargest(A, 4, 4, k));
}
}
}
}
}
K=1,Value=47
K=2,Value=45
K=3,Value=43
K=4,Value=41
K=5,Value=37
K=6,Value=33
K=7,Value=31
K=8,Value=29
K=9,Value=27
K=10,Value=24
K=11,Value=23
K=12,Value=21
K=13,Value=19
K=14,Value=15
K=15,Value=13
K=16,Value=10
also we can optimize the above by removing the inner iterations because they are already sorted and cmax or rmax can be picked and compared.
No comments:
Post a Comment