Posts

44.Example Programs using set

Write a program to do basic set operations na=int(input('Enter number of elements of the set A ..')) A=set() print("Enter the elements of set A...") for i in range(na):     x=int(input())     A.add(x) nb=int(input('Enter number of elements of the set B ..')) B=set() print("Enter the elements of set B...") for i in range(nb):     x=int(input())     B.add(x) print("set operations..") print("union") print(A|B) print("Intersection") print(A&B) print("Difference A-B and B-A") print(A-B) print(B-A) print("symmetric Difference") print(A^B) The simple way to remove duplicate elements from a list is to convert into a set and then convert back to list lst=[] n=int(input("enter how many numbers..")) print("Enter elements...") for i in range(n):     x=int(input())     lst.append(x) nlst=list(set(lst)) print("new list after removing duplicates") print(nlst) This program will compl

43.Set-Built-in Functions and Methods, frozen set

Built-in Functions with Set Built-in functions like all(), any(), enumerate(), len(), max(), min(), sorted(), sum() etc. are commonly used with sets to perform different tasks. Function           Description all()                   Returns True if all elements of the set are true (or if the set is empty). any()                Returns True if any element of the set is true. If the set is empty, returns False. enumerate()     Returns an enumerate object. It contains the index and value for all the items of the set                                as a pair. len()                     Returns the length (the number of items) in the set. max()                   Returns the largest item in the set. min()                     Returns the smallest item in the set. sorted()               Returns a new sorted list from elements in the set(does not sort the set itself). sum()                   Returns the sum of all elements in the set. Example: >>> S={1,0,2,3} >>> all(

42.Set in Python-creating,modifying and removing elements,set operations

A set is an unordered collection of items. Every set element is unique (no duplicates) and must be immutable (cannot be changed). However, a set itself is mutable. We can add or remove items from it. Sets can also be used to perform mathematical set operations like union, intersection, symmetric difference , etc. Creating Python Sets A set is created by placing all the items (elements) inside curly braces {}, separated by comma, or by using the built-in set() function. It can have any number of items and they may be of different types (integer, float, tuple, string etc.). But a set cannot have mutable elements like lists, sets or dictionaries as its elements. Example: >>> S={1,2,3} >>> print(S) {1, 2, 3} >>> S = {1.0, "Hello", (1, 2, 3)} >>> print(S) {1.0, 'Hello', (1, 2, 3)} set cannot have duplicate >>> S = {1, 2, 3, 4, 3, 2} >>> print(S) {1, 2, 3, 4} we can make set from a list >>> l=[1,2,3,4,4] >&g

41.Programming Assignment 10 ( using dictionaries)

Now you can try the following programs  1.Create a student database using dictionary. Read rollnumber, name and mark in computer programming. Use rollnumber as key and the other data must be stored as list.List the students details in the order of roll number. Read a roll number and display the corresponding student details.Delete a particular student details after reading a roll number. 2.Read a list of numbers and print the count of each element in the list in the order. 3.Read a string and print the number of occurrence of vowels in the string. 4.Empno, name and basic pay of ‘n’ employees are stored in a dictionary. Use empno as the key. Read an empno and update the basic pay of that employee. 5.In the above program display the name and basic pay of all the employees in the order of name. 6.Read an octal number( as string) and convert into binary using a dictionary. 7. Write a python program to create a dictionary of roll numbers and names of five students. Display the content of th

40.Example programs using Dictionaries

Program to count the number of occurrence(frequency) of each letters in a given string( histogram) ( university question) S=input("Enter the string…..") d=dict() for c in S:      d[c]=d.get(c,0)+1 print("letter count") print(d) Program to display the frequency of each word in a given string.(university qstn) S=input("Enter the string…..") S=S.split(" ") #splitting it into words d=dict() for w in S:     d[w]=d.get(w,0)+1 print("word count") print(d) Write a Python program to create a dictionary of roll numbers and names of five students. Display the names in the dictionary in alphabetical order.(university question) d={} for i in range(5):     rn=int(input("Enter roll number.."))     name=input("Enter name …")     d[rn]=name l=list(d.items()) l.sort(key=lambda v:v[1]) print("name and roll number in sorted order of name") for i in l:     print(i[1],":",i[0])  Program to read name and phn numbers

39.Dictionary -functions/methods

I.Python Dictionary Built-in Functions Built-in functions like all(), any(), len(), cmp(), sorted(), etc. are commonly used with dictionaries to perform different tasks. Function          Description all()                      Return True if all keys of the dictionary are True (or if the dictionary is empty). any()                    Return True if any key of the dictionary is true. If the dictionary is empty, return False. len()                    Return the length (the number of items) in the dictionary. cmp()                 Compares items of two dictionaries. (Not available in Python 3) sorted()               Return a new sorted list of keys in the dictionary. Examples: >>> squares = {0: 0, 1: 1, 3: 9, 5: 25, 7: 49, 9: 81} >>> len(squares) 6 >>> all(squares) False >>> any(squares) True >>> sorted(squares) [0, 1, 3, 5, 7, 9] II.Python Dictionary Methods Methods that are available with a dictionary are tabulated below. Some of them have

38.Dictionaries in Python- Creating Accessing, adding , removing elements

List organize their element by position. This mode of organization is useful when you want to locate the first element, the last element or visit each element in sequence.However, in some situations, the position of datum in a structure is irrelevant and we are interested in its association with some other elements in the structure.For example persons name with phone number. A dictionary organizes information by association, not position. We can refer to a dictionary as a mapping between a set of indices (which are called keys) and a set of values. Each key maps a value. The association of a key and a value is called a key-value pair. A dictionary is an extremely useful data storage construct for storing and retrieving all key value pairs, where each element is accessed (or indexed) by a unique key. However, dictionary keys are not in sequences. Dictionaries are mutable. Dictionaries are unordered. Items in dictionaries are accessed via keys and not

37.Programming Assignment 9 ( using tuples and set)

Now you can try following programs using tuple-refer examples before trying 1.Read ‘n’ numbers and find their sum,average,min,max and also print a sorted list. 2.Read two tuples and exchange their values. 3.Find the variance and standard deviation of ‘n’ numbers. 4.Check the number of occurrence of an element in a tuple. 5.Find the positions of occurrences(indices) of an element in a tuple. 6.Read rno,name and mark(out of 50) of n students and store the details in a list as tuple and do the following  a)Search for  a given student details(input  rno)  b)Delete a particular student details(input rno)  c)Display the list in descending order of mark  d)Display the list of failed students ( mark < 25) sets- refer example programs 1.Implement the basic set operations union, intersection, difference, symmetric difference  2.Remove duplicate elements from a list ( keep one copy of the duplicate element) 3.Remove duplicate elements from a list ( do not keep any copy of the duplicate element

36.Tuples in python-functions,Operations, Example Programs

Tuples are used for grouping data.A tuple is an immutable list, i.e. a tuple cannot be changed in any way once it has been created. A tuple is defined analogously to lists, except that the set of elements is enclosed in parentheses instead of square brackets. The rules for indices are the same as for lists. Once a tuple has been created, you can't add elements to a tuple or remove elements from a tuple. What are the  benefit of tuple? Tuples are faster than lists. If you know that some data doesn't have to be changed, you should use tuples instead of lists, because this protects your data against accidental changes. Tuples can be used as keys in dictionaries, while lists can't. The following example shows how to define a tuple and how to access a tuple. Furthermore we can see that we raise an error, if we try to assign a new value to an element of a tuple: Tuple creation It is defined within parentheses () where items are separated by commas. >>> t = ("tuples&

35.Programming Assignment 8 ( using lists)

Now you can try the following programs using Lists 1.Read list of numbers and check whether the given element in found in the list. If found display the positions else display the message element is not found.( index() method only find the first occurrence. use a loop) 2.Count the number of occurrences of an element in a list. ( use count() method or use a loop) 3.Read a list and remove the first and last element .Create a new list( use del(), pop() and slicing) 4. Write program to read list of names and print the names in sorted order.(use sort()) 5. Read list of numbers and print the list in reverse sorted order.(use sort()) 6. Program to find the sum of all even numbers in a group of ‘n’ numbers entered by the user. (university question) 7. Write a Python program to count the number of –ve terms and zeros in a given set of n numbers (university question) 8. Write a Python program to input a list of ‘n’ numbers. Calculate and display the average(mean) of ‘n’ numbers. Also display cu

34.Example programs using Lists

Program to read list of names and sort the list in alphabetical order.( university question) n=int(input("Enter the number of names....")) names=[] print("Enter {} names".format(n)) for i in range(n):      nam=input()      names.append(nam) names.sort() print("names in alphabetical order") for nam in names:      print(nam) Program to find the sum of all even numbers in a group of n numbers entered by the user. (university question) n=int(input("Enter the number of elements...")) print("Enter the {} elements".format(n)) l=[] # creating an empty list for i in range(n):     x=int(input())     l.append(x) sum=0 for i in range(n):     if l[i]%2==0:         sum=sum+l[i] print("Sum of all even numbers",sum) Program to read a string and remove the given words from the string. s=input("Enter the string....") wr=input("Enter the word to remove....") wrds=s.split(" ") ns="" for w in wrds:     if w!

33.List functions/methods, searching and sorting, object identity

Image
Useful functions with List len() function will return the number of elements in the list. >>> L=[10,20,30,40] >>> len(L) 4 min() and max() will return the minimum and maximum element >>> L=[10,20,30,40] >>> min(L) 10 >>> max(L) 40 sum() function will return the sum of the elements. >>> L=[10,20,30,40] >>> sum(L) 100 We can find average of the list elements L by sum(L)/len(L) >>> sum(L)/len(L) 25 del() function can be also used for deleting element(s) >>>del(L[1]) >>>L [10,30,40] del() function can be used to delete multiple element(s) >>> l=[4,5,6,7,8,9] >>> del(l[0:3]) >>> l [7, 8, 9] Python List Methods Methods that are available with list objects in Python programming are tabulated below. They are accessed as list.method().  append() - Add an element to the end of the list extend()  - Add all elements of a list to the another list insert()  - Insert an item at th

32.Lists in Python-List operations,creating,accessing, modifying, adding and deleting elements,list comprehensions

List is one of the simplest and most important data structures in Python.A list is an ordered set of values, where each value is identified by an index. The values that make up a list are called its elements. Lists are similar to strings, which are ordered sets of characters, except that the elements of a list can have any type. Lists are the most versatile sequence type. The elements of a list can be any object, and lists are mutable  , meaning you can change its contents. Elements can be reassigned or removed, and new elements can be inserted.Lists are enclosed in square brackets [ ] and each item is separated by a comma. Lists are very flexible and have many built-in control functions. Here are some real-world examples of lists A shopping list for the grocery store A to-do list A recipe, which is a list of instructions....etc 1.Creating Lists To create a list, place a (possibly empty) comma-separated list of objects or expressions in square brackets. For example, the following initi