Search results for 'programming/python'

  1. 2011.03.25 -- Merging two dictionaries in Python
  2. 2011.03.01 -- How to use scikits.statsmodel
  3. 2011.02.05 -- Preprocessor directives in Python
  4. 2009.07.22 -- Python - Chap5
  5. 2009.07.21 -- Python - Q&A
  6. 2009.07.20 -- Python - Chap4
  7. 2009.07.20 -- Python – Chap3
  8. 2009.07.19 -- Python – Chap2
  9. 2009.07.17 -- Python – Chap1

Merging two dictionaries in Python

2011.03.25 15:14

Using update()
 x = {'a':1, 'b': 2}
y = {'b':10, 'c': 11}
z = x.update(y)

print "z: ", z
print "x: ", x
z:  None
x:  {'a': 1, 'c': 11, 'b': 10}

Using dict()
 x = {'a':1, 'b': 2}
y = {'b':10, 'c': 11}

z = dict(x, **y)
print "z: ", z
print "x: ", x

z:  {'a': 1, 'c': 11, 'b': 10}
x:  {'a': 1, 'b': 2}



저작자 표시
신고

'programming > python' 카테고리의 다른 글

Merging two dictionaries in Python  (0) 2011.03.25
How to use scikits.statsmodel  (0) 2011.03.01
Preprocessor directives in Python  (0) 2011.02.05
Python - Chap5  (0) 2009.07.22
Python - Q&A  (0) 2009.07.21
Python - Chap4  (0) 2009.07.20

Frank kenshin579 programming/python merge two dicts, Python

How to use scikits.statsmodel

2011.03.01 16:52
OS: Ubuntu 10.04

Installation
* installation from source. 

1. Download each source code (Scipy, Numpy, statsmodel)

* If any dependency code is needed, then just do apt-get install dependent_pkg_name
># apt-get install python2.5-setuptools
Numpy
># cd numpy-1.5.1; python setup.py install
Scipy
># cd scipy-0.9.0rc5; python setup.py install
Statsmodel
># cd statsmodels-0.2.0; python setup.py install

Testing
># vim 

#!/usr/bin/python

# using statsmodel library

import numpy as np
import scikits.statsmodels as sm

# get data
nsample = 100
x = np.linspace(0,10, 100)
X = sm.add_constant(np.column_stack((x, x**2)))
beta = np.array([1, 0.1, 10])
y = np.dot(X, beta) + np.random.normal(size=nsample)

# run the regression
results = sm.OLS(y, X).fit()

# look at the results
print results.summary()

># ./statsEx1.py



Usage (Example)
* It seems like it's better to get the statsmodels-0.3.0 version. 
1. AR Model
??

2. ARMA Model 
??


References
1. 
저작자 표시
신고

'programming > python' 카테고리의 다른 글

Merging two dictionaries in Python  (0) 2011.03.25
How to use scikits.statsmodel  (0) 2011.03.01
Preprocessor directives in Python  (0) 2011.02.05
Python - Chap5  (0) 2009.07.22
Python - Q&A  (0) 2009.07.21
Python - Chap4  (0) 2009.07.20

Frank kenshin579 programming/python AR, ArmA, numpy, Python, scipy, statsmodel

Preprocessor directives in Python

2011.02.05 22:08

What is the equivalent form in Python?
#ifdef DEBUG
printf ("test: %s\n", test);
#endif


What about in python?
 if __debug__:
   print "test: %s", test

To run with debug on
># python test.py 

To run with debug off
># python -O test.py

저작자 표시
신고

'programming > python' 카테고리의 다른 글

Merging two dictionaries in Python  (0) 2011.03.25
How to use scikits.statsmodel  (0) 2011.03.01
Preprocessor directives in Python  (0) 2011.02.05
Python - Chap5  (0) 2009.07.22
Python - Q&A  (0) 2009.07.21
Python - Chap4  (0) 2009.07.20

Frank kenshin579 programming/python Debug, directive, Python

Python - Chap5

2009.07.22 15:34

Conditionals, Loops, and Some Other Statements

About print and import

  • print

>>> print 'Age:', 42
Age: 42

>>> name = 'Gumby'
>>> salutation = 'Mr.'
>>> greeting = 'Hello,'
>>> print greeting, salutation, name
Hello, Mr. Gumby

  • import

>>> import somedule
>>> from somemodule import somefunction, another function

>>> from somemodule import *

Importing as
>>> import math as foobar
>>> foobar.sqrt(4)
2.0

>>> from math import sqrt as foobar
>>> foobar(4)
2.0

Assignments

Names

Description

Examples

Assignments

assign different
values simultaneously

>>> x, y, z = 1, 2, 3
>>> print x, y, z
1 2 3

Swapping
>>> x, y = y , x

Sequence Unpacking
(iterable unpacking)

 

>>> values = 1, 2, 3
>>> values
(1, 2, 3)
>>> x, y, z = values
>>> x
1
Example 1 (popitem)
>>> scoundrel = {'name': 'Robin', 'girlfriend': 'Marion'}
>>> key, value = scoundrel.popitem()
>>> key
'girlfriend'
>>> value
'Marion'

Chained Assignments

bind several variables

>>> x = y = somefunction()

Augmented Assignments

 

>>> fnord = 'foo'
>>> fnord += 'bar'
>>> fnord *= 2
>>> fnord
'foobarfoobar'

Blocks:
It's to remember about indentation

  • each line in a block must be indented by the same amount
  • use spaces instead of tab (at least four spaces)
  • a colon (:) is used to indicate that a block is about to begin

>>> phonebook = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}
>>> values = ('world', 'Hot')

Boolean values
The following values are considered false

  • False
  • None
  • 0
  • ""
  • () - tuples
  • [] - lists
  • {} - dictionaries

Conditions and Conditional Statements

name = raw_input('What is your name? ')
if name.endswith('Gumby'):
if name.startswith('Mr.'):
print 'Hello, Mr. Gumby'
elif name.startswith('Mrs.'):
print 'Hello, Mrs. Gumby'
else:
print 'Hello, Gumby'
else:
print 'Hello, stranger'

Comparison Operators

Expression

Description

x == y
x < y.
x > y
x >= y
x <= y
x != y
x is y
x in y
x not in y

x equals y.
x is less than y
x is greater than y.
x is greater than or equal to y.
x is less than or equal to y.
y x is not equal to y. x and y are the same object.
x is not y x and y are different objects.
x is a member of the container (e.g., sequence) y.
x is not a member of the container (e.g., sequence) y.

Expression

Description

Examples

Equality Operator

two things (value) are equal?

>>> "foo" == "foo"

is: The Identity Operator

identical? (the same object)

NOTE: do not use IS with immutable values (numbers, strings)

>>> x = y = [1, 2, 3]
>>> z = [1, 2, 3]
>>> x is y
True
>>> x is z
False

in: The Membership Operator

 

name = raw_input('What is your name? ')
if 's' in name:
print 'Your name contains the letter "s".'
else:
print 'Your name does not contain the letter "s".'

Other Comparisons

 

>>> "alpha" < "beta"
True
>>> [1, 2] < [2, 1]
True
>>> [2, [1, 4]] < [2, [1, 5]]
True

Boolean Operators

 

number <= 10 and number >= 1
1 <= number <=10

Loops

Expression

Description

Examples

while loops

 

name = ''
while not name.isspace():
name = raw_input('Please enter your name: ')
print 'Hello, %s!' % name
(or)
while not name.strip()

for loops

NOTE: range(inclusive, exclusive)
vs. xrange creates only one number at a time - good for handling huge sequences

for number in range(1,101):
print number

iterating over dicts

 

Example 1
d = {'x': 1, 'y': 2, 'z': 3}
for key in d:
print key, 'corresponds to', d[key]

Example 2

for key, value in d.items():
print key, 'corresponds to', value

Parallel Iteration

iterate over two or more sequences at the same time
(use built-in function zip)

names = ['anne', 'beth', 'george', 'damon']
ages = [12, 45, 32, 102]
Example 1
for i in range(len(names)):
print names[i], 'is', ages[i], 'years old'

Example 2
for name, age in zip(names, ages):
print name, 'is', age, 'years old'

Numbered Iteration

iterate over a seq of objects and at the same time have access to the index

for index, string in enumerate(strings):
if 'xxx' in string:
strings[index] = '[censored]'

Else Clauses

 

from math import sqrt
for n in range(99, 81, -1):
root = sqrt(n)
if root == int(root):
print n
break
else:
print "Didn't find it!"

List Comprehension (Set Comprehension)
List comprehension creates lists from other lists

>>> [x*x for x in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

>>> [x*x for x in range(10) if x % 3 == 0]
[0, 9, 36, 81]

>>> [(x, y) for x in range(3) for y in range(3)]
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

Executing and Evaluating Strings
It's important to use scope, the concept of namespaces.

  • exec

>>> from math import sqrt
>>> scope = {}
>> exec 'sqrt = 1' in scope
>>> sqrt(4)
2.0
>>> scope['sqrt']
1

  • eval
    evaluates a Python expression (written in string) and return the resulting value. The difference between exec is that it doesn't return anything because it is just a statement itself.

>>> scope = {}
>>> scope['x'] = 2
>>> scope['y'] = 3
>>> eval('x * y', scope)
6

신고

'programming > python' 카테고리의 다른 글

How to use scikits.statsmodel  (0) 2011.03.01
Preprocessor directives in Python  (0) 2011.02.05
Python - Chap5  (0) 2009.07.22
Python - Q&A  (0) 2009.07.21
Python - Chap4  (0) 2009.07.20
Python – Chap3  (0) 2009.07.20

Frank kenshin579 programming/python assignments, eval, exec, For, Iteration, list comprehension, LOOPS, While

Python - Q&A

2009.07.21 17:11

Q & A

* Q: What is iterator data structure??
A:

* Q: Python Documentation Site? (API, Library, etc)
A:
http://docs.python.org/index.html

* Q: How can I find out the type of a variable?

>>> str = 'Frank'
>>>


A:

* Q:
A:

* Q:
A:

* Q:
A:

 

신고

'programming > python' 카테고리의 다른 글

Preprocessor directives in Python  (0) 2011.02.05
Python - Chap5  (0) 2009.07.22
Python - Q&A  (0) 2009.07.21
Python - Chap4  (0) 2009.07.20
Python – Chap3  (0) 2009.07.20
Python – Chap2  (0) 2009.07.19

Frank kenshin579 programming/python

Python - Chap4

2009.07.20 16:05

Dictionaries: When Indices Won't Do

Creating and Using Dictionaries

>>> phonebook = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}
>>> values = ('world', 'Hot')

Use dict function to construct dictionaries from other mappings
Example 1
>>> list_items = [('name', 'Gumby'), ('age', 42)]
>>> d = dict(list_items)
>>> d
{'age' : 42, 'name' : 'Gumby'}
>>> d{'name}
'Gumby'

Example 2
>>> d = dict(name='Gumby', age=42)
>>> d
{'age': 42, 'name': 'Gumby'}

Basic Dictionary Operations

  • len(dict_items)
  • d[dict_key]
  • d[dict_key] = dict_value
  • del d[dict_key]
  • dict_key in d

Dictionary Methods

Functions

Explanation

Examples

clear

remove all elements

>>> x = {}
>>> y = x
>>> x['key'] = 'value'
>>> y
{'key': 'value'}
>>> x.clear()
>>> y
{}

copy deepcopy

copy() - shadow copy (we can think of reference copy)
deepcopy() - duplication

>>> from copy import deepcopy
>>> d = {}
>>> d['names'] = ['Alfred', 'Bertrand']
>>> c = d.copy() <- shadow copy
>>> dc = deepcopy(d) <- deep copy
>>> d['names'].append('Clive')
>>> c
{'names': ['Alfred', 'Bertrand', 'Clive']}
>>> dc
{'names': ['Alfred', 'Bertrand']}

fromkeys

creates a new dict with the given keys

>>> dict.fromkeys(['name', 'age'])
{'age': None, 'name': None}

get

accessing dict items ; similar to my_dict['name]'

>>> d['name'] = 'Eric'
>>> d.get('name')
'Eric'
>>> d.get('name', 'N/A')
'N/A'

has_key

checks whether dict has a given key
(it will be gone in Python 3.0)

>>> d['name'] = 'Eric'
>>> d.has_key('name')
True

items

returns all the items of the dict as a list of items

>>> d = {'title': 'Python Web Site', 'url': 'http://www.python.org', 'spam': 0}
>>> d.items()

[('url', 'http://www.python.org'), ('spam', 0), ('title', 'Python Web Site')]

iteritems

 

>>> it = d.iteritems()
>>> it
<dictionary-iterator object at 169050>
>>> list(it) # Convert the iterator to a list
[('url', 'http://www.python.org'), ('spam', 0), ('title', 'Python Web Site')]

keys

returns a list of the keys in the dict

 

iterkeys

  

pop

gets the value corresponding to a given key (removes an item)

>>> d = {'x': 1, 'y': 2}
>>> d.pop('x')
1
>>> d

{'y': 2}

popitem

pops off the arbitrary item

>>> d
{'url': 'http://www.python.org', 'spam': 0, 'title': 'Python Web Site'}
>>> d.popitem()
('url', 'http://www.python.org')
>>> d
{'spam': 0, 'title': 'Python Web Site'}

setdefault

similar to get ; sets the value correponsiding to the given key if it is not already in the dict

>>> d = {}
>>> d.setdefault('name', 'N/A')
'N/A'
>>> d
{'name': 'N/A'}

update

updates one dict with the items of another

 

values

returns a list of values in the dict (may contain duplicates)

>>> d= {1:1, 2:2, 3:3, 4:1}
>>> d.values()
[1, 2, 3, 1]

itervalues

  
신고

'programming > python' 카테고리의 다른 글

Python - Chap5  (0) 2009.07.22
Python - Q&A  (0) 2009.07.21
Python - Chap4  (0) 2009.07.20
Python – Chap3  (0) 2009.07.20
Python – Chap2  (0) 2009.07.19
Python – Chap1  (0) 2009.07.17

Frank kenshin579 programming/python dict, Dictionary

Python – Chap3

2009.07.20 11:47

Working with Strings

String Basic Operations

>>> format = "Hello, %s. %s enough for ya?"
>>> values = ('world', 'Hot')
>>> print
format % values
Hello, world. Hot enough for ya?

Width and Precision

>>> '%10.2f' % pi # Field width 10, precision 2
' 3.14'
>>> '%.2f' % pi # Precision 2
'3.14'
>>> '%.5s' % 'Guido van Rossum'
'Guido'

>>> '%.
*s' % (5, 'Guido van Rossum')
'Guido'

 

Signs, Alignment, and Zero-Padding

Flag

Explanation

Example

zero

zero-padding at the front

>>> '%010.2f' % pi
'0000003.14'

plus

(either plus or minus)

>>> print ('%+5d' % 10) + '\n' + ('%+5d' % -10)
+10
-10

minus

left-alignment

>>> '%-10.2f' % pi
'3.14

blank

just blank

 

String Methods

Functions

Explanation

Example

See also

find

finds substring and returns the leftmost index

>>> subject = '$$$ Get rich now!!! $$$'
>>> subject.find('$$$')
0
>>> subject.find('$$$', 1) # Only supplying the start
20
>>> subject.find('!!!')
16
>>> subject.find('!!!', 0, 16) # Supplying start and end
-1

rfind, index, rindex, count, startswith, endswith.

join

joins the elements of a sequence

>>> dirs = '', 'usr', 'bin', 'env'
>>> '/'.join(dirs)
'/usr/bin/env'

 

lower

 

>>> 'Trondheim Hammer Dance'.lower()
'trondheim hammer dance'

islower, capitalize, swapcase, title, istitle, upper, isupper.

title, capwords

 

>>> "that's all folks".title()
"That'S All, Folks"

 

replace

 

>>> 'This is a test'.replace('is', 'eez')
'Theez eez a test'

expantabs

split

 

>>> '/usr/bin/env'.split('/')
['', 'usr', 'bin', 'env']

rsplit, splitlines

strip

only performs at the ends so internal characters are not removed

>>> '/usr/bin/env'.split('/')
['', 'usr', 'bin', 'env']

lstrip, rstrip

translate

similar to replace, but only replaces single characters
*. must create translation table
(maketrans)

>>> from string import maketrans
>>> table = maketrans('cs', 'kz')
>>> 'this is an incredible test'.translate(table)
'thiz iz an inkredible tezt'

Deletes ' '
>>> 'this is an incredible test'.translate(table, ' ')
'thizizaninkredibletezt'

 
신고

'programming > python' 카테고리의 다른 글

Python - Chap5  (0) 2009.07.22
Python - Q&A  (0) 2009.07.21
Python - Chap4  (0) 2009.07.20
Python – Chap3  (0) 2009.07.20
Python – Chap2  (0) 2009.07.19
Python – Chap1  (0) 2009.07.17

Frank kenshin579 programming/python Format, Python, strings

Python – Chap2

2009.07.19 17:24

Lists and Tuples

Python Data Structure :

Container (holds any object)
> sequences (ex. lists, tuples)
> mappings (ex. dictionaries)

6 Built-in types of sequences :

  • lists
  • tuples
  • strings
  • Unicode strings
  • buffer objects
  • xrange objects

Common Sequence Operations
Indexing

>>> greeting = 'Hello'
>>> greeting[0]
'H'
>>> greeting[-1]
'o'

Slicing
Extracting parts of a sequence
Remember the following rules: first index (inclusive), last index (exclusive)
We can think of the implicit indexing as simply the beginning or the end.

>>> numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> numbers[3:6]
[4,5,6]
>>> numbers[:1]
[1]
>>> numbers[7:]
[8, 9, 10]
>>> numbers[-3:0]
[8, 9, 10]

Different Step size.

>>> numbers[0:10:2]
[1, 3, 5, 7, 9]
>>> numbers[::4]
[1, 5, 9]

Negative numbers : extracts the elements from right to left
>>> numbers[::-1]
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
>>> numbers[::-2]
[10, 8, 6, 4, 2]
>>> numbers[5::-2]
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[6, 4, 2]
>>> numbers[:5:-2]

# this is a little bit confusing
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[10, 8]

Concatenating

>>> [1, 3, 5] + [2, 4]
[1, 3, 5, 2, 4]
>>> 'Hello ' + 'World'
Hello World

Multiplying

>>> [5] * 7
[5, 5, 5, 5, 5, 5, 5]

Membership

>>> users = ['mlh', 'foo', 'bar']
>>> raw_input('Enter your user name: ') in users
Enter your user name: mlh
True

Lists

list function
Create a list from a string

>>> test=list('Hello')
['H', 'e', 'l', 'l', 'o']

Putting it back to a string
>>> ''.join(test)
'Hello'

Slice Assignments

Insert a list in between

>>> numbers = [1, 5]
>>> numbers[1:1] = [2, 3, 4]
>>> numbers
[1, 2, 3, 4, 5]

Insert at the beginning
>>> numbers[0:0]=[0 0]
>>> numbers
[0, 0, 1, 2, 3, 4, 5]

Replace the entire list with a new one
>>> numbers[:] = [6, 7]

Append at the end
>>> last=len(numbers)
>>> numbers[last:last]=[9, 10 , 11]

List Methods

Function Name

Explanation

numbers.append(4)

In-place

numbers.count(3)

In-place

numbers.extend(b_list)

In-place

numbers.index(5)

 

numbers.insert(3, 'four')

 

numbers.pop()
numbers.pop(0)

In-place
Pop up the last element
Pop up the first element

numbers.remove(4)

In-place

numbers.reverse()

In-place

numbers.sort()

In-place

Data structure

Stack (LIFO): use append()/pop()

Queue (FIFO): use insert()/pop() or deque from collections module

Tuples : Immutable Sequences

What can we do with a tuple? Well, simply we create a tuple and access their elements. It seems very pointless to have tuples since we already have lists that can do more, but there are some cases where we cannot use lists. (ex. Keys in mappings)

>>> 1, 2, 3
(1, 2, 3)

Create a tuple with a single element
NOTE: must include a comma
>>> 42 <- a list
42
>>> 42, <- a tuple
(42,)
>>> (42,) <- a tuple

Basic Tuple Operations
>>> x=1, 2, 3
>> x[1:2]
(2, 3)

신고

'programming > python' 카테고리의 다른 글

Python - Chap5  (0) 2009.07.22
Python - Q&A  (0) 2009.07.21
Python - Chap4  (0) 2009.07.20
Python – Chap3  (0) 2009.07.20
Python – Chap2  (0) 2009.07.19
Python – Chap1  (0) 2009.07.17

Frank kenshin579 programming/python

Python – Chap1

2009.07.17 16:36

Instant Hacking : The Basics

1. Using Modules

Understand the different ways to use modules
METHOD 1

>>> import math

>>> math.floor(32.9)

METHOD 2

>>> from math import floor

>>> floor(32.9)

2. About str, repr=backticks

All three of them convert a Python value to a string.

  1. print str("Hello, world!") -> works good
    Hello, world!
  2. print repr("Hello, world!")
    'Hello, world!'

3. Input vs. raw_input

name = input ("What is your name?")

print "Hello, " + name + "1"

input() treats what you enter is a valid Python expression so it's probably better for us to use raw_input() when a user enters an input value.

신고

'programming > python' 카테고리의 다른 글

Python - Chap5  (0) 2009.07.22
Python - Q&A  (0) 2009.07.21
Python - Chap4  (0) 2009.07.20
Python – Chap3  (0) 2009.07.20
Python – Chap2  (0) 2009.07.19
Python – Chap1  (0) 2009.07.17

Frank kenshin579 programming/python