简体   繁体   中英

How to read an item in list which is passed as an argument to a calling function?

I am trying to solve a problem in Hacker Rank and stuck below:

When I am trying to insert values to the list it is working fine, but when I am trying remove an item from the list, even though the value is available in list the code in the if block (if str(value) in list1:) is not getting executed.

I know I am doing some silly mistakes like passing list in a list. but when I try the same code in just a hardcoded list it is working perfectly fine.

Example: Sample input:

12  
insert 0 5  
insert 1 10  
insert 0 6  
print  
remove 6  
append 9  
append 1  
sort  
print  
pop  
reverse  
print  
list1=[]
def performListOperations(command, value=None):
    if command == "insert":
        index, val = value
        print("insert " + str(val) + " at Index "+ index)
        list1.insert(int(index), int(val))
        print(list1)
    elif command == "print":
        print(list1)
    elif command == "remove":
        value = value[0]
        if str(value) in list1:
            print("remove " + str(value) + " from the list:", list1)
            list1.remove(value)
        print("Value " + str(value) + " does not exist in Array: ", list1)
    elif command == "append":
        print("Append", list1)
    else: print("end.. some more code")

if __name__ == '__main__':
    N = int(input())
    for i in range(N):
        print('Which operation do you want to Perform: "insert", "print", "remove", "append","sort","pop","reverse"')
        getcmd, *value = input().split()
        print("Command:", getcmd, *value, value)
        performListOperations(getcmd, value)

You're inserting integers in the list when you do list1.insert(int(index), int(val)) , not strings.

So you need to use if int(value) in list1: and list1.remove(int(value))

There is a type mismatch. The insert is being done using integers, whereas, remove is looking for string type. Hence, '5' is not found in the list as only 5 [int] is available.

Handle in one of the place, according to you convenience.

below code worked


 elif command == "remove":
        value = value[0]
        print(value, list1)
        if int(value) in list1:
            print(value)
            print("remove " + str(value) + " from the list:", list1)
            list1.remove(int(value))
            return print(list1)
        print("Value " + str(value) + " does not exist in Array: ", list1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM