Python Forum
An idiotic problem on Python lists on HackerRank
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
An idiotic problem on Python lists on HackerRank
#5
In Python are many objects, which allows modification of it's content and None is returned.

For example, the built-in functions sorted and reversed takes an iterable and return a list.
The methods insert, sort, reverse, append, extend of a list do a modification of the list in-place and None is returned. After the use of one of these methods, the list is changed.


This is not a solution, just a good use-case for the new structural pattern matching syntax which was introduced with Python 3.10. Ignore this if you are stuck on Python 3.9 and/or if not enough basics are known yet. Argument unpacking, for example, is much more important for the beginning.

        match cmd:
            # if cmd == "insert"
            case "insert":
                data.insert(*args)
            case "print":
                print(data)
            case "remove":
                data.remove(args[0])
            case "append":
                data.append(args[0])
            case "sort":
                data.sort()
            case "reverse":
                data.reverse()
            case "pop":
                data.pop()
            case _:
                raise ValueError(f"Illegal command: {cmd}")

Before you start with this, I think argument (un)packing is more important to know: https://towardsdatascience.com/a-guide-t...3095dda89b

For example, I used this, to have the command assigned to cmd and the rest assigned to args.
line = "insert 5 6"
cmd, *args = line.split() # splits the line -> list with str
# the type of args is always a list, because of the * in front of args
# then args will take all remaining elements from the iterable on the right side of the =

print(cmd)
print(args)
Quote:insert
['5', '6']

PS: Of course, you can also split the line without using unpacking. Then you have one list, where at index 0 should always be the command.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Messages In This Thread
RE: An idiotic problem on Python lists on HackerRank - by DeaD_EyE - Jun-16-2022, 12:12 PM

Forum Jump:

User Panel Messages

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