行程编码项目未输出

时间:2018-11-10 11:14:25

标签: python string output

def expand(nums):
    finalword = ''
    position = 0
    wordlength = len(nums)
    keypoint = ''
    while position <= wordlength:
        keypoint = nums[position] * int(nums[position + 1])
        finalword = finalword + keypoint
        keypoint = 0
        position + 2
    return finalword

由于某些原因,此函数不返回值。我正在尝试将char后面的整数乘以char。由于在每个第二个索引上都有一个字符,因此我在位置上添加了2个

print(expand("d3o5z2y1")) #should output: dddooooozzy

我在做什么错了?

2 个答案:

答案 0 :(得分:2)

您的行:

position + 2

更改 position的值。计算position + 2,然后丢掉该值,应将结果分配给位置,因此:

def expand(nums):
    finalword = ''
    position = 0
    wordlength = len(nums)
    keypoint = ''
    while position < wordlength:
        keypoint = nums[position] * int(nums[position + 1])
        finalword = finalword + keypoint
        keypoint = 0
        position = position + 2  # or more compact: position += 2
    return finalword

边界检查应该用<替换,因为如果位置等于长度,则我们已经有一个太大的索引。

很多行也是不必要的,我们可以删除很多行并保留:

def expand(nums):
    finalword = ''
    wordlength = len(nums)
    for position in range(0, len(nums), 2):
        keypoint = nums[position] * int(nums[position + 1])
        finalword += keypoint
    return finalword

话虽如此,您可以使用iter(..)运算符和zip来改善上述情况:

def expand(nums):
    inums = iter(nums)
    return ''.join(c * int(n) for c, n in zip(inums, inums))

答案 1 :(得分:2)

您永远不会更新position

position + 2仅在不将计算值存储在任何地方的情况下进行计算。您可能想要position = position + 2

此外,您与position <= wordlength格格不入,因为nums的最后一个索引是len(nums) - 1。将其更改为position < wordlength

有了这些更改

print(expand("d3o5z2y1"))

产生

'dddooooozzy'

但是,您提取字符和计数的方式有些笨拙。我建议使用grouper文档中的itertools recipe

>>> s = "d3o5z2y1"
>>> list(zip(*[iter(s)]*2))
>>> [('d', '3'), ('o', '5'), ('z', '2'), ('y', '1')]
>>>
>>> ''.join(char*int(count) for char, count in zip(*[iter(s)]*2))
>>> 'dddooooozzy'