0

So I'm solving this problem right now: https://www.codewars.com/kata/5279f6fe5ab7f447890006a7/train/python

But essentially my only problem is, that while looping through the data I want to add the string(Index) of '10' as a value to the key 'pos', but as you can see it adds '1','0' instead of '10'.

Same would happen if I'd for example change the value 6 in the array to 12 -> it would '1','2' not 12.

Can anybody tell me how to fix this?

def pick_peaks(data):
    answer = {'pos': [], 'peaks': []}
    
    for index, value in enumerate(data):
        
        if index == 0 or index == len(data)-1:
            pass
        
        elif data[index-1] < value and data[index+1] < value:
            answer['pos'] += str(index)
            answer['peaks'] += str(data[index])
                
        elif data[index] > data[index-1] and max(data[index:]) == data[index]:
            answer['pos'] += str(index)
            answer['peaks'] += str(data[index])
                
    return answer

print(pick_peaks([8, 2, 3, 6, 4, 1, 2, 3, 2, 1, 2, 2, 2, 1]))

Output: {'pos': ['3', '7', '1', '0'], 'peaks': ['6', '3', '2']}
  • Similar question: [Inserting a string into a list without getting split into characters](https://stackoverflow.com/q/8243188/4518341) – wjandrea Jul 02 '20 at 15:06

1 Answers1

0

+= is the same as list.extend, which means the string is treated as an iterable, and each character is added to the list. You meant to use list.append:

answer['pos'].append(str(index))
answer['peaks'].append(str(data[index]))

Or maybe you meant to do += [], but list.append is a better fit.

See documentation: Mutable Sequence Types


Also note that that Codewars challenge expects lists of ints, not strings, and if you try to extend a list with an int, you get an error:

>>> [].extend(0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
wjandrea
  • 28,235
  • 9
  • 60
  • 81