Multiply and Addition in the same loop statement with logic. - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Multiply and Addition in the same loop statement with logic. (/thread-39325.html) |
Multiply and Addition in the same loop statement with logic. - joelraj - Jan-31-2023 Hi Python Community, Greetings to you all ! After the if statement is passed through Reven and Rodd have to take two alternative indexes: one has to do multiply, and another has to do add. like example, wriiten code def AddMult(A): Reven = 0 Rodd = 0 for i in range(len(A)): if i % 2 == 0: Reven = Reven + A[i] else: Rodd = Rodd + A[i] E = (Reven%2) O = (Rodd%2) if(O > E): return "ODD" elif(E > O): return "EVEN" elif(O == E): return "NEUTRAL"Could you please help me solve this? RE: Multiply and Addition in the same loop statement with logic. - tester_V - Jan-31-2023 Buddy, use the 'insert Python' button to post your snipped. RE: Multiply and Addition in the same loop statement with logic. - deanhystad - Feb-02-2023 Which is it? Reven = ((((A[0]*A[2])+A[4])*A[6])+A[8])Reven = (0 * 2 + 4) * 6 + 8 = 32 0 +2 2 *4 8 +6 14 *8Reven = ((0 + 2) * 4 + 6) * 8 = 112 When solving something like this I perform the operation by hand and look for a pattern. values = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) result = [0, 0] # result for even, odd The index for result[index] has a period 2 cycle: 0, 1The operator has a period 4 cycle: +, +, *, * Using that information I might write the function like this: from operator import add, mul def add_mul(numbers): result = [0, 0] for i, number in enumerate(numbers): result[i % 2] = (add, add, mul, mul)[i % 4](result[i % 2], number) return resultI don't quite understand the even/odd evaluation at the end, but this code: E = (Reven%2) O = (Rodd%2) if(O > E): return "ODD" elif(E > O): return "EVEN" elif(O == E): return "NEUTRAL"Can be written like this: even, odd = (result % 2 for result in add_mul(range(10))) print("NEUTRAL" if (even == odd) else "EVEN" if even else "ODD")In Python, 0 is falsey and 1 is truey. If you know the only possible values are 0 and 1 you don't need to do comparisons like E > O. And about using "O" as a variable. Don't do it. Capital o looks like zero, just like lower case L looks like one. Avoid using either to avoid any confusion. |