Notes Module3

Download as pdf or txt
Download as pdf or txt
You are on page 1of 49

17cs664 by G.V. Bhat & S. Samartha , Dept of ECE, C.E.

C Bantwal

Module 3:

Table of contents:
Topics: 02

Web links: 30

University Questions/Question bank: 20

Sample solutions to Programs: 16

Assignment Questions: 66 (6 per student)

Time required:

6 hrs of study time


5 hrs of Practice
5 hrs to complete the assignment

“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)

Python offers a range of compound datatypes often referred


to as sequences. List is one of the most frequently used and
very versatile datatype used in Python. In Python
programming, a list is created by placing all the items
(elements) inside a square bracket [ ], separated by
commas. It can have any number of items and they may be
of different types (integer, float, string etc.).
1. # empty list
2. my_list = []
3. # list of integers
4. my_list = [1, 2, 3]
5. # list with mixed datatypes
6. my_list = [1, "Hello", 3.4]
7. # list can even have list as an item. This is called nested list.
8. my_list = ["mouse", [8, 4, 6], ['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

Q2. How to Access Elements from a List?


(weblink-02 https://www.youtube.com/watch?v=jKHKrzQa2Kw)
There are various ways in which we can access the elements of a list. We
can use the index operator [] to access an item in a list. Index starts from 0. So, a
list having 5 elements will have index from 0 to 4. Trying to access an element
other that this will raise an IndexError. The index must be an integer. We can't
use float or other types, this will result into TypeError. Nested list are accessed
using nested indexing.

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]

Q3. How to slice lists in Python?


We can access a range of items in a list 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 two index that will slice
that portion from the 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

Q4. Describe popular list operations and list methods


(weblink-03 www.youtube.com/watch?v=RVXIBZvg-W8&list=PLQVvvaa0QuDe8XSftW-
RAxdo6OmaeL85M&index=27)
List Methods: The methods that are available with list object in Python
programming are tabulated below. They are accessed as list.method(). Some of the
methods have already been used above.

Python List Methods


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 the defined index
remove() - Removes an item from the list
pop() - Removes and returns an element at the given index
clear() - Removes all items from the list
index() - Returns the index of the first matched item
count() - Returns the count of number of items passed as an argument
sort() - Sort items in a list in ascending order
reverse() - Reverse the order of items in the list
copy() - Returns a shallow copy of the list

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.

Python Expression Results Description


len([1, 2, 3]) 3 Length
[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation
['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] Repetition
3 in [1, 2, 3] True Membership
for x in [1, 2, 3]: print x, 123 Iteration

Q5. How to change or add elements to a list?


(weblink-04
www.youtube.com/watch?time_continue=95&v=ET32jWw6Xr4&feature=emb_logo)
List are mutable, meaning, their elements can be changed unlike string or tuple.
We can use assignment operator (=) to change an item or a range of items. We can
add one item to a list using append() method or add several items using extend()
method. We can also use + operator to combine two lists. This is also called
concatenation. The * operator repeats a list for the given number of times.
Furthermore, we can insert one item at a desired location by using the method
insert() or insert multiple items by squeezing it into an empty slice of a list.

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

3. print (odd) # Output: [1, 3, 5, 7]


4. odd.extend ([9, 11, 13])
5. print(odd) # Output: [1, 3, 5, 7, 9, 11, 13]
6. odd = [1, 3, 5]
7. print (odd + [9, 7, 5]) # Output: [1, 3, 5, 9, 7, 5]
8. print(["re"] * 3) # Output: ["re", "re", "re"]
9.
10. odd = [1, 9]
11. odd.insert(1,3)
12. print(odd) # Output: [1, 3, 9]
13. odd[2:2] = [5, 7]
14. print(odd) # Output: [1, 3, 5, 7, 9]

Q6. How to delete or remove elements from a list?


(weblink-05 https://www.youtube.com/watch?v=0pWwPQaH-98)
We can delete one or more items from a list using the keyword del. It can
even delete the list entirely.

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']

4. del my_list [1:5] # delete multiple items


5. print (my_list) # Output: ['p', 'm']
6. del my_list # delete entire list
7. print (my_list) # Output: Error: List not defined

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

Q7. What are the ways of traversing a list? Explain with


example for each
(weblink-06 https://www.youtube.com/watch?v=5A9nPNgEi6s)
We can pass the list to built-in function |reversed()| which returns a
reverse iterator and doesn’t modify the list.
1. a = [1, 2, 3, 4, 5]
2. for x in reversed(a):
3. print(x)
If you need the indices, use |enumerate()| function for getting the position index
and corresponding value.
1. a = [1, 2, 3, 4, 5]
2. for i, v in reversed(list(enumerate(a))):
3. print(i, v)
Another way to iterate with indices can be done in following manner:

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)

Q8. How can I use List Comprehension to create new List?


(web link -07 https://www.youtube.com/watch?v=17gTGqHG5xQ)
List comprehension is an elegant and concise way to create new list from
an existing list in Python. List comprehension consists of an expression followed
by for statement inside square brackets. Here is an example to make a list with
each item being increasing power of 2. A list comprehension can optionally contain
more for or if statements. An optional if statement can filter out items for the new
list. Here are some examples.

1. pow2 = [2 ** x for x in range(10)]


2. print(pow2) # Output: [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
3.
4. pow2 = [2 ** x for x in range(10) if x > 5]
5. pow2 # Output: [64, 128, 256, 512]
6.
7. odd = [x for x in range(20) if x % 2 == 1]
8. odd # Output: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
9.
10. [x+y for x in ['Python ','C '] for y in ['Language','Programming']
11. # Output: ['Python Language', 'Python Programming', 'C Language', 'C Programming']

“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')])

Q10. How to access elements from a dictionary?


(weblink-09,10 https://www.youtube.com/watch?v=SsjKC_Anl_o ,
https://www.youtube.com/watch?v=P16-o-bRsTU )
While indexing is used with other container types to access values, dictionary uses
keys. Key can be used either inside square brackets or with the get() method. The
difference while using get() is that it returns None instead of KeyError, if the key
is not found.

1. my_dict = {'name':'Jack', 'age': 26}


2. print(my_dict['name']) # Output: Jack
3. print(my_dict.get('age')) # Output: 26
4. # Trying to access keys which doesn't exist throws error
5. # my_dict.get('address')
6. # my_dict['address']

Q11. How to change or add elements in a dictionary?


(weblink-11,12 https://www.youtube.com/watch?v=LEi3aOY3b_s
https://www.youtube.com/watch?v=0JV8ZNIXK4o)
Dictionary are mutable. We can add new items or change the value of existing
items using assignment operator. If the key is already present, value gets updated,
else a new key: value pair is added to the dictionary.

1. my_dict = {'name':'Jack', 'age': 26}

“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. my_dict['age'] = 27 # update value


3. print(my_dict) # Output: {'age': 27, 'name': 'Jack'}
4. my_dict['address'] = 'Dtown' # add item
5. print(my_dict) # Output:{'address':'Dtown','age':27,'name''Jack'}

Q12.How to delete or remove elements from a dictionary?


(weblink-13,14 https://www.youtube.com/watch?v=EnsNV8K_j9Y
https://www.youtube.com/watch?v=795WnZ1S-P4)
We can remove a particular item in a dictionary by using the method pop(). This
method removes as item with the provided key and returns the value. The method,
popitem() can be used to remove and return an arbitrary item (key, value) form the
dictionary. All the items can be removed at once using the clear() method. We can
also use the del keyword to remove individual items or the entire dictionary itself.
1. # create a dictionary
2. squares = {1:1, 2:4, 3:9, 4:16, 5:25}
3. # remove a particular item
4. print(squares.pop(4)) # Output: 16
5. print(squares) # Output: {1: 1, 2: 4, 3: 9, 5: 25}
6.
7. # remove an arbitrary item
8. print(squares.popitem()) # Output: (1, 1)
9. print(squares) # Output: {2: 4, 3: 9, 5: 25}
10. del squares[5] # delete a particular item
11. print(squares) # Output: {2: 4, 3: 9}
12. squares.clear() # remove all items
13. print(squares) # Output: {}
14. del squares # delete the dictionary itself
15. print(squares) # Throws Error

Q13. What is Dictionary Comprehension?


(weblink-15,16 https://www.youtube.com/watch?v=uK7B4TGTwek ,
https://code.tutsplus.com/tutorials/what-are-dictionary-comprehensions-in-python--
cms-29072)
Dictionary comprehension is an elegant and concise way to create new dictionary
from an iterable in Python. Dictionary comprehension consists of an expression
pair (key: value) followed by for statement inside curly braces {}.A dictionary
comprehension can optionally contain more for or if statements. An optional if
statement can filter out items to form the new dictionary. Given below is an
example to make a dictionary with each item being a pair of a number and its
square and an example to make dictionary with only odd items.
1. squares = {x: x*x for x in range(6)}
2. print(squares) # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
3. odd_squares = {x: x*x for x in range(11) if x%2 == 1}
4. print(odd_squares) # Output: {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}

Q14. List and describe some of popular Dictionary methods


available in python?
(weblink-17 https://www.youtube.com/watch?v=oLeNHuORpNY)

“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

Q16. What is Tuple?


(weblink-20 https://www.youtube.com/watch?v=NI26dqhs2Rk )
In Python programming, a tuple is similar to a list. The difference between the two
is that we cannot change the elements of a tuple once it is assigned whereas in a list, elements
can be changed.

Q17. What are the advantages of Tuple over List?


(weblink-21,22 https://realpython.com/lessons/lists-tuples-python-overview/ ,
https://www.youtube.com/watch?time_continue=2&v=RVXIBZvg-
W8&feature=emb_logo)
Since, tuples are quite similar to lists, both of them are used in similar situations as well.
However, there are certain advantages of implementing a tuple over a list. Below listed are
some of the main advantages:

 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

Q18. How are Tuples created in python?


(weblink-23 https://www.youtube.com/watch?v=IP5qEWlaGqQ)
A tuple is created by placing all the items (elements) inside a parenthesis
(), separated by comma. The parentheses are optional but is a good practice to
write it. A tuple can have any number of items and they may be of different types
(integer, float, list, string etc.).
1. # empty tuple
2. my_tuple = ()
3. print(my_tuple) # Output: ()
4. # tuple having integers
5. my_tuple = (1, 2, 3)
6. print(my_tuple) # Output: (1, 2, 3)
7. # tuple with mixed datatypes
8. my_tuple = (1, "Hello", 3.4)
9. print(my_tuple) # Output: (1, "Hello", 3.4)
10. # nested tuple
11. my_tuple = ("mouse", [8, 4, 6], (1, 2, 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

12. print(my_tuple) # Output: ("mouse", [8, 4, 6], (1, 2, 3))


13. # can be created without parentheses also called tuple packing
14. my_tuple = 3, 4.6, "dog" # Output: 3, 4.6, "dog"
15. # tuple unpacking is also possible
16. print(my_tuple) # Output: 3 4.6 dog
17. a, b, c = my_tuple
18. print(a)
19. print(b)
20. print(c)
Creating a tuple with one element is a bit tricky. Having one element within
parentheses is not enough. We will need a trailing comma to indicate that it is in
fact a tuple.
1. my_tuple = ("hello")
2. print(type(my_tuple))
3. # need a comma at the end
4. my_tuple = ("hello",) # Output: <class 'tuple'>
5. print(type(my_tuple))
6. # parentheses is optional
7. my_tuple = "hello",
8. print(type(my_tuple)) # Output: <class 'tuple'>

Q19. Explain different ways of accessing Tuples?


(weblink-24 https://www.youtube.com/watch?v=bdS4dHIJGBc)
There are various ways in which we can access the elements of a tuple.
1. Indexing: We can use the index operator [] to access an item in a tuple where
the index starts from 0. So, a tuple having 6 elements will have index from 0 to 5.
Trying to access an element other that (6, 7, ...) will raise an Index-Error. The index
must be an integer, so we cannot use float or other types. This will result into
Type-Error. Likewise, nested tuple is accessed using nested indexing, as shown in
the example below.
1. my_tuple = ('p','e','r','m','i','t')
2. print(my_tuple[0]) # Output: 'p'
3. print(my_tuple[5]) # Output: 't'
4.
5. # index must be in range If you uncomment below line,
6. # you will get an error. IndexError: list index out of range
7. # print (my_tuple [6])
8. # index must be an integer If you uncomment below line,you will
9. # get an TypeError: list indices must be integers, not float
10. # my_tuple[2.0]
11.
12. # nested tuple
13. n_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
14. # nested index
15. print(n_tuple[0][3]) # Output:'s'
16. # nested index
17. print(n_tuple[1][1]) # Output: 4

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')

Q20. Can I change and Delete a Tuple?


(web link 25,26, https://www.youtube.com/watch?v=pWXuCw863gM
https://www.youtube.com/watch?v=2pCxRTu5SHc)
Unlike lists, tuples are immutable. This means that elements of a tuple cannot be
changed once it has been assigned. But, if the element is itself a mutable datatype
like list, its nested items can be changed. We can also assign a tuple to different
values (reassignment). We can use + operator to combine two tuples. This is also
called concatenation. We can also repeat the elements in a tuple for a given
number of times using the * operator. Both + and * operations result into a new
tuple.

1. my_tuple = (4, 2, 3, [6, 5])


2. # cannot change an element, below line will result in error
3. # my_tuple[1] = 9
# Type Error: 'tuple' object does not support item assignment

4. # but item of mutable element can be changed


5. my_tuple[3][0] = 9
6. print(my_tuple) # Output: (4, 2, 3, [9, 5])
7. # tuples can be reassigned
8. my_tuple = ('p','r','o','g','r','a','m','i','z')
9. print(my_tuple) # Output: ('p','r','o','g','r','a','m','i','z')
10. # Concatenation
11. print ((1, 2, 3) + (4, 5, 6)) # Output: (1, 2, 3, 4, 5, 6)
12. # Repeat
13. print(("Repeat",) * 3) # Output: ('Repeat', 'Repeat', 'Repeat')

“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

Deleting a Tuple: As discussed above, we cannot change the elements in a tuple.


That also means we cannot delete or remove items from a tuple. But deleting a
tuple entirely is possible using the keyword del.

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

3. # TypeError: 'tuple' object doesn't support item deletion


4. #del my_tuple[3]
5. # One can delete entire tuple
6. # NameError: name 'my_tuple' is not defined
7. del my_tuple
8. my_tuple

Q21. Explain DSU Patters?


(weblink-27 )
Comparing Tuples: The relational operators work with tuples and other
sequences; Python starts by comparing the first element from each sequence. If
they are equal, it goes on to the next elements, and so on, until it finds elements
that differ. Subsequent elements are not considered (even if they are really big).

1. >>> (0, 1, 2) < (0, 3, 4)


2. True
3. >>> (0, 1, 2000000) < (0, 3, 4)
4. True

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.

Q22. Compare and contrast between Tuples, Lists, Set,


Dictionary
(weblink-28 https://www.youtube.com/watch?v=n0krwG38SHI)

*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)

Q23. What is Regular Expression


and what are its uses?
Simply put, regular expression is a sequence of
character(s) mainly used to find and replace
patterns in a string or file. Regular Expressions are supported by many of the
programming languages like Python, Perl, R, Java and others. So, learning them
is really helpful.
Regular Expressions use two types of characters:
 Meta characters: As the name suggests, these characters have a
special meaning, similar to * in wild card.
 Literals (like a, b,1,2…)

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

The most common uses of regular expressions are:


 Search a string (search and match)
 Finding a string (findall)
 Break string into a sub strings (split)
 Replace part of a string (sub)

Let’s look at the methods that library “re” provides to perform these tasks.

Q24. What are various methods of Regular Expressions?


The ‘re’ package provides multiple methods to perform queries on an input string. Here are
the most commonly used methods, I will discuss:
 re.match()
 re.search()
 re.findall()
 re.split()
 re.sub()
 re.compile()
Let’s look at them one by one.

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.

1. result =re.match(r'Canara', ''CEC Canara Engineering College CEC')


2. print result.start()
3. print result.end() # Output: 0 2
Above you can see that start and end position of matching pattern ‘CEC’ in the
string and sometime it helps a lot while performing manipulation with 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']

re.split(pattern, string, [maxsplit=0]):


This method helps to split string by the occurrences of given pattern.
1. result=re.split(r'y','Analytics')
2. result # Output: ['Anal', 'tics']
Above, we have split the string “Analytics” by “y”. Method split () has another
argument “maxsplit“. It has default value of zero. In this case it does the maximum
splits that can be done, but if we give value to maxsplit, it will split the string. Let’s
look at the example below:
1. result=re.split(r'i','Analytics Vidhya')
2. print result # Output: ['Analyt', 'cs V', 'dhya']
3. # It has performed all the splits
4. # that can be done by pattern "i".
5.
6. result=re.split(r'i','Analytics Vidhya',maxsplit=1)
7. result # Output: ['Analyt', 'cs Vidhya']
Here, you can notice that we have fixed the maxsplit to 1. And the result is, it has
only two values whereas first example has three values.
re.sub(pattern, repl, string):
It helps to search a pattern and replace with a new sub string. If the pattern is
not found, string is returned unchanged.
1. result=re.sub(r'India','the World','AV is largest community of Ind
ia')
2. result # Output: 'AV is largest community of the World'

re.compile(pattern, repl, string):


We can combine a regular expression pattern into pattern objects, which can be
used for pattern matching. It also helps to search a pattern again without rewriting
it.
1. 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

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']

Some Examples of Regular Expressions


Problem 1: Return the first word of a given string
Step-1 Extract each character (using “\w“)
1. import re
2. result=re.findall(r'.','AV is largest Analytics community of India')
3. print result
# Output: ['A', 'V', ' ', 'i', 's', ' ', 'l', 'a', 'r', 'g', 'e', 's
', 't', ' ', 'A', 'n', 'a', 'l', 'y', 't', 'i', 'c', 's', ' ', 'c', '
o', 'm', 'm', 'u', 'n', 'i', 't', 'y', ' ', 'o', 'f', ' ', 'I', 'n',
'd', 'i', 'a']
Above, space is also extracted, now to avoid it, use “\w” instead of “.“.
1. result=re.findall(r'\w','AV is largest Analytics community of India')
2. print result
3. # Output: ['A', 'V', 'i', 's', 'l', 'a', 'r', 'g', 'e', 's', 't',
'A', 'n', 'a', 'l', 'y', 't', 'i', 'c', 's', 'c', 'o', 'm', 'm', '
u', 'n', 'i', 't', 'y', 'o', 'f', 'I', 'n', 'd', 'i', 'a']
Step-2 Extract each word (using “*” or “+“)
1. result=re.findall(r'\w*','AV is largest Analytics community of India')
2. print result
3. # Output: ['AV', '', 'is', '', 'largest', '', 'Analytics', '', 'co
mmunity', '', 'of', '', 'India', '']

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 “+“.

1. result=re.findall(r'\w+','AV is largest Analytics community of India')


2. print result
#Output: ['AV', 'is', 'largest', 'Analytics', 'community', 'of', 'In
dia']
Solution-2 Extract each word (using “^“)

1. result=re.findall(r'^\w+','AV is largest Analytics community of In


dia')
2. print result # Output: ['AV']
If we will use “$” instead of “^”, it will return the word from the end of the string.
Let’s look at it.
1. result=re.findall (r'\w+$','AV is largest Analytics community of
India')
2. print result # Output: [‘India’]

“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

Problem 2: Return the first two character of each word


Solution-1 Extract consecutive two characters of each word, excluding spaces
(using “\w“)
1. result=re.findall(r'\w\w','AV is largest Analytics community of In
dia')
2. print result # Output: ['AV', 'is', 'la', 'rg', 'es', 'An', 'al'
, 'yt', 'ic', 'co', 'mm', 'un', 'it', 'of', 'In', 'di']
Solution-2 Extract consecutive two characters those available at start of word
boundary (using “\b“)
1. result=re.findall(r'\b\w.','AV is largest Analytics community of I
ndia')
2. print result # Output :['AV', 'is', 'la', 'An', 'co', 'of', 'In']

Problem 3: Return the domain type of given email-ids


To explain it in simple manner, I will again go with a stepwise approach:
Solution-1 Extract all characters after “@”

1. result=re.findall (r'@\w+','[email protected], [email protected], test.


[email protected], [email protected]')
2. print result #Output:['@gmail','@test','@analyticsvidhya','@rest']

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']

Problem 4: Return date from given string


Here we will use “\d” to extract digit.
Solution-1

1. result=re.findall(r'\d{2}-\d{2}-\d{4}','Amit 34-3456 12-05-


2007, XYZ 56-4532 11-11-2011, ABC 67-8945 12-01-2009')
2. print result # Output: ['12-05-2007', '11-11-2011', '12-01-
2009']
If you want to extract only year again parenthesis “( )” will help you.

“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

1. result=re.findall(r'\d{2}-\d{2}-(\d{4})','Amit 34-3456 12-05-


2007, XYZ 56-4532 11-11-2011, ABC 67-8945 12-01-2009')
2. print result # Output: ['2007', '2011', '2009']

Problem 5: Return all words of a string those starts with vowel


Solution-1 Return each words
1. result=re.findall(r'\w+','AV is largest Analytics community of India')
2. print result # Output: ['AV', 'is', 'largest', 'Analytics', 'comm
unity', 'of', 'India']
Solution-2 Return words starts with alphabets (using [])
1. result=re.findall(r'[aeiouAEIOU]\w+','AV is largest Analytics comm
unity of India')
2. print result # Output: ['AV', 'is', 'argest', 'Analytics', 'om
munity', 'of', 'India']
Above you can see that it has returned “argest” and “ommunity” from the mid of
words. To drop these two, we need to use “\b” for word boundary.

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.

1. result=re.findall(r'\b[^aeiouAEIOU]\w+','AV is largest Analytics c


ommunity of India')
2. print result # Output: [' is', ' largest', ' Analytics', ' commu
nity', ' of', ' India']

Above you can see that it has returned words starting with space. To drop it from
output, include space in square bracket[].

1. result=re.findall(r'\b[^aeiouAEIOU ]\w+','AV is largest Analytics


community of India')
2. print result # Output: ['largest', 'community']

Problem 6: Validate a phone number (phone number must be of 10 digits and


starts with 8 or 9)

“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

Problem 7: Split a string with multiple delimiters


Solution
1. import re
2. line = 'asdf fjdk;afed,fjek,asdf,foo'
# String has multiple delimiters (";",","," ").
3. result= re.split(r'[;,\s]', line)
4. print result # Output: ['asdf', 'fjdk', 'afed', 'fjek', 'asdf', 'foo']

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

University Theory Questions

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?

1. # Search for lines that have an at sign between characters


2. # The characters must be a letter or number
3. import re
4. hand = open('mbox-short.txt')
5. for line in hand:
6. line = line.rstrip()
7. x = re.findall('[a-zA-Z0-9]\S+@\S+[a-zA-Z]', line)
8. if len(x) > 0:
9. print(x)

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 ':'

3. # Then print the number if it is greater than zero


4. import re
5. hand = open('mbox-short.txt')
6. for line in hand:
7. line = line.rstrip()
8. x = re.findall('^From .* ([0-9][0-9]):', line)
9. if len(x) > 0:
10. print(x)

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

1. Num = int(input(" Please Enter the Num of Val to be Entered : "))

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

1. # program to count the uppercase, lowercase, special characters


2. # and numeric values
3.
4. def Count(str):
5. my_dict={"LETTERS":0,"DIGITS":0,"UPPERCASE":0,"LOWERCASE":0,
"SPECIAL":0}

“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.

1. from collections import namedtuple


2. my_dict = {}
3. my_dict[('Aly', 'Sivji')] = True
4. my_dict
5. Person = namedtuple('Person', ['first_name', 'last_name'])

“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}

Additional Demo code on Dictionaries and tuples


 Get all tuple keys from dictionary Using list comprehension
1. # Initializing dict
2. test_dict = {(5, 6) : 'gfg', (1, 2, 8) : 'is', (9, 10) : 'best'}

3. # printing original dict


4. print("The original dict is : " + str(test_dict))
5.
6. # Get all tuple keys from dictionary Using list comprehension
7. res = [ele for key in test_dict for ele in key]
8.
9. # printing result
10. print("The dictionary tuple key elements are : " + str(res))
11. # Output: The original dict is :
{(5, 6): 'gfg', (9, 10): 'best', (1, 2, 8): 'is'}
12. # Output: The dictionary tuple key elements are :
[5, 6, 9, 10, 1, 2, 8]

 Python code to convert dictionary into list of tuples


1. # Initialization of dictionary
2. dict = { 'Geeks': 10, 'for': 12, 'Geek': 31 }
3. # Converting into list of tuple
4. list = list(dict.items())
5. # Printing list of tuple
6. print(list)
7. [('for', 12), ('Geeks', 10), ('Geek', 31)]

 Python code to convert into list of tuples to dictionary


1. def Convert(tup, di):
2. for a, b in tup:
3. di.setdefault(a, []).append(b)
4. return di
5.
6. # Driver Code
7. tups = [("akash", 10), ("gaurav", 12), ("anand", 14),
8. ("suraj", 20), ("akhil", 25), ("ashish", 30)]
9. dictionary = {}
10. print (Convert(tups, dictionary))
11. {'akash': [10], 'gaurav': [12], 'anand': [14], 'ashish': [30], 'a
khil': [25], 'suraj': [20]}

“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)]

1. # Function to sort the list using lambda expression


2. def SortTuple(tup):
3.
4. # reverse = None (Sorts in Ascending order)
5. # key is set to sort using first element of
6. # sublist lambda has been used
7. tup.sort(key = lambda x: x[0])
8. return tup
9.
10. # Driver's code
11. tup = [("Amana", 28), ("Zenat", 30), ("Abhishek", 29),
12. ("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

The Submission Format for Assignment


 Title page with Aim and Theory of allotted question
 Algorithm and flowchart
 Python Code with comments
 Expected results for Given Input

Question Allocation List (Questions Given Below the List )

Sl. No USN Name ASSIGNMENT QUESTION TO BE


ANSWER
1 4CB17EC001 ABHISHA SUBRAY TALEKAR 1 21 35 39 57 61
2 4CB17EC002 ADISHRI 1 15 28 51 54 66
3 4CB17EC003 ADITHI 12 23 30 47 57 63
4 4CB17EC004 AHMED FAISAL 13 21 31 51 58 60
5 4CB17EC005 AISHWARYA 10 15 35 40 54 63
6 4CB17EC006 AISHWARYA PRAKASH S 4 15 30 41 56 65
7 4CB17EC007 AKHIL KULAL B 14 24 29 41 55 63
8 4CB17EC008 AKHILESH KUMAR P 14 21 32 49 53 63
9 4CB17EC009 AKSHATHA PRABHU 13 20 37 51 53 59
10 4CB17EC011 ANUSHKA K PAI 14 22 28 42 55 59
11 4CB17EC012 ANVITHA H M 6 20 38 46 55 66
12 4CB17EC013 APOORVA KASHINATH 4 15 34 42 58 60
13 4CB17EC014 ASHISH S U 9 21 33 52 57 62
14 4CB17EC015 B G KEERTHANA 13 24 33 40 54 62
15 4CB17EC017 BANTWAL KIRTHI KAMATH 6 19 30 41 56 62
16 4CB17EC018 BHANUSHREE C L 6 22 28 39 58 61
17 4CB17EC019 CHETHAN S DEVADIGA 11 23 38 50 57 65
18 4CB17EC020 DEEKSHA 10 21 38 48 54 60
19 4CB17EC021 DEEKSHA M 4 19 26 46 58 60
20 4CB17EC022 DHANUSH KAVA 11 15 35 44 58 64
21 4CB17EC024 DHANYA SHETTY 6 25 27 47 58 65
22 4CB17EC025 GAUTAM PAI 4 16 35 46 53 62

“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

69 4CB17EC076 RYAN STEWART 10 23 32 42 53 60


70 4CB17EC077 SAHANA 2 16 35 46 57 63
71 4CB17EC078 SANDHYA 2 23 33 47 53 61
72 4CB17EC079 SAPTHAMI SHUBHAKARA S 3 21 37 51 57 60
73 4CB17EC080 SEEMA 10 15 30 43 58 60
74 4CB17EC081 SEEMA MOHAN NAIK 5 24 34 50 57 60
75 4CB17EC082 SHELDON RODRIGUES 10 21 26 52 57 62
76 4CB17EC083 SHINY SMITHA D SA 7 16 32 44 53 63
77 4CB17EC085 SHREESH KULKARNI 12 25 34 46 54 59
78 4CB17EC087 SHREYA R SUVARNA 3 16 35 51 54 65
79 4CB17EC088 SHWETHA 12 16 32 47 58 65
80 4CB17EC089 SMRUTHI K S 13 19 32 45 58 64
81 4CB17EC090 SOMANNA A P 7 25 37 39 54 62
82 4CB17EC091 SRILAKSHMI V 8 16 31 48 54 65
83 4CB17EC092 SUJITH KUMAR P 12 15 27 42 53 63
84 4CB17EC093 SWAPNIL NAYAK M 8 15 26 39 53 60
85 4CB17EC094 T MANJUNATH SHENOY 13 19 31 49 58 63
86 4CB17EC095 T SUSHMITHA 1 20 36 40 56 62
87 4CB17EC096 THEJAS M.S 8 25 28 52 53 61
88 4CB17EC097 THRUPTI T 1 18 34 45 58 60
89 4CB17EC098 U ADITI PAI 9 15 37 44 55 62
90 4CB17EC099 VINUTHA UDAY SHETTY 2 15 30 47 53 66
91 4CB17EC100 VISHAKA 8 21 36 43 57 59
92 4CB17EC101 YASHASWINI 3 16 31 40 54 64
93 4CB17EC102 YATHISH B.P 8 15 35 46 58 62
94 4CB17EC103 KARTHIK 4 23 35 48 58 61
95 4CB17EC104 CHETHAN SHETTY 5 18 32 50 55 62
96 4CB17EC105 MAHAMMAD SHAFEEQ 8 18 27 51 57 66
97 4CB17EC106 ADESH SHENOY K 9 22 34 40 53 63
98 4CB14EC119 VINAYAK BHAT 8 17 33 52 55 60
99 4CB15EC091 SHRAVAN 4 15 33 42 57 63
100 4CB16EC007 AMOGHAVARSHA 14 17 31 50 57 63
101 4CB16EC088 SHRIRASHMI M T 3 25 27 52 54 59
102 4CB16EC101 THANUSHREE K M 13 20 37 47 56 65
103 4CB16EC109 VRISHABH HAVANAGI 2 20 38 44 56 65

“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]

Use slices to answer the following questions:


1 What is the total number of persons for 5 apartments starting at site 10?
2 What is the total number of persons at the last 6 apartments? Have Python figure out what the
last six apartments are, don't just type in their positions.

“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.

14. Write a function to invert a dictionary. It should accept a dictionary as a parameter


and return a dictionary where the keys are values from the input dictionary and the values
are lists of keys from the input dictionary. For example, this input:
{ "key1" : "value1", "key2" : "value2", "key3" : "value1" }
should return this dictionary:
{ "value1" : ["key1", "key3"], "value2" : ["key2"] }

“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")

16. In bioinformatics a k-mer is a substring of k characters from a string that is longer


than k (see https://en.wikipedia. org/wiki/K-mer for details). Write a function with two
parameters: a string containing DNA and the value of k. Return a dictionary of k-mer counts.

17. Given the following dictionary:


inventory = {
'gold' : 500,
'pouch' : ['flint', 'twine', 'gemstone'],
'backpack' : ['xylophone','dagger', 'bedroll','bread loaf'] }
Try to do the followings:
o Add a key to inventory called 'pocket'.
o Set the value of 'pocket' to be a list consisting of the strings 'seashell', 'strange berry', and 'lint'.
o .sort()the items in the list stored under the 'backpack' key.
o Then .remove('dagger') from the list of items stored under the 'backpack' key.
o Add 50 to the number stored under the 'gold' key.

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:

One point A, E, I, L, N, O, R, S, T and U


Two points D and G
Three points B, C, M and P
Four points F, H, V, W and Y
Five points K
Eight points J and X
Ten points Q and Z
Write a program that computes and displays the Scrabble™ score for a word.
Create a dictionary that maps from letters to point values. Then use the dictionary
to compute the score.

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.

31. Create a Simple Translation Quiz using Dictionaries Input sample:


qs={'sein ':'to be', 'haben ':'to have', 'werden ':'to become', 'sagen ':'to say', 'geben ':'to give'}
Output sample
Please enter your name: IMWhat does 'sein' mean?
(a) 'to be'
(b)'to have' 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

What does 'haben' mean?


(a) 'to be'
(b)'to have' b

What does 'werden' mean?


(a) 'to become'
(b) 'to come' b

What does 'sagen' mean?


(a) 'to say'
(b) 'to hear' a

What does 'geben' mean?


(a) 'to take'
(b) 'to give' b

Im, you scored 4 out of 5.

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.

If the following string is given as input to the program:


aabbbccde
Then, the output of the program should be:

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.

51. Let An =sin(1–sin(2+sin(3–sin(4+…sin(n))…)


Let Sn =(…(A1+n)A2+n–1)A3+…+2)An+1
For given N print SN
Input
One integer N. 1 ≤ N ≤ 200
Output
Line containing SN in tupple
Sample
input output
3 ((sin(1)+3)sin(1–sin(2))+2)sin(1–sin(2+sin(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

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

53. Let's consider an infinite sequence of digits constructed of ascending powers of 10


written one after another. Here is the beginning of the sequence: 110100100010000… You
are to find out what digit is located at the definite position of the sequence.

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

spy_game([1,7,2,0,4,5,0]) --> False

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

You might also like