我在
Glassdoor发现了这个问题:
Generate a new array from an array of numbers. Start from the beginning. Put the number of some number first, and then that number. For example, from array 1, 1, 2, 3, 3, 1 You should get 2, 1, 1, 2, 2, 3, 1, 1 Write a program to solve this problem.
我不确定我是否明白了,为什么1,1,3,3,3,1变成2,1,1,2,2,3,1,1?我首先想到的是它们是一个数字的出现次数,后跟数字本身.但从给定的例子来看,似乎还有其他东西需要.
这种转变是什么?
最佳答案
I first thought they are number of occurrences of a number followed by the number itself.
你的第一个想法是正确的.
将第一个数组分解为:
1, 1,
2,
3, 3,
1
第二个是:
2, 1,
1, 2,
2, 3,
1, 1
那应该更有意义.
示例实施:
#!/usr/bin/env python
import sys
array = map(int, sys.argv[1:])
print array
count = 0
current = array[0]
index = 1
output = []
for number in array:
if current != number:
output.append(count)
output.append(current)
current = number
count = 0
count += 1
output.append(count)
output.append(current)
print output
演示:
> ./arrays.py 1 1 2 3 3 1
[1, 1, 2, 3, 3, 1]
[2, 1, 1, 2, 2, 3, 1, 1]