Codewriting Solutions Python
Codewriting Solutions Python
def centuryFromYear(year):
if year % 100 == 0:
return year/100
else:
return int(year/100) + 1
def firstDuplicate(a):
s=set()
for x in a:
if x in s:
return x
s.add(x)
return -1
def firstNotRepeatingCharacter(s):
res = "_"
d = {}
for i,c in enumerate(s):
if c in d.keys():
d[c] = -1
else:
d[c] = i
min_key = len(s)+1
for k in d.keys():
if d[k]>=0:
min_key = min(min_key,d[k])
res = s[min_key]
return res
def concatenationsSum(a):
t=sum(a)
t1=t*len(a)
t2=sum([t*[len(str(x))-1 for x in a].count(j)*10**(j+1) for j in range(7)])
return t1+t2
def meanGroups(a):
d,e=[],[]
for i,j in enumerate(a):
if sum(j)/len(j)not in e:
e+=[sum(j)/len(j)]
d+=[[i]]
else:
d[e.index(sum(j)/len(j))]+=[i]
return d
def alternatingSort(a):
c,l=0,a[0]
while c!=(len(a)-1)//2:
c=-c if c<0 else -c-1
if a[c]<=l:
return False
l=a[c]
return True
def checkPalindrome(inputString):
return inputString==inputString[-1::-1]
def adjacentElementsProduct(inputArray):
size = len(inputArray)
for x in range(1,size): #From 1 to size-1
prod = inputArray[x-1]*inputArray[x]
if x==1:
maxprod = prod
if prod > maxprod:
maxprod = prod
return maxprod
def shapeArea(n):
area = 1
for i in range(1,n+1):
area = area + ((i-1)*4)
return area
def makeArrayConsecutive2(statues):
return len([i for i in range(min(statues), max(statues)) if i not in statues])
def almostIncreasingSequence(sequence):
numFail = 0
prev = sequence[0]
for i in range(len(sequence)-1):
if sequence[i+1] <= prev:
numFail += 1
if i == 0:
prev = sequence[i+1]
elif i <= len(sequence)-3 and sequence[i+2] <= sequence[i]:
if sequence[i+1] > sequence[i-1]:
prev = sequence[i+1]
else:
prev = sequence[i]
if sequence[i+2] <= prev:
numFail += 1
else:
prev = sequence[i]
if numFail > 1:
return False
else:
prev = sequence[i+1]
return True
def matrixElementsSum(matrix):
matrix_copy = matrix.copy()
total = 0
# Loop over rows.
for row in matrix:
# Loop over columns.
for column_index in range(len(row)):
if row[column_index] == 0:
# Replace all 0s in matrix under current 0 to 0s.
for i in range(matrix.index(row), len(matrix)):
matrix_copy[i][column_index] = 0
# Find sum of all remaining numbers in matrix.
for row_copy in matrix_copy:
total += sum(row_copy)
return total
def allLongestStrings(inputArray):
result = list()
max_len = 0
for _str in inputArray:
_len = len(_str)
if _len > max_len:
max_len = _len
result = [_str]
continue
if _len == max_len:
result.append(_str)
continue
return result
def isLucky(n):
s = str(n)
pivot = len(s) // 2
left, right = s[:pivot], s[pivot:]
return sum(map(int, left)) == sum(map(int, right))
def sortByHeight(a):
n = len(a)
for x in range(n):
for y in range(n - 1):
if a[x] != -1 and a[x] < a[y]:
a[x], a[y] = a[y], a[x]
return a
def reverseInParentheses(inputString):
s = inputString
for i in range(len(s)):
if s[i] == "(":
start = i
if s[i] == ")":
end = i
return reverseInParentheses(s[:start] + s[start+1:end][::-1] + s[end+1:])
return s
def alternatingSums(a):
return [sum(a[0::2]),sum(a[1::2])]
def addBorder(picture):
return [(len(picture[0]) + 2) * '*'] + ['*' + x + '*' for x in picture] + [(len(picture[0]) + 2) * '*']
def arrayChange(inputArray):
c=0
for i in range(1, len(inputArray)):
if(inputArray[i] <= inputArray[i - 1]):
c += inputArray[i-1]-inputArray[i]+1
inputArray[i] = inputArray[i - 1] + 1
return c
def palindromeRearranging(inputString):
characters = set(inputString)
t = False
for x in characters:
if ((inputString.count(x)%2 == 1) and (t == True)):
return False
elif ((inputString.count(x)%2 == 1) and (t == False)):
t = True
return True
def isIPv4Address(inputString):
ip = inputString.split('.')
l = len(ip)
test = []
if l!= 4:
return False
for i in range(256):
test.append(str(i))
for j in range(l):
if ip[j] not in test:
return False
return True
def avoidObstacles(inputArray):
c=2
while True:
if sorted([i%c for i in inputArray])[0]>0:
return c
c += 1
def boxBlur(image):
r = []
for i in range(len(image)-2):
r.append([])
for j in range(len(image[0])-2):
r[i].append(sum(image[i][j:j+3] + image[i+1][j:j+3] + image[i+2][j:j+3])/9//1)
return r
def minesweeper(matrix):
num_mines = []
rows = len(matrix)
cols = len(matrix[0])
adj = [-1, 0, 1]
for r in range(rows):
curr_row = []
for c in range(cols):
# Add neighboring cells if not out of bounds or cell itself
curr_row.append(sum([matrix[r + i][c + j] for i in adj
if (r + i >= 0 and r + i < rows) for j in adj
if (c + j >= 0 and c + j < cols and
not(i == 0 and j == 0))]))
num_mines.append(curr_row)
return num_mines
def evenDigitsOnly(n):
st = str(n)
for i in st:
if not int(i) % 2 == 0:
return False
return True
def variableName(name):
if name[0].isdigit(): return False
for c in name:
if not c.isalnum() and not c == '_':
return False
return True
def alphabeticShift(inputString):
return "".join(chr((ord(i)-96)%26+97) for i in inputString)
def absoluteValuesSumMinimization(a):
return a[(len(a)-1)//2]
# def stringsRearrangement(inputArray):
def stringsRearrangement(inputArray):
for z in permutations(inputArray):
if sum([diff(*x) for x in zip(z, z[1:])]) == len(inputArray) - 1:
return True
return False
def extractEachKth(inputArray, k):
return [ inputArray[i] for i in range(len(inputArray)) if (i+1)%k!=0]
def firstDigit(inputString):
return re.findall('\d', inputString)[0]
def differentSymbolsNaive(s):
return len(set(s))
def arrayMaxConsecutiveSum(inputArray, k):
i=0
max = 0
sum = 0
n = len(inputArray)
while i < k:
sum += inputArray[i]
i += 1
if sum > max:
max = sum
v = sum
for j in range(k, n):
v = v - inputArray[j - k] + inputArray[j]
if v > max:
max = v
return(max)
def longestDigitsPrefix(inputString):
return re.findall('^\d*', inputString)[0]
def digitDegree(n):
c=0
n=str(n)
while len(n)>1:
c+=1
s=0
for char in n:
s+=int(char)
n=str(s)
return c
def isBeautifulString(inputString):
li = list(inputString)
li.sort()
result = []
for i in range(97,ord(li[-1])+1):
if chr(i) not in li:
result.append((chr(i), 0))
else:
result.append((chr(i), li.count(chr(i))))
print(result)
for i in range(len(result)-1):
if result[i][1] == 0 or result[i+1][1] > result[i][1]:
return False
return True
def findEmailDomain(address):
return address.rsplit("@")[-1]
def buildPalindrome(st):
end=""
i=0
while st+end!=(st+end)[::-1] and i<len(st):
end=st[i]+end
i+=1
return st+end
def isDigit(symbol):
return symbol.isdigit()
def lineEncoding(s):
return re.sub(r"(.)\1+", lambda m: str(len(m.group(0))) + m.group(1), s)
def chessKnight(cell):
max_moves = 8
border = 0
near_border = 0
# Check if the cell is either on the edge or next to it
# if cell[0 ] in "ah" -> cell either letter a or h etc
if cell[0] in "ah":
border += 1
if cell[1] in "18":
border += 1
if cell[0] in "bg":
near_border += 1
if cell[1] in "27":
near_border += 1
# We were at the border
if border == 1 and near_border == 0:
return 4
# Calc steps
max_moves -= 3 * border
max_moves -= 2 * near_border
return max_moves
def deleteDigit(n):
n = str(n)
ma = 0
for i in range(len(n)):
k = n[:i] + n[i+1:]
if int(k) > ma:
ma = int(k)
return ma
def longestWord(text):
return sorted( re.findall('([a-zA-Z]*)',text), key=len )[-1]
def validTime(time):
hm = time.split(':')
return 0 <= int(hm[0]) <=23 and 0<= int(hm[1]) <= 59
def sumUpNumbers(inputString):
return sum([int(n) for n in re.findall(r'\d+', inputString)])
def differentSquares(matrix):
lr = len(matrix)
lc = len(matrix[0])
if lr==1 or lc==1:
return 0
serials=[]
count=0
for r in range(lr-1):
for c in range(lc-1):
serial = str(matrix[r][c]) + "_" + str(matrix[r][c+1]) + "_" + str(matrix[r+1][c]) + "_" +
str(matrix[r+1][c+1])
if not serial in serials:
count+=1
serials.append(serial)
return count
def digitsProduct(product):
def get_single_dig_factors(product):
# Helper function to generate single-digit factors of product
n = product
factors = []
for i in range(9, 1, -1):
while n % i == 0 and n > 1:
factors.append(i)
n /= i
if n > 9:
# At least one factor is a two-digit prime number
return None
return sorted(factors)
if product == 0:
return 10
elif product < 10:
return product
factors = get_single_dig_factors(product)
if factors:
return int(''.join([str(i) for i in factors]))
else:
return -1
def fileNaming(names):
r = []
d = {}
for i in names:
if i not in r:
r.append(i)
d[i] = 0
else:
d[i] = d.get(i,0) + 1
while i+'({})'.format(d[i]) in r:
d[i] = d.get(i,0) + 1
r.append(i+'({})'.format(d[i]))
return r
def messageFromBinaryCode(code):
return "".join([chr(int(code[i * 8:i * 8 + 8], 2))for i in range(int(len(code) / 8))])
def spiralNumbers(n):
matrix = [[0 for i in range(n)] for j in range(n)]
numPaths = n + n - 1
for path in range(1, numPaths + 1):
if path % 4 == 1: # Row Left to Right
row = path // 4
for col in range(n):
if col == 0 and row == 0:
matrix[row][col] = 1
elif matrix[row][col] == 0:
matrix[row][col] = matrix[row][col-1] + 1
elif path % 4 == 2: # Col Top to Bottom
col = n - (path // 4 + 1)
for row in range(1, n):
if matrix[row][col] == 0:
matrix[row][col] = matrix[row-1][col] + 1
elif path % 4 == 3: # Row Right to Left
row = n - (path // 4 + 1)
for col in range(n-2, -1, -1):
if matrix[row][col] == 0:
matrix[row][col] = matrix[row][col+1] + 1
elif path % 4 == 0: # Col Bottom to Top
col = path // 4 - 1
for row in range(n-2, 0, -1):
if matrix[row][col] == 0:
matrix[row][col] = matrix[row+1][col] + 1
return matrix
def sudoku(grid):
for value in grid:
if len(set(value)) != 9:
return False
for k in range(9):
if len(set([i[k] for i in grid])) != 9:
return False
for i in range(0, len(grid), 3):
for j in range(0, len(grid), 3):
if len(set(grid[k][w] for w in range(j,j+3) for k in range(i,i+3))) != 9:
return False
return True
def rotateImage(a):
return list(zip(*reversed(a)))
def sudoku2(grid):
rowSet = set()
colSet = set()
gridSet1 = set()
gridSet2 = set()
gridSet3 = set()
n=0
counter = 0
c_max = len(grid) - 1
for i in grid:
if n >= 3 and n % 3 == 0:
gridSet1.clear()
gridSet2.clear()
gridSet3.clear()
for index, x in enumerate(i):
val = grid[index][counter]
val2 = grid[n][index]
if x in rowSet or val in colSet:
return False
else:
rowSet.add(x if x != '.' else None)
colSet.add(val if val != '.' else None)
if val2 in gridSet1 and index < 3 or val2 in gridSet2 and 3 < index < 6 or val2 in gridSet3 and
index > 6:
return False
elif val2 == '.':
pass
elif index < 3:
gridSet1.add(val2)
elif 3 <= index <= 5:
gridSet2.add(val2)
else:
gridSet3.add(val2)
rowSet.clear()
colSet.clear()
if (counter == c_max):
counter = 0
counter += 1
n += 1
return True
---
def decrypt(word, dictionary):
return ''.join([dictionary[w] for w in word])
---
def isListPalindrome(l):
a=convertToArray(l)
for i in range(int(len(a)/2)):
if a[i]!=a[len(a)-i-1]:
return False
return True
def convertToArray(l):
a=[]
if(l!=None):
a.append(l.value)
c=l.next
while(c!=None):
a.append(c.value)
c=c.next
return a
---
def addTwoHugeNumbers(a, b):
s,s1=0,0
strs = ""
strb = ""
while a is not None:
s+=1
strs+=str(a.value).zfill(4)
a=a.next
ans = str(int(strs)+int(strb))
----
def mergeTwoLinkedLists(l1, l2):
if l1 == None or l2 == None:
return l1 or l2
dummy = ListNode(None)
curr = dummy
while True:
if l1.value < l2.value:
curr.next = l1
curr = curr.next
if l1.next == None:
curr.next = l2
break
l1 = l1.next
else:
curr.next = l2
curr = curr.next
if l2.next == None:
curr.next = l1
break
l2 = l2.next
return dummy.next
---
def reverseNodesInKGroups(l, k):
if k == 1:
return l
new_head = None
count = 0
head = None
tail = None
head_parent = None
prev_node = None
while l:
count += 1
if count == 1:
head = l
head_parent = prev_node
elif count == k:
tail = l
l = reverse_nodes(head, tail, head_parent, k)
if head_parent is None:
new_head = tail
count = 0
prev_node = l
l = l.next
return new_head
return head
---
def rearrangeLastN(l, n):
L = []
while l != None:
L.append(l.value)
l = l.next
if len(L) < 2:
return L
k = len(L) - n
L = L[k:] + L[:k]
return L
return helper.next
def groupingDishes(dishes):
_hash = {}
for line in dishes:
for i in line[1:]:
try:
_hash[i] = sorted(_hash[i] + [line[0]])
except KeyError:
_hash[i] = [line[0]]
def newRoadSystem(roadRegister):
for i in range(len(roadRegister)):
outEdges = 0
inEdges = 0
for j in range(len(roadRegister[i])):
if(roadRegister[i][j]):
outEdges += 1
for j in range(len(roadRegister)):
if(roadRegister[j][i]):
inEdges += 1
if(inEdges != outEdges):
return False
return True
ORDER BY email;
SELECT *
FROM results
ORDER BY wins;
SELECT name
FROM Products
ORDER BY price * quantity DESC, name ASC limit 1;
END
The Big Book of Coding Interviews in Python, 3rd Edition: answers to the best programming interview
questions on data structures and algorithms 3rd Edition
https://github.com/parineeth/tbboci-3rd-edition-python
https://yangshun.github.io/tech-interview-handbook/algorithms/algorithms-introduction
Answ:
[True, False]
container.addEventListner(‘click’, function(e) {
if (e.target && e.target.nodeliane === ‘LI’){
process(e.target)
)
});
Answ:
Forward clicks on <li> elements to the container element
Answ:
We use lambda functions when we require a nameless function for a short period of time.
F is a function that takes a list and returns a list which consists of 1/x for each x in it
Answ:
function aaa() {
return
{
test: 1
};
}
alert(typeof aaa());
Answ:
"undefined"
Number("1") - 1 == 0;
Answ:
Number("1") simply resolves to 1, and 1 - 1 == 0 resolves to true.
Answ:
returns 'false
function bar() {
return foo;
foo = 10;
function foo() {}
var foo = '11';
}
alert(typeof bar());
Answ:
the output will be "function".
"1" - - "1";
Answ:
1 - -1 = 1 - (- 1) = 2
var x = 3;
var foo = {
x: 2,
baz: {
x: 1,
bar: function() {
return this.x;
}
}
}
var go = foo.baz.bar;
alert(go());
alert(foo.baz.bar());
Answ:
the answer to the question is: 3, 1
Answ:
returns True
[] + [] + 'foo'.split('');
Answ:
[] + [] + 'foo'.split('') = "" + "" + "f,o,o" = "f,o,o"
new Array(5).toString();
Answ:
new Array(5).toString() = ",,,,,"
Answ:
Therefore myArr.length = 0 empties the array, and thus when 'bin' is pushed myArr == ['bin'].
Answ:
True
var x = 0;
function foo() {
x++;
this.x = x;
return foo;
}
var bar = new new foo;
console.log(bar.x);
Answ:
Since foo is only a function it does not have the property x, and thus bar.x is undefined.
var bar = 1,
foo = {};
foo: {
bar: 2;
baz: ++bar;
};
foo.baz + foo.bar + bar;
Answ:
+ tries to convert it's operands to numbers. Since undefined isn't a number, this results in NaN. If you
add anything to NaN you will always get NaN. Therefore the result is NaN.
function foo(a, b) {
arguments[1] = 2;
alert(b);
}
foo(1);
Answ:
Therefore b is still undefined in the alert, and undefined will be aler
NaN is actually equal to nothing. To test if a variable x is NaN you can either do isNaN(x) or x !== x.
The later one is pretty interesting, since NaN is the only value which is not actually equal to itself!
Answ
SyntaxError - A lambda function can’t contain the return statement. In a lambda function, statements
like return, pass, assert, or raise will raise a SyntaxError exception.
What are the common functional programming methods that use lambdas? Select all that apply:
map(), reduce(), filter(), functools.reduce()
(lambda x: (x + 3) * 5 / 2)(3)
Answ:
15 Reduction is a lambda calculus strategy to compute the value of the expression. It consists of
substituting the argument 3 for x. Overall, the run of this lambda function happens with 3 being passed
into it as an argument.
numbers = [1, 2, 3]
Which of the following would produce the result: [2]
Answ:
list(filter(lambda x: x % 2 == 0, numbers)) - The function above will print all the
numbers from the list that are divisible by 2.
list(filter(lambda x: (x + 1) * 3 / 3 % 3 == 0, numbers)) - The function above will
print 2 as a part of the calculation. (2 + 1) * 3 / 3 % 3 == 0 is True.