# Python Notes-7

 assert 
There are three parts to an assert statement: the assert keyword, an expression which, if False, results in crashing the program. The third part (after the comma after the expression) is a string that appears if the program crashes because of the assertion.

assert (BOARDWIDTH * BOARDHEIGHT) % 2 == 0, ‘Board needs to have an even number of boxes for pairs of matches.’

 import random

 random.randint(1,9); 

As python is strongly type there is no concept of function overload

Python is great for interviews see how easy reversing a string is even without using any function

 astring = "Hello world!" print(astring[::-1])

 astring = "Hello world!" print(astring.upper()) print(astring.lower()) astring = "Hello world!" print(astring.startswith("Hello")) print(astring.endswith("asdfasdfasdf")) astring = "Hello world!" afewwords = astring.split(" ") x = [1,2,3] y = [1,2,3] print(x == y) # Prints out True print(x is y) # Prints out False 

##### Reference comparison

is is reference compare operator

The ‘is’ operator
Unlike the double equals operator “==”, the “is” operator does not match the values of the variables, but the instances themselves.

#### Using else in loops

Unlike languages like C,CPP.. we can use else for loops. When the loop condition of “for” or “while” statement fails then code part in “else” is executed. If break statement is executed inside for loop then the “else” part is skipped. Note that “else” part is executed even if there is a continue statement.

Here are a few examples:

 # Prints out 0,1,2,3,4 and then it prints "count value reached 5"

 count=0 while(count<5): print(count) count +=1 else: print("count value reached %d" %(count)) # Prints out 1,2,3,4 for i in range(1, 10): if(i%5==0): break print(i) else: print("this is not printed because for loop is terminated because of break but not due to fail in condition") 

 list1 = ['physics', 'chemistry', 1997, 2000];

 print list1 del list1[2]; print "After deleting value at index 2 : " print list1 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, 1 2 3 Iteration 

 max(list) 

Returns item from the list with max value.

 min(list) 

Returns item from the list with min value.
 list.append(obj) 

Appends object obj to list
 list.count(obj) 

Returns count of how many times obj occurs in list

 list.extend(seq) 

Appends the contents of seq to list

 list.index(obj) 

Returns the lowest index in list that obj appears

 list.insert(index, obj) 

Inserts object obj into list at offset index

 list.pop(obj=list[-1]) 

Removes and returns last object or obj from list

 list.remove(obj) 

Removes object obj from list

 list.reverse() 

Reverses objects of list in place

To be continued …

# Python Notes-6

In continuation from
Python Notes-5
Python Notes-4
Python Notes-3
Python Notes-2
Python Notes-1

#### Dictionary

dict
 d = {1:2, 'q':2} 
key:value pair

Unlike lists, items in dictionaries are unordered.

So access is only via key not by index. There is no first item or last item in a python dictionary data structure.

The order of items matters for determining whether two lists are the same, it does not matter in what order the key-value pairs are typed in a dictionary. Enter the following into the interactive shell:

 >>> spam = ['cats', 'dogs', 'moose'] >>> bacon = ['dogs', 'moose', 'cats'] >>> spam == bacon False >>> eggs = {'name': 'Zophie', 'species': 'cat', 'age': '8'} >>> ham = {'species': 'cat', 'age': '8', 'name': 'Zophie'} >>> eggs == ham True 


for key, value in d.items()

for key in d.keys()



or just for key in d

#### Loop


for i in range(15):


 for i in range(10): for i in range(0,10): for i in range(0,10,1): 

all equals

you can make for loop count down

 for i in range(5, -1, -1): print(i) 

while True:

while a < 5:

#### Conditional statementif else elif

 if name == 'Alice': print('Hi, Alice.') elif name == ‘Bob’ print(‘hi Bob’); else: print('Hello, stranger.') 

 mystring = "hello" myfloat = 10.0 myint = 20

 # testing code if mystring == "hello": print("String: %s" % mystring) if isinstance(myfloat, float) and myfloat == 10.0: print("Float: %f" % myfloat) if isinstance(myint, int) and myint == 20: print("Integer: %d" % myint) 

When used in conditions, 0, 0.0, and ” (the empty string) are considered False,

When you assign a list to a variable, you are actually assigning a list reference to the variable. A reference is a value that points to some bit of data, and a list reference is a value that points to a list. e.g.

❶ >>> spam = [0, 1, 2, 3, 4, 5]
❷ >>> cheese = spam
❸ >>> cheese[1] = ‘Hello!’
>>> spam
[0, ‘Hello!’, 2, 3, 4, 5]
>>> cheese
[0, ‘Hello!’, 2, 3, 4, 5]
The code changed only the cheese list, but it seems that both the cheese and spam lists have changed.

This is not true for c++ STL vector

To be continued …

# Python Notes-5

In continuation from
Python Notes-4
Python Notes-3
Python Notes-2
Python Notes-1

Let us change the topic for a while from list, string, tuple etc.

Functions in python are also very user friendly for example:

 def func(a, b): return a+b,a*b 

Above function will return a tuple so func(2,3) will give (5,6)

Note: It is never a good practice to do multiple thing in a single function. You should always try to make your function serve single purpose that will make it more usable.

Let us go back to list there is so much to cover there so much power in this data structure.

 del li[indx] 

you can also delete a variable, kind of unassignment .. after deleting use will give you TypeError

Operators in, not in:

operators, in and not in are used very often

 >>>'howdy' in ['hello', 'hi', 'howdy', 'heyas'] >>>True 
in is used to Find a value in a list
You can also use index for find but it will give ValueError if the item is not present in the list.
When there are multiple elements index will give you the lowest index:
 >>> var = ['hello', 'hi', 'howdy', 'heyas'] >>> var.index('hello') 0 >>> spam.index('heyas') 3 
remove()

remove a value from the list

Sorting
 var.sort()

 

var.sort(reverse=True) 
sorts the list IN PLACE SO NONE return value

There is None value whenever something is un-assigned or a function doesn’t return anything None is used.

list can store different type of variables but then you can’t use sort on that list. [GOT YOU!! NOPE]

 name = 'Zophie' >>> name[0] 'Z' >>> name[-2] 'i'

 Zo' in name True >>> 'z' in name False 

#### Repeatation of old concept

A lists and strings are different in an important way. A list value is a mutable data type: It can have values added, removed, or changed. However, a string is immutable: It cannot be changed.

The tuple data type is almost identical to the list data type, except in two ways. First, tuples are typed with parentheses, ( and ), instead of square brackets, [ and ]. For example, enter the following into the interactive shell:
 >>> eggs = ('hello', 42, 0.5) >>> eggs[0] 'hello' 

But the main way that tuples are different from lists is that tuples, like strings, are immutable. Tuples cannot have their values modified, appended, or removed.

If you have only one value in your tuple, you can indicate this by placing a trailing comma after the value inside the parentheses. Otherwise, Python will think you’ve just typed a value inside regular parentheses. The comma is what lets Python know this is a tuple value. (Unlike some other programming languages, in Python it’s fine to have a trailing comma after the last item in a list or tuple.) Enter the following type() function calls into the interactive shell to see the distinction:
 >>> type(('hello',)) 
Just like how str(42) will return ’42’, the string representation of the integer 42, the functions list() and tuple() will return list and tuple versions of the values passed to them. Enter the following into the interactive shell, and notice that the return value is of a different data type than the value passed:
 >>> tuple(['cat', 'dog', 5]) ('cat', 'dog', 5) >>> list(('cat', 'dog', 5)) ['cat', 'dog', 5] >>> list('hello') ['h', 'e', 'l', 'l', 'o'] 
Converting a tuple to a list is handy if you need a mutable version of a tuple value.

To be continued …

# Python Notes-4

In continuation from Python Notes-3
Python Notes-2
Python Notes-1

There are proper ways to format the string in python there is str.format() method then there is % operator like in c

 print "My name is %s." % myName print "I weigh %d k.g." % myWeight 

I can do away just with simple print and print with end=”. When I don’t need new line just after a print. Rest I manage with string concatenation and str() function for converting to str.

the str() flota() int() function
“I am “ + str(29) + “ years old.”

There are couple of interview questions where you need to convert ascii to char and vice-versa. Python gives a very good way to do this using chr() and ord() functions.
 >>> chr(0) '\x00' >>> ord('0') 48 

### Slicing with step

 var[3:7:2] start : stop: step 

#### reverse a string:

 str[::-1] 

We will come back to ord(), chr() and reversing a str again.

 round(9.7) 10 

#### Multiple assignment

var = ['fat', 'orange', 'loud'] >>> size, color, disposition = var 
The number of variables and the length of the list must be exactly equal, or Python will give you a ValueError.

The multiple assignment trick can also be used to swap the values in two variables:
 >>> a, b = 'Alice', 'Bob' >>> a, b = b, a 

To be continued …

# Python Notes-3

In continuation from Python Notes-2
Python Notes-1

We will learn about python string as you know string in python are immutable all function which applies to string will eventually not modify the string but will return a str e.g.

 var = 'ab' var.upper()  can’t change str but returns another string

sometime I just forget this and assume that my original variable is changed to all upper, silly mistake.
 var = var.lower() 

Count number of times a value is appearing in str or tuple or list
var.count('o')
Index of a value
 var.index('o')

To include special characters in a string you can escape using \ for or just use another for quotation then you can use one inside without escaping.
If you want to be more specific you can place r before the beginning quotation mark of a string to make it a raw string. A raw string completely ignores all escape characters and prints any backslash that appears in the string. e.g.

 >>> print(r'This!! This is me \' " cat.') This!! This is me \' " cat. 

Multiline Strings with Triple Quotes
 print('''Dear Apple,

You are so sweet.

Sincerely,
Me”’)

Dear Apple,

You are so sweet.

Sincerely,
Me

After reading about str, list and tuple I wanted to know why use tuple? Why another data structure?

Seems like python uses tuple behind our back when a function has multiple return type. Even when it is not specifically mentioned.
Also since tuple data structure is restrictive it is much faster compared to list. There is one more benefit which relates to code understanding if you use tuple data type in your code for variables which doesn’t need to be changed. It will be known to reader without you telling specifically.

Just like string concatenation list and tuple can also be concatenated. All three cal be multiplied/replicated
 t1 = (1,2) t2 = (3,4) t3 = t1+t2 
Multiplication
 t4 = t1*4 

To be continued …

# Python Notes-2

This is continuation from Python Notes-1. We were learning about python list
li = []
I really like the way python never need the variable to be declared. It is automatically assigned the data type based on it’s last initialization. e.g.


a = 9
a = 'q'


 >>> a = 9 >>> type(a)

 >>> a = 'q' >>> type(a) >>> a = [] >>> type(a) 

As we know from last post that python string are immutable similarly we have another data structure in python called tuple which is similar to list but it is immutable.
 var = () var = ('abc',3,4.8) 
You can’t do var[0] = 3 also if there is only one element in the tuple it doesn’t make sense to write it like var = (2) or var = (x) as this will just mean  var = 2 or var = x. So you have to do it like  var = (2,) or  var = (x,). One item tuple will need a trailing comma.

 len() will give you length of a variable like
 var = "12345" then len(var) will be 5.
Similarly var = [1,2,3,4,5] len(var)

Negative index This is very handy in accessing elements from last so you can say:

 var = [1,2,3,4,5] var[-1] This will give you the last element of the list. This can be applied similarly to list or tuple
-2 will refer to second last element.

##### Slicing

 var = ['apple', 'ball', 'cat', 'dog'] >>> spam[:2] ['apple', 'ball'] >>> spam[1:] ['ball', 'cat', 'dog'] 

 var = input() 
var will be of str type. Also note that Python doesn’t have char data type.

var = int(input())
will try to convert what is read to int.

One important list method is append()
used extensibly in a loop to keep on adding things.

insert() method to insert at a particular index first argument is index second argument is what to insert. insert(indx,val)

 li = [1, 2] >>> li.append(4) >>> li.insert(2,3) >>> li [1, 2, 3, 4] >>> li.insert(2,3) >>> li [1, 2, 3, 3, 4] >>> del(li[2]) >>> li [1, 2, 3, 4]

 

A sample code

To be continued …

# Finding all prime numbers

Till now I just knew only one way of finding all primes i.e. Sieve of Eratosthenes or space optimized version of the same called segmented sieve or time optimized version called Euler’s Sieve.

All of above work on same fundamentals striking out composite numbers from the beginning and what is remaining are the primes.

Recently I came across another way of finding primes the process is called Sieve of Sundaram.

• From the above list remove all numbers which are of the form i + j + 2 * i*j

1<= i <= j

i + j + 2 *i * j <= N
• What is remaining is doubled and incremented by 1 to give all the primes except 2. So basically all odd primes.

Example working:

Let us start with (n = 7) i.e. 1, 2, 3, 4, 5, 6, 7
In first step let us keep i = 1 and j = 1, 2, .. so cross out 1 + 1 + 2*1*1 (=4), 1 + 2 + 2 * 2* 1 (=6) take i = 2 then all are greater than 7 so not needed.
Remaining numbers are 1, 2, 3, 5, 7 So from Sieve of Sundaram all odd primes are:
1*2+1, 2*2+1, 3*2+1 = 3, 5, 7 add 2 and you have your result(all the primes in 1 to n).

# c++ STL map

dictionary data structure.

Problem
Given names and phone numbers, assemble a phone book that maps names to their respective phone numbers.

After this dictionary is created you will then be given an unknown number of names to query your phone book for; for each queried, print the associated entry from your phone book (in the form name=PhoneNumber ) or  ( Not Found) if there is no entry for .

Input Format

The first line contains an integer,N , denoting the number of entries in the phone book.
Each of the subsequent lines describes an entry in the form of space-separated values on a single line. The first value is a friend’s , and the second value is an -digit .

After the lines of phone book entries, there are an unknown number of lines of queries. Each line (query) contains a to look up, and you must continue reading lines until there is no more input.

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <map>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int N;
cin>>N;
map<string,int> dict;
for(int i = 0; i < N; i++){
string name;
int number;
cin>>name;
cin>>number;
dict[name] = number;
}
string line;
vector<string> inp;
//remove top new line
getline(std::cin, line);
while (getline(std::cin, line)){
inp.push_back(line);
}
for(int i = 0; i < inp.size(); i++){
if(dict.find(inp[i]) != dict.end()){
cout<<inp[i]<<"="<<dict[inp[i]]<<endl;
}
else{
}
}
return 0;
}



# Heap in cpp stl

make_heap: rearrange elements in a range such that they form a heap

make_heap(begin,end, comparator)

comparator is a boolean function optional

pop_heap

push_heap

if v is a vector then

std::make_heap (v.begin(),v.end());

v.front() will give you maximum [default is maxheap without comparator]



You can pass the comparator function to each operation to maintain the heap property.

get the element by v.front()

Now pop the element using

pop_heap (v.begin(),v.end()); // can also pass comparator here 
Pop element from heap and rearranges the elements in the heap range [first,last) in such a way that the part considered a heap is shortened by one: The element with the highest value is moved to (last-1).
While the element with the highest value is moved from first to (last-1) (which now is out of the heap), the other elements are reorganized in such a way that the range [first,last-1) preserves the properties of a heap.
Now to actually remove the element from the vector you can use:

v.pop_back();

So a range can be organized into a heap by calling make_heap. After that, its heap properties are preserved if elements are added and removed from it using push_heap and pop_heap, respectively.


pop_heap (v.begin(),v.end()); v.pop_back();
std::cout << "max heap after pop : " << v.front() << '\n';



push_heap (v.begin(),v.end());

Given a heap in the range [first,last-1), this function extends the range considered a heap to [first,last) by placing the value in (last-1) into its corresponding location within it.

 v.push_back(99); std::push_heap (v.begin(),v.end()); std::cout << "max heap after push: " << v.front() << '\n';



# C++ STL std::array

A hybrid between c array and cpp vector but with lot of difference. Size has to be known at compile time. It can’t be dynamic.

Initialized as


std::array myarray;



5 is the size of the array must be known at compile time. You can access elements by [] (array) operator but this will not give in size check. For size check use at operator.

 myarray.at(i)

 myarray.size() 

sort(myarray.begin(),myarray.end(), comparator)