Python: The if statement doesn't work... (comparison code in list order)

Asked 2 years ago, Updated 2 years ago, 13 views

Hi, how are you? I am an ordinary person who learns programming as a hobby. I made a code to compare the list of a and b below in order. First, I'm going to compare it to number 5.

The problem with this code is to cross the if door and go straight to else. The program worked contrary to my intentions.

http://www.pythontutor.com/visualize.html#mode=edit

I... I watched the program. It was confirmed that print('2ss') was printed by crossing the if statement and going to else.

K = 0
numS = 0
a = [1,5,6,6,6,1,6,5,1,5,6,7,8,2,7,4,7,2]
b = [1,5,6,6,7,3,6,2,4,6,1,3,5,6,7,2,4,5]
if a[numS:] == b[numS:] :
    print('3ss')


while K < 5 :
    K = K + 1
    numS = numS + 1
    if a[numS:] == b[numS:] :
        print('1ss')  
    else :
        print('2ss')

I would appreciate it if you could give me some advice on how to modify this code.

In my opinion, a[0:] is possible, but not the same expression as a[numS:]... Huh, I don't know. Please give me some advice from the experts.

python

2022-09-22 19:17

1 Answers

a[numS:] means from a[numS] to the end. When numS is 2, [6,6,6,1,6,6,5,1,5,6,7,8,2,7,4,7,2] I guess

If you want to compare each element of the list of a and b in order,

    if a[numS:] == b[numS:] :
        print('1ss')  
    else :
        print('2ss')

Not

    if a[numS] == b[numS] :
        print('1ss')  
    else :
        print('2ss')

I think you should write it as.

Additionally,

K and numS are exactly the same numbers from beginning to end of the code, so you don't need to write two variables personally,

A[0] and b[0] cannot be compared because the variable is +1 before the while loop starts,

Finally, the code is

numS = 0
a = [1,5,6,6,6,1,6,5,1,5,6,7,8,2,7,4,7,2]
b = [1,5,6,6,7,3,6,2,4,6,1,3,5,6,7,2,4,5]
if a[numS:] == b[numS:] :
    print('3ss')

while numS < 5 :
    if a[numS] == b[numS] :
        print('1ss')  
    else :
        print('2ss')
    numS = numS + 1

I think it should be.

(Note: Park Eung-yong - <Jump to Python> Chapter 2 3. List data type )


2022-09-22 19:17

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.