Reputation: 59
I need a loop to multiply part of a list. I have multiply every Nth element (except 0th) by M. The list is called numbers, the multiplier is M, and the loop should start multiplying at the Nth number. This is what I have:
for i in range(0, len(numbers)):
numbers[i]= int(numbers[i])
for M in range (N, len(numbers)):
if numbers[N] > 0:
numbers.append[N]
if numbers[N] < 0:
total = numbers
print (total)
It keeps returning the wrong output, I've tried everything I can think of to fix it but it still won't work.
Upvotes: 1
Views: 1879
Reputation: 82899
There a quite a few problems and oddities in your code:
M
as the loop variable, thus overwriting the multiplier stored in M
; better use i
as in your first loopnumbers[i] = numbers[i] * M
or just numbers[i] *= M
> 0
and < 0
checks relate to your question, but you should probably check numbers[i]
instead of numbers[N]
, the letter being always the samenumbers
list (instead of e.g. just numbers[i]
to total
and print it...You could also use a list comprehension and assign back to a slice of the original list:
>>> N, M = 3, 10
>>> numbers = list(range(10))
>>> numbers[N::N] = [x*M for x in numbers[N::N]]
>>> numbers
[0, 1, 2, 30, 4, 5, 60, 7, 8, 90]
Upvotes: 1
Reputation: 29307
With map
:
map(lambda (i, el): el*M if i%N==0 else el, enumerate(numbers))
Skipping the first index:
map(lambda (i, el): el*M if i%N==0 and i>0 else el, enumerate(numbers))
Upvotes: 0
Reputation: 126
numbers = [int(n) for n in numbers]
this is for the first function. It's called a list comprehension The second one you got M
and N
mixed up i guess. What is N
anyways?
Upvotes: 0
Reputation: 476574
You usually multiply a number with the asterisk (*
). So we can multiply the i
-th number with:
numbers[i] *= M
To multiply every N
-th element except the first one, we can construct a range:
for i in range(N, len(numbers), N):
numbers[i] *= M
The last argument of the range
is the step
, it means that we thus each time increment i
, until reach len(numbers)
Upvotes: 2