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

Day 2 Python Programs

The document contains a collection of Python functions that perform various tasks, such as removing duplicates from a list, checking for anagrams, generating passwords, and converting temperatures. It also includes functions for analyzing text, manipulating lists, and performing mathematical operations. Each function is accompanied by example usage and output.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views20 pages

Day 2 Python Programs

The document contains a collection of Python functions that perform various tasks, such as removing duplicates from a list, checking for anagrams, generating passwords, and converting temperatures. It also includes functions for analyzing text, manipulating lists, and performing mathematical operations. Each function is accompanied by example usage and output.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

1.

Function to Remove Duplicates from a List


def remove_duplicates(lst):
return list(set(lst))

numbers = [1, 2, 2, 3, 4, 4, 5]
print(remove_duplicates(numbers))

[Link] to Check Anagrams


def are_anagrams(str1, str2):
return sorted([Link]()) == sorted([Link]())

print(are_anagrams("listen", "silent"))

[Link] to Generate Password


import random
import string

def generate_password(length):
chars = string.ascii_letters + [Link] +
[Link]
return ''.join([Link](chars) for _ in
range(length))
print(generate_password(12))
adgjlklkj+123456789+-=@%$
4. Function to Convert Celsius to Fahrenheit
def celsius_to_fahrenheit(c):
return (c * 9/5) + 32

print(celsius_to_fahrenheit(25))
5. function to Find Second Largest Number
def second_largest(lst):
unique = list(set(lst))
[Link]()
return unique[-2]

numbers = [10, 20, 30, 40, 50]


print("Second Largest:", second_largest(numbers))
[Link] to Find Sum of Digits
def sum_of_digits(num):
return sum(int(digit) for digit in str(num))

num = int(input("Enter a number: "))


print("Sum of Digits:", sum_of_digits(num))
7. Function to Check Armstrong Number
def is_armstrong(num):
digits = len(str(num))
total = sum(int(digit) ** digits for digit in
str(num))
return total == num

num = int(input("Enter a number: "))


print("Armstrong" if is_armstrong(num) else "Not
Armstrong")
[Link] to Find GCD
def gcd(a, b):
while b:
a, b = b, a % b
return a

print("GCD:", gcd(24, 36))

9) Check if Two Strings are Rotations


def is_rotation(s1, s2):
return len(s1) == len(s2) and s2 in (s1 + s1)

print(is_rotation("ABCD", "CDAB"))
10) Longest Word in a Sentence
def longest_word(sentence):
words = [Link]()
return max(words, key=len)

s = input("Enter a sentence: ")


print("Longest word:", longest_word(s))
11) Count Words, Characters, and Lines
def text_analysis(text):
words = len([Link]())
chars = len(text)
return words, chars

text = input("Enter text: ")


w, c = text_analysis(text)
print("Words:", w)
print("Characters:", c)
12) Check Pangram
import string

def is_pangram(sentence):
alphabet = set(string.ascii_lowercase)
return alphabet <= set([Link]())
s = input("Enter a sentence: ")
print(is_pangram(s))
13) Most Frequent Character
def most_frequent(text):
return max(set(text), key=[Link])

s = input("Enter a string: ")


print("Most frequent:", most_frequent(s))
14) Convert String to Title Case Without title()
def custom_title(sentence):
return " ".join([Link]() for word in
[Link]())

s = input("Enter sentence: ")


print(custom_title(s))
15) String Compression
def compress(text):
result = ""
count = 1

for i in range(len(text)-1):
if text[i] == text[i+1]:
count += 1
else:
result += text[i] + str(count)
count = 1

result += text[-1] + str(count)


return result

print(compress("aaabbcccc"))
16) Find All Duplicate Characters
def duplicates(text):
dup = []
for ch in text:
if [Link](ch) > 1 and ch not in dup:
[Link](ch)
return dup

print(duplicates("programming"))
17) Reverse Each Word in a Sentence
def reverse_words(sentence):
return " ".join(word[::-1] for word in
[Link]())

s = input("Enter sentence: ")


print(reverse_words(s))
Input: Python is easy
Output: nohtyP si ysae
18) Check Valid Password
def validate_password(password):
return (
len(password) >= 8 and
any([Link]() for c in password) and
any([Link]() for c in password) and
any([Link]() for c in password)
)

pwd = input("Enter password: ")


print("Valid" if validate_password(pwd) else
"Invalid")

19 Find Longest Palindromic Word


def longest_palindrome(sentence):
words = [Link]()
palindromes = [w for w in words if w == w[::-1]]
return max(palindromes, key=len,
default="None")

s = input("Enter sentence: ")


print(longest_palindrome(s))
20. Generate Acronym
def acronym(phrase):
return "".join(word[0].upper() for word in
[Link]())

text = input("Enter phrase: ")


print(acronym(text))
Input: Artificial Intelligence and Machine Learning
Output: AIAML

Find Largest Element in a List


numbers = [10, 25, 8, 45, 32]

largest = max(numbers)
print("Largest element:", largest)

2. Find Smallest Element in a List


numbers = [10, 25, 8, 45, 32]

smallest = min(numbers)
print("Smallest element:", smallest)
3. Find Sum of Elements
numbers = [10, 20, 30, 40, 50]

print("Sum:", sum(numbers))

4. Find Average of Elements


numbers = [10, 20, 30, 40, 50]

average = sum(numbers) / len(numbers)


print("Average:", average)

5. Find Second Largest Element


numbers = [10, 20, 30, 40, 50]

[Link]()
print("Second Largest:", numbers[-2])

6. Remove Duplicates from a List


numbers = [1, 2, 2, 3, 4, 4, 5]

unique = list(set(numbers))
print(unique)
7. Reverse a List
numbers = [10, 20, 30, 40, 50]

[Link]()
print(numbers)

8. Check if Element Exists


numbers = [10, 20, 30, 40, 50]

key = 30

if key in numbers:
print("Found")
else:
print("Not Found")

9. Count Occurrences of an Element


numbers = [1, 2, 3, 2, 4, 2, 5]

print([Link](2))

10. Merge Two Lists


list1 = [1, 2, 3]
list2 = [4, 5, 6]

merged = list1 + list2


print(merged)

11. Find Common Elements Between Two Lists


list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]

common = list(set(list1) & set(list2))


print(common)

12. Sort a List in Ascending Order


numbers = [50, 20, 40, 10, 30]

[Link]()
print(numbers)

13. Sort a List in Descending Order


numbers = [50, 20, 40, 10, 30]
[Link](reverse=True)
print(numbers)

14. Find Even Numbers in a List


numbers = [1, 2, 3, 4, 5, 6]

even = [num for num in numbers if num % 2 == 0]


print(even)

15. Find Odd Numbers in a List


numbers = [1, 2, 3, 4, 5, 6]

odd = [num for num in numbers if num % 2 != 0]


print(odd)

16. Rotate List by One Position


numbers = [1, 2, 3, 4, 5]

rotated = numbers[-1:] + numbers[:-1]


print(rotated)

17. Find Duplicate Elements


numbers = [1, 2, 3, 2, 4, 5, 1]

duplicates = []

for num in numbers:


if [Link](num) > 1 and num not in
duplicates:
[Link](num)

print(duplicates)

18. Separate Positive and Negat


Negative Numbers
numbers = [-5, 10, -2, 15, 0, -8]

positive = [x for x in numbers if x >= 0]


negative = [x for x in numbers if x < 0]

print("Positive:", positive)
print("Negative:", negative)

19. List Comprehension – Squares of Numbers


numbers = [1, 2, 3, 4, 5]

squares = [x**2 for x in numbers]

print(squares)

20. Matrix Addition Using Nested Lists


A = [[1, 2],
[3, 4]]

B = [[5, 6],
[7, 8]]

result = [[0, 0], [0, 0]]

for i in range(2):
for j in range(2):
result[i][j] = A[i][j] + B[i][j]

print(result)

21. Find the Kth Largest Element


def kth_largest(lst, k):
[Link](reverse=True)
return lst[k - 1]

numbers = [10, 5, 20, 8, 15]


k=3

print("Kth Largest:", kth_largest(numbers, k))


Output:
Kth Largest: 10

22. Linear Search


def linear_search(lst, key):
for i in range(len(lst)):
if lst[i] == key:
return i
return -1

numbers = [10, 20, 30, 40, 50]

print("Index:", linear_search(numbers, 40))

23. Binary Search


def binary_search(lst, key):
low = 0
high = len(lst) - 1
while low <= high:
mid = (low + high) // 2

if lst[mid] == key:
return mid
elif lst[mid] < key:
low = mid + 1
else:
high = mid - 1

return -1

numbers = [10, 20, 30, 40, 50]

print("Index:", binary_search(numbers, 30))

24. Remove All Occurrences of an Element


numbers = [1, 2, 3, 2, 4, 2, 5]

key = 2

result = [x for x in numbers if x != key]

print(result)
25. Find Pairs with Given Sum
numbers = [1, 2, 3, 4, 5, 6]
target = 7

for i in range(len(numbers)):
for j in range(i + 1, len(numbers)):
if numbers[i] + numbers[j] == target:
print(numbers[i], numbers[j])
Output:
16
25
34

26. Flatten a Nested List


nested = [[1, 2], [3, 4], [5, 6]]

flat = [item for sublist in nested for item in sublist]

print(flat)
Output:
[1, 2, 3, 4, 5, 6]
27. Transpose a Matrix
matrix = [
[1, 2, 3],
[4, 5, 6]
]

transpose = []

for i in range(len(matrix[0])):
row = []
for j in range(len(matrix)):
[Link](matrix[j][i])
[Link](row)

print(transpose)

28. Find Missing Number


numbers = [1, 2, 3, 5]

n=5

missing = (n * (n + 1)) // 2 - sum(numbers)

print("Missing Number:", missing)


29. Rotate List by K Positions
numbers = [1, 2, 3, 4, 5]

k=2

rotated = numbers[-k:] + numbers[:-k]

print(rotated)
Output:
[4, 5, 1, 2, 3]

30. Merge and Sort Multiple Lists


list1 = [10, 30, 20]
list2 = [50, 40]
list3 = [70, 60]

merged = list1 + list2 + list3

[Link]()

print(merged)
Output:
[10, 20, 30, 40, 50, 60, 70]
Find Frequency of Each Element
numbers = [1, 2, 2, 3, 1, 4, 2]

frequency = {}

for num in numbers:


frequency[num] = [Link](num, 0) + 1

print(frequency)
Output:
{1: 2, 2: 3, 3: 1, 4: 1}

You might also like