关于python 编码问题raise NotImplementedError() 的问题

趣文:Python程序员的进化史 - 博客 - 伯乐在线
& 趣文:Python程序员的进化史
& 18.3K 阅读
导读:下面代码来自
,列举了各种程序员所写的阶乘算法代码,甚至包括网页设计师的。 :)
#新手程序员
def factorial(x):
if x == 0:
return x * factorial(x - 1)
print factorial(6)
#有一年 Pascal 经验的程序员
def factorial(x):
result = 1
while i &= x:
result = result * i
return result
print factorial(6)
#有一年 C 经验的程序员
def fact(x): #{
result = i = 1;
while (i &= x): #{
print(fact(6))
#有一年 SICP 经验的程序员
def fact(x, acc=1):
if (x & 1): return (fact((x - 1), (acc * x)))
else: return acc
print(fact(6))
#有一年 Python 经验的程序员
def Factorial(x):
for i in xrange(2, x + 1):
return res
print Factorial(6)
#懒惰的Python程序员
def fact(x):
return x & 1 and x * fact(x - 1) or 1
print fact(6)
#更懒惰的Python程序员
f = lambda x: x and x * f(x - 1) or 1
print f(6)
#专家级Python程序员
import operator as op
import functional as f
fact = lambda x: f.foldl(op.mul, 1, xrange(2, x + 1))
print fact(6)
#Python 黑客
import sys
def fact(x, acc=1):
if x: return fact(x.__sub__(1), acc.__mul__(x))
return acc
sys.stdout.write(str(fact(6)) + '\n')
#专家级程序员
import c_math
fact = c_math.fact
print fact(6)
#英国专家级程序员 (译注:在英式英语中,“数学”的简写,多用“maths”,不是“math&。)
import c_maths
fact = c_maths.fact
print fact(6)
#网页设计师
def factorial(x):
#-------------------------------------------------
#--- 这段代码是从 Math Vault 那弄过来滴---
#--- 计算阶乘 (C)亚瑟·史密斯 1999年---
#-------------------------------------------------
result = str(1)
i = 1 #谢谢亚当
while i &= x:
#result = result * i #It's faster to use *=
#result = str(result * result + i)
#result = int(result *= i) #??????
result str(int(result) * i)
#result = int(str(result) * i)
return result
print factorial(6)
#Unix 程序员
def fact(x):
os.system('factorial ' + str(x))
#Windows 程序员
NULL = None
def CalculateAndPrintFactorialEx(dwNumber,
hOutputDevice,
lpsscSecurity,
*dwReserved):
if lpsscSecurity != NULL:
return NULL #Not implemented
dwResult = dwCounter = 1
while dwCounter &= dwNumber:
dwResult *= dwCounter
dwCounter += 1
hOutputDevice.write(str(dwResult))
hOutputDevice.write('\n')
import sys
CalculateAndPrintFactorialEx(6, sys.stdout, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL)
#企业程序员
def new(cls, *args, **kwargs):
return cls(*args, **kwargs)
class Number(object):
class IntegralNumber(int, Number):
def toInt(self):
return new (int, self)
class InternalBase(object):
def __init__(self, base):
self.base = base.toInt()
def getBase(self):
return new (IntegralNumber, self.base)
class MathematicsSystem(object):
def __init__(self, ibase):
@classmethod
def getInstance(cls, ibase):
cls.__instance
except AttributeError:
cls.__instance = new (cls, ibase)
return cls.__instance
class StandardMathematicsSystem(MathematicsSystem):
def __init__(self, ibase):
if ibase.getBase() != new (IntegralNumber, 2):
raise NotImplementedError
self.base = ibase.getBase()
def calculateFactorial(self, target):
result = new (IntegralNumber, 1)
i = new (IntegralNumber, 2)
while i &= target:
result = result * i
i = i + new (IntegralNumber, 1)
return result
print StandardMathematicsSystem.getInstance(new (InternalBase, new (IntegralNumber, 2))).calculateFactorial(new (IntegralNumber, 6))
下面代码是给出的,他说是在邮局看到的。
#VBA 程序员
def factorial(x):
if x == 0:
if x == 1:
if x == 2:
return x * (x-1)
if x == 3:
return x * (x-1) * (x-2)
if x == 4:
return x * (x-1) * (x-2) * (x-3)
if x == 5:
return x * (x-1) * (x-2) * (x-3) * (x-4)
if x == 6:
return x * (x-1) * (x-2) * (x-3) * (x-4) * (x-5)
print factorial(6)
关于作者:
#专家级Python程序员
import operator as op
import functional as f
fact = lambda x: f.foldl(op.mul, 1, xrange(2, x + 1))
print fact(6)
import functional as f
这句有点问题吧
functional 是第三方库吧
为作者带来更多读者;为读者筛选优质内容;专注IT互联网。
最新评论(期待您也参与评论)
汇集优质的Python技术文章和资源。人生苦短,我用Python!
JavaScript, CSS, HTML5 这里有前端的技术干货!
关注安卓移动开发业界动态,分享技术文章和优秀工具资源。
关注iOS移动开发业界动态,分享技术文章和优秀工具资源。
关于伯乐在线博客
在这个信息爆炸的时代,人们已然被大量、快速并且简短的信息所包围。然而,我们相信:过多“快餐”式的阅读只会令人“虚胖”,缺乏实质的内涵。伯乐在线博客团队正试图以我们微薄的力量,把优秀的原创/译文分享给读者,做一个小而精的精选博客,为“快餐”添加一些“营养”元素。
欢迎关注更多频道
– 分享和发现有价值的内容与观点
– 为IT单身男女服务的征婚传播平台
– 优秀的工具资源导航
– 翻译传播优秀的外文文章
– 国内外的精选博客文章
– JavaScript, HTML5, CSS
– 专注Android技术分享
– 专注iOS技术分享
– 专注Java技术分享
– 专注Python技术分享
(加好友请注明来意)
网站使用问题
请在询问或者反馈
& 2015 伯乐在线
赞助云主机1773人阅读
今天写代码时无意碰到NotImplemented,我一愣,难道是NotImplementedError的胞弟,所以稍微研究了一下。NotImplemented故名思议,就是“未实现”,一般是用在一些比较算法中的,如class的__eq__,__lt__等,注意NotImplemented并不是异常,所以不能使用raise,当没有实现时应该是return&NotImplemented。我们可以看看django中的Field的实现,@total_ordering
class Field(object):
&&&Base class for all field types&&&
def __eq__(self, other):
# Needed for @total_ordering
if isinstance(other, Field):
return self.creation_counter == other.creation_counter
return NotImplemented
def __lt__(self, other):
# This is needed because bisect does not take a comparison function.
if isinstance(other, Field):
return self.creation_counter & other.creation_counter
return NotImplemented
那提供NotImplemented有什么好处?好处就在于如果A == B&NotImplemented,会去调用B的__eq__方法,如果B也没有会调用cmp方法。我们看下面一个例子:class Person:
def __init__(self, age):
self.age = age
def __eq__(self, other):
if not isinstance(other, Person):
return NotImplemented
return self.age == other.age如果你们稳定库中有这么一段代码,而且Person可能包含了很多字段,但是你想实现Person和整数比较。person=Person(10)
print person == 10 #False很遗憾,上面结果是False,不符合我们要求,至于为什么是10,稍后再说,我们先看看如何解决这个问题?其实这时你可以简单封装一个age对象,class Age:
def __init__(self, age):
self.age = age
def __eq__(self, other):
return self.age == other.age
person=Person(10)
age=Age(10)
print person == age #Trueok,很完美,那我们从上面能得到什么结论呢?我们在写一些基础代码时,即使是没实现,也不要raise&NotImplementedError,而是return&NotImplemented,相当于提供给其它不同对象的比较接口,这对代码扩展非常有好处。我们再来看看上面那么直接和10比,为什么是False?先看下面这段代码:class A:
def __lt__(self, a):
return NotImplemented
def __add__(self ,a):
return NotImplemented
print A() & A() # True
print A() & 1
# False很奇怪吧,明明已经直接是NotImplemented,为什么还有结果?大胆猜测,前面说明最后会使用cmp比较,很明显当都没有定义时会比较id值,也就是内存地址,后创建的对象内存地址大,就是这个道理。至于A() & 1,因为python的小整数对象在初始化时创建的,内存地址肯定小,如果你还不信,不过千万别搞没有意思的操作,这也是这位兄弟不解的地方,
版权声明:本文为博主原创文章,未经博主允许不得转载。
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:374810次
积分:5103
积分:5103
排名:第2446名
原创:109篇
转载:11篇
评论:187条
阅读:22420
文章:15篇
阅读:60413
阅读:19706
(4)(2)(2)(1)(2)(2)(2)(4)(2)(1)(2)(6)(4)(5)(3)(1)(3)(7)(5)(1)(1)(3)(3)(2)(5)(4)(7)(7)(11)(8)(7)(5)(1)关于Python的Traitsui.....
[问题点数:40分]
关于Python的Traitsui.....
[问题点数:40分]
不显示删除回复
显示所有回复
显示星级回复
显示得分回复
只显示楼主
匿名用户不能发表回复!|
每天回帖即可获得10分可用分!小技巧:
你还可以输入10000个字符
(Ctrl+Enter)
请遵守CSDN,不得违反国家法律法规。
转载文章请注明出自“CSDN(www.csdn.net)”。如是商业用途请联系原作者。Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free.
I get a NotImplementedError when i run below code. Why?
import nltk
from nltk import *
from nltk.tag import stanford
from nltk.tag.stanford import StanfordTagger
st = StanfordTagger('C:\\Python27\\stanford-postagger\\models\\english-bidirectional-distsim.tagger',
'C:\\Python27\\stanford-postagger\\stanford-postagger.jar')
print st.tag('What is the airspeed of an unladen swallow ?'.split())
Error Message:
File "C:\Python27\lib\site-packages\nltk\tag\stanford.py", line 51, in _cmd
raise NotImplementedError
NotImplementedError
Looking at the source code :
The _cmd method is not implemented in StanfordTagger
- _cmd property: A property that returns the command that will be
def _cmd(self):
raise NotImplementedError
So when it is called here causes your problem:
# Run the tagger and get the output
stanpos_output, _stderr = java(self._cmd,classpath=self._stanford_jar, \
stdout=PIPE, stderr=PIPE)
In POSTagger the method looks like:
def _cmd(self):
return ['edu.stanford.nlp.tagger.maxent.MaxentTagger', \
'-model', self._stanford_model, '-textFile', \
self._input_file_path, '-tokenize', 'false']
You could edit the method in
StanfordTagger to match the POSTTagger.
61.1k42969
this is not the answer to my question but a workaround: use POSTagger instead of StanfordTagger
import nltk
from nltk import *
from nltk.tag import stanford
#from nltk.tag.stanford import StanfordTagger
from nltk.tag.stanford import POSTagger
st = POSTagger('C:\\Python27\\stanford-postagger\\models\\english-bidirectional-distsim.tagger',
'C:\\Python27\\stanford-postagger\\stanford-postagger.jar')
print st.tag('What is the airspeed of an unladen swallow ?'.split())
Your Answer
Sign up or
Sign up using Google
Sign up using Facebook
Sign up using Stack Exchange
Post as a guest
Post as a guest
By posting your answer, you agree to the
Not the answer you're looking for?
Browse other questions tagged
Stack Overflow works best with JavaScript enabledwowotouweizi
出错和异常
------------------------------------
python的标准异常(内建异常):
BaseException:所有异常的基类。
从BaseException派生的子类:
KeyboardInterrupt:用户中断执行。
SystemExit:python解释器请求退出。
Exception:常规错误的基类。
从Exception派生的子类:包括了所有其它的异常
GeneratorExit:生成器发生异常来通知退出
StopIteration:迭代器没有更多的值
ArithmeticError:所有数值计算错误的基类
AssertionError:断言语句失败
AttributeError:对象没有这个属性
BlockingIOError:
BrokenPipeError:
BufferError:
ChildProcessError:
ConnectionAbortedError:
ConnectionError:
ConnectionRefusedError:
ConnectionResetError:
EOFError:没有内建输入,到达EOF标记
EnvironmentError:操作系统错误的基类
FileExistsError:
FileNotFoundError:
FloatingPointError:浮点计算错误
IOError:输入输出操作失败
ImportError:导入模块或对象失败
IndentationError:缩进错误
IndexError:序列中没有次索引
InterruptedError:
IsADirectoryError:
KeyError:映射中没有这个键
LookupError:无效数据查询的基类
MemoryError:内存溢出错误
NameError:未申明或初始化对象
NotADirectoryError:
NotImplementedError:尚未实现的方法
OSError:操作系统错误
OverflowError:数值运算超出最大限制
PermissionError:
ProcessLookupError:
ReferenceError:弱引用,试图访问已经垃圾回收的对象
RuntimeError:一般的运行时错误
SyntaxError:python语法错误
SystemError:一般的解释器系统错误
TabError:tab和空格混用
TimeoutError:
TypeError:对类型无效的操作
UnboundLocalError:访问未初始化的本地变量
UnicodeError:unicode相关的错误
UnicodeDecodeError:unicode解码时的错误
UnicodeEncodeError:unicode编码时错误
UnicodeTranslateError:unicode转换时错误
ValueError:传入无效的参数
WindowsError:windows系统调用失败
ZeroDivisionError:除0
Warning:警告的基类
BytesWarning:
DeprecationWarning:关于被弃用的特征的警告
FutureWarning:关于构造将来语义会有改变的警告
ImportWarning:
PendingDeprecationWarning:关于特性将会被抛弃的警告
ResourceWarning:
RuntimeWarning:可疑的运行时行为的警告
SyntaxWarning:可疑的语法的警告
UnicodeWarning:
UserWarning:用户代码生成的警告
------------------------------------
try-except-else-finally语句结构:
try_suite(监控这里的异常)
exceptException1[, reason1]:
except_suite(异常处理代码)
except ExceptionN[, reasonN]:
except_suite(可以用多个except处理一个try)
except(Exception1, Exception2,…) [, reason]:
except_suite(可以一个except处理多个异常)
except_suite_for_all(处理所有except类中的异常)
else_suite(try没有检测到异常时执行else部分)
[finally:]
finally_suite(无论是否检测到异常都执行finally部分)
ExceptionX是一个异常的类类型。
reason是导致异常的代码的诊断信息的类实例
如果有必须执行的部分可以用下面结构:
finally_suite
------------------------------------
with上下文管理:
withcontext_expr(上下文表达式)[as
var] (context_expr的返回值赋给var):
with_suite
只有支持上下文管理协议的对象才能使用with。
下列对象支持该协议:
decimal.Context
thread.LockType
threading.Lock
threading.Rlock
threading.Condition
threading.Semaphore
threading.BoundedSemaphore
------------------------------------
raise触发异常:
try和except是捕获一个解释器产生的异常,raise可以定义自己的异常。
raise的通用结构:
raise[someException [, args [, traceback]]]
someException是异常名称
args是异常参数
traceback是追踪标志
raise一般使用下列格式:
raiseexclass:触发一个异常,从exclass生成一个实例
raiseexclass, args:同上,同时提供异常参数
raiseexclass, args, tb:同上,提供一个追踪记录对象tb
raiseexclass():通过函数调用操作符作用于类名生成一个exclass实例
raiseexclass(args):同上,同时提供异常参数
raiseexclass, instance:通过实例触发异常,
raiseinstance:通过实例触发异常,异常类型是实例的类型
raise:重新触发前一个异常,如果之前没有异常,触发TypeError。
------------------------------------
assert断言
测试一个表达式,如果返回值是假,触发异常。
assertexpression[, arguments]
如果断言成功不做任何处理,如果断言失败,触发AssertionError错误。
arguments是一个异常参数。
------------------------------------
sys模块中和异常相关的函数:
sys.exc_info()可以返回一个异常信息的三元组
type异常类、value异常类实例、traceback跟踪记录对象。}

我要回帖

更多关于 python 编码问题 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信