Python Coding – Interview Questions – 1


Please find below some of the common interview questions asked and their solutions related to coding in interviews:

Expand All Questions   Collapse All Questions
Question 1: How to reverse a string in python?

Answer: There are many ways to reverse a string in python:

  1. Slicing syntax of strings:
def reverse(stri):
    return stri[::-1]

print(reverse("string"))  # gnirts

2. Using list reverse() function and join:

def reverse(stri):
    stri = [ s for s in stri ] # stri = list(stri)
    stri.reverse()
    return (''.join(stri))

print(reverse("string"))  # gnirts

3. Using reversed() in=built funciton:

def reverse(stri):
    l = list(reversed(stri))
    return ''.join(l)

print(reverse("string")) # gnirts

Question 2: Write a function to find factorial of a number and optimize it using generator by storing the generate values.

Answer:

memory={}
def decorater_memo(fibonacci):
    def memoize(num):
        if num in memory.keys():
            return memory[num]
        else:
            memory[num]=fibonacci(num)
        return memory[num]
    return memoize

@decorater_memo
def fibonacci(num):
    if num <0:
        return 0
    elif num==0:
        return 1
    else:
        return fibonacci(num-2)+fibonacci(num-1)
    
for i in range(100):
    #print(memory)
    print(fibonacci(i))


Question 3: Given an array of integers and a target sum, find all pairs of integers in the array that sum up to the target.
Input: nums = [2,7,11,15], target = 9
Output: [0,1]

Answer: We will create a function which will take a list and target as input then check every pair of elements and their sum against target value:

def pair_sum(arr,target):
    for i in range(len(arr)):
        for j in range(i,len(arr)):
            if i != j and arr[i] + arr[j] == target:
                print([i,j])
pair_sum([2,7,11,15], 9)

Question 4: Write a Python program to print a Triangle pattern
Input: 5
Output:

Answer:

def pattern(num):
    for i in range(num):
        print("* "*(num-i),end="")
        print("  "*((i*2)+1),end="")
        print("* "*(num-i),end="")
        print()
pattern(5)

Following is single line print statement:

def pattern(num):
    print( '\n'.join([("  "*((i*2)+1)).join(["* "*(num-i),"* "*(num-i)]) for i in range(num) ]))
        
pattern(5)

Question 5: Count number of vowels in a string in python.

Answer: Following code can count the number of vowels in python string:

def count_vowels(s):
    c = {}
    for x in s:
        if x in 'aeiouAEIOU':
            if(x in c.keys()):
                c[x] += 1
            else:
                c[x] = 1
    return sum(c.values())

print(count_vowels("this is a string")) #4

using string.count() and dict comprehension:

def count_vowels(s):
    c = { x: s.count(x) for x in 'aeiouAEIOU'}
    return sum(c.values())

print(count_vowels("this is a string")) #4

using collections.Counter() and filter function:

from collections import Counter
def count_vowels(s):
    c = Counter(s)
    c = dict(filter(lambda x: x[0] in 'aeiouAEIOU' ,c.items()))
    return sum(c.values())

print(count_vowels("this is a string")) #4

Note: we have calculated each character occurrence separately and then added the values to provide two types of solutions at the same time. first separate count and second total count of vowels.


Leave a Reply

Your email address will not be published. Required fields are marked *

Related Post