0% found this document useful (0 votes)
3 views10 pages

TCS NQT Python Codes

The document provides a comprehensive guide to Python coding for the TCS NQT exam, covering essential topics such as basic programming, arrays and strings, functions and recursion, number theory, pattern problems, and data structures. Each section includes code examples and explanations for various concepts, algorithms, and problem-solving techniques. The content is structured to facilitate learning and practice for candidates preparing for the exam.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views10 pages

TCS NQT Python Codes

The document provides a comprehensive guide to Python coding for the TCS NQT exam, covering essential topics such as basic programming, arrays and strings, functions and recursion, number theory, pattern problems, and data structures. Each section includes code examples and explanations for various concepts, algorithms, and problem-solving techniques. The content is structured to facilitate learning and practice for candidates preparing for the exam.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

TCS NQT EXAM

Complete Python Codes


Covering the Full Coding Syllabus

# Section Topics

1 Basic Programming I/O, Operators, Conditionals, Loops

2 Arrays & Strings Search, Sort, Manipulation

3 Functions & Recursion Factorial, Fibonacci, Tower of Hanoi

4 Number Theory Prime, GCD, Armstrong, Perfect, etc.

5 Pattern Problems Star, Number, Pascal's, Diamond

6 Data Structures Stack, Queue, Linked List

7 Important Problems Kadane's, Two Sum, Spiral Matrix, etc.

8 Time Complexity Big-O, Memoization


SECTION 1: BASIC PROGRAMMING

1.1 Input / Output


name = input("Enter your name: ") age = int(input("Enter your age: ")) print(f"Hello {name}, you
are {age} years old.")

1.2 Arithmetic Operators


a, b = 10, 3 print(a + b) # Addition → 13 print(a - b) # Subtraction → 7 print(a * b) #
Multiplication→ 30 print(a / b) # Division → 3.33 print(a // b) # Floor Div → 3 print(a % b) #
Modulus → 1 print(a ** b) # Power → 1000

1.3 If-Else: Even/Odd & Grade Calculator


def check_even_odd(n): return "Even" if n % 2 == 0 else "Odd" def grade_calculator(marks): if
marks >= 90: return "A" elif marks >= 75: return "B" elif marks >= 60: return "C" elif marks >=
40: return "D" else: return "F" print(check_even_odd(7)) # Odd print(grade_calculator(85)) # B

1.4 Loops
# Multiplication Table def print_table(n): for i in range(1, 11): print(f"{n} x {i} = {n * i}")
# Sum of Digits def sum_of_digits(n): total = 0 while n > 0: total += n % 10 n //= 10 return
total # Reverse a Number def reverse_number(n): rev = 0 while n > 0: rev = rev * 10 + n % 10 n
//= 10 return rev print(sum_of_digits(1234)) # 10 print(reverse_number(12345)) # 54321

1.5 Switch-Case (via Dictionary)


def day_name(day): days = {1:"Monday", 2:"Tuesday", 3:"Wednesday", 4:"Thursday", 5:"Friday",
6:"Saturday", 7:"Sunday"} return [Link](day, "Invalid day") print(day_name(3)) # Wednesday
SECTION 2: ARRAYS & STRINGS

2.1 Array Operations


arr = [3, 1, 4, 1, 5, 9, 2, 6] def find_max_min(arr): return max(arr), min(arr) def
array_sum_avg(arr): return sum(arr), sum(arr)/len(arr) def second_largest(arr): u =
sorted(set(arr)); return u[-2] if len(u)>=2 else None def remove_duplicates(arr): return
list(set(arr)) def rotate_left(arr, k): k %= len(arr); return arr[k:] + arr[:k]
print(find_max_min(arr)) # (9, 1) print(second_largest(arr)) # 6 print(rotate_left(arr, 2))

2.2 Searching
def linear_search(arr, target): for i, v in enumerate(arr): if v == target: return i return -1
def binary_search(arr, target): # arr must be sorted lo, hi = 0, len(arr)-1 while lo <= hi:
mid = (lo+hi)//2 if arr[mid] == target: return mid elif arr[mid] < target: lo = mid+1 else:
hi = mid-1 return -1

2.3 Sorting Algorithms


def bubble_sort(arr): arr = [Link](); n = len(arr) for i in range(n): for j in range(n-i-1):
if arr[j] > arr[j+1]: arr[j],arr[j+1]=arr[j+1],arr[j] return arr def selection_sort(arr):
arr = [Link](); n = len(arr) for i in range(n): m = min(range(i,n), key=arr.__getitem__)
arr[i],arr[m] = arr[m],arr[i] return arr def insertion_sort(arr): arr = [Link]() for i in
range(1, len(arr)): key = arr[i]; j = i-1 while j>=0 and arr[j]>key: arr[j+1]=arr[j]; j-=1
arr[j+1]=key return arr def merge_sort(arr): if len(arr)<=1: return arr mid=len(arr)//2 L,R =
merge_sort(arr[:mid]), merge_sort(arr[mid:]) res=[]; i=j=0 while i<len(L) and j<len(R):
if L[i]<=R[j]: [Link](L[i]); i+=1 else: [Link](R[j]); j+=1 return res+L[i:]+R[j:]

2.4 String Operations


def is_palindrome(s): s = [Link]().replace(" ",""); return s == s[::-1] def
count_vowels_consonants(s): v = sum(1 for c in s if c in "aeiouAEIOU" and [Link]()) c = sum(1
for c in s if [Link]() and c not in "aeiouAEIOU") return v, c def check_anagram(s1, s2):
return sorted([Link]()) == sorted([Link]()) def reverse_words(s): return "
".join([Link]()[::-1]) def first_non_repeating(s): from collections import Counter cnt =
Counter(s) return next((c for c in s if cnt[c]==1), None) def string_compression(s): res=""; i=0
while i<len(s): cnt=1 while i+cnt<len(s) and s[i]==s[i+cnt]: cnt+=1 res+=s[i]+(str(cnt)
if cnt>1 else ""); i+=cnt return res print(is_palindrome("racecar")) # True
print(check_anagram("listen","silent")) # True print(string_compression("aaabbc")) # a3b2c
SECTION 3: FUNCTIONS & RECURSION

3.1 Factorial
def factorial_iterative(n): result = 1 for i in range(2, n+1): result *= i return result def
factorial_recursive(n): if n <= 1: return 1 return n * factorial_recursive(n-1)
print(factorial_iterative(6)) # 720 print(factorial_recursive(6)) # 720

3.2 Fibonacci
def fibonacci_iterative(n): a, b = 0, 1; series = [] for _ in range(n): [Link](a); a, b =
b, a+b return series def fibonacci_recursive(n): if n <= 0: return 0 if n == 1: return 1
return fibonacci_recursive(n-1) + fibonacci_recursive(n-2) # Memoized (Fast) def fib_memo(n,
memo={}): if n in memo: return memo[n] if n <= 1: return n memo[n] = fib_memo(n-1, memo) +
fib_memo(n-2, memo) return memo[n] print(fibonacci_iterative(8)) # [0,1,1,2,3,5,8,13]

3.3 Power, Sum, Tower of Hanoi


def power(base, exp): if exp == 0: return 1 return base * power(base, exp-1) def sum_natural(n):
if n == 0: return 0 return n + sum_natural(n-1) def tower_of_hanoi(n, src, tgt, aux): if n == 1:
print(f"Move disk 1: {src} → {tgt}"); return tower_of_hanoi(n-1, src, aux, tgt) print(f"Move
disk {n}: {src} → {tgt}") tower_of_hanoi(n-1, aux, tgt, src) tower_of_hanoi(3, 'A', 'C', 'B')

3.4 Binary Search (Recursive)


def binary_search_rec(arr, lo, hi, target): if lo > hi: return -1 mid = (lo+hi)//2 if
arr[mid] == target: return mid elif arr[mid] < target: return binary_search_rec(arr, mid+1,
hi, target) else: return binary_search_rec(arr, lo, mid-1, target)
SECTION 4: MATHEMATICS & NUMBER THEORY

4.1 Prime Number Checks


def is_prime(n): if n < 2: return False for i in range(2, int(n**0.5)+1): if n%i == 0: return
False return True # Sieve of Eratosthenes (fastest for range) def sieve(n): s = [True]*(n+1);
s[0]=s[1]=False for i in range(2, int(n**0.5)+1): if s[i]: for j in range(i*i, n+1, i):
s[j]=False return [i for i in range(n+1) if s[i]] print(is_prime(17)) # True print(sieve(30)) #
[2,3,5,7,11,13,17,19,23,29]

4.2 GCD & LCM


def gcd(a, b): while b: a, b = b, a%b return a def lcm(a, b): return (a*b)//gcd(a,b)
print(gcd(48, 18)) # 6 print(lcm(4, 6)) # 12

4.3 Armstrong, Palindrome, Perfect, Strong Numbers


def is_armstrong(n): d = str(n); p = len(d) return sum(int(x)**p for x in d) == n def
is_perfect(n): return n>1 and sum(i for i in range(1,n) if n%i==0)==n def is_strong(n): fact
= lambda x: 1 if x<=1 else x*fact(x-1) return sum(fact(int(d)) for d in str(n)) == n def
is_palindrome_num(n): return str(n)==str(n)[::-1] print(is_armstrong(153)) # True
(1^3+5^3+3^3=153) print(is_perfect(28)) # True (1+2+4+7+14=28) print(is_strong(145)) # True
(1!+4!+5!=145)

4.4 Digit Operations & Number Conversions


def digit_sum(n): return sum(int(d) for d in str(abs(n))) def digit_prod(n): r=1 for d in
str(abs(n)): r*=int(d) return r def largest_digit(n): return max(int(d) for d in str(abs(n))) #
Conversions def to_binary(n): return bin(n)[2:] def to_octal(n): return oct(n)[2:] def
to_hex(n): return hex(n)[2:].upper() def bin_to_dec(b):return int(str(b), 2)
print(to_binary(10)) # 1010 print(to_hex(255)) # FF

4.5 Special Numbers


def is_neon(n): # Neon: sum of digits of n^2 == n return sum(int(d) for d in str(n*n)) == n def
is_harshad(n): # Harshad: n divisible by sum of its digits return n % digit_sum(n) == 0 def
is_automorphic(n): # Automorphic: n^2 ends with n return str(n*n).endswith(str(n)) def
is_leap_year(y): return (y%4==0 and y%100!=0) or (y%400==0) print(is_neon(9)) # True (81 →
8+1=9) print(is_automorphic(5)) # True (25 ends with 5) print(is_leap_year(2024)) # True
SECTION 5: PATTERN PROBLEMS

5.1 Right Triangle & Inverted Triangle


def right_triangle(n): for i in range(1, n+1): print("* " * i) def inverted_triangle(n): for i
in range(n, 0, -1): print("* " * i) # Output for n=4: # * * * * * # * * * * * # * * * * * # * * *
* *

5.2 Pyramid & Diamond


def pyramid(n): for i in range(1, n+1): print(" "*(n-i) + "* "*i) def diamond(n): for i in
range(1, n+1): print(" "*(n-i)+"* "*i) for i in range(n-1,0,-1): print(" "*(n-i)+"* "*i)

5.3 Floyd's Triangle & Pascal's Triangle


def floyds_triangle(n): num = 1 for i in range(1, n+1): for j in range(i): print(num, end=" ");
num+=1 print() def pascals_triangle(n): row = [1] for i in range(n): print(" ".join(map(str,
row))) row = [1]+[row[j]+row[j+1] for j in range(len(row)-1)]+[1] # Pascal's output (n=5): # 1 #
1 1 # 1 2 1 # 1 3 3 1 # 1 4 6 4 1

5.4 Hollow Rectangle & Butterfly


def hollow_rectangle(rows, cols): for i in range(rows): for j in range(cols): if i in(0,rows-1)
or j in(0,cols-1): print("*",end=" ") else: print(" ", end=" ") print() def butterfly(n): for i
in range(1, n+1): print("*"*i+" "*(2*(n-i))+"*"*i) for i in range(n, 0, -1): print("*"*i+"
"*(2*(n-i))+"*"*i)
SECTION 6: DATA STRUCTURES

6.1 Stack
class Stack: def __init__(self): [Link] = [] def push(self, v): [Link](v) def
pop(self): return [Link]() if [Link] else "Underflow" def peek(self): return
[Link][-1] if [Link] else "Empty" def is_empty(self): return len([Link])==0 def
size(self): return len([Link]) # Application: Balanced Parentheses def is_balanced(s): m =
{')':'(', '}':'{', ']':'['}; st=[] for c in s: if c in '({[': [Link](c) elif c in ')}]': if
not st or st[-1]!=m[c]: return False [Link]() return not st print(is_balanced("{[()]}")) # True
print(is_balanced("{[(])}")) # False

6.2 Queue
from collections import deque class Queue: def __init__(self): self.q = deque() def
enqueue(self, v): [Link](v) def dequeue(self): return [Link]() if self.q else
"Underflow" def front(self): return self.q[0] if self.q else "Empty" def is_empty(self): return
len(self.q)==0

6.3 Singly Linked List


class Node: def __init__(self, data): [Link]=data; [Link]=None class LinkedList: def
__init__(self): [Link]=None def append(self, data): n=Node(data) if not [Link]:
[Link]=n; return c=[Link] while [Link]: c=[Link] [Link]=n def display(self): r=[];
c=[Link] while c: [Link]([Link]); c=[Link] return r def reverse(self): prev=None;
c=[Link] while c: nxt=[Link]; [Link]=prev; prev=c; c=nxt [Link]=prev ll = LinkedList() for
v in [1,2,3,4,5]: [Link](v) print([Link]()) # [1,2,3,4,5] [Link]()
print([Link]()) # [5,4,3,2,1]

6.4 Hash Map / Dictionary Tricks


def frequency_count(arr): freq={} for x in arr: freq[x]=[Link](x,0)+1 return freq def
two_sum(arr, target): seen={} for i,v in enumerate(arr): if target-v in seen: return
(seen[target-v], i) seen[v]=i return None print(frequency_count([1,2,2,3,3,3])) # {1:1,2:2,3:3}
print(two_sum([2,7,11,15], 9)) # (0,1)
SECTION 7: IMPORTANT TCS NQT PROBLEMS

7.1 Kadane's Algorithm – Maximum Subarray Sum


def max_subarray_sum(arr): max_sum = curr = arr[0] for n in arr[1:]: curr = max(n, curr+n)
max_sum = max(max_sum, curr) return max_sum print(max_subarray_sum([-2,1,-3,4,-1,2,1,-5,4])) #
6

7.2 Find Missing Number


def find_missing(arr, n): return n*(n+1)//2 - sum(arr) print(find_missing([1,2,3,5,6,7,8,9],
9)) # 4

7.3 Move Zeros to End


def move_zeros(arr): arr=[Link](); pos=0 for i in range(len(arr)): if arr[i]!=0:
arr[pos],arr[i]=arr[i],arr[pos]; pos+=1 return arr print(move_zeros([0,1,0,3,12])) #
[1,3,12,0,0]

7.4 Leaders in an Array


def find_leaders(arr): leaders=[arr[-1]]; mx=arr[-1] for x in reversed(arr[:-1]): if x>=mx:
[Link](x); mx=x return leaders[::-1] print(find_leaders([16,17,4,3,5,2])) # [17,5,2]

7.5 Majority Element (Boyer-Moore Voting)


def majority_element(arr): cand=None; cnt=0 for n in arr: if cnt==0: cand=n cnt += 1 if n==cand
else -1 return cand if [Link](cand)>len(arr)//2 else None
print(majority_element([2,2,1,2,3,2,2])) # 2

7.6 Longest Substring Without Repeating Characters


def longest_unique(s): seen={}; start=mx=0 for i,c in enumerate(s): if c in seen and
seen[c]>=start: start=seen[c]+1 seen[c]=i; mx=max(mx,i-start+1) return mx
print(longest_unique("abcabcbb")) # 3

7.7 Check Rotation of String


def are_rotations(s1, s2): return len(s1)==len(s2) and s2 in s1+s1
print(are_rotations("abcde","cdeab")) # True

7.8 Matrix Spiral Traversal


def spiral_order(matrix): result=[] while matrix: result+=[Link](0)
matrix=list(zip(*matrix))[::-1] return result m=[[1,2,3],[4,5,6],[7,8,9]]
print(spiral_order(m)) # [1,2,3,6,9,8,7,4,5]

7.9 Matrix Transpose & Symmetric Check


def transpose(m): return [[m[j][i] for j in range(len(m))] for i in range(len(m[0]))] def
is_symmetric(m): n=len(m) return all(m[i][j]==m[j][i] for i in range(n) for j in range(n))
7.10 Count Inversions & Set Bits
def count_inversions(arr): return sum(1 for i in range(len(arr)) for j in range(i+1,len(arr)) if
arr[i]>arr[j]) def count_set_bits(n): return bin(n).count('1') def generate_subsets(arr):
res=[[]] for n in arr: res+=[s+[n] for s in res] return res print(count_inversions([2,4,1,3,5]))
# 3 print(count_set_bits(13)) # 3 (1101)

7.11 AP & GP Series


def nth_ap(a, d, n): return a + (n-1)*d # Arithmetic Progression def nth_gp(a, r, n): return a *
(r**(n-1)) # Geometric Progression def sum_of_squares(n): return sum(i**2 for i in range(1,n+1))
def sum_of_cubes(n): return sum(i**3 for i in range(1,n+1)) print(nth_ap(2, 3, 5)) # 14
(2,5,8,11,14) print(nth_gp(2, 3, 4)) # 54 (2,6,18,54)
SECTION 8: TIME COMPLEXITY & OPTIMIZATION

8.1 Big-O Reference Table

Complexity Name Example

O(1) Constant Array access arr[i]

O(log n) Logarithmic Binary Search

O(n) Linear Linear Search, Single loop

O(n log n) Log-linear Merge Sort, Quick Sort

O(n^2) Quadratic Bubble/Selection/Insertion Sort

O(2^n) Exponential Recursive Fibonacci (naive)

O(n!) Factorial Permutations of n elements

8.2 Memoization (Dynamic Programming)


# Naive Fibonacci: O(2^n) — too slow for large n def fib_naive(n): if n<=1: return n return
fib_naive(n-1) + fib_naive(n-2) # Memoized Fibonacci: O(n) — fast def fib_memo(n, memo={}): if n
in memo: return memo[n] if n<=1: return n memo[n] = fib_memo(n-1, memo) + fib_memo(n-2, memo)
return memo[n] print([fib_memo(i) for i in range(10)]) # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

8.3 Key Optimization Tips


• Use dict/set for O(1) lookups instead of O(n) list search
• Prefer Merge Sort / built-in sort O(n log n) over O(n²) algorithms
• Use memoization to convert exponential recursion → O(n)
• Use two-pointer technique to reduce O(n²) problems to O(n)
• Use sliding window for substring / subarray problems
• Use Kadane's algorithm for maximum subarray problems
• Use binary search whenever data is sorted

All TCS NQT Topics Covered!


Best of Luck with Your Exam! ■

You might also like