Notes Module3
Notes Module3
Notes Module3
C Bantwal
Module 3:
Table of contents:
Topics: 02
Web links: 30
Time required:
“Don’t wish it were easier; wish you were better.” – Jim Rohn
17cs664 by G.V. Bhat & S. Samartha , Dept of ECE, C.E.C Bantwal
MODULE 3
A. Python Data
Structures
Data structures by themselves
aren’t all that useful, but they’re
indispensable when used in
specific applications, like finding
the shortest path between points
in a map, or finding a name in a phone book with say, a billion elements
(no, binary search just doesn’t cut it sometimes!).
You can think of a data structure as a way of organizing and storing data such
that we can access and modify it efficiently. Earlier, we have seen primitive data
types like integers, floats, Booleans, and Strings. Now, we’ll take a deeper look at
the non-primitive Python data structures.
Lists:
Q1. What are lists? How to create a list? Are lists mutable
justify the statement with example?
(weblink-01 www.youtube.com/watch?v=RVXIBZvg-
W8&list=PLQVvvaa0QuDe8XSftW-
RAxdo6OmaeL85M&index=27)
“Don’t wish it were easier; wish you were better.” – Jim Rohn
17cs664 by G.V. Bhat & S. Samartha , Dept of ECE, C.E.C Bantwal
1. # Nested List
2. n_list = ["Happy", [2,0,1,5]]
3. # Nested indexing
4. print (n_list [0] [1]) # Output: a
5. print (n_list [1] [3]) # Output: 5
6. my_list = ['p','r','o','b','e']
7. print (my_list [0]) # Output: p
8. print (my_list [2]) # Output: o
9. print (my_list [4]) # Output: e
10. # Error! Only integer can be used for indexing my_list[4.0]
11. my_list = ['p','r','o','b','e']
12. print(my_list[-1]) # Output: e
13. print(my_list[-5]) # Output: p
Python allows negative indexing for its sequences. The index of -1 refers to the last
item, -2 to the second last item and so on.
1. # Nested List
2. n_list = ["Happy", [2,0,1,5]]
3. my_list = ['p','r','o','g','r','a','m','i','z']
4. print(my_list[2:5]) # elements 3rd to 5th
5. print(my_list [:-5]) # elements beginning to 4th
6. print(my_list[5:]) # elements 6th to end
7. print(my_list[:]) # elements beginning to end
8. odd = [2, 4, 6, 8]
9. odd[0] = 1 # change the 1st item
10. print(odd) # Output: [1, 4, 6, 8]
11. odd[1:4] = [3, 5, 7] # change 2nd to 4th items
12. print(odd) # Output: [1, 3, 5, 7]
“Don’t wish it were easier; wish you were better.” – Jim Rohn
17cs664 by G.V. Bhat & S. Samartha , Dept of ECE, C.E.C Bantwal
List Operations: Lists respond to the + and * operators much like strings; they
mean concatenation and repetition here too, except that the result is a new list,
not a string. In fact, lists respond to all of the general sequence operations we used
on strings in previously.
1. odd = [1, 3, 5]
2. odd.append(7)
“Don’t wish it were easier; wish you were better.” – Jim Rohn
17cs664 by G.V. Bhat & S. Samartha , Dept of ECE, C.E.C Bantwal
1. my_list = ['p','r','o','b','l','e','m']
2. del my_list [2] # delete one item
3. print (my_list) # Output: ['p', 'r', 'b', 'l', 'e', 'm']
We can use remove() method to remove the given item or pop() method to remove
an item at the given index. The pop() method removes and returns the last item if
index is not provided. This helps us implement lists as stacks (first in, last out
data structure). We can also use the clear() method to empty a list.
1. my_list = ['p','r','o','b','l','e','m']
2. my_list.remove('p')
3. print(my_list) # Output: ['r', 'o', 'b', 'l', 'e', 'm']
4. print(my_list.pop(1)) # Output: 'o'
5. print(my_list) # Output: ['r', 'b', 'l', 'e', 'm']
6. print(my_list.pop()) # Output: 'm'
7. print(my_list) # Output: ['r', 'b', 'l', 'e']
8. my_list.clear()
9. print(my_list) # Output: []
Finally, we can also delete items in a list by assigning an empty list to a slice of
elements
1. my_list = ['p','r','o','b','l','e','m']
2. my_list[2:3] = []
3. my_list # Output: ['p', 'r', 'b', 'l', 'e', 'm']
4. my_list[2:5] = []
5. my_list # Output: ['p', 'r', 'm']
“Don’t wish it were easier; wish you were better.” – Jim Rohn
17cs664 by G.V. Bhat & S. Samartha , Dept of ECE, C.E.C Bantwal
1. a = [1, 2, 3, 4, 5]
2. for i in range(len(a) - 1, -1, -1):
3. print(i, a[i])
Extended slicing :The |[::-1]| slice make a copy of the list in reverse order which
can be used in the for loop to print items in reverse order.
1. a = [1, 2, 3, 4, 5]
2. for x in a[::-1]:
3. print(x)
“Don’t wish it were easier; wish you were better.” – Jim Rohn
17cs664 by G.V. Bhat & S. Samartha , Dept of ECE, C.E.C Bantwal
DICTIONARIES:
Q9 Explain
dictionaries.
Demonstrate with a
python code?
(web link-08 https://www.youtube.com/watch?v=dpDDQiZpx34)
Python dictionary is an unordered collection of items. While other
compound data types have only value as an element, a dictionary has a key: value
pair. Dictionaries are optimized to retrieve values when the key is known.
Creating a dictionary is as simple as placing items inside curly braces {} separated
by comma. An item has a key and the corresponding value expressed as a pair,
key: value. While values can be of any data type and can repeat, keys must be of
immutable type (string, number or tuple with immutable elements) and must be
unique. we can also create a dictionary using the built-in function dict().
1. # empty dictionary
2. my_dict = {}
3. # dictionary with integer keys
4. my_dict = {1: 'apple', 2: 'ball'}
5. # dictionary with mixed keys
6. my_dict = {'name': 'John', 1: [2, 4, 3]}
7. # using dict()
8. my_dict = dict({1:'apple', 2:'ball'})
9. # from sequence having each item as a pair
10. my_dict = dict([(1,'apple'), (2,'ball')])
“Don’t wish it were easier; wish you were better.” – Jim Rohn
17cs664 by G.V. Bhat & S. Samartha , Dept of ECE, C.E.C Bantwal
“Don’t wish it were easier; wish you were better.” – Jim Rohn
17cs664 by G.V. Bhat & S. Samartha , Dept of ECE, C.E.C Bantwal
Methods that are available with dictionary are tabulated below. Some of them have
already been used in the above examples.
Python Dictionary Methods
Method Description
clear() Remove all items form the dictionary.
copy() Return a shallow copy of the dictionary.
fromkeys(seq[, v]) Return a new dictionary with keys from seq and value equal to v
(defaults to None).
get(key[,d]) Return the value of key. If key doesnot exit, return d (defaults to
None).
items() Return a new view of the dictionary's items (key, value).
keys() Return a new view of the dictionary's keys.
pop(key[,d]) Remove the item with key and return its value or d if key is not
found. If d is not provided and key is not found, raises KeyError.
popitem() Remove and return an arbitary item (key, value). Raises
KeyError if the dictionary is empty.
setdefault(key[,d]) If key is in the dictionary, return its value. If not, insert key with a
value of d and return d (defaults to None).
update([other]) Update the dictionary with the key/value pairs from other,
overwriting existing keys.
values() Return a new view of the dictionary's values
Q15. List and describe some of popular built-in Dictionary
functions available in python ?
(weblink-18,19 https://www.youtube.com/watch?v=4pKV6Ye7XPY
https://www.youtube.com/watch?v=7rjJrQy9gi4)
Built-in functions like all(), any(), len(), cmp(), sorted() etc. are commonly used
with dictionary to perform different tasks.
Built-in Functions with Dictionary
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.
sorted() Return a new sorted list of keys in the dictionary.
TUPLES:
“Don’t wish it were easier; wish you were better.” – Jim Rohn
17cs664 by G.V. Bhat & S. Samartha , Dept of ECE, C.E.C Bantwal
We generally use tuple for heterogeneous (different) datatypes and list for homogeneous
(similar) datatypes.
Since tuple are immutable, iterating through tuple is faster than with list. So there is a slight
performance boost.
Tuples that contain immutable elements can be used as key for a dictionary. With list, this
is not possible.
If you have data that doesn't change, implementing it as tuple will guarantee that it remains
“Don’t wish it were easier; wish you were better.” – Jim Rohn
17cs664 by G.V. Bhat & S. Samartha , Dept of ECE, C.E.C Bantwal
2. Negative Indexing: Python allows negative indexing for its sequences. The
index of -1 refers to the last item, -2 to the second last item and so on
“Don’t wish it were easier; wish you were better.” – Jim Rohn
17cs664 by G.V. Bhat & S. Samartha , Dept of ECE, C.E.C Bantwal
1. my_tuple = ('p','e','r','m','i','t')
2. print (my_tuple [-1]) # Output: 't'
3. print (my_tuple [-6]) # Output: 'p'
3. Slicing: We can access a range of items in a tuple by using the slicing operator
- colon ":". Slicing can be best visualized by considering the index to be between
the elements as shown below. So if we want to access a range, we need the index
that will slice the portion from the tuple.
1. my_tuple = ('p','r','o','g','r','a','m','i','z')
2. # elements 2nd to 4th
3. print(my_tuple[1:4]) # Output: ('r', 'o', 'g')
4. # elements beginning to 2nd
5. print(my_tuple[:-7]) # Output: ('p', 'r')
6. # elements 8th to end
7. print(my_tuple[7:]) # Output: ('i', 'z')
8. # elements beginning to end
9. print(my_tuple[:]) # Output: ('p','r','o','g','r','a','m','i','z')
“Don’t wish it were easier; wish you were better.” – Jim Rohn
17cs664 by G.V. Bhat & S. Samartha , Dept of ECE, C.E.C Bantwal
1. my_tuple = ('p','r','o','g','r','a','m','i','z')
2. # can't delete items, if you uncomment below line, you will get
The sort function works the same way. It sorts primarily by first element, but in
the case of a tie, it sorts by second element, and so on. This feature lends itself
to a pattern called DSU for
Decorate: a sequence by building a list of tuples with one or more sort keys
preceding the elements from the sequence,
Sort: the list of tuples, and
Undecorate: by extracting the sorted elements of the sequence.
For example, suppose you have a list of words and you want to sort them from
longest to shortest:
1. def sort_by_length(words):
2. t = []
3. for word in words:
4. t.append((len(word), word))
5. t.sort(reverse=True)
6. res = []
7. for length, word in t:
8. res.append(word)
9. return res
The first loop builds a list of tuples, where each tuple is a word preceded by its
length. sort compares the first element, length, first, and only considers the second
element to break ties. The keyword argument reverse=True tells sort to go in
“Don’t wish it were easier; wish you were better.” – Jim Rohn
17cs664 by G.V. Bhat & S. Samartha , Dept of ECE, C.E.C Bantwal
decreasing order. The second loop traverses the list of tuples and builds a list of
words in descending order of length.
*one can use curly braces to define a set like this: {1, 2, 3}. However, if you leave the
curly braces empty like this: {} Python will instead create an empty dictionary. So to
create an empty set, use set().
* *A dictionary itself is mutable, but each of its individual keys must be immutable.
B. REGULAR
EXPRESSIONS:
(weblink-29,30
https://www.youtube.com/watch?v=sZyAn2TW7GY
https://www.youtube.com/watch?v=GEshegZzt3M)
In Python, we have module “re” that helps with regular expressions. So you need
to import library re before you can use regular expressions in Python. (Import re)
“Don’t wish it were easier; wish you were better.” – Jim Rohn
17cs664 by G.V. Bhat & S. Samartha , Dept of ECE, C.E.C Bantwal
Let’s look at the methods that library “re” provides to perform these tasks.
re.match(pattern, string):
This method finds match if it occurs at start of the string. For example, calling
match() on the string 'CEC Canara Engineering College CEC'and looking for a
pattern ‘CEC’ will match. However, if we look for only Canara, the pattern will not
match. Let’s perform it in python now.
1. import re
2. result = re.match(r'CEC', 'CEC Canara Engineering College CEC')
3. print result
4. # Output:<_sre.SRE_Match object at 0x0000000009BE4370>
Above, it shows that pattern match has been found. To print the matching string
we’ll use method group (It helps to return the matching string). Use “r” at the start
of the pattern string, it designates a python raw string.
1. result = re.match(r'CEC', 'CEC Canara Engineering College CEC')
2. print result.group(0) # Output: CEC
Let’s now find ‘Canara’ in the given string. Here we see that string is not starting
with CEC’ so it should return no match. Let’s see what we get:
1. result =re.match(r'Canara', ''CEC Canara Engineering College CEC')
2. print result # Output: None
There are methods like start () and end () to know the start and end position of
matching pattern in the string.
“Don’t wish it were easier; wish you were better.” – Jim Rohn
17cs664 by G.V. Bhat & S. Samartha , Dept of ECE, C.E.C Bantwal
re.search(pattern, string):
It is similar to match() but it doesn’t restrict us to find matches at the beginning
of the string only. Unlike previous method, here searching for pattern
‘Analytics’ will return a match.
1. result =re.search(r'Canara', 'CEC Canara Engineering College CEC')
2. print result.group(0) # Output: Canara
Here you can see that, search () method is able to find a pattern from any position
of the string but it only returns the first occurrence of the search pattern.
re.findall (pattern, string):
It helps to get a list of all matching patterns. It has no constraints of searching
from start or end. If we will use method findall to search ‘AV’ in given string it will
return both occurrence of AV. While searching a string, I would recommend you
to use re.findall() always, it can work like re.search() and re.match() both.
1. result = re.findall(r'CEC', 'CEC Canara Engineering College CEC')
2. print result # Output: ['CEC', 'CEC']
“Don’t wish it were easier; wish you were better.” – Jim Rohn
17cs664 by G.V. Bhat & S. Samartha , Dept of ECE, C.E.C Bantwal
2. pattern=re.compile('AV')
3. result=pattern.findall('AV Analytics Vidhya AV')
4. print result Output: ['AV', 'AV']
5. result2=pattern.findall('AV is largest community of India')
6. print result2 # Output: ['AV']
Again, it is returning space as a word because “*” returns zero or more matches
of pattern to its left. Now to remove spaces we will go with “+“.
“Don’t wish it were easier; wish you were better.” – Jim Rohn
17cs664 by G.V. Bhat & S. Samartha , Dept of ECE, C.E.C Bantwal
Above, you can see that “.com”, “.in” part is not extracted. To add it, we will go
with below code.
1. result=re.findall (r'@\w+.\w+','[email protected],[email protected],
[email protected], [email protected]')
2. print result # Output
['@gmail.com', '@test.in', '@analyticsvidhya.com', '@rest.biz']
Solution – 2 Extract only domain name using “( )”
1. result=re.findall (r'@\w+.(\w+)','[email protected],[email protected],
[email protected], [email protected]')
2. print result # Output: ['com', 'in', 'com', 'biz']
“Don’t wish it were easier; wish you were better.” – Jim Rohn
17cs664 by G.V. Bhat & S. Samartha , Dept of ECE, C.E.C Bantwal
Solution-2
Solution- 3
1. result=re.findall(r'\b[aeiouAEIOU]\w+','AV is largest Analytics co
mmunity of India')
2. print result # Output: ['AV', 'is', 'Analytics', 'of', 'India']
In similar ways, we can extract words those starts with constant using “^” within
square bracket.
Above you can see that it has returned words starting with space. To drop it from
output, include space in square bracket[].
“Don’t wish it were easier; wish you were better.” – Jim Rohn
17cs664 by G.V. Bhat & S. Samartha , Dept of ECE, C.E.C Bantwal
We have a list phone numbers in list “li” and here we will validate phone
numbers using regular
1. import re
2. li=['9999999999','999999-999','99999x9999']
3. for val in li:
4. if re.match(r'[8-9]{1}[0-9]{9}',val) and len(val) == 10:
5. print 'yes'
6. else:
7. print 'no'
8. # Output: yes no no
We can also use method re.sub() to replace these multiple delimiters with one as
space ” “.
1. import re
2. line = 'asdf fjdk;afed,fjek,asdf,foo'
3. result= re.sub(r'[;,\s]',' ', line)
4. print result # Output: asdf fjdk afed fjek asdf foo
“Don’t wish it were easier; wish you were better.” – Jim Rohn
17cs664 by G.V. Bhat & S. Samartha , Dept of ECE, C.E.C Bantwal
Q1 What are lists? Are lists mutable justify the statement with example?
Q2 How are tuples created in python? Explain different ways of accessing
and creating them?
Q3 Explain dictionaries. Demonstrate with a python code?
Q4 Describe any two list operations and list methods
Q5 List the merits of dictionary over list.
Q6 Compare and contrast tuples with lists. Explain the following
operators in tuples, Sum of two tuples
Slicing operator, Compression of two tuples
Assignment to variables
Q7 Explain extracting data using regular expressions.
Q8 what are the ways of traversing a list? Explain with example for
each.
Q9 Differentiate pop and remove methods on lists. How to delete more
than one elements from a list.
Q10 Explain join(), split(), pop() and append() methods in a list with
examples.
Q11 Define Tuples. Explain DSU Patters?
Q12 Why do you need regular expression in python?
“Don’t wish it were easier; wish you were better.” – Jim Rohn
17cs664 by G.V. Bhat & S. Samartha , Dept of ECE, C.E.C Bantwal
Programming Excises:
P1. Write a Python code to read all lines in a file
accepted from the user and print all email
addresses contained in it. Assume the email
address contain only non-white space characters?
P2. Implement a python program using lists to store and display the average of N
integers accepted from the user?
1. n=int(input("Enter the number of elements to be inserted: "))
2. a=[]
3. for i in range(0,n):
4. elem=int(input("Enter element: "))
5. a.append(elem)
6. avg=sum(a)/n
7. print("Average of elements in the list",round(avg,2))
P3. Write a python code to search for lines that start with the word ‘From’ and a
character followed by two digit number between 00 and 99 followed by ‘:’ Print the
number if it is greater than zero. Assume any input file.
1. # Search for lines that start with From and a character
2. # followed by a two digit number between 00 and 99 followed by ':'
P4. Write a python code to accept ‘n’ numbers from the user. Find the sum of all even
numbers and product of all odd numbers in entered list.
“Don’t wish it were easier; wish you were better.” – Jim Rohn
17cs664 by G.V. Bhat & S. Samartha , Dept of ECE, C.E.C Bantwal
2. even_total = 0
3. odd_prod = 1
4. my_list=[]
5.
6. for number in range(1, Num + 1):
7. my_list.append(int(input("Enter the {} Value".format(number)))
)
8.
9. for Val in my_list:
10. if(Val % 2 == 0):
11. even_total = even_total + Val
12. else:
13. odd_prod = odd_prod * Val
14.
15. print("The Sum of Even Numbers is {}".format(even_total))
16. print("The Product of Odd Numbers is {}".format(odd_prod))
P5. Write a python program to accept USN and marks obtained, find maximum,
minimum and student USN who have scored in the range 100-85. 85-75, 75-60 and
below 60 marks separately.
P6. Implement a python program to find for lines having @ sign between character in
a read text file.
1. # Search for lines that have an at sign between characters
2. import re
3. hand = open('mbox-short.txt')
4. for line in hand:
5. line = line.rstrip()
6. x = re.findall('\S+@\S+', line)
7. if len(x) > 0:
8. print(x)
P7.. Write a python program that accepts a sentence and build dictionary with
LETTERS DIGITS UPPERCASE, LOWERCASE as key and their count in the sentences
as values Ex:[email protected],
d={“LETTERS”:3,”DIGITS”:3,UPPERCASE”:4,”LOWERCASE”:8
“Don’t wish it were easier; wish you were better.” – Jim Rohn
17cs664 by G.V. Bhat & S. Samartha , Dept of ECE, C.E.C Bantwal
6. for i in range(len(str)):
7. if str[i] >= 'A' and str[i] <= 'Z':
8. my_dict["UPPERCASE"]+= 1
9. my_dict["LETTERS"]+= 1
10. elif str[i] >= 'a' and str[i] <= 'z':
11. my_dict["LOWERCASE"]+= 1
12. my_dict["LETTERS"]+= 1
13. elif str[i] >= '0' and str[i] <= '9':
14. my_dict["DIGITS"]+= 1
15. else:
16. my_dict["SPECIAL"]+= 1
17. return (my_dict)
18.
19. # Driver Code
20. str = “[email protected]”
21. dict=Count(str)
22. print(dict)
1. def Count(str):
2. my_dict={"LETTERS":0,"DIGITS":0,"UPPERCASE":0,"LOWERCASE":0,"S
PECIAL":0}
3. for i in range(len(str)):
4. if (str[i].isupper()):
5. my_dict["UPPERCASE"]+= 1
6. my_dict["LETTERS"]+= 1
7. elif(str[i].islower()):
8. my_dict["LOWERCASE"]+= 1
9. my_dict["LETTERS"]+= 1
10. elif str[i].isdigit():
11. my_dict["DIGITS"]+= 1
12. else:
13. my_dict["SPECIAL"]+= 1
14. return (my_dict)
15.
16. # Driver Code
17. str = “[email protected]"
18. dict=Count(str)
19. print(dict)
P8 Write a program to check the validity of a password read by the user. The following
criteria should be used to check the validity. Password should have at least one lower
case letter ii) One digit iii) One Upper case letter iv) One special Character from
[$#@!] v) Six character. The Program should accept a Password and check the
validity using the criteria’s and print ‘valid’ or ‘invalid’ as the case may be.
“Don’t wish it were easier; wish you were better.” – Jim Rohn
17cs664 by G.V. Bhat & S. Samartha , Dept of ECE, C.E.C Bantwal
1. import re
2. password = "R@m@_f0rtu9e$"
3. flag = 0
4. while True:
5. if (len(password)!= 6):
6. flag = -1
7. break
8. elif not re.search("[a-z]", password):
9. flag = -1
10. break
11. elif not re.search("[A-Z]", password):
12. flag = -1
13. break
14. elif not re.search("[0-9]", password):
15. flag = -1
16. break
17. elif not re.search("[$#@!]", password):
18. flag = -1
19. break
20. else:
21. flag = 0
22. print("Valid Password")
23. break
24.
25. if flag ==-1:
26. print("Not a Valid Password")
P9. Demonstrate i) How a dictionary items can be represented as a list of tuples ii)
How tuples can be used as keys in dictionary
1. # Initialization of dictionary
2. dict = { 'Cats': 10, 'Dogs': 12, 'Birds': 31 }
3.
4. # Converting into list of tuple
5. list = [(k, v) for k, v in dict.items()]
6.
7. # Printing list of tuple
8. print(list)
Wait a minute.... tuples are immutable, can they be used as dictionary keys? YES! , Because tuples
are hashable and lists are not, i f we want to create a composite key to use in a dictionary
we must use a tuple as the key. We would encounter a composite key if we wanted to create
a telephone directory that maps from last-name, first-name pairs to telephone numbers.
“Don’t wish it were easier; wish you were better.” – Jim Rohn
17cs664 by G.V. Bhat & S. Samartha , Dept of ECE, C.E.C Bantwal
6. me = Person(first_name='Bob', last_name='Smith')
7. my_dict[me] = True
8. my_dict
9. {('Aly', 'Sivji'): True, Person(first_name='Bob', last_name='Smith
'): True}
“Don’t wish it were easier; wish you were better.” – Jim Rohn
17cs664 by G.V. Bhat & S. Samartha , Dept of ECE, C.E.C Bantwal
P10. Write a python code to input information about 20 students as given : 1) Roll
Number 2) Name 3) Total marks . Get the input from the user for a student name .
The program should display the Roll number and total marks for the given student
name. Also, find the average marks of all the students, Use dictionaries.
1. n = int(raw_input("Please enter number of students:"))
2. all_students = []
3.
4. for i in range(0, n):
5. stud_name = raw_input('Enter the name of student: ')
6. print stud_name
7. stud_rollno = input('Enter the roll number of student: ')
8. print stud_rollno
9. mark1 = input('Enter the marks in subject 1: ')
10. print mark1
11. mark2 = input('Enter the marks in subject 2: ')
12. print mark2
13. mark3 = input('Enter the marks in subject 3: ')
14. print mark3
15. total = (mark1 + mark2 + mark3)
16. print"Total is: ", total
17. average = total / 3
18. print "Average is :", average
19.
20. all_students.append({
21. 'Name': stud_name,
22. 'Rollno': stud_rollno,
23. 'Mark1': mark1,
24. 'Mark2': mark2,
25. 'Mark3': mark3,
26. 'Total': total,
27. 'Average': average
28. })
29.
30. for student in all_students:
31. print ('\n')
32. for key, value in student.items():
33. print( '{0}: {1}'.format(key, value))
P11. Write a python code to demonstrate tuples by sorting a list of words from longest
to shortest using loops?
1. a = [('a', 12), ('ccc', 4), ('bb', 3), ('eeeee', 6), ('dddd', 5),
('g', 50),('f', 30),]
2. for elem in range(len(a)-1, 0, -1):
3. for i in range(elem):
4. if len(a[i][0])<len(a[i+1][0]):
5. a[i], a[i+1] = a[i+1], a[i]
6. print(a)
“Don’t wish it were easier; wish you were better.” – Jim Rohn
17cs664 by G.V. Bhat & S. Samartha , Dept of ECE, C.E.C Bantwal
P12. Python program to sort a list of tuples alphabetically using for loop
1. # Function to sort the list of tuples using for loop
2. def SortTuple(tup):
3. # Getting the length of list of tuples
4. n = len(tup)
5. for i in range(n):
6. for j in range(n-i-1):
7. if tup[j][0] > tup[j + 1][0]:
8. tup[j], tup[j + 1] = tup[j + 1], tup[j]
9. return tup
10.
11. # Driver's code
12. tup = [("Amana", 28), ("Zenat", 30), ("Abhishek", 29), ("Nikhil",
21), ("B", "C")]
13. print(SortTuple(tup))
14. # Output: [('Abhishek', 29), ('Amana', 28), ('B', 'C'), ('Nikhil',
21), ('Zenat', 30)]
“Don’t wish it were easier; wish you were better.” – Jim Rohn
17cs664 by G.V. Bhat & S. Samartha , Dept of ECE, C.E.C Bantwal
Assignments 3
“Don’t wish it were easier; wish you were better.” – Jim Rohn
17cs664 by G.V. Bhat & S. Samartha , Dept of ECE, C.E.C Bantwal
23 4CB17EC026 HARIKISHOR U R 8 22 35 46 54 66
24 4CB17EC027 HETHAL GOPAL 2 25 29 45 56 64
25 4CB17EC028 JAYAPRASAD B 11 15 27 44 57 66
26 4CB17EC029 JEMSTON PREETHAM S 5 18 29 43 55 64
27 4CB17EC030 JESTON D SOUZA 13 16 35 41 54 64
28 4CB17EC031 K V KAILAS SHETTY 5 18 31 43 54 64
29 4CB17EC032 KALPITHA B 11 24 26 50 56 59
30 4CB17EC033 KARTHIK S RAIKAR 10 16 35 49 53 65
31 4CB17EC034 KASHI PRITHEESH ANNAPPA 5 15 31 43 55 63
32 4CB17EC035 KAVYA 9 18 37 49 58 66
33 4CB17EC036 KAVYA SUBRAY HEGDE 8 25 26 51 55 59
34 4CB17EC037 KEERTHAN 8 17 36 51 57 62
35 4CB17EC038 KRISHNAPRASAD V 2 23 33 47 53 63
36 4CB17EC039 LEANNE MARIA MIRANDA 6 24 26 51 54 63
37 4CB17EC040 M ANJANA BHAT 12 18 29 39 53 61
38 4CB17EC041 MADHURYA 9 20 32 47 56 61
39 4CB17EC042 MAHIMA K MAYYA 1 16 35 45 58 63
40 4CB17EC043 MANASA G.V 1 21 37 43 58 66
41 4CB17EC044 MAULYA RAI C 6 17 27 51 56 65
42 4CB17EC046 MICHELLE SONIA FERNANDES 11 24 34 49 58 65
43 4CB17EC047 N V PRAJWAL 9 18 37 47 53 63
44 4CB17EC048 N YASHODHARA 4 25 28 47 55 59
45 4CB17EC049 NAMRATHA SHENOY 5 16 34 43 53 60
46 4CB17EC050 NIDHI PAI 11 17 30 51 57 60
47 4CB17EC051 NIHARIKA K P 6 16 31 51 56 61
48 4CB17EC052 NISARGA P 2 22 38 43 56 65
49 4CB17EC053 NISHA D PARANJAPE 2 19 28 44 54 65
50 4CB17EC056 PHALGUNI 9 20 29 45 54 62
51 4CB17EC057 PRABHA KUMARI 8 20 36 39 54 64
52 4CB17EC058 PRAJWAL N 9 25 30 47 53 60
53 4CB17EC059 PRAJWAL S K 1 25 34 45 57 64
54 4CB17EC060 PRAMILA SHREE 7 17 29 39 56 61
55 4CB17EC061 PRATHIKSHA 2 18 29 46 55 60
56 4CB17EC062 PRIYA A 1 25 30 49 53 59
57 4CB17EC063 PRIYA MANJUNATH NAIK 3 25 26 48 55 64
58 4CB17EC065 RAHUL SHASTRY D 14 15 35 50 54 59
59 4CB17EC066 RAKSHA B SHETTY 10 23 27 41 57 62
60 4CB17EC067 RAKSHA D S 12 20 29 51 56 63
61 4CB17EC068 RAMYA HOLLA 9 15 38 46 58 64
62 4CB17EC069 RAMYA P S 1 23 30 49 55 62
63 4CB17EC070 RANJITA SATYANARAYANA Y 12 19 37 48 57 65
64 4CB17EC071 RASHMI JAGADISH KARNIK 12 21 27 44 55 60
65 4CB17EC072 ROHAN GAJANAN SHIROOR 3 16 34 50 56 61
66 4CB17EC073 ROHIT SHENOY K 6 23 36 39 55 60
67 4CB17EC074 ROLVIN LOBO 8 23 27 39 53 61
68 4CB17EC075 ROYCEE DEN MARIA VEIGAS 1 19 37 41 53 64
“Don’t wish it were easier; wish you were better.” – Jim Rohn
17cs664 by G.V. Bhat & S. Samartha , Dept of ECE, C.E.C Bantwal
“Don’t wish it were easier; wish you were better.” – Jim Rohn
17cs664 by G.V. Bhat & S. Samartha , Dept of ECE, C.E.C Bantwal
1.The number of persons live at series of apartments has been counted by your field crew and
entered into the following list. Counts are entered in order and apartments are numbered
starting at one.
number_of_ persons = [28, 32, 1, 0, 10, 22, 30, 19, 145, 27, 36,
25, 9, 38, 21, 12, 122, 87, 36, 3, 0, 5, 55,
62, 98, 32, 900, 33, 14, 39, 56, 81, 29, 38,
1, 0, 143, 37, 98, 77, 92, 83, 34, 98, 40,
45, 51, 17, 22, 37, 48, 38, 91, 73, 54, 46,
102, 273, 600, 10, 11]
How many apartments are there?
How many persons were counted at site 42? Remember, the number of the site and the number of
its position may not be exactly the same.
How many persons were counted at the last site? Have the computer choose the last site
automatically in some way, not by manually entering its position.
What is the total number of persons counted across all of the apartments?
What is the smallest number of persons counted?
What is the largest number of persons counted?
What is the average number of persons seen at a site? You will need to combine two built-in
functions.
2.Discover that the values for site number 27 (count = 900) and site number 59 (count = 600)
are typos. Whoever entered the data actually hit the zero key twice when they should have
only hit it once, so the numbers should actually be 90 and 60. Use a Python command to
replace the erroneous values with the correct values
number_of_persons = [28, 32, 1, 0, 10, 22, 30, 19, 145, 27, 36,
25, 9, 38, 21, 12, 122, 87, 36, 3, 0, 5, 55,
62, 98, 32, 900, 33, 14, 39, 56, 81, 29, 38,
1, 0, 143, 37, 98, 77, 92, 83, 34, 98, 40,
45, 51, 17, 22, 37, 48, 38, 91, 73, 54, 46,
102, 273, 600, 10, 11]
While you are looking through the raw datasheets you also notice that your field crew has
forgotten to enter a whole stack of datasheets. Sigh, make a mental note to "discuss" your
crews data entry habits with them tomorrow, and then create a new list with the missing
data:
unentered_apartments = [27, 24, 16, 9, 23, 39, 102, 0, 14, 3, 9, 93, 64]
Now, combine your new list with the corrected version of number_of_persons (these new
apartments are entered in order starting at the end of the previous list) and then answer
the following questions.
What is the total number of persons counted across all of the apartments?
What is the largest number of persons counted?
What is the smallest number of persons counted?
What is the average number of persons seen at a site?
3. For your research on person counts you need to not only know what many persons are
at a single site, but also how many persons occur on groups of apartments.
number_of_persons = [28, 32, 1, 0, 10, 22, 30, 19, 145, 27, 36, 25, 9,
38, 21, 12, 122, 87, 36, 3, 0, 5, 55, 62, 98, 32,
90, 33, 14, 39, 56, 81, 29, 38, 1, 0, 143, 37, 98,
77, 92, 83, 34, 98, 40, 45, 51, 17, 22, 37, 48, 38,
91, 73, 54, 46, 102, 273, 60, 10, 11, 27, 24, 16,
9, 23, 39, 102, 0, 14, 3, 9, 93, 64]
“Don’t wish it were easier; wish you were better.” – Jim Rohn
17cs664 by G.V. Bhat & S. Samartha , Dept of ECE, C.E.C Bantwal
4. Use the function to calculate and return the total count of all persons for the n
apartments starting at the start site. For example, if there are 5 apartments and
number_of_persons_list = [5, 5, 10, 10, 8], then if starting_site = 2 and number_of_apartments
= 3 then the function should return the value 25 (5 + 10 + 10). Use the data on the number of
persons given in the list above (just copy and paste it into your code) to answer the following
questions.
What is the total number of persons for 5 apartments starting at site 10?
What is the total number of persons for 7 apartments starting at site 1?
What is the total number of persons for 1 site starting at site 23?
Think about what the funtion should do if asked for the total number of persons for
10 apartments starting at site 70 (Note: there are only 74 apartments). Print out a
sentence that explains what it actually does.
5. Write a function that returns the complement of an arbitrary DNA strand passed as a
string. The complement of a DNA strand is that strand with A's replaced by T's, T's replaced
by A's, G's replaced by C's, and C's replaced by G's. E.g., the complement of 'attgcga' is 'taacgct'.
Use this function in combation with a for loop to determine the complement of the following
strands of DNA (included in a list that can be pasted into your code) and print the complements
to the screen.
sequences = ['GCCATTCTGC', 'GCTTACCCAA', 'CCTCTAGCGC', 'TAAATTTTGT',
'TGTGATACTG', 'AACAGAGCATCTCTTGTGACCAGTT',
'TAGGCTGCCTGTGGCAGGTTGTTGCATTCTCTTAGAACCGCCCTGAACTC',
'ATCCACAGACATCTCGTGTAAGGGG', 'CCCTCTTTCCAATTGACAGGATCAG']
6. Write function dna (list_of_sequences) that takes a list of dna sequences as input,
determines whether each sequence is DNA, RNA, or UNKNOWN, and then returns a list of those
values (i.e., 'DNA', 'RNA', 'UNKNOWN') in the same order as the list_of_sequences.
I would recommend:
Calling this function from inside of your new function instead of rewriting or copying
all of that code.
Starting with an empty list to store the output.
Using the the append method.
7.Use this new function to return the values for the following list of DNA sequences and then
(outside of the function) print the values in the resulting list, one value per line.
list_of_sequences = ['attgcccaat', 'agcuucua', 'attuuccaga',
'ggcccacacgg', 'atattagcc', 'startcodon', 'uucaaggu', 'tttttttttt',
'aaaaaaaaa']
8.Write a program that uses a for loop to produce a list of the GC contents of the following
sequences (copy this list into your code):
sequences = ['GCTTACCCAA', 'gctaatta', 'CCTCTAGCGC', 'TAAATTTTGT', 'TGTGATACTG',
'AACAGAGCATCTCTTGTGACCAGTT',
'TAGGCTGCCTGTGGCAGGTTGTTGCATTCTCTTAGAACCGCCCTGAACTC',
'ATCCACAGACATCTCGTGTAAGGGG',
'CCCTCTTTCCAATTGACAGGATCAG', 'taggattgacctagaaa']
Print the list to the screen. Remember, the GC content is just the
number of G's plus the number of C's divided by the total number of
bases.
You may use a function if you wish, but it is not necessary.
9.Use slices from the following list of lists that contains information about characters in Harry
Potter to answer the questions below. Each sublist contains the last name, first name (if the
“Don’t wish it were easier; wish you were better.” – Jim Rohn
17cs664 by G.V. Bhat & S. Samartha , Dept of ECE, C.E.C Bantwal
character has two names) and occupation of a single character. Paste the list into your code
to get started.
harry_potter_characters = [['Potter', 'Harry', 'Student'], ['Dobby', 'House Elf'], ['Granger',
'Hermione', 'Student'], ['Hagrid', 'Rubeus', 'Keeper of Keys and Grounds']]
Print the following lines with the the appropriate answers inserted into the blanks by taking
slices from the list:
Harry ______________ is a ______________ at Hogwarts.
The Keeper of Keys and Grounds at Hogarts is ______________ ______________ who is typically
refered to only by his last name.
The entire entry in the table for Hagrid is _________________________________________________. [i.e.,
print out the sublist for Hagrid]
Dobby is a ______________.
______________ Granger has a time-turner, which would be really useful for completing this
homework.
10. Here is a list of different ultimate answers to the the ultimate question of life the
universe and everything:
answers = [42, 0, 'money', 'children', 'friends', 'dancing', 'cheetos', "ERROR: THIS IS A VIOLATION
OF SKYNET'S QUERY POLICY. A TERMINATOR WILL ARRIVE SHORTLY"]
Copy this list into your code and use a for loop to print out:
The ultimate answer to the ultimate question of life, the universe, and everything is: XXX.
for each item in the list, where XXX is the item in the list.
11. When we iterate through a dictionary using a for loop, we actually iterate over the
keys:
d = { "key1":1, "key2":2, "key3":1, "key4":3, "key5":1, "key6":4, "key7":2 }
for k in d :
print("key=", k, " value=", d[k], sep="")
Modify the code above to print just the keys associated to values that are greater than 1.
12. Write a function called accept login (users, username, password) with three
parameters: users a dictionary of username keys and password values, username a string for
a login name and password a string for a password. The function should return True if the user
exists and the password is correct and False otherwise. Here is the calling code, test your code
with both good and bad passwords as well as non-existent login names:
13. Write a function called findvalue(mydict,val) that accepts a dictionary called mydict
and a variable of any type called val. The function should return a list of keys that map to the
value val in mydict.
“Don’t wish it were easier; wish you were better.” – Jim Rohn
17cs664 by G.V. Bhat & S. Samartha , Dept of ECE, C.E.C Bantwal
15. Write a function called wordfrequencies(mylist) that accepts a list of strings called
mylist and returns a dictionary where the keys are the words from mylist and the values are
the number of times that word appears in mylist:
word_list = list("aaaaabbbbcccdde")
word_freq = { ’a’ : 5, ’b’ : 4, ’c’ : 3, ’d’ : 2, ’e’ : 1 }
if word_frequencies(word_list) == word_freq :
print("correct")
else :
print("wrong")
18. Follow the steps bellow: -Create a new dictionary called prices using {} format like the
example above.
o Put these values in your prices dictionary:
o "banana": 4,
o "apple": 2,
o "orange": 1.5,
o "pear": 3
o Loop through each key in prices. For each key, print out the key along with its price
and stock information. Print the answer in the following format:
o apple
o price: 2
o stock: 0
o Let's determine how much money you would make if you sold all of your food.
o Create a variable called total and set it to zero.
o Loop through the prices dictionaries.For each key in prices, multiply the number in
prices by the number in stock. Print that value into the console and then add it to
total.
o Finally, outside your loop, print total.
19. Follow the steps: First, make a list called groceries with the values "banana","orange",
and "apple".Define this two dictionaries:
stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}
prices = {
"banana": 4,
"apple": 2,
“Don’t wish it were easier; wish you were better.” – Jim Rohn
17cs664 by G.V. Bhat & S. Samartha , Dept of ECE, C.E.C Bantwal
"orange": 1.5,
"pear": 3
}
o Define a function compute_bill that takes one argument food as input. In the function, create a
variable total with an initial value of zero.For each item in the food list, add the price of that item
to total. Finally, return the total. Ignore whether or not the item you're billing for is in stock.Note
that your function should work for any food list.
o Make the following changes to your compute_bill function:
o While you loop through each item of food, only add the price of the item to total if the item's
stock count is greater than zero.
o If the item is in stock and after you add the price to the total, subtract one from the item's stock
count.
20. The aim of this exercise is to make a gradebook for teacher's students.
Try to follow the steps:
o Create three dictionaries: lloyd, alice, and tyler.
o Give each dictionary the keys "name", "homework", "quizzes", and "tests".Have the "name" key
be the name of the student (that is, lloyd's name should be "Lloyd") and the other keys should
be an empty list. Look in solutions, the "solution 1". Chechk if you have done it rigth.
o Now copy this code:
lloyd = {
"name": "Lloyd",
"homework": [90.0,97.0,75.0,92.0],
"quizzes": [88.0,40.0,94.0],
"tests": [75.0,90.0] }
alice = {
"name": "Alice",
"homework": [100.0, 92.0, 98.0, 100.0],
"quizzes": [82.0, 83.0, 91.0],
"tests": [89.0, 97.0] }
tyler = {
"name": "Tyler",
"homework": [0.0, 87.0, 75.0, 22.0],
"quizzes": [0.0, 75.0, 78.0],
"tests": [100.0, 100.0] }
Below your code, create a list called studentsthat contains lloyd, alice, and `tyler.
for each student in your students list, print out that student's data, as follows:
o print the student's name
o print the student's homework
o print the student's quizzes
o print the student's tests
Write a function average that takes a list of numbers and returns the average.
Define a function called average that has one argument, numbers.
Inside that function, call the built-in sum() function with the numbers list as a
parameter. Store the result in a variable called total.
Use float() to convert total and store the result in total.
Divide total by the length of the numbers list. Use the built-in len() function to calculate
that.
Return that result.
“Don’t wish it were easier; wish you were better.” – Jim Rohn
17cs664 by G.V. Bhat & S. Samartha , Dept of ECE, C.E.C Bantwal
21. Write a function called get_average that takes a student dictionary (like lloyd, alice,
or tyler) as input and returns his/her weighted average following the steps given below .
o Define a function called get_average that takes one argument called student.
o Make a variable homework that stores the average() of student["homework"].
o Repeat step 2 for "quizzes" and "tests".
o Multiply the 3 averages by their weights and return the sum of those three. Homework is 10%,
quizzes are 30% and tests are 60%.
o Define a new function called get_letter_grade that has one argument called score. Expect score
to be a number.
o Inside your function, test score using a chain of if: / elif: / else: statements, like so:
o If score is 90 or above: return "A"
o Else if score is 80 or above: return "B"
o Else if score is 70 or above: return "C"
o Else if score is 60 or above: return "D"
o Otherwise: return "F"
o Finally, test your function. Call your get_letter_grade function with the result
of get_average(lloyd). Print the resulting letter grade.
o Define a function called get_class_average that has one argument, students. You can expect
students to be a list containing your three students.
o First, make an empty list called results.
o For each student item in the class list, calculate get_average(student) and then call
results.append() with that result.
o Finally, return the result of calling average() with results.
o Finally, print out the result of calling get_class_averagewith your students list. Your students
should be [lloyd, alice, tyler].
o Then, print the result of get_letter_grade for the class's average.
22. Define a function which can print a dictionary where the keys are numbers between
m to n and the values are square of keys.
23. Define a function which can generate a dictionary where the keys are numbers between
m to n (both included) and the values are squareroot of keys. The function should just print
the keys only.
24. we will keep track of when our friend’s birthdays are, and be able to find that
information based on their name. Create a dictionary of names and birthdays. When you run
your program it should ask the user to enter a name, and return the birthday of that person
back to them. The interaction should look something like this:
>>> Welcome to the birthday dictionary. We know the birthdays of:
Albert Einstein
Benjamin Franklin
Ada Lovelace
>>> Who's birthday do you want to look up?
Benjamin Franklin
>>> Benjamin Franklin's birthday is 01/17/1706.
25. create a dictionary of famous scientists’ birthdays. In this exercise, extract the
months of all the birthdays, and count how many scientists have a birthday in each month.
Your program should output something like:
{
"May": 3,
"November": 2,
"December": 1
}
“Don’t wish it were easier; wish you were better.” – Jim Rohn
17cs664 by G.V. Bhat & S. Samartha , Dept of ECE, C.E.C Bantwal
26. Write a function named reverseLookup that finds all of the keys in a dictionary that
map to a specific value. The function will take the dictionary and the value to search for as
its only parameters. It will return a (possibly empty) list of keys from the dictionary that map
to the provided value. Include amain program that demonstrates the reverseLookup function
as part of your solution to this exercise. Your program should create a dictionary and then
show that the reverseLookup function works correctly when it returns multiple keys, a single
key, and no keys. Ensure that your main program only runs when the file containing your
solution to this exercise has not been imported into another program.
27. Create a program that determines and displays the number of unique characters in a
string entered by the user. For example, Hello, World! has 10 unique characters While zzz has
only one unique character. Use a dictionary or set to solve this problem.
28. Two words are anagrams if they contain all of the same letters, but in a different order.
For example, “evil” and “live” are anagrams because each contains one e, one i, one l, and one
v. Create a program that reads two strings from the user, determines whether or not they are
anagrams, and reports the result.
29. In the game of Scrabble™, each letter has points associated with it. The total score of
a word is the sum of the scores of its letters. More common letters are worth fewer points
while less common letters are worth more points. The points associated with each letter are
shown below:
30. While the popularity of cheques as a payment method has diminished in recent years,
some companies still issue them to pay employees or vendors. The amount being paid
normally appears on a cheque twice, with one occurrence written using digits, and the other
occurrence written using English words. Repeating the amount in two different formsmakes
it much more difficult for an unscrupulous employee or vendor to modify the amount on the
cheque before depositing it. In this exercise, your task is to create a function that takes an
integer between 0 and 999 as its only parameter, and returns a string containing the English
words for that number. For example, if the parameter to the function is 142 then your function
should return “one hundred forty two”. Use one or more dictionaries to implement your
solution rather than large if/elif/else constructs. Include a main program that reads an integer
from the user and displays its value in English words.
“Don’t wish it were easier; wish you were better.” – Jim Rohn
17cs664 by G.V. Bhat & S. Samartha , Dept of ECE, C.E.C Bantwal
32. In this exercise you will simulate 1,000 rolls of two dice. Begin by writing a function
that simulates rolling a pair of six-sided dice. Your function will not take any parameters. It
will return the total that was rolled on two dice as its only result. Write a main program that
uses your function to simulate rolling two six-sided dice 1,000 times. As your program runs,
it should count the number of times that each total occurs. Then it should display a table that
summarizes this data. Express the frequency for each total as a percentage of the total number
of rolls. Your program should also display the percentage expected by probability theory for
each total. Sample output is shown below.
33. write a program that simulates a game of Bingo for a single card. Begin by generating
a list of all of the valid Bingo calls (B1 through O75). Once the list has been created you can
randomize the order of its elements by calling the shufflefunction in therandommodule. Then
your program should consume calls out of the list, crossing out numbers on the card, until
the card contains a crossed out line (horizontal, vertical or diagonal). Simulate 1,000 games
and report the minimum, maximum and average number of calls that must be made before
the card wins.
“Don’t wish it were easier; wish you were better.” – Jim Rohn
17cs664 by G.V. Bhat & S. Samartha , Dept of ECE, C.E.C Bantwal
34. Write a program for smart appointment booking system that provides patients or any
user an easy way of booking a doctor’s appointment using dictionary method.
35. List Less Than Ten Take a list, say for example this one: a = [1, 1, 2, 3, 5, 8, 13, 21,
34, 55, 89]
write a program that prints out all the elements of the list that are less than 5.
Instead of printing the elements one by one, make a new list that has all the elements
less than 5 from this list in it and print out this new list. Write this in one line of Python code.
Ask the user for a number and return a list that contains only elements from the
original list a that are smaller than that number given by the user.
36. List Overlap Take two lists, say for example these two:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
write a program that returns a list that contains only the elements that are common between the
lists (without duplicates). Make sure your program works on two lists of different sizes.
37. List Comprehension Let’s say I give you a list saved in a variable: a = [1, 4, 9, 16, 100,
64, 81, 100, 23 3 4 78 100 34 55 43 76 100 23 100 24]. Write one line of
1.Python that takes this list a and makes a new list that has only the even elements of this list
in it.
2. only the pure square numbers elements
3. only divisible 5.
4.only adjacent value of 100.
5.only that index which adjacent difference is more than 30.
6. that takes a list and returns a new list that contains all the elements of the first list minus all
the duplicates.
38. A website requires the users to input username and password to register. Write a
program to check the validity of list of password input by users. Following are the criteria for
checking the password:
At least 1 letter between [a-z]
At least 1 number between [0-9]
At least 1 letter between [A-Z]
At least 1 character from [$#@]
Minimum length of transaction password: 6
Maximum length of transaction password: 12
Your program should accept a sequence of comma separated passwords and will check
them according to the above criteria. Passwords that match the criteria are to be printed,
each separated by a comma.
Example
If the following passwords are given as input to the program:
ABd1234@1,a F1#,2w3E*,2We3345
Then, the output of the program should be:
ABd1234@1
39. You are required to write a program to sort the (name, age, score) tuples by ascending
order where name is string, age and score are numbers. The tuples are input by console. The
sort criteria are:
1: Sort based on name
2: Then sort based on age
3: Then sort by score
The priority is that name > age > score.
If the following tuples are given as input to the program:
Tom,19,80
“Don’t wish it were easier; wish you were better.” – Jim Rohn
17cs664 by G.V. Bhat & S. Samartha , Dept of ECE, C.E.C Bantwal
John,20,90
Jony,17,91
Jony,17,93
Json,21,85
Then, the output of the program should be:
[('John', '20', '90'), ('Jony', '17', '91'), ('Jony', '17', '93'), ('Json', '21', '85'), ('Tom', '19', '80')]
40. Write a program which takes 2 digits, X,Y as input and generates a 2-dimensional
array. The element value in the i-th row and j-th column of the array should be i * j. Note:
i=0,1.., X-1; j=0,1,¡Y-1. Suppose the following inputs are given to the program: 3,5 Then, the
output of the program should be:
[[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 6, 8]]
write a binary search function which searches an item in a sorted list. The function should
return the index of element to be searched in the list.
41. You are given words. Some words may repeat. For each word, output its number of
occurrences. The output order should correspond with the input order of appearance of the
word. See the sample input/output for clarification. If the following string is given as input to
the program:
4
bcdef
abcdefg
bcde
bcdef
Then, the output of the program should be:
3
2 1 1
42. You are given a string.Your task is to count the frequency of letters of the string and
print the letters in descending order of frequency.
b3
a2
c2
d1
e1
43. Write a Python program that create separate list for character and separate list for
number and separate list for symbol. and create dictionary where key is either character or
number or symbol
Input
Hello31@(21Bye*&360
44. Given the participants' score sheet for your University Sports Day, you are required to
find the runner-up score. You are given scores. Store them in a list and find the score of the
runner-up.
If the following string is given as input to the program:
5
23665
Then, the output of the program should be:
5
“Don’t wish it were easier; wish you were better.” – Jim Rohn
17cs664 by G.V. Bhat & S. Samartha , Dept of ECE, C.E.C Bantwal
45. Given a string S and width W. Your task is to wrap the string into a paragraph of width.
If the following string is given as input to the program:
ABCDEFGHIJKLIMNOQRSTUVWXYZ
4
Then, the output of the program should be:
ABCD
EFGH
IJKL
IMNO
QRST
UVWX
YZ
46. You are given an integer, N. Your task is to print an alphabet rangoli of size N. Different
sizes of alphabet rangoli are shown below:
#size 3
----c----
--c-b-c--
c-b-a-b-c
--c-b-c--
----c----
#size 5
--------e--------
------e-d-e------
----e-d-c-d-e----
--e-d-c-b-c-d-e--
e-d-c-b-a-b-c-d-e
--e-d-c-b-c-d-e--
----e-d-c-d-e----
------e-d-e------
--------e--------
47. Given 2 sets of integers, M and N, print their symmetric difference in ascending order.
The term symmetric difference indicates those values that exist in either M or N but do not
exist in both.
Input
The first line of input contains an integer, M.The second line contains M space-separated
integers.The third line contains an integer, N.The fourth line contains N space-separated
integers.
4
2459
4
2 4 11 12
Output
Output the symmetric difference integers in ascending order, one per line.
5
9
11
12
48. Write code for Dictionary Password Validator determines whether a proposed password
is acceptable based on whether the given password value appears in a provided dictionary file.
A large dictionary file is provided with the server, but the administrator can supply an
alternate dictionary. In this case, then the dictionary must be a plain-text file with one word
per line
Basic Properties
“Don’t wish it were easier; wish you were better.” – Jim Rohn
17cs664 by G.V. Bhat & S. Samartha , Dept of ECE, C.E.C Bantwal
case-sensitive-validation
check-substrings
dictionary-file
enabled
min-substring-length
test-reversed-password
49. Consider the sequence of numbers ai, i = 0, 1, 2, …, which satisfies the following
requirements:
o a0 = 0
o a1 = 1
o a2i = ai
o a2i+1 = ai + ai+1
for every i = 1, 2, 3, … .
Write a program which for a given value of n finds the largest number among the
numbers a0, a1, …, an.
1. Input
You are given several test cases (not more than 10). Each test case is a line containing an
integer n (1 ≤ n ≤ 99 999). The last line of input contains 0.
2. Output
For every n in the input write the corresponding maximum value found.
50. While preparing this problem set the jury has run into the following problem: it was
necessary to send by e-mail the texts of the problems. As it is well known, e-mail is not reliable,
messages are sent not enciphered, there is a danger that someone can intercept them. The
members of the program committee wanted no participant know the texts of the problems
before the start of the contest. That's why they resorted to cryptography methods in order to
save the texts of the problems from an unsanctioned reading. The jury gas worked up a new
way of enciphering of a text. It is not patented yet, so it's kept secret. However, we'll reveal
you one secret: the new algorithm is based on the work with prime numbers. In particular, in
uses a calculation of n-th by order prime number.
Several members of the program committee independently have worked up programs
that make such calculations, but these programs produce different answers. Each
one of the programmers is sure that his program works correctly. That's why the jury
has reached the deadlock and can't continue working. The contest is about not to
take place.
You are to help to the jury and to save the contest. We want you to write a program
that calculates the n-th by order prime number. The main thing is that your program
should work correctly.
1. Input
First line contains a positive integer k. Then k positive integers follow (one in each line).
The numbers don't exceed 15000.
2. Output
For each number n you should output the n-th by order prime number. Each number
should be in its line.
“Don’t wish it were easier; wish you were better.” – Jim Rohn
17cs664 by G.V. Bhat & S. Samartha , Dept of ECE, C.E.C Bantwal
52. You are to determine how many squares of the chessboard can be attacked by a knight
standing alone on the board. Recall that a knight moves two squares forward (horizontally or
vertically in any direction) and then one square sideways (perpedicularly to the first direction).
Input
The first line contains the number N of test cases, 1 ≤ N ≤ 100. Each of the following N lines
contains a test: two characters. The first character is a lowercase English letter from 'a' to 'h'
and the second character is an integer from 1 to 8; they specify the rank and file of the square
at which the knight is standing.
Output
Output N lines. Each line should contain the number of the squares of the chessboard that
are under attack by the knight.
Sample
input output
3 2
a1 8
d4 6
g6
Input
There is the only integer N in the first line (1 ≤ N ≤ 65535). The i-th of N left lines contains the
integer Ki — the number of position in the sequence (1 ≤ Ki ≤ 231 − 1).
Output
You are to output N digits 0 or 1 separated with a space. More precisely, the i-th digit of output is to
be equal to the Ki-th digit of described above sequence.
Sample
input output
4 0010
3
14
7
6
54. Den has two four-digit combination locks for protecting his bicycle from thieves. Every
evening he arms the bicycle antitheft alarm and fastens the bicycle to a special stand with
one of the locks. Den never uses the same lock two evenings in a row. One night a thief tried
to open the lock using the code 0000. The alarm went off and the thief hurried away. The next
night the thief decided to try the code 0001, then 0002, and so on in ascending order of the
number.
Den never changes the codes of his locks. On the night when the thief came for the
first time the bicycle was fastened with the first lock.
Input
The first line contains the combination that opens the first lock and the second line contains
the combination that opens the second lock. Both combinations are strings consisting of
four digits from 0 to 9.
Output
Output “yes” if the thief will open the lock sooner or later and “no” otherwise.
Samples
input output
0001 no
0000
0002 yes
0001
“Don’t wish it were easier; wish you were better.” – Jim Rohn
17cs664 by G.V. Bhat & S. Samartha , Dept of ECE, C.E.C Bantwal
55. One day, two mathematicians were walking in the forest and picking berries. They’d
been walking for two hours, and then they stopped and decided to see who’s got more berries.
They took out the scales and they weighed their baskets with berries. They wrote the resulting
numbers a1 and b1 down on a piece of paper. Then the second mathematician put all his
berries to the first one’s basket (so that his basket became completely empty) and they
weighed their baskets again and they received numbers a2 and b2, correspondingly. At last,
the first mathematician put all the berries to the second one’s basket (so that his basket
became completely empty); they weighed the baskets and got numbers a3 and b3,
correspondingly. This data was enough to find the winner and the happy mathematicians
moved on.
Your task is to calculate the mass of the berries in each mathematician’s basket by the start
of the competition.
Input
The input data consists of three lines. The i’th line (1 ≤ i ≤ 3) contains integers ai and bi (0
≤ ai, bi ≤ 10 000).
Output
Output the weight of berries in the basket of the first and the second mathematician
correspondingly.
Sample
input output
12 11
21
03
56. At last the first term at the University came to its finish. Android Vasya has already
passed all the exams and wants to know if he gets a scholarship. There is the following practice
of giving scholarship to students at the University:
if a student has got satisfactory marks, the scholarship is not given,
if a student has passed through the examination period with only excellent marks, he gets
a personal scholarship,
if a student doesn’t get a personal scholarship and his average mark is not less than 4.5, he
gets a high scholarship,
if a student gets neither high nor personal scholarship and doesn’t have satisfactory marks,
he gets a common scholarship.
A satisfactory mark corresponds to value 3, a good mark corresponds to value 4, and an excellent
mark corresponds to value 5. An average mark for a student is the average value of all the marks
this student got in his exams. Help Vasya find out which scholarship he gets.
Input
The first line contains an integer n that is the number of exams (1 ≤ n ≤ 10). In the i-th of the
next n lines there is an integer mi that is value of Vasya’s mark in i-th exam (3 ≤ mi ≤ 5).
Output
If Vasya doesn’t get any scholarship output “None”. If he gets a common scholarship output
“Common”, if he gets a high scholarship output “High”, if he gets a personal one output
“Named”.
Samples
input output
3 High
5
5
4
3 None
3
3
3
“Don’t wish it were easier; wish you were better.” – Jim Rohn
17cs664 by G.V. Bhat & S. Samartha , Dept of ECE, C.E.C Bantwal
57. You are given three nonnegative integers a, b, c. You have to arrange them in some
order and put +, − or × signs between them to minimize the outcome of the resulting
expression. You are not allowed to use unary minus and parentheses in the expression. There
must be exactly one sign between every pair of neighbouring numbers. You should use
standard order for performing operations (multiplication first, addition and subtraction then).
Input
There are three lines with one integer in each line. The numbers are arranged in non-
decreasing order (0 ≤ a ≤ b ≤ c ≤ 100).
Output
Print one number — the minimal outcome.
Sample
input output
1 -5
2
3
58. Young and ambitious manager of a transport company Plato got a big order for shipping
products from the capital to n cities of the country. Every city is connected with the capital
by a double-sided road. There are no other roads in the country. The length of the road between
the capital and the city number i equals di kilometers. What a coincidence, that a total weight
of the products to ship to the city number i is exactly di tons.
Plato’s truck is loaded only once in the capital. Then Plato starts shipping the
products. Of course, he is able to drive only on the road. He may visit the cities
in any order, leaving necessary amount of products in each one. There is a tax
system, working in the country. To transport m tons of cargo in l kilometers
Plato has to pay m × l rubbles. Help Plato calculate the minimum amount of
money he has to pay in order to ship all the products to the cities.
Input
The first line contains a single integer n (1 ≤ n ≤ 105) — the number of cities in the country.
The next line contains n integers separated with a space, i-th of which di (1 ≤ di ≤ 104) — is
the length of the road between the city number i and the capital.
Output
In a single line output the minimum amount of money Platon has to pay in order to ship all
the products to the cities.
Sample
input output
3 36
123
59. Everyone knows that computer see integers not in the same way as humans do. Instead
of digits from 0 to 9 they use digits from 0 to 255. For example, the integer 1 000 000 can by
represented by a computer with three digits 15, 66, 64 (let’s denote it as 15;66;64), because
15· 2562 + 66· 256 + 64 = 1 000 000. On top of that, integers in computers have a fixed size.
In this problem the size of an integer is always 4 digits, so the integer 1 000 000 will be
represented as 0;15;66;64. Computers use this exact format to communicate with each other.
This system may seem strange, but it works. Or, it used to work, until an evil genius
reversed the order of digits in half of the computers! These computers now interpret
0;15;66;64 not as 1 000 000 but as 1 078 071 040 (64· 2563 + 66· 2562 + 15· 256 + 0 =
1 078 071 040). No one knows how to fix it, so the computers that are left untouched are now
called “good”, and other computers are called “bad”. In order for “good” and “bad” computers
to communicate, the integers that are read incorrectly must be translated into correct
integers.
For example, let A and B be two computers of opposite types. Let’s say the
computer A wants to send the computer B a non-negative integer not exceeding
4 294 967 295. The computer A writes this integer down with four digits from 0 to 255 and
“Don’t wish it were easier; wish you were better.” – Jim Rohn
17cs664 by G.V. Bhat & S. Samartha , Dept of ECE, C.E.C Bantwal
sends them to the computer B. Computer B reads the received digits as v, which doesn’t
necessary match the integer the computer A was trying to send.
Write a program that would help a “good” or a “bad” computer B determine, what integer the
computer A of the opposite type tried to send.
Input
The first line contains one word, denoting the type of the computer A, which sent the integer:
“GOOD” (without quotes), if the computer is “good”, and “BAD” (without quotes), if the
computer is “bad”.
The second line contains a non-negative integer v that the computer B received (0 ≤ v ≤
4 294 967 295).
Output
In the only line output the non-negative integer that the computer A sent.
Samples
input output
GOOD 1
16777216
BAD 3892510720
1000
60. Did you ever dream of becoming a wizard? Or of being able to solve every problem of
every contest?
Valya wanted to try out magic since childhood, so he became a programmer. One time
he fell asleep trying to solve a problem, and he saw some magical dreams.
In his dream, Valya owns A red lands, B blue lands and C blue-red lands. A red land
gives him one red mana, a blue land — one blue mana, and a blue-red land gives him either
one red or one blue mana (for each blue-red land Valya can decide whether he gets red or blue
mana from this land). Valya wants to cast a spell that costs X red mana, Y blue mana, and
additionally Z mana of any color. Casting this spell will help him to solve the problem he fell
asleep to. Determine if Valya has enough mana to use the spell.
Input
The first line contains three space-separated integers A, B and C — the number of red, blue and
blue-red lands respectively (0 ≤ A, B, C ≤ 109).
The second line contains three space-separated integers X, Y and Z — amount of red mana, blue
mana and additional mana of any color required to cast the spell (0 ≤ X, Y, Z ≤ 109).
Output
If Valya is able to cast the spell, print “It is a kind of magic” (without quotes). Otherwise, print “There
are no miracles in life” (without quotes).
Samples
input output
331 It is a kind of magic
221
565 There are no miracles in life
656
61. Ural doctors worry about the health of their youth very much. Special investigations
showed that a lot of clever students instead of playing football, skating or bicycling had
participated in something like Programming Olympiads. Moreover, they call it sports
programming! To sit near the monitor and think during 5 hours a day – is it a sport? To do it
two times per year during the contests – it is more or less normal, but during the preparations
to the nearest contest they spend several hours a week sitting at their computers! It would be
possible to understand if they were some blockheads and dunces, but they are ones of the best
students all over the world!
To save students from the harmful habit to sit at the computer for hours, Ural doctors
has invented a fundamentally new monitor with diagonal trace of a beam in its electron-beam
tube. Soon the winners of Ural Programming Championship would be awarded with such
monitors. In the specially designed square monitor the electronic beam would scan the screen
not horizontally but diagonally. The difference of the lengths of different diagonals causes
such effects as non-uniform brightness, flashing and non-linear distortions. The terrible
properties of such monitors would break of the habit of looking at the monitor for hours. There
“Don’t wish it were easier; wish you were better.” – Jim Rohn
17cs664 by G.V. Bhat & S. Samartha , Dept of ECE, C.E.C Bantwal
is a little problem: the majority of computer video cards generates the normal “rectangle”
signal for monitor. So it is necessary to develop special adapter-program, which should
transform the usual “rectangle” signal to the signal necessary for this kind of monitors.
Program should be fast and reliable. That’s why the development of this program is entrusted
to the participants of the Ural Championship for Sports Programming.
Input
The first input line contains the single integer N (1 ≤ N ≤ 100) – the number of pixels on the
side of new square monitor. It is followed by N lines, each containing N positive integers not
exceeding 100 divided by spaces. It is the image outputting by the usual video card (as you
can see the color depth of new monitor is not so large – anyway usual programmer does not
need more than 100 colors).
Output
You are to write the program that outputs the sequence for input into the new monitor.
Pixels are numbered from the upper-left corner of the screen diagonally from left ot right and
bottom-up. There is no need to explain details – look at the sample and you'll understand
everything.
Sample
input output
4 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
1 3 6 10
2 5 9 13
4 8 12 15
7 11 14 16
62. You are given a strictly increasing sequence of integers A1,A2,…,ANA1,A2,…,AN. Your
task is to compress this sequence.
The compressed form of this sequence is a sequence of ranges separated by commas
(characters ','). A range is either an integer or a pair of integers separated by three dots (the
string "..."). When each range a...b in the compressed form is decompressed into the
subsequence (a,a+1,…,b)(a,a+1,…,b), we should obtain the (comma-separated)
sequence AA again.
For each maximal contiguous subsequence (a,a+1,…,b)(a,a+1,…,b) of AA such
that b≥a+2b≥a+2, the compressed form of AA must contain the range a...b; if b≤a+1b≤a+1, such
a sequence should not be compressed into a range. A contiguous subsequence is maximal if it
cannot be extended by at least one element of AA next to it. It can be proved that the
compressed form of any sequence is unique (i.e. well-defined).
Input
The first line of the input contains a single integer TT denoting the number of test cases.
The description of TT test cases follows.
The first line of each test case contains a single integer NN.
The second line contains NN space-separated integers A1,A2,…,ANA1,A2,…,AN.
Output
For each test case, print a single line containing one string ― the compressed form of the
given sequence.
Sample
input output
3 1...3,5,6,8...12,15,17
12 4,5,7,8
1 2 3 5 6 8 9 10 11 12 15 17 4
4
4578
1
4
63. SPY GAME: Write a function that takes in a list of integers and returns True if it
contains 007 in order
spy_game([1,2,4,0,0,7,5]) --> True
spy_game([1,0,2,4,0,5,7]) --> True
“Don’t wish it were easier; wish you were better.” – Jim Rohn
17cs664 by G.V. Bhat & S. Samartha , Dept of ECE, C.E.C Bantwal
64. PRINT BIG: Write a function that takes in a single letter(from A to E), and returns a
5x5 representation of that letter
print_big('a')
out: *
* *
*****
* *
* *
HINT: Consider making a dictionary of possible patterns, and mapping the alphabet to specific 5-
line combinations of patterns. For purposes of this exercise, it's ok if your dictionary stops at "E".
65. SUMMER OF '69: Return the sum of the numbers in the array, except ignore sections
of numbers starting with a 6 and extending to the next 9 (every 6 will be followed by at least
one 9). Return 0 for no numbers.
summer_69([1, 3, 5]) --> 9
summer_69([4, 5, 6, 7, 8, 9]) --> 9
summer_69([2, 1, 6, 9, 11]) --> 14
66. FIND 33: Given a list of ints, return True if the array contains a 3 next to a 3
somewhere.
has_33([1, 3, 3]) → True
has_33([1, 3, 1, 3]) → False
has_33([3, 1, 3]) → False
“Don’t wish it were easier; wish you were better.” – Jim Rohn