100% found this document useful (4 votes)
444 views

Codewriting Solutions Python

The document contains code snippets and solutions for various coding problems and exercises related to Python. Some of the problems addressed include finding the century from a given year, finding the first duplicate value in an array, finding the first non-repeating character in a string, and merging two strings based on character counts.

Uploaded by

Marlin Pohlman
Copyright
© © All Rights Reserved
Available Formats
Download as ODT, PDF, TXT or read online on Scribd
100% found this document useful (4 votes)
444 views

Codewriting Solutions Python

The document contains code snippets and solutions for various coding problems and exercises related to Python. Some of the problems addressed include finding the century from a given year, finding the first duplicate value in an array, finding the first non-repeating character in a string, and merging two strings based on character counts.

Uploaded by

Marlin Pohlman
Copyright
© © All Rights Reserved
Available Formats
Download as ODT, PDF, TXT or read online on Scribd
You are on page 1/ 25

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 mutateTheArray(n, a):


return [a[0]+a[1]]+[sum(a[x-1:x+2])for x in range(1,len(a))]if n>1 else a

def countTinyPairs(a, b, k):


return sum([1 if int(str(x)+str(y))<k else 0for x,y in zip(a,b[::-1])])

def mergeStrings(s1, s2):


count1 = {}
for i in s1:
try:
count1[i] += 1
except:
count1[i] = 1
count2 = {}
for i in s2:
try:
count2[i] += 1
except:
count2[i] = 1
res = ''
while True:
if s1 == '':
return res+s2
if s2 == '':
return res+s1
if count1[s1[0]] == count2[s2[0]]:
if s1[0] == s2[0]:
res += s1[0]
s1 = s1[1:]
elif s1[0] < s2[0]:
res += s1[0]
s1 = s1[1:]
else:
res += s2[0]
s2 = s2[1:]
continue
else:
if count1[s1[0]] < count2[s2[0]]:
res += s1[0]
s1 = s1[1:]
else:
res += s2[0]
s2 = s2[1:]
continue
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 mergeStrings(s1, s2):


s,o1,o2='',s1,s2
while len(s1)*len(s2)!=0:
if o1.count(s1[0])>o2.count(s2[0]) or (o1.count(s1[0])==o2.count(s2[0]) and s1[0]>s2[0]):
s+=s2[0]
s2=s2[1:]
else:
s+=s1[0]
s1=s1[1:]
return s+s1+s2

def hashMap(queryType, query):


hash_dict = {}
get_total = 0
for i, prompt in enumerate(queryType):
if prompt == 'insert':
hash_dict[query[i][0]] = query[i][1]
elif prompt == 'addToValue':
hash_dict = {key: val + query[i][0] for key, val in hash_dict.items()}
elif prompt == 'addToKey':
hash_dict = {key + query[i][0]: val for key, val in hash_dict.items()}
elif prompt == 'get':
get_total += hash_dict[query[i][0]]
return get_total

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 commonCharacterCount(s1, s2):


count = 0
for i in range(0, len(s1)):
for j in range(0, len(s2)):
if s1[i] == s2[j]:
count = count + 1
s2 = s2[:j] + s2[(j+1):]
break
return count

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 areSimilar(a, b):


count = 0
list_a = []
list_b = []
for i in range(len(a)):
if (a[i]!= b[i]):
count +=1
list_a.append(a[i])
list_b.append(b[i])
if (count ==0):
return True

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 areEquallyStrong(yourLeft, yourRight, friendsLeft, friendsRight):


if (yourLeft == friendsLeft) and (yourRight == friendsRight):
return True
elif (yourRight == friendsLeft) and (yourLeft == friendsRight):
return True
else:
return False
def arrayMaximalAdjacentDifference(inputArray):
m=0
for i in range(len(inputArray)-1):
t = abs(inputArray[i] - inputArray[i+1])
if m < t:
m=t
return m

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 arrayReplace(inputArray, elemToReplace, substitutionElem):


for n,i in enumerate(inputArray):
if i == elemToReplace:
inputArray[n] =substitutionElem
return inputArray

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 chessBoardCellColor(cell1, cell2):


if (ord(cell1[0]) + ord(cell1[1]) + ord(cell2[0]) + ord(cell2[1])) % 2 == 0:
return True
return False

def circleOfNumbers(n, firstNumber):


return (firstNumber + n / 2) % n

def depositProfit(deposit, rate, threshold):


return math.ceil(math.log(threshold/deposit,1+rate/100))

def absoluteValuesSumMinimization(a):
return a[(len(a)-1)//2]

# def stringsRearrangement(inputArray):

from itertools import permutations

def diff(w1, w2):


return sum([a[0] != a[1] for a in zip(w1, w2)]) == 1

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 growingPlant(upSpeed, downSpeed, desiredHeight):


days = 0
height = 0
while height <= desiredHeight:
height += upSpeed
days += 1
if height >= desiredHeight:
break
height -= downSpeed
return days

def knapsackLight(value1, weight1, value2, weight2, maxW):


if weight1 + weight2 <= maxW:
return value1 + value2
else:
if weight1 <= maxW and value1 > value2 :
return value1
elif weight2 <= maxW and value2 > value1:
return value2
elif maxW >= weight2:
return value2
elif maxW >= weight1:
return value1
return 0

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 bishopAndPawn(bishop, pawn):


return (ord(bishop[0]) + int(bishop[1]) == ord(pawn[0]) + int(pawn[1])) or (ord(bishop[0]) +
int(pawn[1]) == ord(pawn[0]) + int(bishop[1]))

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 electionsWinners(votes, k):


m = max(votes)
return int(votes.count(m) == 1) if k == 0 else len([i for i in votes if i + k > m])
def isMAC48Address(inputString):
return True if re.match("^([0-9A-F]{2}-){5}[0-9A-F]{2}$", inputString) else False

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 isCryptSolution(crypt, solution):


t = tuple(c.translate(str.maketrans(dict(solution))) for c in crypt)
any_zeros = any(v[0] == '0' for v in t if len(v) > 1)
return not ((int(t[0]) + int(t[1]) != int(t[2])) or any_zeros)
import unittest

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 isCryptSolution(crypt, solution):


d = dict(solution)
decryption = []
for w in crypt:
temp = decrypt(w, d)
if temp == '0' or temp[0] != '0':
decryption.append(int(temp))
else:
return False
return decryption[0] + decryption[1] == decryption[2]

---
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

while b is not None:


s1+=1
strb+=str(b.value).zfill(4)
b=b.next

ans = str(int(strs)+int(strb))

temp=[ans[::-1][i:i+4] for i in range(0, len(ans[::-1]), 4)]


ans1=[]
for i in temp:
ans1.append(int(i[::-1]))
ans1=ans1[::-1]
return ans1

----
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

def reverse_nodes(head, tail, head_parent, num_nodes):


new_end_parent = tail.next
count = 0
parent = tail.next
temp_child = None
cur = head
while count < num_nodes:
count += 1
temp_child = cur.next
cur.next = parent
parent = cur
cur = temp_child
if head_parent:
head_parent.next = parent

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

def removeKFromList(l, k):


helper = ListNode(0)
helper.next = l
p = helper

while p.next != None:


if p.next.value == k:
p.next = p.next.next
else:
p = p.next

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]]

return [[r] + _hash[r] for r in sorted(_hash.keys()) if len(_hash[r]) > 1]

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

def regularExpressionMatching(s, p):


if not p:
return not s

first_match = s and p[0] in {s[0], '.'}

if len(p) >= 2 and p[1] == '*':


return bool((regularExpressionMatching(s, p[2:]) or
first_match and regularExpressionMatching(s[1:], p)))
else:
return bool(first_match and regularExpressionMatching(s[1:], p[1:]))

CREATE PROCEDURE projectList()


BEGIN
SELECT project_name,team_lead,income FROM Projects;
END

CREATE PROCEDURE countriesSelection()


BEGIN
SELECT c.name, c.continent, c.population
FROM countries c
WHERE c.continent = "Africa"
ORDER BY c.name;
END

CREATE PROCEDURE monthlyScholarships()


BEGIN
SELECT id,(scholarship / 12) AS scholarship FROM scholarships;
END

CREATE PROCEDURE projectsTeam()


BEGIN
SELECT DISTINCT (name) as name FROM projectLog order by name;
END

CREATE PROCEDURE automaticNotifications()


SELECT email
FROM users
WHERE role NOT IN ("admin", "premium")

ORDER BY email;

CREATE PROCEDURE volleyballResults()

SELECT *
FROM results
ORDER BY wins;

CREATE PROCEDURE mostExpensive()

SELECT name
FROM Products
ORDER BY price * quantity DESC, name ASC limit 1;

CREATE PROCEDURE contestLeaderboard()


BEGIN
SELECT name FROM leaderboard ORDER BY score DESC LIMIT 3, 5;
END

CREATE PROCEDURE gradeDistribution()


BEGIN
SELECT Name, ID
FROM Grades
WHERE Final > (0.5 * Midterm1 + 0.5 * Midterm2) AND Final > (0.25 * Midterm1+0.25 *
Midterm2+0.5 * Final)
ORDER BY substring(Name,1,3) ASC, ID ASC;
END
CREATE PROCEDURE mischievousNephews()
BEGIN
SELECT (DAYOFWEEK(mischief_date) + 5) MOD 7 AS "weekday", mischief_date, author, title
FROM mischief
ORDER BY weekday, FIND_IN_SET(author, 'Huey,Dewey,Louie'), mischief_date, title ASC;
END

CREATE PROCEDURE suspectsInvestigation()


BEGIN
SELECT id, name, surname
FROM Suspect
WHERE height <= 170 AND surname LIKE 'Gre_n' AND name LIKE 'B%';
END

CREATE PROCEDURE suspectsInvestigation2()


BEGIN
SELECT id, name, surname
FROM Suspect
WHERE NOT (height > 170 AND surname LIKE 'Gre_n' AND name LIKE 'B%');
END

CREATE PROCEDURE securityBreach()


BEGIN
SELECT first_name,second_name,attribute
FROM users
WHERE attribute REGEXP BINARY CONCAT('[a-zA-Z0-9]%', CONCAT(first_name,
'_',second_name), '%');

END

CREATE PROCEDURE testCheck()


SELECT id, IF (given_answer IS NULL, "no answer",
IF(given_answer = correct_answer, "correct", "incorrect")
) AS checks
FROM answers
ORDER BY id;\

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

Multiple Choice Word Problems


xs = [()]
res = [False] * 2
if xs: ← not empty thus True therefore executes
res[0] = True
if xs[0] ← empty thus False therefore does not execute
res[1] = True

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

f= lambda my_list: list(map(lambda x: = ** -1, my_list))

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

var foo = function foo() {


console.log( foo == foo):
}:
foo():

Answ:

Comparing a function to itself returns true, so the console prints true.

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.

(true + false) > 2 + 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

new String("This is a string") instanceof String;

Answ:
returns True

[] + [] + 'foo'.split('');
Answ:
[] + [] + 'foo'.split('') = "" + "" + "f,o,o" = "f,o,o"

new Array(5).toString();
Answ:
new Array(5).toString() = ",,,,,"

var myArr = ['foo', 'bar', 'baz'];


myArr.length = 0;
myArr.push('bin');
console.log(myArr);

Answ:
Therefore myArr.length = 0 empties the array, and thus when 'bin' is pushed myArr == ['bin'].

String('Hello') === 'Hello';

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.

"This is a string" instanceof String;


Answ:
"This is a string" instanceof String is false

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.

var myArr = ['foo', 'bar', 'baz'];


myArr.length = 0;
myArr.push('bin');
console.log(myArr);
Answ:
Since it has 3 elements it has the properties 0, 1 and 2. Therefore '2' in myArr is true.

var arr = [];


arr[0] = 'a';
arr[1] = 'b';
arr.foo = 'c';
alert(arr.length);
Answ:
The length of an array is only influenced by it's numeric properties. Thus arr.length

10 > 9 > 8 === true;


Answ
((10 > 9) > 8) === true;
(true > 8) === true;
(1 > 8) === true;
false === true;
false;

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 === NaN


Answ:
NaN === NaN returns false.

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!

func = lambda x: return x


print(func(2))

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.

my_list = ['Real', ' Python']


def func(x):
return ''.join(x)
translate the following function to an anonymous lambda function?
Answ:
lambda x: ''.join(x)
numbers = [1, 2, 3]
map() allows you to apply a function to every item of an iterable. Can you figure
out how many of the following programs won’t have an error?
Select all that apply:
Answ:
list(map(lambda x: x % 2 == 0, numbers))
list(map(lambda x: x, numbers))
map(lambda x: x, numbers)
Numbers is not defined. If you check carefully, we defined numbers. Python is a
case-sensitive language.

from functools import reduce


numbers = [1, 2, 3]
reduce(lambda x, y: x + y, numbers)
Answ:
6 - reduce() applies the function cumulatively to the items of the given sequence.
Hence, it becomes 1 + 2 = 3 and then 3 + 3 = 6.

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.

What will be the output of the following code :


print type(type(int))
Answ:
type 'type'

Which of the following is the use of id() function in python?


Answ:
Id returns the identity of the object

You might also like