# Coding Interview Questions in Python

## Coding Interview Questions and Answers in Python

Coding Interview Questions and Answers in Python” is given here on this apge.

Below you will get all the Interview Coding Questions in Python. You will get to know what type of coding questions are asked in the Interview that will help you to crack the interview.

Below you will find similar pattern based questions of coding that are asked in the Interview. These are the most asked questions in the Interview.

## What is Python Programming Langauge?

Python is a general purpose and high level programming language. You can use Python for developing desktop GUI applications, websites and web applications. Also, Python, as a high level programming language, allows you to focus on core functionality of the application by taking care of common programming tasks.

## Commonly Asked Coding Interview Questions and Answers in Python

#### 1. Python Program for Program to find the area of a circle using radius.

Solution:-
Area = pi * r2
where r is radius of circle

`# Python program to find Area of a circle`

def findArea(r):
PI = 3.142
return PI * (r*r);

# Driver method
print(“Area is %.6f” % findArea(5));

#### 2. Write a Python Program for Sum of squares of first n natural numbers

Solution:-

Given a positive integer N. The task is to find 12 + 22 + 32 + ….. + N2.

Examples:

Input : N = 4

Output : 30 12 + 22 + 32 + 42 = 1 + 4 + 9 + 16 = 30

Input : N = 5 Output : 55

`sm = 0for i in range(1, n+1) : sm = sm + (i * i)return sm# Driven Program n = 4print(squaresum(n))`

#### 3.Write a Python program to interchange first and last elements in a list.

Solution:-

Input : [12, 35, 9, 56, 24]

Output : [24, 35, 9, 56, 12]

Input : [1, 2, 3]

Output : [3, 2, 1]

```def swapList(newList):
size = len(newList)

# Swapping
temp = newList[0]
newList[0] = newList[size - 1]
newList[size - 1] = temp

return newList newList = [12, 35, 9, 56, 24]

print(swapList(newList))

OUTPUT:-
[24, 35, 9, 56, 12]

```

#### 4. Write a Python program to find smallest number in a list.

```Input : list1 = [10, 20, 4]Output : 4Input : list2 = [20, 10, 20, 1, 100] Output : 1# list of numbers
list1 = [10, 20, 4, 45, 99]# sorting the listlist1.sort()# printing the first elementprint("Smallest element is:", *list1[:1])```

Output:-

smallest element is: 4

#### 5. Write a Python program to print even numbers in a list.

Input: list1 = [2, 7, 5, 64, 14] Output: [2, 64, 14]

Input: list2 = [12, 14, 95, 3]

Output: [12, 14]

`# list of numbers list1 = [10, 21, 4, 45, 66, 93]# iterating each number in list for num in list1: # checking condition if num % 2 == 0: print(num, end = " ") `

OUTPUT:-

10,4,66

#### 6.Write a Python program to print all negative numbers in a range.

Solution:-

Input: start = -4, end = 5

Output: -4, -3, -2, -1

Input: start = -3, end = 4 Output: -3, -2, -1

```# Python program to print negative Numbers in given range

start, end = -4, 19

# iterating each number in list
for num in range(start, end + 1):

# checking condition
if num < 0:
print(num, end = " ")

```

OUTPUT

-4, -3, -2, -1

#### 7. Python program to check if a string is palindrome or not.

Solution:-

Input : malayalam Output : Yes

Input : geeks Output : No

```# function which return reverse of a string

def isPalindrome(s):
return s == s[::-1]

# Driver code
s = "malayalam"
ans = isPalindrome(s)

if ans:
print("Yes")
else:
print("No")```

OUTPUT:-

Yes

#### 8.Python program to print even length words in a string.

Solution:-

```Input: s = "This is a python language"
Output: This
is
python
language

Input: s = "i am muskan"
Output: am
muskan

```
```# even length words in a string

def printWords(s):

# split the string
s = s.split(' ')

# iterate in words of string
for word in s:

# if length is even
if len(word)%2==0:
print(word)

# Driver Code
s = "i am muskan"
printWords(s)```

OUTPUT:
am
muskan

#### 9.Write a Python Program for QuickSort.

Solution:-

`def partition(arr,low,high): i = ( low-1 ) # index of smaller element pivot = arr[high] # pivotfor j in range(low , high): # If current element is smaller than or # equal to pivot if arr[j] <= pivot: # increment index of smaller element i = i+1 arr[i],arr[j] = arr[j],arr[i] arr[i+1],arr[high] = arr[high],arr[i+1] return ( i+1 ) # The main function that implements QuickSort # arr[] --> Array to be sorted, # low --> Starting index, # high --> Ending index # Function to do Quick sort def quickSort(arr,low,high): if low < high: # pi is partitioning index, arr[p] is now # at right place pi = partition(arr,low,high) # Separately sort elements before # partition and after partition quickSort(arr, low, pi-1) quickSort(arr, pi+1, high) # Driver code to test above arr = [10, 7, 8, 9, 1, 5] n = len(arr) quickSort(arr,0,n-1) print ("Sorted array is:") for i in range(n): print ("%d" %arr[i]), `

#### 10. Python Program for Find sum of odd factors of a number.

Solution:- Input : n = 30 Output : 24 Odd dividers sum 1 + 3 + 5 + 15 = 24 Input : 18 Output : 13 Odd dividers sum 1 + 3 + 9 = 13
```# Returns sum of all factors
# of n.
def sumofoddFactors( n ):
# Traversing through all
# prime factors.
res = 1

# ignore even factors by
# of 2
while n % 2 == 0:
n = n // 2

for i in range(3, int(math.sqrt(n) + 1)):

# While i divides n, print
# i and divide n
count = 0
curr_sum = 1
curr_term = 1
while n % i == 0:
count+=1

n = n // i
curr_term *= i
curr_sum += curr_term

res *= curr_sum

# This condition is to
# handle the case when
# n is a prime number.
if n >= 2:
res *= (1 + n)

return res

# Driver code
n = 30
print(sumofoddFactors(n))
```
11. Write a Python program to convert time from 12 hour to 24 hour format. Solution:-  Given a time in 12-hour AM/PM format, convert it to military (24-hour) time. Note : Midnight is 12:00:00 AM on a 12-hour clock and 00:00:00 on a 24-hour clock. Noon is 12:00:00 PM on 12-hour clock and 12:00:00 on 24-hour clock. Examples : Input : 11:21:30 PM Output : 23:21:30 Input : 12:12:20 AM Output : 00:12:20
```# Function to convert the date format
def convert24(str1):
# Checking if last two elements of time
# is AM and first two elements are 12
if str1[-2:] == "AM" and str1[:2] == "12":
return "00" + str1[2:-2]

# remove the AM
elif str1[-2:] == "AM":
return str1[:-2]

# Checking if last two elements of time
# is PM and first two elements are 12
elif str1[-2:] == "PM" and str1[:2] == "12":
return str1[:-2]

else:

# add 12 to hours and remove PM
return str(int(str1[:2]) + 12) + str1[2:8]

# Driver Code
print(convert24("08:05:45 PM"))
```
```OUTPUT

20:05:45
```

#### 12. Write a Python Program for Find largest prime factor of a number.

Solution:- Given a positive integer \’n\'( 1 <= n <= 1015). Find the largest prime factor of a number. Input: 6 Output: 3 Explanation Prime factor of 6 are- 2, 3 Largest of them is \’3\’ Input: 15 Output: 5
```# Initialize the maximum prime factor
# variable with the lowest one
maxPrime = -1
# Print the number of 2s that divide n
while n % 2 == 0:
maxPrime = 2
n >>= 1 # equivalent to n /= 2

# n must be odd at this point,
# thus skip the even numbers and
# iterate only for odd integers
for i in range(3, int(math.sqrt(n)) + 1, 2):
while n % i == 0:
maxPrime = i
n = n / i

# This condition is to handle the
# case when n is a prime number
# greater than 2
if n > 2:
maxPrime = n

return int(maxPrime)

# Driver code to test above function
n = 15
print(maxPrimeFactors(n))

n = 25698751364526
print(maxPrimeFactors(n))
```

#### 13. Write a Python Program for n-th Fibonacci number.

Fn = Fn-1 + Fn-2

with seed values

F0 = 0 and F1 = 1.

`def Fibonacci(n): if n<0: print("Incorrect input") # First Fibonacci number is 0 elif n==1: return 0# Second Fibonacci number is 1 elif n==2: return 1else: return Fibonacci(n-1)+Fibonacci(n-2)`

# Driver Program

print(Fibonacci(9))

#### 14. Write a Python Program for Bubble Sort.

Solution:-
```def bubbleSort(arr):
n = len(arr)
# Traverse through all array elements
for i in range(n-1):
# range(n) also work but outer loop will repeat one time more than needed.

# Last i elements are already in place
for j in range(0, n-i-1):

# traverse the array from 0 to n-i-1
# Swap if the element found is greater
# than the next element
if arr[j] > arr[j+1] :
arr[j], arr[j+1] = arr[j+1], arr[j]

# Driver code to test above
arr = [64, 34, 25, 12, 22, 11, 90]

bubbleSort(arr)

print ("Sorted array is:")
for i in range(len(arr)):
print ("%d" %arr[i]),
```

#### 15. How can you create Empty NumPy Array In Python?

Solution:- We can create Empty NumPy Array in two ways in Python:

```import numpy
numpy.array([])```
`numpy.empty(shape=(0,0))`

#### 16. How to convert a list into a set?

Solution:-
```weekdays = ['sun','mon','tue','wed','thu','fri','sat','sun','tue']
listAsSet = set(weekdays)
print(listAsSet)```

#### 17. How to convert a list into a string?

Solution:-
```weekdays = ['sun','mon','tue','wed','thu','fri','sat']
listAsString = ' '.join(weekdays)
print(listAsString)```

#### 18. How to convert a list into a set?

Solution:-

`weekdays = ['sun','mon','tue','wed','thu','fri','sat','sun','tue']listAsSet = set(weekdays)print(listAsSet)`

#### 19. How to count the occurrences of a particular element in the list?

Solution:- We can count the occurrences of an individual element by using a <count()> function.
```weekdays = ['sun','mon','tue','wed','thu','fri','sun','mon','mon']
print(weekdays.count('mon'))```

#### 20. How to generate random numbers in Python?

Solution:- We can generate random numbers using different functions in Python. They are:

1.  random() – This command returns a floating point number, between 0 and 1.
2.  uniform(X, Y) – It returns a floating point number between the values given as X and Y.
3.  randint(X, Y) – This command returns a random integer between the values given as X and Y.