为什么以下在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
运算符可以区分.为什么泄漏抽象?当我不知道它们是否是数字时,比较两个任意对象以查看它们是否相同的更好的方法是什么?
在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 3中的itertools.product结果中获取特定索引中的元素吗?像下面这样:
xlist = itertools.product('abc', repeat=3)
element = xlist[10]
Run Code Online (Sandbox Code Playgroud)