Wednesday, July 20, 2022

Python Assignment 3

 Assignment 3 - List, Tuples, Sets, and Dictionary


SET A
List
1) Write a Python program to sum all the items in a list.

def sum_list(items):
    sum_numbers = 0
    for x in items:
        sum_numbers += x
    return sum_numbers
print(sum_list([1,2,-8]))


2) Write a Python program to multiplies all the items in a list.

def multiply_list(items):
    tot = 1
    for x in items:
        tot *= x
    return tot
print(multiply_list([1,2,-8]))

3) Write a Python program to get a list, sorted in increasing order by the last element in each tuple from a given list of non-empty tuples.

def last(n): return n[-1]

def sort_list_last(tuples):
  return sorted(tuples, key=last)

print(sort_list_last([(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]))


Tuples
1) Write a Python program to create a tuple.

# Creating an empty Tuple
Tuple1 = ()
print("Initial empty Tuple: ")
print(Tuple1)

# Creating a Tuple
Tuple1 = ('Geeks', 'For')
print("\nTuple with the use of String: ")
print(Tuple1)

# Creating a Tuple with the use of list
list1 = [1, 2, 4, 5, 6]
print("\nTuple using List: ")
print(tuple(list1))

# Creating a Tuple with the use of built-in function
Tuple1 = tuple('Geeks')
print("\nTuple with the use of function: ")
print(Tuple1)


2) Write a Python program to create a tuple with different data types.

# Creating a Tuple with Mixed Datatype
Tuple1 = (5, 'Welcome', 7, 'Geeks')
print("\nTuple with Mixed Datatypes: ")
print(Tuple1)

3) Write a Python program to check whether an element exists within a tuple.

test_tup = (10, 4, 5, 6, 8)
 print("The original tuple : " + str(test_tup))
N = 6
res = False
for ele in test_tup :
    if N == ele :
        res = True
        break
print("Does tuple contain required value ? : " + str(res))


Sets
1) Write a Python program to create a set.

print("Create a new set:")
x = set()
print(x)
print(type(x))
print("\nCreate a non empty set:")
n = set([0, 1, 2, 3, 4])
print(n)
print("\nUsing a literal:")
a = {1,2,3,'foo','bar'}
print(a)

2) Write a Python program to iterate over sets.

num_set = set([0, 1, 2, 3, 4, 5])
for n in num_set:
  print(n, end=' ')
print("\n\nCreating a set using string:")
char_set = set("w3resource")  
# Iterating using for loop
for val in char_set:
    print(val, end=' ')

3) Write a Python program to create set difference.

setn1 = set([1, 1, 2, 3, 4, 5])
setn2 = set([1, 5, 6, 7, 8, 9])
print("\nOriginal sets:")
print(setn1)
print(setn2)
r1 = setn1.difference(setn2)
print("\nDifference of setn1 - setn2:")
print(r1)
r2 = setn2.difference(setn1)
print("\nDifference of setn2 - setn1:")
print(r2)


Dictionary
1) Write a Python script to sort (ascending and descending) a dictionary by value.

import operator
d = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
print('Original dictionary : ',d)
sorted_d = sorted(d.items(), key=operator.itemgetter(1))
print('Dictionary in ascending order by value : ',sorted_d)
sorted_d = dict( sorted(d.items(), key=operator.itemgetter(1),reverse=True))
print('Dictionary in descending order by value : ',sorted_d)

2) Write a Python script to add a key to a dictionary.

d = {0:10, 1:20}
print(d)
d.update({2:30})
print(d)

3) Write a Python program to iterate over dictionaries using for loops.
d = {'Red': 1, 'Green': 2, 'Blue': 3} 
for color_key, value in d.items():
     print(color_key, 'corresponds to ', d[color_key]) 


SET B
List
1. Write a Python program to remove duplicates from a list.
a = [10,20,30,20,10,50,60,40,80,50,40]

dup_items = set()
uniq_items = []
for x in a:
    if x not in dup_items:
        uniq_items.append(x)
        dup_items.add(x)

print(dup_items)

2. Write a Python program to check a list is empty or not.
my_list = []
if not len(my_list):
    print("the list is empty")

Tuples
1. Write a Python program to convert a list to a tuple.
listx = [5, 10, 7, 4, 15, 3]
print(listx)
tuplex = tuple(listx)
print(tuplex)

2. Write a Python program to remove an item from a tuple.
tuplex = "S","H","R","A","D","D","H","A"
print(tuplex)

tuplex = tuplex[:2] + tuplex[3:]
print(tuplex)

listx = list(tuplex) 

listx.remove("H") 

tuplex = tuple(listx)
print(tuplex)

3. Write a Python program to slice a tuple.
tuplex = (2, 4, 3, 5, 4, 6, 7, 8, 6, 1)
_slice = tuplex[3:5]
print(_slice)
#if the start index isn't defined, is taken from the beg inning of the tuple
_slice = tuplex[:6]
print(_slice)
#if the end index isn't defined, is taken until the end of the tuple
_slice = tuplex[5:]
print(_slice)
#if neither is defined, returns the full tuple
_slice = tuplex[:]
print(_slice)
#The indexes can be defined with negative values
_slice = tuplex[-8:-4]
print(_slice)

4. Write a Python program to find the length of a tuple.
tuplex = tuple("Shraddha")
print(tuplex)
print(len(tuplex))

Sets
1. Write a Python program to check if a set is a subset of another set.
print("Check if a set is a subset of another set, using comparison operators and issubset():\n")
setx = set(["apple", "mango"])
sety = set(["mango", "orange"])
setz = set(["mango"])
print("x: ",setx)
print("y: ",sety)
print("z: ",setz,"\n")
print("If x is subset of y")
print(setx <= sety)
print(setx.issubset(sety))
print("If y is subset of x")
print(sety <= setx)
print(sety.issubset(setx))
print("\nIf y is subset of z")
print(sety <= setz)
print(sety.issubset(setz))
print("If z is subset of y")
print(setz <= sety)
print(setz.issubset(sety))

2. Write a Python program to find maximum and the minimum value in a set.
setn = {5, 10, 3, 15, 2, 20}
print("Original set elements:")
print(setn)
print(type(setn))
print("\nMaximum value of the said set:")
print(max(setn))
print("\nMinimum value of the said set:")
print(min(setn))

3. Write a Python program to find the length of a set.

setn = {5, 10, 3, 15, 2, 20}
print("Original set elements:")
print(setn)
print(type(setn))
print("\nLength of the said set:")
print(len(setn))

setn = {2,2,2,2,2}
print("Original set elements:")
print(setn)
print(type(setn))
print("\nLength of the said set:")
print(len(setn))

setn = {3,3,3,3,3,3,5}
print("Original set elements:")
print(setn)
print(type(setn))
print("\nLength of the said set:")
print(len(setn))

Dictionary
1. Write a Python script to generate and print a dictionary that contains a number (between 1 and n) in the form (x, x*x).

n=int(input("Input a number "))
d = dict()

for x in range(1,n+1):
    d[x]=x*x

print(d) 


2. Write a Python script to merge two Python dictionaries.

d1 = {'a': 100, 'b': 200}
d2 = {'x': 300, 'y': 200}
d = d1.copy()
d.update(d2)
print(d)

3. Write a Python program to get a dictionary from an object's fields.

class Obj_Dictionary(object):
     def __init__(self):
         self.x = 'red'
         self.y = 'Yellow'
         self.z = 'Green'
     def do_nothing(self):
         pass
test = Obj_Dictionary()
print(test.__dict__)


PROGRAMS FOR PRACTICE:
1. Write a Python program to get the largest number from a list.
2. Write a Python program to get the smallest number from a list.
3. Write a Python program to count the number of strings where the string length is 2 or more and the
first and last character are same from a given list of strings.
4. Write a Python program to add an item in a tuple.
5. Write a Python program to convert a tuple to a string.
6. Write a Python program to create the colon of a tuple.
7. Write a Python program to unpack a tuple in several variables.
8. Write a Python program to add member(s) in a set.
9. Write a Python program to remove item(s) from set
10. Write a Python program to create an intersection of sets.
11. Write a Python program to create a union of sets.
12. Write a Python script to concatenate following dictionaries to create a new one.
13. Write a Python program to map two lists into a dictionary.
14. Write a Python program to sort a dictionary by key.
15. Write a Python program to get the maximum and minimum value in a dictionary.
16. Write a Python program to clone or copy a list.
17. Write a Python program to find the list of words that are longer than n from a given list of words.
18. Write a Python program to unzip a list of tuples into individual lists.
19. Write a Python program to reverse a tuple.
20. Write a Python program to convert a list of tuples into a dictionary.
21. Write a Python program to print a tuple with string formatting.
22. Write a Python program to create a symmetric difference.
23. Write a Python program to check if a given value is present in a set or not.
24. Write a Python program to check if a given set is superset of itself and superset of another given set.
25. Write a Python program to check a given set has no elements in common with other given set.
26. Write a Python program to remove the intersection of a 2nd set from the 1st set.
27. Write a Python program to remove duplicates from Dictionary.
28. Write a Python script to check whether a given key already exists in a dictionary.
29. Write a Python program to sum all the items in a dictionary.
30. Write a Python program to multiply all the items in a dictionary.
31. Write a Python program to remove a key from a dictionary.

No comments:

Post a Comment