Python:将元组转换为字符串表示

时间:2017-11-21 16:45:26

标签: python

我正在编写一个功能卷,它采用电话簿分区的数字表示。如果传递给函数的参数不表示电话簿分区的有效数字表示,则该函数会使用消息无效分区引发AssertionError。否则,该函数必须返回给定分区的字符串表示。

使用我的代码我仍然没有解决以下情况: 1.卷(' A-D E-J K-O P-Z')必须引发断言错误 2.卷(42)必须引发断言错误 3.卷((1,10,1,12,1,1))必须返回'A B-K L M-X Y Z'而不是。{1,10,1,12,1,1) 'A B-K L M-X Y Z-Z'我的代码就是这种情况

任何人都可以帮助我吗?

def volumes(seq):
    '''
    >>> volumes((4, 6, 5, 11))
    'A-D E-J K-O P-Z'
    >>> volumes((7, 8, 1, 10))
    'A-G H-O P Q-Z'
    >>> volumes((4, 7, 5, 10))
    'A-D E-K L-P Q-Z'
    >>> volumes((8, 3, 9, 7))
    Traceback (most recent call last):
    AssertionError: invalid partitioning
    '''
    if type(seq) is tuple:
        import itertools
        q = list(itertools.accumulate(seq))


    if type(seq) is tuple:
        assert "invalid partitioning" 

    assert (sum(x for x in seq) == 26), "invalid partitioning"
    assert q[-1] == 26, "invalid partitioning" 
    assert seq[-1] != 0, "invalid partitioning"  
    assert seq[-1] > 0, "invalid partitioning" 

    st = 'A'
    count = 0

    for x in seq:
        count += int(x)
        new = count + 64
        if int(x) < 2 and new < 90:
            st = st + " " + chr(new+1)
        elif int(x) >= 2 and new < 90:
            st = st + "-" + chr(new) + " " + chr(new+1)
        else:
            st = st + "-" + chr(new)

    return st

1 个答案:

答案 0 :(得分:1)

您可以更改代码的最后一部分,以便在最后一位数字为1时允许特殊情况:

names1 <- names(df_wide)[-1]
pat <- "(.[a-z]+)_(.*)|(.*)_(.[a-z]+)"
varying <- split(names1, sub(pat, "\\2\\3", names1))
v.names <- names(varying)
locations <- unique(sub(pat, "\\1\\4", names1))

df_long <- reshape(df_wide, dir = "long", varying = varying, v.names = v.names, 
     times = locations)[-7]
names(df_long)[2] <- "LOCATION"