bloggerads

2017年8月11日 星期五

Python : Use dictionary to simulate multi-dimension array

Since there is no array in Python. Use dictionary instead.

Follows are the example to initialize a 2x2 array

>>>a={}
>>>for i in range(4):
. . .      a[i/2, i%2] = i
>>> a
{ (0,1):1, (1,0):2, (0,0):0, (1,1):3 }
>>>a[0,1]
1

2017年8月9日 星期三

Python : string related

### Demonstrate join

>>> list = ['Nice', 'to', 'meet', 'you']
>>> ''.join(list)
Nicetomeetyou

>>> ' '.join(list)
Nice to meet you

>>>'_'.join(list)
Nice_to_meet_you

2017年8月6日 星期日

Python : Exception Handling

以parsing文字檔的內容來做例外處理的範例, parsing過程中其它列的內容可能和原本預設格式不同, 此時就會有例外產生:

with open('a.txt', 'r') as f:
    badLine = 0
    goodLine = 0
    totalLine = 0

    for line in f:
        try:
            d1, d2, d3 = line.split()
        except:
            badLine += 1    
        else:
            goodLine += 1
        finally:  
            totalLine += 1   

    print('totalLine : {}, badLine: {}, goodLine: {}'.format(str(totalLine), str(badLine), str(goodLine)))

2017年8月4日 星期五

Python : class method / static method / method

This is a good example for showing the difference between class method, static method and method in Python.


class Demo:     
    y=1 # class (or static) variable
    def __init__(self,z):
        self.z = z

    @classmethod
    def class_method(cls, x):
        return x + cls.y

    @staticmethod
    def static_method(x):
        return x  #cannot invoke cls.z

    def method(self, x):
        return x + self.z


print Demo.class_method(2)  # show 3
print Demo.static_method(2)  # show 2

#print Demo.method(2) #Error, must declare first
demo = Demo(2)
print demo.method(2) # show 4

2017年8月3日 星期四

Python : dictionary

Follows are the Dictionary example. Key and value can be string or number.

● Initial a dictionary
>>> d={'a':'Martin', 'b':'John'}

● Add new item
>>> d['c']='Mary'

 Add items
>>> d.update({'d':'Megan', 'e':'May'})

 Check item in a dictionary (return True/False)
>>> 'd' in d
True
>>> 'f' in d
False

 Enumerate the items in a dictionary
>>> for id, name in d.items():
...         print id, name

 Delete an item
>>> del d['a']

2017年7月31日 星期一

Python : list

In Python, We have list and and dictionary, similarly as the container list and map in C++, follows are the list example.

● Init a list in even numbers from 0 to 6


>>>list = [i for i in range(8) if i%2==0]
>>>list
[0, 2, 4, 6]

● Append data:2 to the tail

>>>list.append(2)

>>>list
[0, 2, 4, 6, 2]

● Insert data:3 to index: 2



>>>list.insert(2, 3)
>>>list
[0, 2, 3, 4, 6, 2]

● Remove data:3 

>>>list.remove(3)

>>>list
[0, 2, 4, 6, 2]


2017年7月29日 星期六

Python : Some notes

(1) How to import a user's defined module 't1.py' in 't.py' ?

@t1.py
def watchout():
  print "Did you call me?"

@t.py
#! python2
import t1
t1.watchout()

=========Output===========
> t.py
Did you call me?
==========================

(2) Popen, same as C++

@c.cpp, compile it to c.exe
#include <stdio.h>
int main()
{
    printf("Hi Martin\nHi Megan\n");
    return 0;
}

@p.py
#! python2
import os
output = os.popen('c.exe')
print output.read()

=========Output===========
> p.py
Hi Martin
Hi Megan
==========================