Python Coding Cheat Sheet for Cognizant GenC Interview
1. Reverse a String
def reverse_string(s):
return s[::-1]
# Example:
print(reverse_string("hello")) # Output: "olleh"
2. Check if a String is Palindrome
def is_palindrome(s):
return s == s[::-1]
# Example:
print(is_palindrome("madam")) # Output: True
print(is_palindrome("python")) # Output: False
3. Factorial of a Number
def factorial(n):
if n == 0 or n == 1:
return 1
return n * factorial(n - 1)
# Example:
print(factorial(5)) # Output: 120
4. Fibonacci Series
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
print(a, end=' ')
a, b = b, a + b
# Example:
fibonacci(6) # Output: 0 1 1 2 3 5
5. Sum of Digits of a Number
def sum_of_digits(n):
return sum(int(digit) for digit in str(n))
# Example:
print(sum_of_digits(1234)) # Output: 10
6. Check Prime Number
def is_prime(n):
if n <= 1:
Python Coding Cheat Sheet for Cognizant GenC Interview
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
# Example:
print(is_prime(11)) # Output: True
print(is_prime(10)) # Output: False
7. Print All Primes in a Range
def primes_in_range(start, end):
for num in range(start, end + 1):
if is_prime(num):
print(num, end=' ')
# Example:
primes_in_range(10, 20) # Output: 11 13 17 19
8. Second Largest Number in a List
def second_largest(nums):
nums = list(set(nums)) # Remove duplicates
nums.sort()
return nums[-2]
# Example:
print(second_largest([4, 1, 7, 3, 7, 2])) # Output: 4
9. Check for Anagrams
def are_anagrams(str1, str2):
return sorted(str1) == sorted(str2)
# Example:
print(are_anagrams("listen", "silent")) # Output: True
print(are_anagrams("hello", "world")) # Output: False
10. Frequency of Each Character
from collections import Counter
def char_frequency(s):
return dict(Counter(s))
# Example:
print(char_frequency("hello")) # Output: {'h': 1, 'e': 1, 'l': 2, 'o': 1}