Python Forum
Python for loops giving error
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python for loops giving error
#10
(Jan-08-2019, 12:48 PM)perfringo Wrote: Is the code you provided intended correctly?

It suspect that problem is that you overwriting combination value with every loop iteration and therefore you get only last result.

>>> combinations = list()
>>> for i in range(3):
...     combinations.append([1, 2, 3])
...
>>> combinations
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]
>>> for row in combinations:
...     print(sequence_product(row))
...
6
6
6

I think the problem is when I tried the combinations in new code this does not work.
So what I do now is:
1 step)=> run the code until containing print(combinations), this will give me a result(see solution box above)

2 step )=> Use this code given
 
from functools import reduce
from operator import mul
 
def sequence_productx(combinations):
    """Return sequence elements product; if empty return zero."""
 
    if not combinations:
        return 0
    else:
        return reduce(mul, combinations)
3 step ) =>
sequence_productx(combinations)
sequence_productx(combinations) # this print out 32768

4 step ) = > problem is I don't get answer 96, 128, 192, 13824, 32768.
Reply


Messages In This Thread
Python for loops giving error - by Petrus - Jan-07-2019, 10:01 PM
RE: Python for loops giving error - by xhughesey - Jan-07-2019, 10:18 PM
RE: Python for loops giving error - by Petrus - Jan-07-2019, 10:56 PM
RE: Python for loops giving error - by perfringo - Jan-08-2019, 05:37 AM
RE: Python for loops giving error - by Petrus - Jan-08-2019, 10:23 AM
RE: Python for loops giving error - by Petrus - Jan-08-2019, 11:38 AM
RE: Python for loops giving error - by perfringo - Jan-08-2019, 11:58 AM
RE: Python for loops giving error - by Petrus - Jan-08-2019, 12:29 PM
RE: Python for loops giving error - by perfringo - Jan-08-2019, 12:48 PM
RE: Python for loops giving error - by Petrus - Jan-08-2019, 01:24 PM
RE: Python for loops giving error - by perfringo - Jan-08-2019, 01:48 PM
RE: Python for loops giving error - by Petrus - Jan-08-2019, 02:27 PM
RE: Python for loops giving error - by Petrus - Jan-09-2019, 08:02 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  New to python! Loops Seeley307 3 62,226 May-15-2020, 02:27 PM
Last Post: ibreeden
  Error in loops, new to Python jhall710 20 12,398 Apr-25-2017, 05:18 AM
Last Post: smbx33

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020