python循环移位字符串中的字符 [英] python cyclic shifting of the characters in the string
问题描述
实现<<"的标准str类型的子类sstr和>>"方法作为字符串中字符的循环移位.尝试做的是
Subclass sstr of the standard str type that implements the "<<" and ">>" methods as a cyclic shifting of the characters in the string.What trying to do is
>>> s1 = sstr("abcde")
>>> s1 << 0
'abcde'
>>> s1 >> 0
'abcde'
>>> s1 << 2
'cdeab'
>>> s1 >> 2
'deabc'
>>> s1 >> 5
'abcde'
# my attempt:
import string
class sstr(str):
def __new__(self, other):
return str.__new__(self, other.upper())
def __ilshift__(self, other):
return str.__ilshift(other)
def __rshift__(self, other):
return str.__rshift(other)
推荐答案
这有点像作业,所以我不打算在这里发布实际代码.但为了提供帮助,我将指出我在您的代码和算法中看到的缺陷:
This smells like homework, so I'm not going to post actual code here. But to help, I will point out flaws I see in your code and an algorithm:
我的python 2.7.2 在str
中没有报告__ilshift
或__irshift
.此外,如果您试图将字符串移动一定数量的字符,那么您不应该移动您调用 other
的变量.您应该将 self
移动 other
多个字符.话虽如此,您可能最好将 other
命名为 n
或类似的名称.
My python 2.7.2 reports no __ilshift
or __irshift
in str
. Also, if you are trying to shift a string by a certain number of characters, then you shouldn't be shifting the variable you call other
. You should be shifting self
by other
many characters. That being said, you're probably better off naming other
as n
or some such.
现在,我假设您知道循环移位应该如何工作.您提供的示例很好地传达了信息.
Now, I assume you know how circular shifting is supposed to work. The examples you provide get the message across well.
作为一个简单的算法(易于阅读/理解),试试这个(伪代码如下):
As a simple algorithm (easy to read/understand), try this (pseudo-code follows):
function __ilshift(self, n) { // self is the string to be shifted. n denotes how many characters to shift it by
answer = copy()
for i = 1 to n {
answer = self[1:] //answer = everything in self excluding the first character
answer += self[0] // append the first character of self to answer
}
return answer
}
上述解决方案可行.尽管如此,它的效率很低.我们知道,当一个 n 个字符的字符串被 n
移位时,移位的结果就是字符串本身.当您再仔细考虑一下时,您会意识到您最终会移动 n % lengthOfSelf
.因此,for i = 1 to n
变成了 for i = 1 to n%len(self)
.
The above solution would work. Though, it is quite inefficient. We know that when an n-character string is shifted by n
, the result of the shifting is the string itself. When you think about this a little more, you realize that you end up shifting by n % lengthOfSelf
. Thus, the for i = 1 to n
turns into for i = 1 to n%len(self)
.
不过,我们可以提高效率.要做到这一点,需要在适当的索引处拼接 self
,我会让你弄清楚,因为我认为这是功课.
Still, we can make this more efficient. To do this would require splicing self
at the appropriate index, which I'll let you figure out, because I think this is homework.
希望这能让你更接近!
这篇关于python循环移位字符串中的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!