-2
list = [1,1,4,4,4,0,1]
    new_list = []
    sum_ = 0
    for number in list:
        if number == number+1:
            sum_ += number
        else: 
            sum_ += number
            new_list.append(sum_)
print(new_list)

Output => [1, 2, 6, 10, 14, 14, 15]

Expected => [2, 12, 0, 1]

  • Maybe [`itertools.groupby`](https://docs.python.org/3/library/itertools.html#itertools.groupby) is what you're looking for? Please add more details to the question. Explain to us in the question what you're trying to do, how it is not doing that, and what you want the end-result to look like. – Hampus Larsson Jul 26 '21 at 18:40
  • First of all, `if number == number+1` will never be `True`, and secondly, in the `else` branch your are always updating the `sum_`, instead of resetting it to zero. – Akhaim Jul 26 '21 at 18:51
  • @HampusLarsson Regarding the end result I wrote what I am expecting, I want it to be [2, 12, 0, 1] – Hamza Tanya Jul 26 '21 at 18:59
  • @HamzaTanya Please ASK A QUESTION inside of the question block instead of just posting a block of code. Explain, using your words, what part of the code you're struggling with, explain why you think your logic should be `True` to what you want, so that we know what part we need to help explain to you. Please read the help-page [ask]. – Hampus Larsson Jul 26 '21 at 19:00

2 Answers2

0

Check this code:

my_list = [1,1,4,4,4,0,1]
my_sum = my_list[0]
my_results = []
    
for i in range(1, len(my_list)):
    if my_list[i] == my_list[i-1]:
        my_sum += my_list[i]
    else:
        my_results.append(my_sum)
        my_sum = my_list[i]
else:
    my_results.append(my_sum)

I first initialize my_sum to the first element of the list, and then I sweep over the remaining elements of the list, always comparing adjacent elements for equality. If they are equal, my_sum us updated, and if they are not equal my_sum is first stored to the output list my_results and then reinitialized to a new number from the original list.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Akhaim
  • 122
  • 7
0

The code counts the number of consecutive identical numbers and multiplies these numbers by their number

numbers = [1, 1, 4, 4, 4, 0, 1]
hook, cnt, out = numbers[0], 0, []
for i in numbers:
    if i == hook:
        cnt += 1
    else:
        out.append(hook * cnt)
        hook, cnt = i, 1
out.append(hook * cnt)
print(out)  # [2, 12, 0, 1]
Алексей Р
  • 7,507
  • 2
  • 7
  • 18