P3 Python - TYL - Tuples and Sets.
1. Write a Python program to replace last value of tuples in a list.
Sample list: [(10, 20, 40), (40, 50, 60), (70, 80, 90)]
Expected Output: [(10, 20, 100), (40, 50, 100), (70, 80, 100)]
Remember that tuples are immutable.
A singleton tuple can be created only by following a value by a comma.
To change an item in a tuple, you can slice and then concatenate the value required, create a new tuple
For this program,
lst_tup[i]=lst_tup[i][:2]+(100,) is equivalent to lst_tup[i]=lst_tup[i][:-1]+(100,)
If we want to generalize to remove last element of any length of the tuple the later should be used.
for i in range(0, len(lst_tup) ):
#slices the first two elements, appends 100 to the end in another tuple.
lst_tup[i]=lst_tup[i][:-1]+(100,)
print(lst_tup)
lst_tup= [(10, 20, 40), (40, 50, 60), (70, 80, 90)]
lst_tup=[x[:-1]+(100,) for x in lst_tup]
print(lst_tup)
2. Write a Python program to sort a tuple by its float element.
Sample data: [('item1', '12.20'), ('item2', '15.10'), ('item3', '24.5')]
Expected Output: [('item3', '24.5'), ('item2', '15.10'), ('item1', '12.20')]
Method 1 :
lst_tuple=[('item1', '12.20'), ('item2', '15.10'), ('item3', '24.5')]
#use DSU
#bring the key you want to the front
lst = []
for key,val in lst_tuple: #decorate
lst.append( (val,key) )
lst.sort() #sort
sorted_lst=[]
for val,key in lst: #undecorate
sorted_lst.append( (key,val) )
print(sorted_lst)
Output:
[('item1', '12.20'), ('item2', '15.10'), ('item3', '24.5')]
Method 2 :
Use the sort() method
list.sort(reverse=True|False, key=myFunc)
You can specify a different key by passing a function to it that returns the key. In our case we want the second element.
def myFunc(e):
return e[1]
lst_tuple=[('item1', '12.20'), ('item2', '15.10'), ('item3', '24.5')]
lst_tuple.sort(key=myFunc)
Method 3:
This can be written more briefly by using a lambda function which is an anonymous function in Python
lst_tuple=[('item2', '15.10'),('item1', '12.20'),('item3', '24.5')]
lst_tuple.sort(key=lambda e:e[1])
print("Using lambda:", lst_tuple)
3. Use python set to check if string is panagram, i.e., a sentence that uses every letter in the alphabet.
-Generates lowercase alphabets from a to z using inbuilt functions or manually,
- convert the string to check for panagram to lower case
- convert it into a set
- the string might contain other special characters or whitespaces.
- so set of alphabets should be a subset of the set of characters in the string.
Program:
alp=''
for asc in range(ord('a'), ord('z')+1):
alp+=chr(asc)
def panagram(s):
s= s.lower()
if set(alp).issubset(set(s)):
print("Panagram")
else: print("Not a Panagram")
s='The quick brown fox jumps over the lazy dog!'
print(s)
panagram(s)
s='The quick brown fox jumps over the fence.'
print(s)
panagram(s)
Sample list: [(10, 20, 40), (40, 50, 60), (70, 80, 90)]
Expected Output: [(10, 20, 100), (40, 50, 100), (70, 80, 100)]
Remember that tuples are immutable.
A singleton tuple can be created only by following a value by a comma.
To change an item in a tuple, you can slice and then concatenate the value required, create a new tuple
For this program,
lst_tup[i]=lst_tup[i][:2]+(100,) is equivalent to lst_tup[i]=lst_tup[i][:-1]+(100,)
If we want to generalize to remove last element of any length of the tuple the later should be used.
Program:
lst_tup= [(10, 20, 40), (40, 50, 60), (70, 80, 90)]for i in range(0, len(lst_tup) ):
#slices the first two elements, appends 100 to the end in another tuple.
lst_tup[i]=lst_tup[i][:-1]+(100,)
print(lst_tup)
Output:
[(10, 20, 100), (40, 50, 100), (70, 80, 100)]
Using List comprehension:
lst_tup= [(10, 20, 40), (40, 50, 60), (70, 80, 90)]lst_tup=[x[:-1]+(100,) for x in lst_tup]
print(lst_tup)
2. Write a Python program to sort a tuple by its float element.
Sample data: [('item1', '12.20'), ('item2', '15.10'), ('item3', '24.5')]
Expected Output: [('item3', '24.5'), ('item2', '15.10'), ('item1', '12.20')]
Method 1 :
lst_tuple=[('item1', '12.20'), ('item2', '15.10'), ('item3', '24.5')]
#use DSU
#bring the key you want to the front
lst = []
for key,val in lst_tuple: #decorate
lst.append( (val,key) )
lst.sort() #sort
sorted_lst=[]
for val,key in lst: #undecorate
sorted_lst.append( (key,val) )
print(sorted_lst)
Output:
[('item1', '12.20'), ('item2', '15.10'), ('item3', '24.5')]
Method 2 :
Use the sort() method
list.sort(reverse=True|False, key=myFunc)
You can specify a different key by passing a function to it that returns the key. In our case we want the second element.
def myFunc(e):
return e[1]
lst_tuple=[('item1', '12.20'), ('item2', '15.10'), ('item3', '24.5')]
lst_tuple.sort(key=myFunc)
Method 3:
This can be written more briefly by using a lambda function which is an anonymous function in Python
lst_tuple=[('item2', '15.10'),('item1', '12.20'),('item3', '24.5')]
lst_tuple.sort(key=lambda e:e[1])
print("Using lambda:", lst_tuple)
3. Use python set to check if string is panagram, i.e., a sentence that uses every letter in the alphabet.
-Generates lowercase alphabets from a to z using inbuilt functions or manually,
- convert the string to check for panagram to lower case
- convert it into a set
- the string might contain other special characters or whitespaces.
- so set of alphabets should be a subset of the set of characters in the string.
Program:
alp=''
for asc in range(ord('a'), ord('z')+1):
alp+=chr(asc)
def panagram(s):
s= s.lower()
if set(alp).issubset(set(s)):
print("Panagram")
else: print("Not a Panagram")
s='The quick brown fox jumps over the lazy dog!'
print(s)
panagram(s)
s='The quick brown fox jumps over the fence.'
print(s)
panagram(s)
Output:
The quick brown fox jumps over the lazy dog!
Panagram
The quick brown fox jumps over the fence.
Not a Panagram
4. Use python sets to check if two lists have at-least one element in common
Convert both the lists to sets
find intersection.
Either check if length of the intersection set is at least 1 OR
check if the resulting set after intersection is not an empty set, set()
def checkcommon(a,b):
inter = set(a) & set(b)
#print('Debug',inter)
if inter != set():
print('Has at least one common element')
else : print('Does not have a common element')
lst1 = [2,5,6,7,8]
lst2 = [10,2,5,6,8]
lst3 = [11,12,13]
print(lst1,lst2)
checkcommon(lst1,lst2)
print(lst1,lst3)
checkcommon(lst1,lst3)
Alternative:
def checkcommon(a,b):
inter = set(a) & set(b)
#print('Debug',inter)
if len(inter) >=1:
print('Has at least one common element')
else : print('Does not have a common element')
tyl_list_common.py
[2, 5, 6, 7, 8] [10, 2, 5, 6, 8]
Has at least one common element
[2, 5, 6, 7, 8] [11, 12, 13]
Does not have a common element
find intersection.
Either check if length of the intersection set is at least 1 OR
check if the resulting set after intersection is not an empty set, set()
Program:
def checkcommon(a,b):
inter = set(a) & set(b)
#print('Debug',inter)
if inter != set():
print('Has at least one common element')
else : print('Does not have a common element')
lst1 = [2,5,6,7,8]
lst2 = [10,2,5,6,8]
lst3 = [11,12,13]
print(lst1,lst2)
checkcommon(lst1,lst2)
print(lst1,lst3)
checkcommon(lst1,lst3)
Alternative:
def checkcommon(a,b):
inter = set(a) & set(b)
#print('Debug',inter)
if len(inter) >=1:
print('Has at least one common element')
else : print('Does not have a common element')
Output:
tyl_list_common.py[2, 5, 6, 7, 8] [10, 2, 5, 6, 8]
Has at least one common element
[2, 5, 6, 7, 8] [11, 12, 13]
Does not have a common element
5. Write a Python program to find maximum and the minimum value in a set
Program:
s= {10,2,5,6,8}
max_val =max(s)
min_val = min(s)
print('Maximum value',max_val)
print('Minimum value', min_val)
Minimum value 2
s= {10,2,5,6,8}
max_val =max(s)
min_val = min(s)
print('Maximum value',max_val)
print('Minimum value', min_val)
Output:
Maximum value 10Minimum value 2
Comments
Post a Comment