Record File
Record File
def odd_sum(lst):
return sum(x for x in lst if x % 2)
lst = [3, 1, 9, 7, 4]
d = max(lst) - min(lst)
print(d)
3. Function to remove all occurrences of a given element from a list:
def is_sorted(lst):
for i in range(len(lst) - 1):
if lst[i] > lst[i + 1]:
return False
return True
5. Program to count the number of elements greater than a given
value in a list:
def split_lst(lst):
m = len(lst) // 2
return lst[:m], lst[m:]
7. Program to find the product of all elements in a list:
lst = [2, 3, 4, 5]
p = 1
for x in lst:
p *= x
print(p)
8. Function that takes a list and returns a new list with only the
elements at even indices:
def even_idx(lst):
return lst[::2]
9. Program to rotate a list to the left by one position:
lst = [1, 2, 3, 4, 5]
lst.append(lst.pop(0))
print(lst)
Tuples
t = (1, 2, 3, 4, 5)
s = sum(t)
print(s)
11. Function to convert a tuple of strings into a single concatenated
string:
def tup_str(t):
return ''.join(t)
12. Program to find the length of a tuple without using len():
t = (1, 2, 3, 4, 5)
c = 0
for _ in t:
c += 1
print(c)
13. Function to check if a given element exists in a tuple:
t = (1, 3, 2, 3, 4, 3, 5)
m = max(set(t), key=t.count)
print(m)
Strings
def is_digit(s):
return s.isdigit()
s = "hello world"
s = s.title()
print(s)
17. Function to remove all punctuation from a string:
import string
def rm_punct(s):
return s.translate(str.maketrans('', '',
string.punctuation))
18. Program to count the occurrences of each character in a string:
s = "banana"
d = {}
for c in s:
d[c] = d.get(c, 0) + 1
print(d)
19. Function to replace multiple spaces in a string with a single space:
def fix_spaces(s):
return ' '.join(s.split())
Dictionaries
20. Program to create a dictionary from two lists (keys and values):
d1 = {'a': 1, 'b': 2}
d2 = {'a': 1, 'b': 2}
print(d1 == d2)
23. Function to get the sum of all values in a dictionary:
def sum_vals(d):
return sum(d.values())
24. Program to find the key with the smallest value in a dictionary:
lst = [4, 2, 9, 1, 5]
s = min(lst)
print(s)