0% found this document useful (0 votes)
2 views2 pages

Python Coding Questions and Solutions

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)
2 views2 pages

Python Coding Questions and Solutions

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

Python Coding Questions with Solutions (Set 1)

1. Reverse a String
def reverse_string(s):
return s[::-1]

2. Check if a number is prime


def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5)+1):
if n % i == 0:
return False
return True

3. Find the factorial of a number


def factorial(n):
if n == 0 or n == 1:
return 1
return n * factorial(n-1)

4. Fibonacci sequence up to N terms


def fibonacci(n):
seq = [0, 1]
for i in range(2, n):
[Link](seq[-1] + seq[-2])
return seq[:n]

5. Check if a string is a palindrome


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

6. Find the largest element in an array


def find_max(arr):
return max(arr)

7. Find the second largest element in an array


def second_largest(arr):
arr = list(set(arr))
[Link]()
return arr[-2] if len(arr) > 1 else None

8. Remove duplicates from a list


def remove_duplicates(lst):
return list(set(lst))
9. Sort a list without using built-in sort
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr

10. Merge two sorted arrays


def merge_sorted_arrays(a, b):
result = []
i = j = 0
while i < len(a) and j < len(b):
if a[i] < b[j]:
[Link](a[i])
i += 1
else:
[Link](b[j])
j += 1
result += a[i:] + b[j:]
return result

You might also like