Interview Questions Asked in TCS & Infosys
(You will get the video explanation at the bottom of page)
1) Prime Numbers using Sieve of Eratosthenes:
# https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
def prime(n): prime_list = [True for i in range(n + 1)] p = 2 while p * p <= n: if prime_list[True]: for i in range(p * 2, n + 1, p): prime_list[i] = False p += 1 prime_list[0] = False prime_list[1] = False return prime_list ans = prime(20) for i in range(len(ans)): if ans[i]: print(i, end = " ")
2) Frequency Count:
s = 'aabbcaabc' #Using Counter from collections import Counter freq = Counter(s) print(freq) #Using Dictionary d = dict.fromkeys(s, 0) print(d) for i in s: d[i] = d[i] + 1 print("Frequency :", d)
3) Nth Largest Number:
val = [4, 9, 5, 6, 1, 2, 7] import heapq heapq.heapify(val) print(heapq.nlargest(2, val))
4) Combinations:
comb = [1, 2, 3] from itertools import combinations #print(list(combinations(comb, 1))) ans = [] for i in range(1, len(comb) + 1): ans.append(list(combinations(comb, i))) print(and) #Binary bin_val = [str(bin(i))[2:] for i in range(1, 2 ** len(comb))] val = list(map(str,comb[:])) print(bin_val) for i in bin_val: temp = '' for j in range(len(i)): if i[j] == '1': temp += str(comb[j]) val.append(temp) print(set(val))
5) Middle Element of Linked List in Single Loop:
class Node: def __init__(self, data, next = None): self.data = data self.next = next def print_List(List): l = [] while List != None: l.append(List.data) List = List.next print(l) array = [1, 2, 3, 4, 5, 6, 7] List = None for i in array: List = Node(i, List) #print_List(List) ptr1 = List count = 1 while count != len(array) - 1: if count & 1 == 1: ptr1 = ptr1.next count += 1 print(ptr1.data)
0 Comments
Please don't enter any spam link in comment box.
Emoji