Tuesday, 28 May 2019

Assessment 4



Assignment 4


1.  Print “t” in the below tuple: t=(“p”, “y”, “t”, “h”, “o”, “n”)
2.  a = ["apple", "banana", "cherry"]. In this list change the “banana” to “mango” and display the list.
3.  Remove “Chennai” and display the deleted item from the list: 
     a = ["Hyd", "Vijayawada", "Tirupathi",'Chennai',2.6,4+5j]
4.  Display element 20 in the following list: a=["python",[10,20,30]] 
5.  List out the differences between list and tuple.
6.  Display starting element to below 6th element from the list: words = ['how', 'much', 'is[br]', 'the', 'fish[br]', 'no', 'really']
7. Swap the two number without using third variable.(input values are: a=10, b=20)
8. What will be the output when we run the below code:
>>> a = ('rama', "sitha", True)
>>> a
('rama', 'sitha', True)
>>> del a
>>> print(a)

9. (i) What do you understand the following statement? 
           raj=3,4,True,'Ram'

   (ii) display in the following output:
a=3
b=4
c=True
e=’Ram’
>>> a,b,c,e=raj

10.  t=('c','a','t') :How do you test element ‘t’ is exists in the tuple are not?

Answers:

1.      print(t[2]) or t[2] 
2.      a[1]= "mango"
       print(a)
3.       a.pop(3)

4.      a[1][1]

5.      Differences: 
a.       Lists are mutable while tuples are immutable.
b.      Lists can be copied but Tuples cannot be copied (The reason is that tuples are immutable).
c. A list is created using square brackets [] whereas the tuple is created using parenthesis ().

6.      words[0:6]

7.      a = 10
 b = 20
 a = a + b
 b = a - b
 a = a - b
print(a, b) 

8.      Error 

9.      (i) Its Packing the tuples. 
(ii) Unpacking the tuples is >>> a,b,c,e=raj
print(‘t’ in t)

Next
Previous Assessment: Assessment Exam2

Set data type


 Set data type:
It is a collection of elements of different datatypes without duplicate elements where order is not important.

Examples:

1. Set is Unordered List
>>> s={10,20,30,"Hello"}
>>> type(s)
<class 'set'>
>>> print(s)
{'Hello', 10, 20, 30}

(or)
s=set([10,20,30]) # create

2. Set may contain different data  types
>>> a={10,2.5,True,3+4j,’Ram’}
>>> type(a)
<class 'set'>
>>> print(a)
{True, 2.5, 10, 'Ram', (3+4j)}

3. Since it unordered list so index concept is not available and slicing operation is also not available
>>> s={10,30,50}
>>> s[0]=20 #error
>>> s[1:3] #error there is no slicing   operation since index is not available

4. Dynamically grow able
>>> s={10,20,False,2.3}
>>> s.add(40)
>>> print(s)
{False, 40, 2.3, 10, 20}
>>> s.remove(2.3)
>>> print(s)
{False, 40, 10, 20} 

5. Duplication is not allowed
>>> s={'h','e','l','l','o','o'}
>>> print(s)
{'o', 'e', 'l', 'h'}

By using del keyword we can delete entire set
Ex:
s={'h','e','l','l','o','o'}
>>> del s
>>> print(s) #it is deleted entire set

Assignments:

1. Which of the following is not the correct syntax for creating a set? 
a)    set([[1,2],[3,4]])
b)    set([1,2,2,3,4])
c)    set((1,2,3,4))
d)    {1,2,3,4}

Answer: a

2. Which of the following statements is used to create an empty set? 
a)   { }
b)   set()
c)   [ ].
d)   ( )
Answer: b

Explanation: { } creates a dictionary not a set. Only set() creates an empty set. 

3. What is the output of the following piece of code when executed in the python shell? 
>>> a={5,4}
>>> b={1,2,4,5}
>>> a<b
a)   {1,2}
b)   True
c)   False
d)   Invalid operation

Answer: b
Explanation: a<b returns True if a is a proper subset of b

4. If a={5,6,7,8}, which of the following statements is false? 
a)   print(len(a))
b)   print(min(a))
c)   a.remove(5)
d)   a[2]=45

Answer: d
Explanation: The members of a set can be accessed by their index values since the elements of the set are unordered. 

5. If a={5,6,7}, what happens when a.add(5) is executed? 
a)   a={5,5,6,7}
b)   a={5,6,7}
c)   Error as there is no add function for set data type
d)   Error as 5 already exists in the set 
Answer: b

Explanation: There exists add method for set data type. However 5 isn’t added again as set consists of only non-duplicate elements and 5 already exists in the set. Execute in python shell to verify.

Net topic         : frozenset datatype
Previous Topic: Tuple
Assignment 4

range data type



Range datatype:

The range data type represents a sequence of numbers. The numbers in the range are not modifiable. Generally, range is used for repeating a ‘for loop’ for a specific numbers of times.
Or
It is a collection of numbers in the form of the list.

Creating range data type:

>>> r=range(2,10) #one range data type is created, r is the variable which points to elements
>>> print(r)
range(2, 10)
#Displaying the elements in the range data type:
>>> for i in r: print(i)
2
3
4
5
6
7
8
9
>>> 
 # range data type is created from 3rd to below 10, each element is incremented by 2
>>> r=range(3,10,2) 
>>> for i in r: print(i)

3
5
7
9

>>> r=range(3,10,2) #displays the numbers from 3 to below 10, every element is incremented by 2
>>> for i in r: print(i)
3
5
7
9

r=range(0,15,3)
#numbers starts from 0 to below 15, and each element is incremented by 3
Output:
>>> r=range(0,15,3)
>>> for i in r:print(i)
0
3
6
9
12
>>>

Any doubts you can mail: rajendra.apssdc@gmail.com


Next topic      : dictionary data type
Previous topic: frozenset datatype

You may like the following posts:
  Built-in Data types

dictionary data type

dict:(Dictionary Data type)

It is a collection of elements in the form of key and value pairs.
If you want to represent a group of values as key-value pairs then we go for dict data types.

The dict represents the key and the next one becomes its value.
The key and its value should be separated by a colon (:) and every pair should be separated by comma. All the elements should be enclosed inside braces (curly brackets).
We can create dict by typing the roll numbers and names of students. Dict data type is mutable.


Syntax:
Variable={key1:’value’, key2:’value’,..}

Example:
(1. )a={10:’ram’,20:’sita’,30:’rajesh’}
print(a)
{10: 'ram', 20: 'sita', 30: 'rajesh'}

Other Examples:

(2.) >>> a[10]='rajendra' #We can modify the values
>>> print(a)
{10: 'rajendra', 20: 'sita', 30: 'rajesh'}
(3)>>> b={'a':'apple','c':'cat'}
>>> b['b']='bat' #we can add the values
>>> print(b)
{'a': 'apple', 'c': 'cat', 'b': 'bat'}

(4) Different data types also we can use in dict
>>> s={10:"raj",10+3j:True,2.4:3.6}

(5)  a={} # empty dict can be created, later we can add

a[2]=”ram”
a[4]=’sita’
print(a)

Empty dict can be created:
>>> a={} # empty dictionary
>>> type(a)
<class 'dict'>
>>> a[4]='ravi' #we can add the key values
>>> a[7]='sita'
>>> print(a)
{4: 'ravi', 7: 'sita'}

Values can be duplicated. Duplicate values can be given.

>>> a={10:'rajendra',20:'rajendra',30:"siva"}
>>> print(a)
{10: 'rajendra', 20: 'rajendra', 30: 'siva'}

Duplicated key values are not allowed
>>> b={10:'ravi',10:'siva'}
>>> print(b)
{10: 'siva'}

Dictionary is a mutable
>>> b={10:'ravi',10:'siva'}
b[10]=’rajendra’ #we can modify the values
>>>print(b)
b={10:' rajendra',10:'siva'}

dictionary of strings
>>> a={"hi":10,"vij":30,"hyd":40}
>>> print(a)
{'hi': 10, 'vij': 30, 'hyd': 40}
>>> a["hi"] #accessing the values
10
>>> 

To access only values
>>> a={10:"ravi",20:"siva"}
>>> print(a.values())

To access only keys in the dictionary
dict_values(['ravi', 'siva'])
>>> print(a.keys())
dict_keys([10, 20])
>>> 

Keys are not modifiable if you try to modify, it will be added
Ex:
>>> a={10:'ravi',20:'siva'}
>>> a['ravi']=30
>>> print(a)
{10: 'ravi', 20: 'siva', 'ravi': 30}

>>> 
5. #deleting  dict values
s={10:'rj',20:"sita"}
>>> del s[10]

6. To delete entire dict we can use 
>>> s={10:'rj',20:"sita"}
>>> del s # it deletes entire dictionary elements

7. To delete a particular element from the dictionary we can use

>>> s={10:'rj',20:"sita"}
>>> s.pop(20) 

8. To delete a random element from the dictionary we can use (it mostly removes end of the elements)
       >>> s={10:'raj',20:"sita",30:"Ravi",40:"krish",16:"ram"}
       >>> s.popitem()
       (16, 'ram')
       >>> s.popitem()
       (40, 'krish')
       >>> s.popitem()
       (30, 'Ravi')
       >>>       
9. To delete all the elements from the dictonary:
 >>> s={10:'raj',20:"sita",30:"Ravi",40:"krish",16:"ram"}
 >>>s.clear()

10. Nested dictionary

>>>a = {1: 'Rama', 2: 'Sita', 3:{'V' : 'Vij', 'H' : 'Hyd', 'R' : 'Rama'}}
>>>print(a)

"""output
{1: 'Rama', 2: 'Sita', 3: {'V': 'Vij', 'H': 'Hyd', 'R': 'Rama'}}
>>> """


update() :
update method is used to append a new element to it

>>>a = {"1" : "C", "2" : "Java"}
>>>print(a)
>>>a["3"] = "C++" #Adding the key-value
>>>a.update({"4" : "JavaScript"})#Another way to adding the key-value
>>>print(a)#displaying the all the dict key-values

"""
output:

{'1': 'C', '2': 'Java'}
{'1': 'C', '2': 'Java', '3': 'C++', '4': 'JavaScript'}

"""

Assignments:

1. Which of the following statements create a dictionary? 
a) d = {}
b) d = {“Ram”:10, “Ravi”:35}
c) d = {10:”Krishna”, 35:”Radha”}
d) All of the mentioned
Answer: d (Dictionaries are created by specifying keys and values. )

2. Read the code shown below carefully and pick out the keys? 
d = {"Rama":10, "Krishna":35}
a) “Rama”, 10, 35, and “Krishna”
b) “Rama” and “Krishna”
c) 10 and 35
d) d = (10:”Rama”,345:”Krishna”)
Answer: b (Dictionaries appear in the form of keys and values. )

3. d = {"Rama":10, "Krishna":35}, to delete the entry for “Rama” what command do we use 
a) d.delete(“Rama”:10)
b) d.delete(“Rama”)
c) del d[“Rama”].
d) del d(“Rama”:10)

Answer: c

YouTube related videos

Next topic: Mixed dictionary data type
bytes data type
Previous topic: range data type

You may like the following posts:
  Built-in Data types

frozenset datatype


Frozenset

See the below examples:

 1.
>>> s={10,20,30,"hello"} #created set elements, where s is the variable (object reference) to it


>>>s=frozenset(s) # type casting from set into frozenset
>>>print(s)
20,'hello',10,30 # frozen set is unordered list


2. >>> b={10,20,30,"hello"} # set b is created
>>> b
{10, 'hello', 20, 30} # set b is displayed
>>> b=frozenset(b) # type casting from set b to frozenset b
>>> b #frozenset b is displayed
frozenset({10, 'hello', 20, 30})

3. b=frozenset({10,20,30,"hello"}) # frozenset b is created

4. s={10,2.5,True,"Ram",2+3j} # same different types
5. s[0] # Error No slicing operation
6. We can not modify as frozen set is immutable so can not add and remove
>>> s={10,20,,30}
>>>s=frozenset(s)
>>>s.add(40)#error
s.remove(10)#error

5. Accessing Set elements:
>>> s={"app","bana","cherry"}
>>> s=frozenset(s)
>>> for i in s: print(i)
App bana cherry
>>> 
>>> s={"app","bana","cherry"}
>>> for x in s:
        print(x)
output:
cherry
bana
app



Now we will understand the definitoin: 


Definition:


The frozenset datatype is same as set data type. The main difference is that elements in the set datatype can be modified whereas, the elements of frozenset can not be modified.

Creating frozenset data type:

We can create frozenset data type in two ways
1. By typecasting
2. Bypassing elements to the frozenset function 

1. By typecasting

s={10,20,30,"hello"} #created set elements, where s is the variable (object reference) to it
s=frozenset(s) # type casting from set into frozenset

Displaying the frozenset elements:
>>> s
frozenset({'hello', 10, 20, 30})
>>> print(s)
frozenset({'hello', 10, 20, 30})
>>> 

2. By passing elements to the frozenset function 

Another way of creating frozenset is by passing elements to the frozenset function.
a=frozenset({10,20,True,2+3j})
>>> type(a)
<class 'frozenset'>
>>> 


Output: Random output as it is unordered
frozenset({10, 'hello', 20, 30})





Ex 1:
Unordered List
>>> s=frozenset({10,20,,30,"hello"})
>>> s
Frozenset({'hello', 10, 20, 30})

Ex2: Different type of data
s=frozenset({10,2.5,True,"Ram",2+3j})
>>> s
{True, 2.5, 10, (2+3j), 'Ram'}
>>> 

Ex3: Index concept is not available thus it is unordered set and slicing operations
>>> s={10,20,30}
>>>s[0] #Error as no index
>>>s[0:2] #Error no slicing operation
Ex 4: How can we access each element in a set?
>>> s=frozenset({2,5,7,8,9,10})
>>> for i in s:
        print(i)
2 5 7 8 9 10
Ex 5: How do we check one item in set
B=frozenset({10,20,30})
print(10 in b)
True
Ex4: we cant not modify
>>> s=frozenset({10,20,30})
>>>s.add(40)#error
>>>s.remove(10) #error
Ex5: Duplication is not allowed
b=frozenset({10,20,10,20})
>>> b
frozenset({10, 20})
>>> 

Exercise:
find out the output:
>>> a={1,2,3}
>>> b=frozenset([3,4,5])
>>> a-b
{1, 2}


Next topic: range data type
Previous topic: Set data type


How to read multiple values from the keyboard in a single line

#how to read multiple values from the keyboard in a single line
a,b=(int(x) for x in input("enter 2 numbers:").split())
print(a,b)
print("product =",a*b)
"""output:
enter 2 numbers:10 20
10 20
product = 200

1Q: Why do use split()?

Ans: There are two reasons:
(1) It leads to error if I give i/ps by giving spaces.
Ex: 10 20 #error
(2) It takes only 1 input, and stores into two inputs like 1 and 0
so we will get a result like the below:
1 0
product=0

so the split() function is mandatory when we want to read more than one i/p from the keyboard

What is split()?
The split() method splits a string into a list.

You can specify the separator, the default separator is any whitespace.

Example:
"2 4".split() #We have to call the split() function w.r.t string
['2', '4']
>>> "1, 2 3 Hyd, Vij Kurnul,Kadapa atp".split(',')
['1', ' 2 3 Hyd', ' Vij Kurnul', 'Kadapa atp']
>>>

Find ncr and npr

Ex3: Find ncr and npr:
"""
c= no of distinct combinations
n=total no of objects in the set
r=no of choosing objects from the set
5c2=n!/(n-r)!
Input: Two positive integers as the total no of objects and sample size
Output:A positive integer as the permutation or permutation of 'n' objects
taken at 'r' at a time
"""
import math
#n,r=(int(x)for x in input("enter 2 numbers:").split())
n=int(input("enter n value: ="))
r=int(input("enter r value: ="))
if n>=r:
    print("ncr=",math.factorial(n)/(math.factorial(r)*math.factorial(n-r)))
    print("npr=",math.factorial(n)/(math.factorial(n-r)))
else:
    print("value of n can not be <r")

"""enter n value: =5
enter r value: =2
ncr= 10.0
npr= 20.0
>>>
===================== RESTART: F:\Programs\input\ncr.py =====================
enter n value: =2
enter r value: =5
value of n can not be <r
>>> """

Monday, 27 May 2019

bytes data type

Bytes data type:

In Python, we have several ways to store the sequences:
list, tuple,dictionary, strings.

In the same way we have other way to store the sequence is 'Bytes'..elements

Definition:

Bytes data type is a collection of byte numbers just like an array.
A byte number is any positive integer from 0 to 255 (inclusive)
A byte can store in the range from 0 to 255 and it can not store even negative numbers
Once we create the bytes data type it is not possible to modify the values

Syntax:

1. Create one list (2.) type caste into bytes

Variable=[number1,no2,no3,…]

Example:

>>> a=[10,20,30,40]#creating list
>>> type(a)
<class 'list'>
>>> a=bytes(a)#type casting into bytes data type
>>> type(a)
<class 'bytes'>
>>> for i in a:print(i) #processing each bytes #element where i varies from index 0 to size-1
10
20
30
40

In general we can use bytes and bytearray data types to represent binary information. 
Example: images, video files,…etc

2nd way to create bytes data type elements:

Syntax:
Variable=bytes([no1,n02,….etc])

Example:
>>> a=bytes([10,20,30,40])#direct way to create bytes data elements

It is not possible to modify:
>>> a[0]=15 #Error

Negative values are not allowed:
a=bytes([10,-20,30]) #Error

Bytes data type is a homogeneous collection of nos:
a=bytes([10,'sita',True,2+3j]) #Error

Bytes elements can be 0 to 255 only
>>> a=bytes([10,0,10,256]) #Error
>>> a=bytes([10,0,10,255]) #ok

Compare between Strings and Bytes

a='aws course' #string data type

c=b'aws course' #byte data type

print(type(a))

print(type(c))


Example:

a='Python'

c=b'Python'

print(type(c))

print(type(a))

print(a)

print(c)

d=a.encode('ASCII')

if(d==c):

    print("it is same")

else:

    print("it is not same")



Difference between String and byte:

 

Byte

String

It is stored in the form of bytes

It is stored in the form of characters

Directly system readable

System is not readable directly. Encoding should be done to understand the system

 


Next topic : bytearray
Previous topic: Mixed dictionary data type
dictionary data type

Files with Exception handling

#Ask the user to take two input integer values var a,b try:     a=int(input("enter any integer value:"))     b=int(input(&qu...