将一串数字作为单词读取,然后将每个单词打印为数字

时间:2012-01-23 00:06:57

标签: python

我正在试图弄清楚如何编写一个从0输入任何正整数的代码,当输入0时返回0的字符串,输入1时返回10,当2输入时返回1110输入时输入3110,输入3时输入等等,这就是说当输入0时发生输出为0,然后当输入1时,它将输入视为0并将其读作“一个零”并打印10,为2将输入1读作“一个零和一个零”并打印1110,依此类推。我知道该怎么做但是转换成代码太模糊了。当我发布这个我不知道它叫什么但从那时起我发现它是外观和看到序列,我的问题是我不能使用迭代,我也不能使用内置的len()或string.append()函数。

2 个答案:

答案 0 :(得分:3)

如果你不能使用任何迭代,那么你需要在0处停止使用递归。它看起来像这样:

def whatever(input):
    """
    >>> whatever(0)
    '0'
    >>> whatever(1)
    '10'
    >>> whatever(2)
    '1110'
    >>> whatever(3)
    '3110'
    >>> whatever(4)
    '132110'
    >>> whatever(5)
    '1113122110'
    """
    def looksay(input, result):
        if not input:
            return result
        else:
            left, right = input[0], input[1:]
            if not result:
                result = '1' + left
            else:
                left_result, count, right_result = result[:-2], int(result[-2]), result[-1]
                if left == right_result:
                    result = left_result + str(count + 1) + right_result
                else:
                    result = result + '1' + left
            return looksay(right, result)
    def helper(number, result):
        if number == 0:
            return result
        else:
            return helper(number - 1, looksay(result, ''))
    return helper(input, '0')

if __name__ == '__main__':
    import doctest
    doctest.testmod()

答案 1 :(得分:1)

好的,我想我想出了你打算在这里做什么。这是一个可能的解决方案:

import collections

def string(n):
    if n == 0:
        return '0'
    # We're going to count the digits in the previous number
    previous = string(n - 1)

    # This creates a dictionary with the number of occurences of each digit
    current = collections.Counter(previous)

    # Now format it as desired:
    return ''.join(['{}{}'.format(c, d)
                    for d, c in sorted(current.items(), reverse=True)])

print(string(4))
# prints 132110

@DSM,正确地指出下面有另一种解释,按顺序读出前一个数字的数字。这是一种方法:

def string(n):
    if n == 0:
        return '0'

    result = []
    # We're going to iterate over the previous number's digits.
    # The loop will transform '3110' to ['3', '11', '0'].
    for digit in string(n - 1):
        # If it's the first char, just add it to the list
        if not result:
            result.append(digit)
        # If the current digit is the same as the last one, add it to the 
        # last element of the list
        elif digit == result[-1][0]:
            result[-1] += digit
        # If it's a different digit, add it to the end of the list.
        else:
            result.append(digit)

    # Now format the resulting list and return it.
    return ''.join(['{}{}'.format(len(digits), digits[0])
                    for digits in result])

print(string(4))
# prints 132110