Learning_Python icon indicating copy to clipboard operation
Learning_Python copied to clipboard

The solution seems not to work correctly

Open hiro106 opened this issue 3 years ago • 0 comments

Thank you so much for your making great learning materials. I am relearning Python with PLYMI now.

By the way, the solution of the exercise below seems not to work correctly for me.

https://github.com/rsokl/Learning_Python/blob/64653935e85643b10926edb0e7daa0019219b186/Python/Module2_EssentialsOfPython/ForLoops.md?plain=1#L257-L280

Using the original solution in the page above

The code below outputs 240. (It seems that too many iterations have occurred.)

x = list(range(1, 31))
num_loop = 0
total = 0

while total < 100:
    for item in x:
        if item % 2 == 1:
            num_loop += 1
            # Additional code for checking the process
            print (f"num_loop: {num_loop}, item: {item}, total: {total}")
            continue
        else:
            total += item
            num_loop += 1
            # Additional code for checking the process
            print (f"num_loop: {num_loop}, item: {item}, total: {total}")

    # break from while-loop if
    # more than 50 items tallied
    if 50 < num_loop:
        break
else:
    print(total)

Revising the code

The code below outputs 110. (It seems to have worked correctly.)

The while-for nest seemed not to work correctly (as intended) for me, so I removed the while-loop and added some conditional statements in the for-loop instead. (I don't think this is the best way..., so would like to know more elegant one. )

x = list(range(1, 31))
num_loop = 0
total = 0

for item in x:
    if (100 < total) or (50 < num_loop):
        # Additional code for checking the process
        print (f"num_loop: {num_loop}, item: {item}, total: {total}")
        break
    elif item % 2 == 1:
        num_loop += 1
        # Additional code for checking the process
        print (f"num_loop: {num_loop}, item: {item}, total: {total}")
        continue
    else:
        total += item
        num_loop += 1
        # Additional code for checking the process
        print (f"num_loop: {num_loop}, item: {item}, total: {total}")

print(total)

I'm sorry and please ignore this issue if I am just mistaken.

Thanks,

hiro106 avatar Sep 11 '22 12:09 hiro106