三等分

2024-09-30 20:37:30 发布

您现在位置:Python中文网/ 问答频道 /正文

编写一个函数,将字符串“s”作为参数,拆分为,并返回一个元组(左、中、右)。如果字符串的长度不能被3平均整除,那么函数应该尽可能平均地分割字符串。你知道吗

我试过使用for循环和string替换,strip函数,显然不起作用。。。我不知所措。我的代码现在输出3的所有东西

def trisect(s): 
    print(tuple([s[i:i+3] for i in range(0, len(s), 3)]))
s = input("what is your string: ")
trisect(s)

预期结果:输入:"123456789012" 输出:('1234', '5678', '9012')

实际结果:输入:"123456789012" 输出:('123', '456', '789', '012')


Tags: 函数字符串代码infor参数stringlen
3条回答

可以使用len(s)获取字符串的长度,然后使用len(s) // 3//执行整数除法)获取节的长度。你知道吗

从那里,只需根据需要切片:


length = len(s) // 3
trisections = s[:length], s[length:length * 2], s[length * 2:]

编辑:

使用length = round(len(s) / 3)

代码:

for s in ["abcdef", "abcdefg", "abcdefgh"]:
    n, r = divmod(len(s), 3)
    trisections = s[:n], s[n:2*n+(r>1)], s[2*n+(r>1):]
    print(trisections)

输出:

('ab', 'cd', 'ef')
('ab', 'cd', 'efg')
('ab', 'cde', 'fgh')

编辑:一种广义的方法。你知道吗

# The method.
def n_sect(s, n):
    m, r = divmod(len(s), n)
    idx_a = 0
    result = []
    for i in range(n):
        idx_b = idx_a + m + (i < r)
        result.append(s[idx_a:idx_b])
        idx_a = idx_b
    return result

# Try it yourself!
import string
for n in range(3, 5):
    for i in range(1, 27):
        s = string.ascii_lowercase[:i]
        print(n_sect(s, n))
    print()

起初,我认为这是一个重复,但现有的线程似乎没有考虑到“尽可能均匀”的要求。使用textwrap.wrapzip和大多数itertools解决方案会在最后留下一个悬空的不均匀块。这个解决方案从前面分块n和焊盘的任意值。你知道吗

方法是取iterable长度的商和余数,并开始按所需的块大小进行迭代。对于每个区块,如果有余数,则向区块添加1。按块大小+1递增步长,并递减余数。如果没有剩余,则正常生成块。你知道吗

下面是函数和测试代码:

def chunk(iterable, chunks):
    if chunks < 1: 
        raise ValueError("invalid chunk size")

    q, r = divmod(len(iterable), chunks)
    i = 0

    while i < len(iterable):
        if r > 0: 
            r -= 1
            yield iterable[i:i+q+1]
            i += 1
        else:
            yield iterable[i:i+q]

        i += q


if __name__ == "__main__":
    s = "".join(map(chr, range(97, 115)))

    for i in range(len(s) + 1):
        for j in range(1, len(s[:i]) + 1):
            print(repr(s[:i]), " chunk size", j, ":")
            print(list(chunk(s[:i], j)), "\n")

输出摘录:

'abcde'  chunk size 1 :
['abcde']

'abcde'  chunk size 2 :
['abc', 'de']

'abcde'  chunk size 3 :
['ab', 'cd', 'e']

'abcde'  chunk size 4 :
['ab', 'c', 'd', 'e']

'abcde'  chunk size 5 :
['a', 'b', 'c', 'd', 'e']
'abcdefgh'  chunk size 1 :
['abcdefgh']

'abcdefgh'  chunk size 2 :
['abcd', 'efgh']

'abcdefgh'  chunk size 3 :
['abc', 'def', 'gh']

'abcdefgh'  chunk size 4 :
['ab', 'cd', 'ef', 'gh']

'abcdefgh'  chunk size 5 :
['ab', 'cd', 'ef', 'g', 'h']

'abcdefgh'  chunk size 6 :
['ab', 'cd', 'e', 'f', 'g', 'h']

'abcdefgh'  chunk size 7 :
['ab', 'c', 'd', 'e', 'f', 'g', 'h']

'abcdefgh'  chunk size 8 :
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
'abcdefghijklm'  chunk size 1 :
['abcdefghijklm']

'abcdefghijklm'  chunk size 2 :
['abcdefg', 'hijklm']

'abcdefghijklm'  chunk size 3 :
['abcde', 'fghi', 'jklm']

'abcdefghijklm'  chunk size 4 :
['abcd', 'efg', 'hij', 'klm']

'abcdefghijklm'  chunk size 5 :
['abc', 'def', 'ghi', 'jk', 'lm']

'abcdefghijklm'  chunk size 6 :
['abc', 'de', 'fg', 'hi', 'jk', 'lm']

'abcdefghijklm'  chunk size 7 :
['ab', 'cd', 'ef', 'gh', 'ij', 'kl', 'm']

'abcdefghijklm'  chunk size 8 :
['ab', 'cd', 'ef', 'gh', 'ij', 'k', 'l', 'm']

'abcdefghijklm'  chunk size 9 :
['ab', 'cd', 'ef', 'gh', 'i', 'j', 'k', 'l', 'm']

'abcdefghijklm'  chunk size 10 :
['ab', 'cd', 'ef', 'g', 'h', 'i', 'j', 'k', 'l', 'm']

'abcdefghijklm'  chunk size 11 :
['ab', 'cd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm']

'abcdefghijklm'  chunk size 12 :
['ab', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm']

'abcdefghijklm'  chunk size 13 :
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm']

现在,编写trisect函数如下所示:

def trisect(s):
    return list(chunk(s, 3))

相关问题 更多 >