Python Programs

 

1. Fibonacci Series

Problem: Generate a Fibonacci series up to n terms.

python
def fibonacci(n):
    a, b = 0, 1
    series = []
    while len(series) < n:
        series.append(a)
        a, b = b, a + b
    return series

# Example usage
print(fibonacci(10))

2. Prime Number Check

Problem: Check if a given number is a prime number.

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

# Example usage
print(is_prime(29))

3. Palindrome Check

Problem: Check if a given string is a palindrome.

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

# Example usage
print(is_palindrome("racecar"))

4. Factorial

Problem: Compute the factorial of a number.

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

# Example usage
print(factorial(5))

5. Bubble Sort

Problem: Sort an array using bubble sort.

python
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

# Example usage
print(bubble_sort([64, 34, 25, 12, 22, 11, 90]))

6. Reverse a String

Problem: Reverse a given string.

python
def reverse_string(s):
    return s[::-1]

# Example usage
print(reverse_string("hello"))

7. Merge Two Sorted Lists

Problem: Merge two sorted lists into a single sorted list.

python
def merge_lists(l1, l2):
    sorted_list = []
    while l1 and l2:
        if l1[0] < l2[0]:
            sorted_list.append(l1.pop(0))
        else:
            sorted_list.append(l2.pop(0))
    sorted_list.extend(l1 if l1 else l2)
    return sorted_list

# Example usage
print(merge_lists([1, 3, 5], [2, 4, 6]))

8. Find Largest Element in an Array

Problem: Find the largest element in a list.

python
def find_largest(arr):
    return max(arr)

# Example usage
print(find_largest([3, 41, 12, 9, 74, 15]))

9. Sum of Digits

Problem: Find the sum of the digits of a number.

python
def sum_of_digits(num):
    return sum(int(digit) for digit in str(num))

# Example usage
print(sum_of_digits(12345))

10. Anagram Check

Problem: Check if two strings are anagrams.

python
def are_anagrams(str1, str2):
    return sorted(str1) == sorted(str2)

# Example usage
print(are_anagrams("listen", "silent"))

11. Find the Second Largest Element in an Array

Problem: Find the second largest element in a list.

python
def second_largest(arr):
    first, second = float('-inf'), float('-inf')
    for number in arr:
        if number > first:
            second, first = first, number
        elif first > number > second:
            second = number
    return second

# Example usage
print(second_largest([3, 41, 12, 9, 74, 15]))

12. Armstrong Number

Problem: Check if a given number is an Armstrong number.

python
def is_armstrong(num):
    sum = 0
    temp = num
    while temp > 0:
        digit = temp % 10
        sum += digit ** 3
        temp //= 10
    return num == sum

# Example usage
print(is_armstrong(153))

13. Remove Duplicates from a List

Problem: Remove duplicates from a list while maintaining the order.

python
def remove_duplicates(lst):
    seen = set()
    result = []
    for item in lst:
        if item not in seen:
            seen.add(item)
            result.append(item)
    return result

# Example usage
print(remove_duplicates([1, 2, 2, 3, 4, 4, 5]))

14. Find Common Elements in Two Lists

Problem: Find common elements between two lists.

python
def common_elements(lst1, lst2):
    return list(set(lst1) & set(lst2))

# Example usage
print(common_elements([1, 2, 3, 4], [3, 4, 5, 6]))

15. Sum of Even Numbers in a List

Problem: Find the sum of all even numbers in a list.

python
def sum_of_evens(lst):
    return sum(num for num in lst if num % 2 == 0)

# Example usage
print(sum_of_evens([1, 2, 3, 4, 5, 6]))

16. Count Vowels in a String

Problem: Count the number of vowels in a given string.

python
def count_vowels(s):
    vowels = "aeiouAEIOU"
    return sum(1 for char in s if char in vowels)

# Example usage
print(count_vowels("hello world"))

17. Reverse Words in a Sentence

Problem: Reverse the words in a given sentence.

python
def reverse_words(sentence):
    words = sentence.split()
    return ' '.join(reversed(words))

# Example usage
print(reverse_words("hello world"))

18. Find the Longest Word in a Sentence

Problem: Find the longest word in a given sentence.

python
def longest_word(sentence):
    words = sentence.split()
    return max(words, key=len)

# Example usage
print(longest_word("This is an example sentence to find the longest word"))

19. Count the Frequency of Elements in a List

Problem: Count the frequency of each element in a list.

python
def count_frequency(lst):
    frequency = {}
    for item in lst:
        if item in frequency:
            frequency[item] += 1
        else:
            frequency[item] = 1
    return frequency

# Example usage
print(count_frequency([1, 2, 2, 3, 3, 3, 4, 4, 4, 4]))

20. Find the Intersection of Two Lists

Problem: Find the intersection of two lists.

python
def intersection(lst1, lst2):
    return list(set(lst1) & set(lst2))

# Example usage
print(intersection([1, 2, 3, 4], [3, 4, 5, 6]))

21. Convert Decimal to Binary

Problem: Convert a given decimal number to its binary equivalent.

python
def decimal_to_binary(n):
    return bin(n).replace("0b", "")

# Example usage
print(decimal_to_binary(10))

22. Generate All Subsets of a Set

Problem: Generate all possible subsets of a set.

python
from itertools import chain, combinations

def all_subsets(s):
    return list(chain.from_iterable(combinations(s, r) for r in range(len(s) + 1)))

# Example usage
print(all_subsets([1, 2, 3]))

23. GCD of Two Numbers

Problem: Find the greatest common divisor (GCD) of two numbers.

python
import math

def gcd(a, b):
    return math.gcd(a, b)

# Example usage
print(gcd(54, 24))

24. LCM of Two Numbers

Problem: Find the least common multiple (LCM) of two numbers.

python
def lcm(a, b):
    return abs(a * b) // math.gcd(a, b)

# Example usage
print(lcm(54, 24))

25. Check for Balanced Parentheses

Problem: Check if a string of parentheses is balanced.

python
def is_balanced(s):
    stack = []
    mapping = {')': '(', '}': '{', ']': '['}
    for char in s:
        if char in mapping:
            top_element = stack.pop() if stack else '#'
            if mapping[char] != top_element:
                return False
        else:
            stack.append(char)
    return not stack

# Example usage
print(is_balanced("()[]{}"))
print(is_balanced("([)]"))

26. Matrix Transpose

Problem: Find the transpose of a matrix.

python
def transpose(matrix):
    return [list(row) for row in zip(*matrix)]

# Example usage
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]
print(transpose(matrix))

27. Count Occurrences of a Character in a String

Problem: Count the number of occurrences of a specific character in a string.

python
def count_char(s, char):
    return s.count(char)

# Example usage
print(count_char("hello world", 'o'))

28. Find the Missing Number in an Array

Problem: Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.

python
def find_missing(arr):
    n = len(arr)
    total = (n * (n + 1)) // 2
    return total - sum(arr)

# Example usage
print(find_missing([0, 1, 3, 4, 5]))

29. Find Duplicates in an Array

Problem: Find all the duplicates in an array.

python
def find_duplicates(arr):
    seen = set()
    duplicates = set()
    for num in arr:
        if num in seen:
            duplicates.add(num)
        else:
            seen.add(num)
    return list(duplicates)

# Example usage
print(find_duplicates([1, 2, 3, 1, 2, 4, 5]))

30. Find the Intersection of Multiple Lists

Problem: Find the intersection of multiple lists.

python
def intersection_of_lists(*lists):
    return list(set.intersection(*map(set, lists)))

# Example usage
print(intersection_of_lists([1, 2, 3], [2, 3, 4], [3, 4, 5]))




Comments

Popular posts from this blog

Resume Work and Project Details

Time Series and MMM basics

LINEAR REGRESSION