由买买提看人间百态

topics

全部话题 - 话题: def
首页 上页 1 2 3 4 5 6 7 8 9 10 下页 末页 (共10页)
j*****k
发帖数: 1198
1
来自主题: Programming版 - python decorator 调用问题
比如有下面一个decorator, 怎么调用?
def decorator(func,aa):
def wrapper(*args, **argd):
if aa:
func(*args, **argd)
return wrapper
@decorator
def myfunc(a1,a2)
or
@decorator(True)
def myfunc(a1,a2)
都不行。
谢谢
i*****f
发帖数: 578
2
来自主题: Programming版 - python decorator 调用问题
This decorator definition seems not make sense to me.
From your dec. definition, it's obvious it takes two arguments: func, aa. So:
@decorator
def f():
...
is transformed to:
decorator(func, aa)(f)
Your decorator is **got** to take exactly two arguments. If this is the case
, seems that the wrapper is not doing what you want.
Are you trying to do something like:
def decorator(aa):
def outer_wrapper(func):
def wrapper(*args, **argd):
if
t****t
发帖数: 6806
3
来自主题: Programming版 - string operator +
first of all, it is not up to you or me to say compiler "should" do what and
what. a rule is there and it applies, that's it.
second, why it is designed this way? suppose in addition to std::string, you
define another class A that can converts const char* implicitly, and also
defines operator+(A, A). now you write "abc"+"def". what does it mean? it is
not clear. it can mean string("abc")+string("def"), or means A("abc")+A("
def"), or string("abc")+A("def"), etc. basically a mess. compiler must
g... 阅读全帖
w******p
发帖数: 166
4
来自主题: Programming版 - Python擂台:算24点
python code can be under 20 lines too:
import sys, operator, itertools, math;
def reverseOp(op):
def reverseFun(*args): return op(*reversed(args))
return reverseFun
binaryOps = { '+': operator.add, '/': operator.div, '*': operator.mul, '^
': operator.pow, '-': operator.sub, 'L': math.log, '!-': reverseOp(
operator.sub), '!/': reverseOp(operator.div), '!^': reverseOp(operator.pow),
'!L': reverseOp(math.log), }
def appl(ops, nums):
r, repr = nums[0], '{0}'.format(nums[0])
try... 阅读全帖
b*******t
发帖数: 34
5
来自主题: Programming版 - 问个PYTHON问题
新手问个问题。下面的PYTHON程序
在decorator里面是怎么绑定的? 这个程序里
n <---5
func <---LLL
args,kwds <--- a,b (or 1,1)
是什么样的规则?
========================
> cat a.py
def XXX(n):
def Wrapper (func):
def S(*args,**kwds):
for i in xrange(n):
print 20+func(*args, **kwds), ","
return S
return Wrapper
@XXX(5)
def LLL(a,b):
return a+b+1
print LLL(1,1)
========================
》python a.py
23 ,
23 ,
23 ,
23 ,
23 ,
None
m********2
发帖数: 89
6
来自主题: Programming版 - 问个PYTHON问题
In your code, you need "Wrapper" to bind the "func" var inside "S" to the
original "LLL".
def YYY(n):
def decor2(f):
def wrapper(*args, **kws):
for i in range(n):
f(*args, **kws)
return wrapper
return decor2
@YYY(3)
@XXX(5)
def LLL():
...
t**r
发帖数: 3428
7
/**
* Returns whether all bounded integers within `s` satisfy `p`.
*/
def forall(s: Set, p: Int => Boolean): Boolean = {
def iter(a: Int): Boolean = {
if (a > bound) true
else if (contains(s, a) && !p(a)) false
else iter(a + 1)
}
iter(-bound)
}
/**
* Returns whether there exists a bounded integer within `s`
* that satisfies `p`.
*/
def exists(s: Set, p: Int => Boolean): Boolean = !forall(s, (x => !p(x)))
/**
* Returns a set transformed ... 阅读全帖
e*********6
发帖数: 3453
8
来自主题: Programming版 - 这个python code能否优化去掉file write
class C:
def __init__(self, x):
self.x = x
def write_to_file(object, filename):
f = open(filename, 'a')
f.write(str(object.x) + 'n')
def large_loop(object):
print(object.x)
if (object.x == 1000):
print ('finish')
else:
n = object.x + 1
new_object = C(n)
if (object.x % 100 == 0):
# we need record some information
write_to_file(object, "temp.log")
return large_loop(new_object)
def working_on_intermidiat... 阅读全帖
t***q
发帖数: 418
9
大家好。我的那个web service 做成了。用了python 的 web.py.
install web.py
cd webpy
编辑python web service.
#!/usr/bin/env python
import web
import csv
import difflib
import re
import operator
import Levenshtein
urls = ('/title_matching2','title_matching2')
app = web.application(urls,globals())
class title_matching2:
def __init__(self):
self.hello = "hello world"
def GET(self):
getInput = web.input(name="World")
b=[]
with open("Book1.txt","rb") as k:
for row in k:
... 阅读全帖
d******e
发帖数: 2265
10
来自主题: Programming版 - 继续吐槽scala
开始试水 akka-slick-spray-play 技术stack. 大吃一惊。
先看fsm.
case class Supplier(id: Option[Int],name: String,desc: String)
case class SimpleSupplier(name: String,desc: String)
trait Suppliers extends Profile{
import profile.api._
class Suppliers(tag: Tag) extends Table[Supplier](tag, "SUPPLIERS") {
def id = column[Int]("id", O.PrimaryKey, O.AutoInc)
def name = column[String]("userID")
def desc = column[String]("last_name")
def * = (id.?, name, desc) <> (Supplier.tupled, Supplier.unapply... 阅读全帖
L***s
发帖数: 1148
11
来自主题: Programming版 - python还是有些傻傻的行为的

这个问题在别处有讨论过
http://www.newsmth.net/bbstcon.php?board=Python&gid=84864
发信人: pulo (普洛米·我们的民族从来不缺乏苦难), 信区: Python
标 题: Re: 关于空list做默认参数的一个疑问
发信站: 水木社区 (Thu Dec 29 04:32:28 2011), 转信
一个函数的默认参数是该函数(对象)的一个属性,存在一个叫func_defaults
的tuple里,而函数(类)本身在def时就实例化了,其func_defaults属性
有可能在多次函数调用过程中改变。
拿楼主的例子来说:
>>> def test1( x=[] ):
... print(type(x))
... x.append(0)
... return x
...
>>> test1.func_defaults
([],)
>>> test1()

[0]
>>> test1.func_defaults
([0],)
>>> test1()

[0... 阅读全帖
S********y
发帖数: 182
12
这儿是定义chappage的code,有什么不对的么。
% Definition of 'chapter header' page style
%
% Moves the page number to the lower center of the page, instead of
% the usual upper-right.
%
\def\ps@chappage{\let\@mkboth\@gobbletwo
\def\@oddhead{}\def\@oddfoot{\rm\hfil\thepage\hfil}
\def\@evenhead{}\let\@evenfoot\@oddfoot
}
b*******h
发帖数: 56
13
谢谢版主的关心,找到了解决方法
\def\beforesep{-0.5in}
\def\aftersep{0pt}
\makeatletter
\def\@makechapterhead#1{%
\vspace*{\beforesep}%
{\parindent \z@ \raggedright \normalfont
\ifnum \c@secnumdepth >\m@ne
\if@mainmatter
\large\centering\bfseries \@chapapp\space \thechapter
\par\nobreak
\vskip 0\p@
\fi
\fi
\interlinepenalty\@M
\large \centering\bfseries #1\par\nobreak
\vskip \aftersep
}}
\def\@makeschapterhead#1{%
\vspace*{\beforesep}%
{\parinden
l*******r
发帖数: 322
14
来自主题: TeX版 - sty的路径设置
在公共硬盘上和别人合作写tex
需要一个特别的package
已经安装调试通过
问题是:
不能把sty/def放在这个公共硬盘的其他地方(没有写的权限)
不想把sty/def放在我自己的机器上(否则每个合作者都需要重新在他的机器上装)
也不想把所有sty/def文件放在工作目录下(太乱)
能不能把sty/def文件放在工作目录的某个子目录下(i.e. $(WORKING)\sty\*.sty)
然后修改sty的引入路径?(i.e. somewhere in the working TEX file)
谢谢
e****c
发帖数: 183
15
beamer 里面,
\frame{
\frametitle{ABC}
\begin{figure}
\centering
\includegraphics[scale=0.55]{DEF.jpg}
\caption{XYZ}
\label{fig:DEF}
\end{figure}
}
出来后图的标题没有figure 1:DEF,而是figure:DEF。 怎么回事?
g*********r
发帖数: 124
16
对于第一个问题,
{\obeyspaces%
\gdef\uppercasefirst#{\bgroup\obeyspaces\let =\capaftersp%
\UppercaseSec}}
\def\UppercaseSec#1{\futurelet\next\CapAFTERsp#1{}\egroup}
\def\capaftersp{\space\futurelet\next\CapAFTERsp}
\def\CapAFTERsp{\ifx\next\egroup\let\next\relax\else
\ifx\next\capaftersp \unskip \let\next\relax \else
\def\next##1{\uppercase{##1}}\fi\fi \next}
\uppercasefirst{I love using the new version of Latex}
l******9
发帖数: 579
17
【 以下文字转载自 Statistics 讨论区 】
发信人: light009 (light009), 信区: Statistics
标 题: solve equations of integrals in python
发信站: BBS 未名空间站 (Fri Mar 21 12:21:31 2014, 美东)
I need to solve system equations of integrals in python 3.2.
from sympy import S, Eq, solve, integrals
import sympy as sym
import scipy.integrate as integ
x, b, c, m, v, L, u = S('x, b, c, m, v, L, u'.split())
equations = [Eq(m, integ.quad(xf(x, b, c), L, u))]
def xf(x, b,c):
return x*f(x,b,c)
def f(x, b, c):
return g(x, ... 阅读全帖
S******y
发帖数: 1123
18
# it is easy in Python
def unique(a):
return list(set(a))
def intersect(a, b):
return list(set(a) & set(b))
def union(a, b):
return list(set(a) | set(b))
def difference(a, b):
return list(set(b).difference(set(a)))
l1=[1,3,5,7,9]
l2=[2,4,6,8,10,1]
z=difference(l1,l2)
print z
D******n
发帖数: 2836
19
来自主题: Statistics版 - 有什么sas log的viewer吗
syn match sasNote "\s*NOTE:.*"
syn match sasWarn "\s*WARNING:.*"
syn match sasError "\s*ERROR.*"
syn region sasEp start="^\s\+_$" end="^\s\+\d\+$"
hi sNote term=NONE cterm=bold ctermfg=Blue ctermbg=Black gui=bold
guifg=Blue guibg=black
hi sWarn term=NONE cterm=bold ctermfg=Green ctermbg=Black
gui=bold guifg=Green guibg=black
hi sError term=NONE cterm=bold ctermfg=Red ctermbg=Black gui=bold
guifg=Red guibg=black
hi def link sasNote sNote
hi def link sasWarn sWarn
hi d... 阅读全帖
l******9
发帖数: 579
20
来自主题: Statistics版 - solve equations of integrals in python
I need to solve system equations of integrals in python 3.2.
from sympy import S, Eq, solve, integrals
import sympy as sym
import scipy.integrate as integ
x, b, c, m, v, L, u = S('x, b, c, m, v, L, u'.split())
equations = [Eq(m, integ.quad(xf(x, b, c), L, u))]
def xf(x, b,c):
return x*f(x,b,c)
def f(x, b, c):
return g(x, b,c) * (x/b)**(c-1) * sym.exp(-x/b)
def g(x, b, c):
c = 1+c // TypeError: unsupported operand type(s) for +: 'int' and '
tuple'
L = 1
u = 10
... 阅读全帖
F*******n
发帖数: 182
21
来自主题: Statistics版 - 请教两个 excel 问题
1,
有两个excel文件, 比如一个文件名:abc.xlsx,另一个:def.xlsx
现在需要在def.xlsx文件中,A1 输入第一个excel的文件名 abc,就能自动将 abc.
xlsx 中 B2~B100 的数据自动导入到 def.xlsx 中 A2~A100
请问用什么函数能做到?
2,
上面那个问题,如果第一个文件名可能是 abc-xxxx.xlsx 其中 xxxx 根据不同情况有
可能不一样,位数也不一样。还是在def.xlsx文件中,A1 处只输入 abc 而不是完整的
文件名,如何能达到问题1 的目的?
(也就是说有没有类似于通用符的东西,不如说 * 号,这样我只要在A1 处输入 abc,
就能从文件名以 abc 开头的文件中导入数据。)
谢谢
e*n
发帖数: 1511
22
【 以下文字转载自 Stock 讨论区 】
发信人: mitbbs2020 (bbc), 信区: Stock
标 题: Re: 【Stragety论坛】Trading with correlations.
发信站: BBS 未名空间站 (Sun Jul 25 19:52:04 2010, 美东)
用option当然可以,但不是必须,
用option可以得到更高的leverage,
但是缺点是散户量小,不容易实现market neutral。
比如1.37的hedge ratio,你要long 137和short 100个才能实现。
13和10就不那么好,而且不容易adjust,看附图就知道不怎么neutral的情况。
说stock不便于对冲,这点我不懂你什么意思。
这本身就是market neutral的strategy。
我测试过DISCA和AXP(paper account),追踪了至少2个月,涨跌幅从来没超过3%的,
但是这反过来说明这不是一对好的pair。
别的pair,没有任何leverage,一年可以做到100%以上的也有,如果我实际做stock到
这个%,
已经很满意了... 阅读全帖
l******9
发帖数: 579
23
【 以下文字转载自 Statistics 讨论区 】
发信人: light009 (light009), 信区: Statistics
标 题: solve equations of integrals in python
发信站: BBS 未名空间站 (Fri Mar 21 12:21:31 2014, 美东)
I need to solve system equations of integrals in python 3.2.
from sympy import S, Eq, solve, integrals
import sympy as sym
import scipy.integrate as integ
x, b, c, m, v, L, u = S('x, b, c, m, v, L, u'.split())
equations = [Eq(m, integ.quad(xf(x, b, c), L, u))]
def xf(x, b,c):
return x*f(x,b,c)
def f(x, b, c):
return g(x, ... 阅读全帖
s*****m
发帖数: 8094
24
没什么复杂的,
def IsFemale(appearance, genital):
return LooksLikeFemale(appearance) and DefinedAsFemale(genital)
def IsMale(appearance, genital, gay):
return LooksLikeMale(appearance) and DefinedAsMale(genital) and not gay
def Abnormal(appearance, genital, gay):
return not IsFemale(appearance, genital) and not IsMale(appearance,
genital, gay)
d*******l
发帖数: 338
25
来自主题: JobHunting版 - 这个facebook puzzle样题怎么做?
这学期试着在学习python,用python也写了一个。力求简练,效率应该不怎么高。
def getpath(now, visited, steps):
if now == visited[h(now)]:
print steps;
return ;
prev = visited[h(now)];
p = [i for i in xrange(0, len(now)) if now[i] != prev[i]][0];
getpath(prev, visited, steps + 1);
print prev[p], now[p];
def h(node):
return ''.join([str(n) for n in node]);

def solve(N, K, init, target):
q = [init];
visited = {h(init):init};
while q != []:
now = q.pop(0);
if no... 阅读全帖
x*******5
发帖数: 152
26
来自主题: JobHunting版 - 问一道programming peals上的题
终于有人做pearl,给一个我的解答
此题是第9题的扩展,第9题求的是subvector whose sum is close to zero,解答如下
(python)
def Subvector_Zero(v):
"find the subvector whose sum is close to zero"
s=[0 for a in range(len(v))]
s[0]=v[0]
for i in range(1,len(v)):
s[i]=v[i]+s[i-1]

s=sorted(s)
minv=sys.maxint
for i in range(1,len(v)):
minv=min(minv,s[i]-s[i-1])
return minv
C++:
/*Description: find the subvector whose sum is close to zero
Input: vector t
Output: int
K.O.: auxil... 阅读全帖
p*****2
发帖数: 21240
27
我写了一下,用的greedy的算法。没想到反例,但是感觉也不容易证明。
from heapq import *
class Node:
def __init__(self, val):
self.val=val
self.In=set()
self.Out=set()
def __cmp__(self, other):
if len(self.Out) return 1
elif len(self.Out)>len(other.Out):
return -1
else:
return 0
def __str__(self):
return self.val+":"+str(self.In)+":"+str(self.Out)

courses=[['D','A'],['D','B'],['E','B'],['F','A'],['F','C'],... 阅读全帖
p*****2
发帖数: 21240
28
来自主题: JobHunting版 - FB面试题:binary tree inorder successor
写了一个练练手
def first(root):
if root!=None:
l=first(root.left)
if l: return l
return root
def dfs(root,node):
if root==None: return root

if root==node:
r=first(root.right)
return r if r else root
else:
l=dfs(root.left,node)
if l: return l if l!=node else root
else: return dfs(root.right,node)

def next(root,node):
ret=dfs(root,node)
return ret if ret!=node else None
l****p
发帖数: 397
29
来自主题: JobHunting版 - 请教MapReduce怎么找median
刚写了一个O(lg N)的算法:
import math
import random
NUM_MAP_TASKS = 3000
NUM_REDUCE_TASKS = 2
def select(array, order = (len(array)+1)/2):
pivot = array.pop(random.random()*len(array))
length = math.floor(len(array)/NUM_MAP_TASKS)
map_results = {'less than or equal to pivot': [], 'greater than pivot':
[]}
for i in range(0, NUM_MAP_TASKS):
r = map(array[length*i:length*(i+1)], pivot)
map_results['less than or equal to pivot'] += r['less than or equal
to pivot']
map_... 阅读全帖
p*****2
发帖数: 21240
30
来自主题: JobHunting版 - iterator 实现 如何 peek(),pop()?
class Iterator[T](arr:Array[T]){
private[this] var pos=0
def peek()={
if(pos }

def pop()={
if(pos }

def reset(){
pos=0
}
}
object test2 extends App {
val arr=Array(1,2,3,4,5)
val it=new Iterator(arr)
println(it.peek())
println(it.pop())
println(it.peek())
println(it.pop())
println(it.peek())
println(it.pop())

}
p*****2
发帖数: 21240
31
来自主题: JobHunting版 - 关于尾递归

尾递归
def getHeight(root:TreeNode):Int={
recursion(0,List(root))
}

def recursion(layer:Int, list:List[TreeNode]):Int= list match{
case Nil=> layer
case _ => recursion(layer+1, process(list))
}

def process(list:List[TreeNode]):List[TreeNode]={
var newlist:List[TreeNode]=Nil
for(node<-list){
if(!node.left.isEmpty) newlist=node.left.get::newlist
if(!node.right.isEmpty) newlist=node.right.get::newlist
... 阅读全帖
p*****2
发帖数: 21240
32
来自主题: JobHunting版 - 关于尾递归

尾递归
def C(m:Int, n:Int):Int={
recursion(m, 0, None)(n)
}

def recursion(m:Int, i:Int, arr:Option[Array[Int]]):Array[Int]= i match{
case _ if i==m+1 => arr.get
case 0 => recursion(m, 1, Option(Array[Int](0)))
case _ => val ret=process(i,arr.get); recursion(m, i+1, Option(ret))
}

def process(i:Int, arr:Array[Int]):Array[Int]={
val ar=new Array[Int](i+1)
ar(0)=1
ar(i)=1

1 until i foreach(j=>ar(j)=arr... 阅读全帖
a******3
发帖数: 113
33
来自主题: JobHunting版 - Scala怎么通过index访问set或者array
定义了一个
val map = new ConcurrentSkipListMap[Key, Value]()
因为要实现多线程,需要重写他的iterator
我的代码如下
def keyIterator: Iterator[Key] = new Iterator[Key] {
val newMap=getMapClone
var set=newMap.keySet()
var pos = 0
def hasNext = pos < newMap.size()
def next: Key = { val z = array(pos) ; pos += 1 ; z }
}
[error] found : Int
[error] required: Key
array(pos)这方法貌似是通过key去访问,但是我想通过index去访问这个set,该怎么
写呢?或者有什么办法可以iterate这个map的key集合吗
本人新手,无奈网上找不到,求各位不吝赐教
f********d
发帖数: 51
34
来自主题: JobHunting版 - Java编程讨论:LinkedIn的H2O
while(true) {
CountDownLatch o = oq.take(); // take an O
CountDownLatch h1 =hq.take(); // take an H
hq.take().countDown(); // take another H
h1.countDown(); // count down all the rest
o.countDown();
}
any new formula, you only need to make sure the first 3 lines reflects your
formula well. it becomes very extensible. and you can also do
Collection list = Lists.newArrayList();
for (ElementDefinition ed : defs) {
BlockingQueue ... 阅读全帖
f********d
发帖数: 51
35
来自主题: JobHunting版 - Java编程讨论:LinkedIn的H2O
while(true) {
CountDownLatch o = oq.take(); // take an O
CountDownLatch h1 =hq.take(); // take an H
hq.take().countDown(); // take another H
h1.countDown(); // count down all the rest
o.countDown();
}
any new formula, you only need to make sure the first 3 lines reflects your
formula well. it becomes very extensible. and you can also do
Collection list = Lists.newArrayList();
for (ElementDefinition ed : defs) {
BlockingQueue ... 阅读全帖
t*********h
发帖数: 941
36
来自主题: JobHunting版 - 问一道前几天在版上看见的题
from collections import defaultdict
num1=2345678
num2=3429
def convert2int(lst):
return int(''.join(map(str,lst)))
def compare(num, result,l,digits):
n1=convert2int(str(num)[:l+1])
n2=convert2int(result[:l+1])
if l==(digits-1):
return n2>n1
return n2>=n1
def find_next(x1,num,result,digits,l):
if l==digits:
print 'found:'+''.join(map(str,result))
return
for i in xrange(10):
x=x1.copy()
if x[i]>0:
result[l]=i
x[i]-=1
if compare(num,result,l,digit... 阅读全帖
o*****n
发帖数: 189
37
来自主题: JobHunting版 - 请教一道比身高题目
一开始没用BST,做出来费老劲了。BST就容易太多了。 看看对吗? ;)
A=[5, 10, 15, 4, 13, 6, 3, 12]
B=[0, 0, 0, 1, 1, 1, 2, 2]
class tree:
def __init__(self, data):
self.data= data
self.left= None
self.right= None
n=len(A)
rootlst=[]
def build_tree(node, t): #Build BST tree
if node.data > t.data :
if t.right == None:
t.right = node
return
else: build_tree(node, t.right)
if node.data <= t.data :
if t.left == None:
t.left = node
... 阅读全帖
w*********m
发帖数: 4740
38
来自主题: JobHunting版 - 电话号码的英文combination变种
不是打印所有可能的组合。只打印valid的
字典里保存的是单个的词,不是整个的词组。比如一个电话的10位数match上了abc def
ghij。
abc,def,ghij是3个不同的词。字典里保存的是abc,def,ghij是3个词,不是abcdefghij。
seems最快的办法要先给字典建prefix tree,这样才可以在扫瞄电话的过程中提前返回。
比如前2个数列举到了ab,没有任何词以ab开头,也没有任何词以b开头(虽然a在字典中
),这时就不用在往下try aba了,直接开始try ac。
d*k
发帖数: 207
39
来自主题: JobHunting版 - 请教一道CS常见题的解法
这题有O(n),O(1)的方法,不过那些算法都是发过paper的,很复杂。
我说个O(nlogn),O(1)的吧:分治法,分别处理左右两半,同时返回正负分界点(第一
个正数的下标),合并只需将左半边的正数(右侧)和右半边的负数(左侧)交换即可。
Online coding一把,欢迎review.
# should call sort(array, 0, len(array) - 1)
def sort(array, left, right):
if left > right:
return 0
if left == right:
return left if array[left] > 0 or left + 1
mid = (left + right) / 2
x = sort(array, left, m - 1)
y = sort(array, m, right)
mid_rev(array, x, m, y - 1)
return x + y - m
def mid_rev(array, x... 阅读全帖
c***C
发帖数: 139
40
来自主题: JobHunting版 - 纽约小公司skype电面一题
Given a binary search tree, find the total number of integers
in between min and max.
30
/
25 40
/
15 28 50
i.e.: count_nodes(..., 20, 50) --> 5
class BST(object):
"""
A Binary search tree.
"""
def __init__(self, value, left, right):
self.value = value
self.left = left
self.right = right
def count_nodes(self, min_, max_):
def count_nodes_(self, coun... 阅读全帖
l*********8
发帖数: 4642
41
来自主题: JobHunting版 - 上一道小题
他的程序是有问题,改了改:
def nextPalindrome(num):
oddDigits = (len(str(num)) %2 != 0)
leftHalf = getLeftHalf(num)
newNum = getPalin(leftHalf, oddDigits)
if newNum > num:
return newNum
nextLeftHalf = str(int(leftHalf) + 1)
if len(nextLeftHalf) == len(leftHalf):
return getPalin(nextLeftHalf, oddDigits)
if oddDigits:
return getPalin(nextLeftHalf[:-1], 0)
else:
return getPalin(nextLeftHalf, 1)
def getLeftHalf(num):
return str(num)[:(len(str(nu... 阅读全帖
l*********8
发帖数: 4642
42
来自主题: JobHunting版 - 上一道小题
用ruby写了个任意非负整数的下一个Palindrome:
class Integer
def nextPalin
num = self.to_s.toPalin!.to_i
return num if num > self
self.to_s.nextPalin.to_i
end
end
class String
def toPalin!
self[(size+1)/2...size] = self[0...size/2].reverse
self
end
def nextPalin
(self[0...(size+1)/2].next + self[(size+1)/2...size]).toPalin!
end
end
e********r
发帖数: 24
43
来自主题: JobHunting版 - 小弟求问LinkedIn那道Deep Iterator的题
这个可能犯规了……
import scala.collection.mutable.ArrayBuffer
def deepFlatten(list: Seq[Any]):ArrayBuffer[Int] = list match {
case Nil => ArrayBuffer()
case elem::rest => elem match {
case v: Int => v +=: deepFlatten(rest)
case l: Seq[Any] => deepFlatten(l) ++=: deepFlatten(rest)
}
}

class DeepIterator(list: Seq[Any]) {
val content = deepFlatten(list)
def hasNext = !content.isEmpty
def next = {
val item = content.head
content -= item
item
}
}
e********r
发帖数: 24
44
来自主题: JobHunting版 - 小弟求问LinkedIn那道Deep Iterator的题
这个可能犯规了……
import scala.collection.mutable.ArrayBuffer
def deepFlatten(list: Seq[Any]):ArrayBuffer[Int] = list match {
case Nil => ArrayBuffer()
case elem::rest => elem match {
case v: Int => v +=: deepFlatten(rest)
case l: Seq[Any] => deepFlatten(l) ++=: deepFlatten(rest)
}
}

class DeepIterator(list: Seq[Any]) {
val content = deepFlatten(list)
def hasNext = !content.isEmpty
def next = {
val item = content.head
content -= item
item
}
}
w****r
发帖数: 28
45
来自主题: JobHunting版 - 如何求一个整数阶乘的各位数字和
试着写了个python的, n = 2000 花时间大概十几秒钟
def tolist(n):
result = []
while (n >= 10):
result.append(n % 10)
n = n / 10
result.append(n)
return result

def mult(num1, num2):
result = [0]*(len(num1) + len(num2))
for i in range(len(num1)):
for j in range(len(num2)):
temp = num1[i] * num2[j]
if temp >= 10:
result[i + j] += temp % 10
result[i + j + 1] += temp / 10
else:
result[i + j] += temp
for k in range(len(result)):
if result[k] >= 1... 阅读全帖
b***p
发帖数: 700
46
来自主题: JobHunting版 - 问道G家的题
这个行吗?
#!/usr/bin/python
class WordAbbr:
def __init__(self):
pass
def word_abbr(self, word, start, len_abbr):
if len(word) < start + len_abbr:
return False
return word[:start] + word[start+len_abbr:]
def solution(self, word, list_words):
word_len = len(word)
for i in range(word_len - 1):
len_abbr = word_len - i
for j in range(word_len + 1 - len_abbr):
word_abbr = self.word_abbr(word, j, len_abb... 阅读全帖
b***p
发帖数: 700
47
来自主题: JobHunting版 - 问道G家的题
这个行吗?
#!/usr/bin/python
class WordAbbr:
def __init__(self):
pass
def word_abbr(self, word, start, len_abbr):
if len(word) < start + len_abbr:
return False
return word[:start] + word[start+len_abbr:]
def solution(self, word, list_words):
word_len = len(word)
for i in range(word_len - 1):
len_abbr = word_len - i
for j in range(word_len + 1 - len_abbr):
word_abbr = self.word_abbr(word, j, len_abb... 阅读全帖
j*******p
发帖数: 73
48
来自主题: JobHunting版 - python里面怎么表示树?
'''Create a binary tree from an input list.'''
import math
# If we store a full binary tree using BFS into a list, map the index of the
# node to its parent and which branch this node is.
# node_index parent_index branch
# 1 0 0
# 2 0 1
# 3 1 0
# 4 1 1
# 5 2 0
# ...
def GetParentMap(max_nodes):
parent_map = {} # index: (parent_index, left_or_right)
current_parent = 0
current_branch = 0
for i in range(1, max_nodes):
parent_map[i] = (current_parent, current_branch)
# Switch betwe... 阅读全帖
x*******9
发帖数: 138
49
def get_next(needle):
l = len(needle)
nexts = [0 for i in xrange(l + 1)]
nexts[0] = -1
i, j = 0, -1
while i < l:
while j >= 0 and needle[i] != needle[j]:
j = nexts[j]
i += 1
j += 1
nexts[i] = j
return nexts
def get_prefix_match(S):
nexts = get_next(S)
print S
print nexts
for i, u in enumerate(nexts):
if u <= 0:
continue
v = u
print '>>', S[:u], "\t[0...%d]" % u, S[i - u: i], "\... 阅读全帖
C****t
发帖数: 53
50
def revSum(a):
d = height(a)
level, sum = 1, [0]
helper(a, d, level, sum)
return sum[0]
def height(a):
d = 1
for ele in a:
if type(ele) == list:
d = max(d, 1+height(ele))
return d
def helper(a, d, level, sum):
for i in range(len(a)):
if type(a[i]) != list:
sum[0] += a[i]*(d-level+1)
else:
helper(a[i], d, level+1, sum)
首页 上页 1 2 3 4 5 6 7 8 9 10 下页 末页 (共10页)