staticclass Status{ int id;//current city String action; int distance; Vector<Integer> unvisited; HashSet<Integer> visited; public Status(int id) { this.id=id; } }
staticclass DirtyDot{ int id;//current city int x; int y;
public DirtyDot(int id, int x, int y) { this.id=id; this.x=x; this.y=y; } } /* Head ends here */ staticvoid next_move(int x, int y, String[] board){ TSP(board,x,y);
}
/* Tail starts here */ publicstaticvoid main(String[] args) { //TSP(null,0,0);
Scanner in = new Scanner(System.in); int [] pos = newint[2]; String board[] = new String[5]; for(int i=0;i<2;i++) pos[i] = in.nextInt(); for(int i=0;i<5;i++) board[i] = in.next(); System.out.println("begin now!"); next_move(pos[0], pos[1], board); }
publicstaticvoid TSP(String[] board, int x, int y) {
int dist[][]={{-1,3,6,7},{2,-1,8,6},{7,3,-1,5,},{7,3,7,-1}};
Vector<Status> currentStatus=new Vector<Status>(); Vector<Status> previousStatus; /*Initialize current Status Vector*/ for(int i=1;i<MAX;i++) { Status status=new Status(i); status.distance=dist[i][0]; status.unvisited=new Vector<Integer>(); status.visited=new HashSet<Integer>(); currentStatus.add(status); } System.out.println("Initialized current Status Vector"); //System.out.println(currentStatus.size());
for(int j=0;j<MAX-2;j++) { previousStatus=currentStatus; currentStatus=new Vector<Status>(); //System.out.println(previousStatus.size()); for(int i=1;i<MAX;i++)// enumerate each node { for(int k=0;k<previousStatus.size();k++) { Status tempStatus=previousStatus.elementAt(k); if(isContain(tempStatus,i)==false)//gurantee node i is not in tempStatus { Status newStatus=new Status(i); newStatus.distance=tempStatus.distance+dist[i][tempStatus.id]; System.out.println("id"+tempStatus.id); newStatus.visited=new HashSet<Integer>(tempStatus.visited); newStatus.unvisited=new Vector<Integer>(tempStatus.unvisited); newStatus.unvisited.add(0,(Integer)(tempStatus.id)); newStatus.visited.add(tempStatus.id); currentStatus.add(newStatus); System.out.println(newStatus.unvisited.size()); System.out.println(newStatus.distance);
} } } //System.out.println(currentStatus.size()); currentStatus=optimize(currentStatus);//dp process //System.out.println(currentStatus.size()); }//end for
Status tempStatus=iterator.next(); Status shortest=tempStatus; int minDistance=dist[0][tempStatus.id]+tempStatus.distance; System.out.println("1:"+tempStatus.distance); System.out.println("2:"+dist[0][tempStatus.id]);
while (iterator.hasNext()) { tempStatus=iterator.next(); int tempDistant=dist[0][tempStatus.id]+tempStatus.distance; System.out.println("11:"+tempStatus.distance); System.out.println("22:"+dist[0][tempStatus.id]); System.out.println("33:"+tempStatus.id);
]]>Python extract all comments:提取所有comments,提取c/c++中注释Python脚本http://www.shnenglu.com/luyulaile/archive/2012/12/03/195907.htmlluisluisMon, 03 Dec 2012 00:35:00 GMThttp://www.shnenglu.com/luyulaile/archive/2012/12/03/195907.htmlhttp://www.shnenglu.com/luyulaile/comments/195907.htmlhttp://www.shnenglu.com/luyulaile/archive/2012/12/03/195907.html#Feedback0http://www.shnenglu.com/luyulaile/comments/commentRss/195907.htmlhttp://www.shnenglu.com/luyulaile/services/trackbacks/195907.html如果 E序中出C“/*”,会有bug
#!/usr/bin/env python
import sys import re
def comment_finder(text): pattern = re.compile( r'//.*?$|/\*.*?\*/', re.DOTALL | re.MULTILINE) result = pattern.findall(text) return result
def print_command(filename):
codefile = open(filename,'r') commentfile = open(filename+".txt",'w') lines=codefile.read() codefile.close() #the list of comments list_of_comments = comment_finder(lines) for comment in list_of_comments: #print comment[0:2] if comment[0:2] == "//": comment_to_write = comment[2:] else: comment_to_write = comment[2:-2] if len(comment_to_write)!=0: commentfile.write(comment_to_write) commentfile.write('\n') commentfile.close()
if__name__ == "__main__": for filename in sys.argv[1:]: print_command(filename)
]]>Latex 表格http://www.shnenglu.com/luyulaile/archive/2012/11/22/195518.htmlluisluisWed, 21 Nov 2012 17:07:00 GMThttp://www.shnenglu.com/luyulaile/archive/2012/11/22/195518.htmlhttp://www.shnenglu.com/luyulaile/comments/195518.htmlhttp://www.shnenglu.com/luyulaile/archive/2012/11/22/195518.html#Feedback0http://www.shnenglu.com/luyulaile/comments/commentRss/195518.htmlhttp://www.shnenglu.com/luyulaile/services/trackbacks/195518.html\begin{tabular}{|c|c|c|c|c|c|} \hline Accuracy & General & test 1 & test 2 & test 3 & test 4\tabularnewline \hline
]]>Python W记 pi tan {公?/title>http://www.shnenglu.com/luyulaile/archive/2012/11/08/194861.htmlluisluisThu, 08 Nov 2012 00:21:00 GMThttp://www.shnenglu.com/luyulaile/archive/2012/11/08/194861.htmlhttp://www.shnenglu.com/luyulaile/comments/194861.htmlhttp://www.shnenglu.com/luyulaile/archive/2012/11/08/194861.html#Feedback0http://www.shnenglu.com/luyulaile/comments/commentRss/194861.htmlhttp://www.shnenglu.com/luyulaile/services/trackbacks/194861.html
Return a randomly selected element from range(start, stop, step). This is equivalent tochoice(range(start, stop, step)), but doesn’t actually build a range object.
And range(start, stop) returns [start, start+step, ..., stop-1], not [start, start+step, ..., stop]. As for why... zero-based counting rules and range(n) should return n elements, I suppose. Most useful for getting a random index, I suppose.
While randint is documented as:
random.randint(a, b)
Return a random integer N such that a <= N <= b. Alias for randrange(a, b+1)
So randint is for when you have the maximum and minimum value for the random number you want.
A new operator, //, is the floor division operator. (Yes, we know it looks like C++'s comment symbol.) // always performs floor division no matter what the types of its operands are, so 1 // 2 is 0 and 1.0 // 2.0 is also 0.0.
]]>Latex 中插入代?/title>http://www.shnenglu.com/luyulaile/archive/2012/10/31/194135.htmlluisluisWed, 31 Oct 2012 13:30:00 GMThttp://www.shnenglu.com/luyulaile/archive/2012/10/31/194135.htmlhttp://www.shnenglu.com/luyulaile/comments/194135.htmlhttp://www.shnenglu.com/luyulaile/archive/2012/10/31/194135.html#Feedback0http://www.shnenglu.com/luyulaile/comments/commentRss/194135.htmlhttp://www.shnenglu.com/luyulaile/services/trackbacks/194135.htmlhttp://en.wikibooks.org/wiki/LaTeX/Algorithms_and_Pseudocode Typesetting using the algorithm2e package
The algorithm2e package (first released 1995, latest updated December 2009 according to the v4.01 manual) allows typesetting algorithms with a lot of customization. The package is loaded like
\usepackage[options]{algorithm2e}
and a simple example, taken from the v4.01 manual, is
\begin{algorithm}[H] \SetAlgoLined \KwData{this text} \KwResult{how to write algorithm with \LaTeX2e } initialization\; \While{not at end of this document}{ read current\; \eIf{understand}{ go to next section\; current section becomes this one\; }{ go back to the beginning of current section\; } } \caption{How to write algorithms} \end{algorithm}
]]>Python generate corpus using Dirichlet distributionhttp://www.shnenglu.com/luyulaile/archive/2012/10/28/193960.htmlluisluisSun, 28 Oct 2012 02:13:00 GMThttp://www.shnenglu.com/luyulaile/archive/2012/10/28/193960.htmlhttp://www.shnenglu.com/luyulaile/comments/193960.htmlhttp://www.shnenglu.com/luyulaile/archive/2012/10/28/193960.html#Feedback0http://www.shnenglu.com/luyulaile/comments/commentRss/193960.htmlhttp://www.shnenglu.com/luyulaile/services/trackbacks/193960.htmlAt first, let's define the sample function:
def sample(dist, num_samples=1): """ Uses the inverse CDF method to return samples drawn from an (unnormalized) discrete distribution.
Arguments:
dist -- (unnormalized) distribution
Keyword arguments:
num_samples -- number of samples to draw """
cdf = cumsum(dist) r = uniform(size=num_samples) * cdf[-1]
return cdf.searchsorted(r)
As we can see, the sample function input two parameters, one is dist, which can be an un-normalized distribution, another is the sample we want to draw.
Let's see how to generate corpus for Dirichlet--multinomial unigram language model
def generate_corpus(beta, mean, N): """ Returns a corpus of tokens drawn from a Dirichlet--multinomial unigram language model. Each token is an instance of one of V unique word types, represented by indices 0, , V - 1.
Arguments:
beta -- concentration parameter for the Dirichlet prior mean -- V-dimensional mean of the Dirichlet prior N -- number of tokens to generate """
pass# YOUR CODE GOES HERE #print mean #print beta #print dot(mean,beta) #print dirichlet(mean*beta,size=1) temp=sample(dirichlet(beta*array(mean),size=1),N) #print temp return temp
please keep in mind the dirichlet function is “from numpy.random.mtrand import dirichlet" and the parameters it receives are corresponding to beta*array(mean). beta is the concentration factor, and mean is the vector which sum to 1.
another way is to generate corpus is using the property: P(D'|D,H)= Nv+beta_nv/N+beta
def generate_corpus_collapsed(beta, mean, N): """ Returns a corpus of tokens drawn from a Dirichlet--multinomial unigram language model using the 'collapsed' generative process (i.e., phi is not explicitly represented). Each token is an instance of one of V unique word types.
Arguments:
beta -- concentration parameter for the Dirichlet prior mean -- V-dimensional mean of the Dirichlet prior N -- number of tokens to generate """
V = len(mean) # vocabulary size
corpus = zeros(N, dtype=int) # corpus
Nv = zeros(V, dtype=int) # counts for each word type
pass# YOUR CODE GOES HERE for n in xrange(N): corpus[n]=sample((Nv+beta*array(mean))/(n+beta),1) Nv[corpus[n]]+=1; return corpus
Let's see how to generate corpus for Mixture of Dirichlet-multinomial unigram language model
def generate_corpus(alpha, m, beta, n, D, Nd): """ Returns a grouped corpus drawn from a mixture of Dirichlet--multinomial unigram language models.
Arguments:
alpha -- concentration parameter for the Dirichlet prior over theta m -- T-dimensional mean of the Dirichlet prior over theta beta -- concentration parameter for the Dirichlet prior over phis n -- V-dimensional mean of the Dirichlet prior over phis D -- number of documents to generate Nd -- number of tokens to generate per document """ corpus = GroupedCorpus()
pass# YOUR CODE GOES HERE #determine the topic the distribution for topic dirichlet(dot(m,alpha),size=1) #given the topic, the distribtuion for word dirichlet(dot(n,beta),size=1) theta=dirichlet(alpha*array(m),1) phis=dirichlet(beta*array(n),len(m)) for d in range(0,D): [t]=sample(theta,1) #print groupVcab corpus.add(str(d),str(t),[str(x) for x in sample(phis[t,:],Nd)]) return corpus
\begin{itemize} \item First level, itemize, first item \begin{itemize} \item Second level, itemize, first item \item Second level, itemize, second item \begin{enumerate} \item Third level, enumerate, first item \item Third level, enumerate, second item \end{enumerate} \end{itemize} \item First level, itemize, second item \end{itemize} ==
\begin{figure} \centering \subfigure[Small Box with a Long Caption]{ \label{fig:subfig:a} %% label for first subfigure \includegraphics[width=1.0in]{graphic.eps}} \hspace{1in} \subfigure[Big Box]{ \label{fig:subfig:b} %% label for second subfigure \includegraphics[width=1.5in]{graphic.eps}} \caption{Two Subfigures} \label{fig:subfig} %% label for entire figure \end{figure}
len(dict) Gives the total length of the dictionary. This would be equal to the number of items in the dictionary.
3
str(dict) Produces a printable string representation of a dictionary
4
type(variable) Returns the type of the passed variable. If passed variable is dictionary then it would return a dictionary type.
Pythoncȝ定义和类Ҏ的定?br />定义cM需要用def class,直接
class ClassName(object): 每个c都?__init__(self,arg): ҎQ注意是 左右各两个下划线Qd4根下划线
cL法都需要包含selfq个参数Q但是用的时候不需要self,见下?br /> 例如
class Adder(object):
def __init__(self):
self.baseNum = 2
def prnt_num(self):
print self.baseNum
def add_to_base(self, arg):
# Your code here
self.baseNum+=arg
print self.baseNum
objectVar = Adder()
objectVar.prnt_num()
# Your code here
objectVar.add_to_base(3)
Python中的cd量不?self.xxx来引用,但是成员变量可以 Class variables are special because they belong to the class; the objects created do not get their own copies of the class variable. Class variables are accessed using the class name and dot notation. ClassName.classVar Class variables are created outside of__init__ 例如Q?br />
class Widget(object):
objID = 0
def __init__(self):
Widget.objID += 1
# Your code here
self.myID=Widget.objID
常犯错误Qindentation is very important python indentation error expected an indented block q有一个错误就?cL法,必须使用 self参数Q即使没有参敎ͼQ?/span> 另外一个常错的地方是 __init__(self,arg) 一定是四根下划U?/span>