+ 1
What's the logic behind it how to we skip odd part ?
Find the sum of all the numbers in the array excluding the odd numbers that occur after an even number Example: 1: Input. [4,2,3, 6] Output: 12 Explanation: Since 3 (odd number) occurs after an even number 2 we are skipping it. Thus 4+2+6=12. 2: Input [3,6,4,8,5,5] Output: 26 Explanation: 5 is skipped since it occurs after an even number.
11 odpowiedzi
+ 5
arr=[3,6,4,8,5,5]
sum = 0
for i in range(len(arr)):
# to skip
if arr[i]%2==1 and arr[i-1]%2==0: continue
# else add to sum
else: sum += arr[i]
print(sum)
#range(len(arr)) returns indexes values 0 to arr.length-1
# continue skips current iteration so that element won't be added to sum. by else part, it adds value to sum..
You loop gives all values . You can find previous value by that approach..
Also add condition i-1>0 so it won't get accessing to arr[-1] which raise error..
Hope it helps..
+ 4
Mustafa A ,
have you compared the result of your code with the mentioned result from Jeya Prakash J ?
what your code is doing: it just sum the odd numbers. but this is not what is requested. read the task description carefully.
+ 4
Jeya Prakash J ,
the condition should be:
if arr[i - 1] % 2 == 0 and arr[i] % 2 !=0:
0
nums[i-1] is the value in previous index and nums[i] is the current value..
nums[i] % 2 returns 0 for even number, 1 for odd number.....
hope this helps to solve it.. ..
0
Lothar Yeah you are right. Wasn't trying to solve it for him. Just to show the concept.
0
arr=[3,6,4,8,5,5]
sum = 0
for i in range(len(arr)):
# to skip
if arr[i]%2==1:
continue
# else add to sum
else:
sum += arr[i]
print(sum)
0
arr=[3,6,4,8,5,5]
sum = 0
for i in range(len(arr)):
# to skip
if arr[i]%2==1:
continue
# else add to sum
else:
sum += arr[i]
print(sum)
Here is your solution
0
arr=[3,6,4,8,5,5]
sum = 0
for i in range(len(arr)):
# to skip
if arr[i]%2==1:
continue
# else add to sum
else:
sum += arr[i]
print(sum)
- 1
sum([num if num % 2 else 0 for num in nums])
- 1
If the number is odd then the modulo operation will leave a remainder. Any number that isn't 0 is considered logically true. Thus the simplified if statement. The number if odd or 0. Then sum it up.
- 1
Jayakrishna🇮🇳 Mustafa A
Can you improve this code
I still don't get
It should only skip the odd number that comes right after the even number and count(sum up with even) the odd the number
https://code.sololearn.com/ckn7e62xjNs2/?ref=app