Pages

Showing posts with label Cpp. Show all posts
Showing posts with label Cpp. Show all posts

Wednesday, August 14, 2013

Equalities

It seems to be simple to compare two values: 1 == 1 or 2 == 3? However, when a variable is assigned to a value, it's a little bit more complicated: x = 3, y = 3, x == y? The different type of data can represent the same value: 1.0 == 0?

Lisp

> (= 1.0 1)
T

> (eql 1.0 1)
NIL

> (eql (cons 'a nil) (cons 'a nil)
NIL

> (setf x (cons 'a nil))
> (eql x x)
T

> (equal x (cons 'a nil))
T

C/C++

int x = 10;
int y = 20;

x == y // equal in Lisp
&x == &y // eql in Lisp
10 == 20 // = in Lisp

Python

>>> x = 10
>>> id(x)
1764365084

>>> y = 10
>>> id(y)
1764365084

>>> x is y // eql in LISP
True

>>> x == y // equal in LISP
True

>>> a = [1,2,3]
>>> a == [1,2,3]
True

>>> a is [1,2,3]
False

>>> id(a)
4359792
>>> id([1,2,3])
4225424

Reference

Friday, May 31, 2013

Deleting elements in map: C++ and Python

C++

std::listlist<int> keys;
// 1. get all the keys that has the elements from bList
for (std::listlist<int>::iterator it = bList.begin(); it != bList.end(); ++it)
{
    for (std::map<string, int>::iterator j = aMap.begin(); j != aMap.end(); ++j)
    {
        if (j->second == *it) keys.push_back(j->first);
    }
}

// 2. remove all the items of the key
for (auto it = keys.begin(); it != keys.end(); ++it)
{
    aMap.erase(*it);
}
std::list<int> keys;
for (auto it = bList.begin(); it != bList.end(); ++it)
{
    for (auto j = aMap.begin(); j != aMap.end(); ++j)
    {
        if (j->second == *it) keys.push_back(j->first);
    }
}

// 3. remove all the items of the key
for (auto it = keys.begin(); it != keys.end(); ++it)
{
    aMap.erase(*it);
}

Python

http://stackoverflow.com/questions/11277432/how-to-remove-a-key-from-dictionary
for e in elements:
    if e in aDict:
        del aDict[e]
for e in elements:
	aDict.pop(e, None)