相关疑难解决方法(0)

"是"运算符与整数意外行为

为什么以下在Python中出现意外行为?

>>> a = 256
>>> b = 256
>>> a is b
True           # This is an expected result
>>> a = 257
>>> b = 257
>>> a is b
False          # What happened here? Why is this False?
>>> 257 is 257
True           # Yet the literal numbers compare properly
Run Code Online (Sandbox Code Playgroud)

我使用的是Python 2.5.2.尝试一些不同版本的Python,似乎Python 2.3.3显示了99到100之间的上述行为.

基于以上所述,我可以假设Python在内部实现,使得"小"整数以不同于大整数的方式存储,is运算符可以区分.为什么泄漏抽象?当我不知道它们是否是数字时,比较两个任意对象以查看它们是否相同的更好的方法是什么?

python int identity operators python-internals

476
推荐指数
11
解决办法
6万
查看次数

克服Ashton String任务中的MemoryError/Slow Runtime

Ashton String任务中,目标是:

按字典顺序排列给定字符串的所有不同子串并将它们连接起来.打印连接字符串的第K个字符.确保K的给定值有效,即将存在第K个字符.

Input Format:

第一行将包含数字T即测试用例数.每个测试用例的第一行将包含一个包含字符(a-z)的字符串,第二行将包含一个数字K.

Output Format:

打印第K个字符(字符串为1索引)

而且Constraints

1≤:T≤5
1≤长度≤105
k将是一个适当的整数.

例如,给定输入:

1
dbac
3
Run Code Online (Sandbox Code Playgroud)

输出将是: c

我已尝试使用此代码完成任务,它适用于相对较短的字符串:

from itertools import chain

def zipngram(text, n=2):
    words = list(text)
    return zip(*[words[i:] for i in range(n)])

for _ in input():
    t = input()
    position = int(input())-1 # 0th indexing
    chargrams = chain(*[zipngram(t,i) for i in range(1,len(t)+1)])
    concatstr = ''.join(sorted([''.join(s) for s in chargrams]))
    print (concatstr[position])
Run Code Online (Sandbox Code Playgroud)

但是如果输入文件看起来像这样:http://pastebin.com/raw/WEi2p09H并且所需的输出是:

l
s …
Run Code Online (Sandbox Code Playgroud)

python string out-of-memory n-gram

6
推荐指数
1
解决办法
279
查看次数

Itertools.product 中索引处的元素

我们可以从Python 3中的itertools.product结果中获取特定索引中的元素吗?像下面这样:

xlist = itertools.product('abc', repeat=3)
element = xlist[10]
Run Code Online (Sandbox Code Playgroud)

更新
整个问题颠倒了!我发现生成所有集合并查找索引是一个很大的错误!我查看了我的问题可能的重复项,但没有得到答案

python python-itertools

5
推荐指数
1
解决办法
2039
查看次数