Posted in

Python programming

1. Python program for n-th Fibonacci number using Recursion

def fibonacci(n):
if n == 1 or n == 2:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)

n = int(input(“Enter n: “))
print(“Fibonacci number:”, fibonacci(n))


2. Python function to reverse a string if its length is a multiple of 4

def reverse_string(s):
if len(s) % 4 == 0:
return s[::-1]
else:
return s

print(reverse_string(“abcd”))
print(reverse_string(“python”))


3. Combine list of tuples into a dictionary (sum duplicate keys)

data = [(“apple”, 2), (“banana”, 3), (“apple”, 4)]
result = {}

for key, value in data:
result[key] = result.get(key, 0) + value

print(result)


4. Pair elements of two tuples into a list of tuples

t1 = (1, 2, 3)
t2 = (‘a’, ‘b’, ‘c’)

paired = list(zip(t1, t2))
print(paired)


5. Create a new tuple of words ending with letter “e”

words = (“apple”, “banana”, “orange”, “grape”, “mango”)
new_tuple = tuple(word for word in words if word.endswith(‘e’))

print(new_tuple)


6. Student class with pass/fail method

class Student:
def __init__(self, roll, marks):
self.roll = roll
self.marks = marks

def check_pass(self):
if self.marks >= 40:
return “Passed”
else:
return “Failed”

s1 = Student(1, 55)
print(s1.check_pass())


7. Count occurrences of each word in a sentence

sentence = “python is fun and python is powerful”
words = sentence.split()
count = {}

for word in words:
count[word] = count.get(word, 0) + 1

print(count)


8. Use filter() and lambda to extract numbers divisible by 10

nums = [5, 10, 15, 20, 25]
result = list(filter(lambda x: x % 10 == 0, nums))

print(result)


9. Function to find the maximum number in a list

def find_max(numbers):
return max(numbers)

print(find_max([10, 25, 5, 40, 15]))


10. Inheritance: Employee and SalesEmployee classes

class Employee:
def __init__(self, id, salary):
self.id = id
self.salary = salary

class SalesEmployee(Employee):
def __init__(self, id, salary, sales):
super().__init__(id, salary)
self.sales = sales

se = SalesEmployee(101, 30000, 5000)
print(se.id, se.salary, se.sales)

Leave a Reply

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