tosay.net
BAN USERPython working code.
Output of the OP's sample missing a 'l', should be:
abcdef; lmnop; tuvwxyz
"""
12:10
@Python 2.7
Print continuous alphabets from a sequence of arbitrary alphabets
For example:
Input: abcdefljdflsjflmnopflsjflasjftuvwxyz
Output: abcdef; mnop; tuvwxyz
Input: AbcDefljdflsjflmnopflsjflasjftuvWxYz
Output: abcdef; mnop; tuvwxyz
- Anony on February 02, 2012 in United States Report Duplicate | Flag
"""
class CountiA(object):
def __init__(self, inputs):
if inputs is None:
print 'invalid inputs'
raise SystemExit
self._inputs = inputs
def findSeq(self):
output = []
tmp = [self._inputs[0].lower()]
lastChar = self._inputs[0].lower()
for i in range(1, len(self._inputs)):
if ord(self._inputs[i].lower()) - ord(lastChar) == 1:
lastChar = self._inputs[i].lower()
tmp.append(self._inputs[i].lower())
else:
if len(tmp) > 1:
output.append(''.join(tmp))
tmp = [self._inputs[i].lower()]
lastChar = self._inputs[i].lower()
if len(tmp) > 1:
output.append(''.join(tmp))
return '; '.join(output)
if __name__ == '__main__':
ca = CountiA('abcdefljdflsjflmnopflsjflasjftuvwxyz')
print ca.findSeq()
ca = CountiA('AbcDefljdflsjflmnopflsjflasjftuvWxYz')
print ca.findSeq()
Python working code. didn't take repeat number into consideration ..
"""
11:33
@Python 2.7
write a program in c# or java or c that prints saddle points in a N by N Matrix.
saddle point is nothing but a cell values which has greater value among all the cell values in that row as well as it should be the smallest value among the column in which it is found......???
- vamcrulz09 on February 19, 2012 in United States Report Duplicate | Flag
Max in row, Min in col
"""
class SaddlePoint(object):
def __init__(self, matrix):
if matrix is None:
print 'invalid matrix'
raise SystemExit
self._matrix = matrix
def getSaddle(self):
rowMax = []
colMin = []
output = []
# find max in each row
for i in range(len(self._matrix)):
curMax = self._matrix[i][0]
rowMax.append([i, 0])
for j in range(len(self._matrix[i])):
if self._matrix[i][j] > curMax:
curMax = self._matrix[i][j]
rowMax.pop()
rowMax.append([i, j])
# find min in each col
for i in range(len(self._matrix[0])):
curMin = self._matrix[0][i]
colMin.append([0, i])
for j in range(len(self._matrix)):
if self._matrix[j][i] < curMin:
curMin = self._matrix[j][i]
colMin.pop()
colMin.append([j, i])
# print rowMax
# print colMin
#find all the Saddle Point
for c in rowMax:
if c in colMin:
output.append(c)
return output
if __name__ == '__main__':
s = SaddlePoint([[4,5,6],
[1,3,9],
[7,8,7],
[10,11,12]
])
print s.getSaddle()
Python working code.
"""
9:15
@Python 2.7
replace a to one
- Anonymous on May 25, 2010 Report Duplicate | Flag
"""
class AtoOne(object):
def __init__(self, inputs):
if inputs is None:
print 'Invalid inputs'
raise SystemExit
self._inputs = inputs
def __repr__(self):
return self._inputs
def replace(self, fromChar, toChar):
output = self._inputs.split()
for i in range(len(output)):
if output[i] == fromChar:
output[i] = toChar
else:
continue
self._inputs = ' '.join(output)
if __name__ == '__main__':
sen = AtoOne('A quick brown fox jumped over a bridge on a box. ')
sen.replace('a', 'one')
sen.replace('A', 'One')
print sen
Python working code.
"""
8:45
@Python 2.7
There is a security keypad at the entrance of a building. It has 9 numbers 1 - 9 in a 3x3 matrix format.
1 2 3
4 5 6
7 8 9
The security has decided to allow one digit error for a person but that digit should be horizontal or vertical.
Example: for 5 the user is allowed to enter 2, 4, 6, 8 or for 4 the user is allowed to enter 1, 5, 7. IF the security code to enter is 1478 and if the user enters 1178 he should be allowed.
Write a function to take security code from the user and print out if he should be allowed or not
- Anonymous on May 25, 2010 Report Duplicate | Flag
"""
class SecurityCode(object):
def __init__(self, number = 1478):
if number is None:
print 'Invalid Inputs'
raise SystemExit
self._number = str(number)
self.matrix = [[1,2,3], [4,5,6], [7,8,9]]
def typoCheck(self, pos = None, num = None):
if pos is None or num is None:
return
correct = int(self._number[pos])
num = int(num)
if ((correct - 1) / 3 == (num - 1) / 3) or (abs(num - correct) % 3 == 0):
return True
return False
def validate(self, input):
input = str(input)
wrongPos = []
if len(input) != len(self._number):
print 'Invalid'
return False
for i in range(len(input)):
if self._number[i] != input[i]:
wrongPos.append(i)
if len(wrongPos) > 1:
print 'Invalid'
return False
elif len(wrongPos) == 1:
if self.typoCheck(wrongPos[0], input[wrongPos[0]]):
print 'Valid'
return True
else:
print 'Invalid'
return False
else:
print 'valid!'
return True
if __name__ == '__main__':
s = SecurityCode()
s.validate(1178)
Python working code.
"""
8:29
@Python 2.7
write a code of fibonacci series.
- sonali on August 03, 2010 Report Duplicate | Flag
"""
class Fbi(object):
def __init__(self, n):
if n is None:
print 'invalid n'
raise SystemExit
self._n = n
def find(self, number = None):
if number is None:
number = self._n
if number == 0:
return 0
elif number == 1:
return 1
else:
return self.find(number-1) + self.find(number-2)
if __name__ == '__main__':
f = Fbi(30)
print f.find()
Python working code.
"""
@Python 2.7
Given a string...replace all occurances of a with the.
eg. A quick brown fox jumped over a bridge on a box.
should change to
The quick brown fox jumped over the bridge on the box.
You cannot use the inbuilt replace function for string manipulation.
- Troy on October 07, 2010 Report Duplicate | Flag
"""
class AtoThe(object):
def __init__(self, inputs):
if inputs is None:
print 'invalid inputs'
self._input = inputs
def fromAToThe(self):
input = self._input.split()
output = []
for c in input:
if c == 'a':
output.append('the')
elif c == 'A':
output.append('The')
else:
output.append(c)
return ' '.join(output)
if __name__ == '__main__':
a = AtoThe('A quick brown fox jumped over a bridge on a box.')
print a.fromAToThe()
Python working code.
"""
6:13
@Python 2.7
write a program in c# or java or c
print the sequences from the input given by the user separated by semicolon
eg: 4678912356012356
output: 6789;123;56;0123;56;
- vamcrulz09 on February 19, 2012 in United States Report Duplicate | Flag
"""
class SemiSeq(object):
def __init__(self, inputs):
if inputs is None:
print 'Invalid Inputs'
raise SystemExit
self._inputs = str(inputs)
self._output = []
def __repr__(self):
return ';'.join(self._output)
def findSeq(self):
tmpOut = [self._inputs[0]]
lastNum = int(self._inputs[0])
i = 1
while i < len(self._inputs):
if int(self._inputs[i]) == lastNum + 1:
tmpOut.append(self._inputs[i])
lastNum = int(self._inputs[i])
i += 1
else:
if len(tmpOut) > 1:
self._output.append(''.join(tmpOut))
tmpOut = [self._inputs[i]]
lastNum = int(self._inputs[i])
i += 1
# terminate case special
if len(tmpOut) > 1:
self._output.append(''.join(tmpOut))
if __name__ == '__main__':
s = SemiSeq(4678912356012356)
s.findSeq()
print s
Python working code.
"""
6:00
@Python 2.7
Take a series of integers as input till a zero is entered. Among these given integers, find the maximum of the odd numbers and the minimum of the even integers (not including zero) and print them.
"""
class MaxOMinE(object):
def __init__(self, inputs):
if inputs is None:
print 'Invalid inputs'
raise SystemExit
self._inputs = inputs
self._maxOdd = None
self._minEven = None
def getResult(self):
for num in self._inputs:
# Terminate case
if num == 0:
print 'max odd: ', self._maxOdd
print 'min even: ', self._minEven
return
if num % 2 == 0: #even case
if self._minEven is None:
self._minEven = num
else:
if self._minEven > num:
self._minEven = num
else:
if self._maxOdd is None:
self._maxOdd = num
else:
if self._maxOdd < num:
self._maxOdd = num
# End of the inputs
print 'max odd: ', self._maxOdd
print 'min even: ', self._minEven
return
if __name__ == '__main__':
inputs = MaxOMinE([1,2,34,35,15])
inputs.getResult()
Python version, use Hash table and store subset as key, index as value.
"""
5:03
@Python 2.7
Verify if the given password is valid/invalid;
1. must be 5-12 characters long
2. must contain atleast one number and one lowercase character
3. a sequence must not be followed by the same sequence (like 123123qs is invalid, 123qs123 is valid)
- S.A.M on March 10, 2012 in United States Report Duplicate | Flag
"""
class VeriPwd(object):
def __init__(self, pwd):
if pwd is None:
print 'Invalid Passwod'
raise SystemExit
self._pwd = pwd
self._seq = {}
def validate(self):
lenFlag = False
numFlag = False
lowFlag = False
seqFlag = True
if 5 <= len(self._pwd) <= 12:
lenFlag = True
for c in self._pwd:
if '0' <= c <= '9':
numFlag = True
if 'a' <= c <= 'z':
lowFlag = True
seqFlag = self.checkSeq()
# print lenFlag, numFlag, lowFlag, seqFlag
return (lenFlag and numFlag and lowFlag and seqFlag)
def checkSeq(self, seqLen = 2):
if seqLen >= len(self._pwd) / 2 + 1:
return True
for i in range(len(self._pwd) - seqLen + 1):
if self._pwd[i:i+seqLen] not in self._seq:
self._seq[self._pwd[i:i+seqLen]] = [i+seqLen]
print 'excuted',self._pwd[i:i+seqLen], str(i+seqLen)
else:
if i in self._seq[self._pwd[i:i+seqLen]]:
return False
# print 'XXX at', self._seq[self._pwd[i:i+seqLen]]
else:
self._seq[self._pwd[i:i+seqLen]].append(i+seqLen)
# print 'insert at', self._seq[self._pwd[i:i+seqLen]]
return self.checkSeq(seqLen+1)
if __name__ == '__main__':
vp = VeriPwd('12qs12ad12')
print vp.validate()
print '--------------'
vp = VeriPwd('123123qs')
print vp.validate()
Working Python code, using recursion.
"""
3:40
@Python 2.7
Find all the possible passwords, given the length of the password and that it is a well ordered number (159 is well-ordered as 1<5<9)
- S.A.M on March 10, 2012 in United States Report Duplicate | Flag
"""
class IncPWD(object):
def __init__(self, n):
if n is None:
print 'Invalid N'
raise SystemExit
self._n = n
self._src = [str(x) for x in range(10)]
self._output = []
def findAll(self, pos = 0):
if len(self._output) == self._n:
print ''.join(self._output)
return
while pos < 10 - self._n + 1 + len(self._output):
self._output.append(self._src[pos])
self.findAll(pos + 1)
self._output.pop()
pos += 1
if __name__ == '__main__':
ip = IncPWD(4)
ip.findAll()
Python working code. correct me if you find bugs ;)
Algo: for each YYYY in range, reverse it and assign to MMDD, validate if MMDD is valid format. Also validate the special case on Feb in leap years.
"""
2:30
@Python 2.7
Write a program to generate all palindrome dates by taking the beginning and the ending dates as an input from the user. The format of the date is given as MMDDYYYY.
"""
class PaDates(object):
def __init__(self, startDates, endDates):
if startDates is None or endDates is None:
print 'Invalid Dates'
raise SystemExit
self._startDates = startDates
self._endDates = endDates
self._startYYYY = self._startDates[-4:]
self._endYYYY = self._endDates[-4:]
self._output = []
def validateDates(self, mmdd, yyyy):
flag = False
mm = int(mmdd[:2])
dd = int(mmdd[-2:])
monthArray = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if 0 < mm < 13 and 0 < dd <= monthArray[mm - 1]:
flag = True
# exclude special cases that we have invalid 29 on Feb.
if mm == 2 and dd == 29 and not ((yyyy % 400 == 0) or (yyyy % 100 != 0 and yyyy % 4 == 0)):
flag = False
return flag
def gen(self):
for i in range(int(self._startYYYY), int(self._endYYYY) + 1):
mmdd = str('%04d' % i)[::-1]
if self.validateDates(mmdd, i):
tmp = mmdd + str('%04d' % i)
self._output.append(tmp)
def printAll(self):
print ', '.join(self._output)
if __name__ == '__main__':
pd = PaDates('04020001', '04023000')
pd.gen()
pd.printAll()
Python working code.
Just made the loop up to the given number, and mul each individual digits in the i, if product == sum, return i. Intuitive algo, maybe could be improved.
"""
3/19/2013 3:16
@Python 2.7
Find the seed of a number.
Eg : 1716 = 143*1*4*3 =1716 so 143 is the seed of 1716. find all possible seed for a given number.
"""
class FindSeed(object):
def __init__(self, num):
if num is None:
print 'invalid number!!'
raise SystemExit
self._num = int(num)
def findS(self):
result = []
for i in range(self._num):
tmp = str(i)
product = i
for c in tmp:
product *= int(c)
if product == self._num:
result.append(str(i))
if result == []:
return 'No seed found!'
else:
return ', '.join(result)
if __name__ == '__main__':
seed = FindSeed(1716)
print seed.findS()
Python working code.
Modification from string permutation question.
"""
2:48
@Python 2.7
User inputs a sequence of digits. Every digit is a keystroke, that is equivalent to some character out of a sequence of characters. Digit zero and five mean NULL. The table is given below
0 - NULL
1 - v, t, f, r, q
2 - f, t, k
3 - w, z, b, g
4 - r, s
5 - NULL
6 - f, i, r
7 - p
8 - l, o
9 - p
Generate all possible character sequence for a given sequence of digits.
Ex - If the user input 9801, your program should generate
{plv, plt, plf, plr, plq, pov, pot, pof, por, poq} (not necessarily in this order).
This problem is somewhat similar to the SMS problem. It basically boils down to generating a cartesian product of the character sets corresponding to keys.
"""
class InputsToChar(object):
def __init__(self, inputs):
if inputs is None:
print 'Invalid Inputs!'
raise SystemExit
inputs = str(inputs)
inputs = inputs.replace('0', '')
inputs = inputs.replace('5', '')
self._inputs = inputs
self._charArray = [None, 'vtfrq', 'ftk', 'wzbg', 'rs', None, 'fir', 'p', 'lo', 'p']
self._result = []
def printAll(self, pos = 0):
if pos > len(self._inputs) - 1:
print ''.join(self._result)
return
for c in self._charArray[int(self._inputs[pos])]:
self._result.append(c)
self.printAll(pos + 1)
self._result.pop()
if __name__ == '__main__':
input = InputsToChar(9801)
input.printAll()
Working Python version using sort().
If sort() is not allowed to use, the best algo will be have 3 extra vars keep the max three, and you sum the array as you scan it, finally deduct the 3 vars. This yields to O(n).
"""
2:12
@Python 2.7
User inputs a series of numbers and terminates the series by a zero. Your program should find the first three maximum values in the series and exclude them from the series and compute the average of the remaining numbers. (excluding zero as well)
Ex - 3, 7, 12, 2, 25, 8, 9, 13, 10, 0
First three maximum numbers = 25, 13, 12
Average of the rest = (3 + 7 + 2 + 8 + 9 + 10) / 6 = 6.5
"""
class NotMaxThree(object):
def __init__(self, input):
if input is None:
print 'Invalid Input!'
raise SystemExit
self._input = []
for c in input:
if c != 0:
self._input.append(c)
else:
break
print self._input
def getAvg(self):
self._input.sort()
self._input = self._input[:-3]
return sum(self._input) * 1.0 / len(self._input)
if __name__ == '__main__':
input = NotMaxThree([3, 7, 12, 2, 25, 8, 9, 13, 10, 0])
print input.getAvg()
Python working code, using max()
"""
1:45
Written round question for Epic systems. They asked two dynamic programming problems.
Write a dynamic programming solution for finding maximum contiguous sub-sequence sum.
"""
class MaxSub(object):
def __init__(self, listNum):
if listNum is None:
print 'Invalid!'
raise SystemExit
self._listNum = listNum
def getMaxSum(self):
curMax = 0
maxMax = 0
for num in self._listNum:
curMax = max(num, curMax + num)
maxMax = max(maxMax, curMax)
return maxMax
m = MaxSub([2, 3 , -2 , 4 , -8 , 8, 9, -2, 10])
print m.getMaxSum()
Python version working code. loop through all the numbers, convert to string, if validate, print.
"""
Print all valid phone numbers of length n subject to following constraints:
1.If a number contains a 4, it should start with 4
2.No two consecutive digits can be same
3.Three digits (e.g. 7,2,9) will be entirely disallowed, take as input
"""
class ValidPhone(object):
def __init__(self, n):
if n is None:
print 'Invalid length!'
raise SystemExit
self._n = n
def validate(self, number):
isValid = True
#rule 1
if '4' in number and number[0] != '4':
isValid = False
# rule 3
if ('7' in number) or ('2' in number) or ('9' in number):
isValid = False
# rule 2
for i in range(len(number)-1):
if number[i] == number[i+1]:
isValid = False
return isValid
def gen(self):
for i in range(10 ** self._n):
out = str(i)
if len(out) < self._n:
out = '0' * (self._n - len(out)) + out
if self.validate(out):
print out
if __name__ == '__main__':
phone = ValidPhone(3)
phone.gen()
Python version, working code.
Printed all the possible continuely subsets. O(n^2)
@input 16
@output (2 - 4), (4 - 6)
"""
1.Substring Addition
Write a program to add the substring
eg :say you have a list {1 7 6 3 5 8 9 } and user is entering a sum 16.Output should display (2-4) that is {7 6 3} cause 7+6+3=16.
"""
class SubStringAdd(object):
def __init__(self, string, sum):
if string is None or sum is None:
print 'Invalid paras!'
raise SystemExit
self._string = string
self._sum = sum
def findSub(self):
output = []
for i in range(len(self._string)):
tmpSum = self._string[i]
if tmpSum == self._sum:
output.append('(' + str(i+1) + ' - ' + str(i+1) + ')')
for j in range(i+1, len(self._string)):
tmpSum += self._string[j]
# print tmpSum
if tmpSum > self._sum:
break
if tmpSum == self._sum:
output.append('(' + str(i+1) + ' - ' + str(j+1) + ')')
if output == []:
return 'Not FOUND!'
else:
return ', '.join(output)
if __name__ == '__main__':
sub = SubStringAdd([1, 7, 6, 3, 5, 8, 9], 16)
print sub.findSub()
Python version using list with string.
Working code:
"""
* Using string manipulation and concat the results.
Implement LookAndSay function. For example, first, let user input a number, say 1. Then, the function will generate the next 10 numbers which satisfy this condition:
1, 11,21,1211,111221,312211...
explanation: first number 1, second number is one 1, so 11. Third number is two 1(previous number), so 21. next number one 2 one 1, so 1211 and so on...
"""
def lookAndSay(number):
if number is None or type(number) != type(1):
print 'Invalid Number!'
raise SystemExit
result = []
result.append(str(number))
for i in range(10):
tmpOutput = []
# print result
cur = result[i][0]
count = 1
for j in range(1, len(result[i])):
if result[i][j] != cur:
tmpOutput.append(str(count))
tmpOutput.append(cur)
cur = result[i][j]
count = 1
else: # when result[i][j] == cur
count += 1
# print tmpOutput
tmpOutput.append(str(count))
tmpOutput.append(cur)
if len(tmpOutput) == 0:
result.append('1' + cur)
else:
result.append(''.join(tmpOutput))
print ', '.join(result)
if __name__ == '__main__':
lookAndSay(1)
Python version. Working code.
"""
Length is given as input.Print all possible permutations of numbers between 0-9.
Eg: if input length=4
all possible combinations can be 0123, 1234, 5678,9864,...etc all combinations of length from in all numbers between 0-9
"""
class NumPerm(object):
def __init__(self, length):
if length is None or type(length) != type(1):
print 'Invalid Length'
return False
self._length = length
self._out = []
self._src = [str(x) for x in range(10)]
self._flag = [False] * 10
def permute(self, pos = 0):
if pos == self._length:
print ''.join(self._out)
return
for i in range(len(self._src)):
if self._flag[i] is True:
continue
self._out.append(self._src[i])
self._flag[i] = True
self.permute(pos + 1)
self._out.pop()
self._flag[i] = False
if __name__ == '__main__':
n = NumPerm(3)
n.permute()
Python working code
- tosay.net March 20, 2013