内部的python

时间:2018-06-02 17:30:54

标签: python loops

  

你的程序应该读取一个L整数序列,其中每个整数   是N,用空格分隔。 N在[0,99]范围内。 L在范围内   [1,400]。测试样本

     

输入40 40 40 40 29 29 29 29 29 29 29 29 17 17 92 92 92 92 92 86 86   86 86 86 86 86 86 86 86

     

输出4 40 8 29 2 17 5 92 10 86

line = input('Please enter the sequence: ').split()

list = []

for value in line:

    print('\nvalue -', value)

    count = 0

    while value in line:
        if value == '17':
            print('found')

        if line[0] == '17':
            print('is here')

        del line[0]
        count += 1
        print('\ninside value -', value, ' count - ', count)
        print('\n', line)

    list.extend([count, value])
print('\n', list)

这是一个简单的问题,但要注意数字17,如果序列是2或更少的数字,则不计算,如果它至少有3个数字,则通常计算。有人可以解释一下问题是什么吗?我已经多次检查过,无法理解。我已经找到了更好的解决方案,但我仍然想知道上面Python代码中的问题是什么。谢谢!

1 个答案:

答案 0 :(得分:0)

不使用任何库,可以使用(逐步过程):

_input = "40 40 40 40 29 29 29 29 29 29 29 29 17 17 92 92 92 92 92 86 86 86 86 86 86 86 86 86 86"

# transforming the raw values into a list/array
number_array = [int(i) for i in _input.split(' ')]

# returns unique values from input
number_unique = []
for na in number_array:
    if na not in number_unique:
        number_unique.append(na)
    pass

# counts how many times the values appeared on the list, respectively
number_count = []
for n in number_unique:
    number_count.append(number_array.count(n))

# pairing of the count and the unique value
res = []
for nc, nu in zip(number_count, number_unique):
    res.append("{} {}".format(nc, nu))

print(' '.join(res))
# 4 40 8 29 2 17 5 92 10 86
# concatenating using join