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
#1
I found the hackerrank.com, where you can solve tasks and use whatever tutorials for this.
There's one problem on Python lists, which seems idiotic and ill-defined:

Quote:Consider a list (list = []). You can perform the following commands:
1. insert i e: Insert integer e at position i.
2. print: Print the list.
3. remove e: Delete the first occurrence of integer e.
4. append e: Insert integer e at the end of the list.
5. sort: Sort the list.
6. pop: Pop the last element from the list.
7. reverse: Reverse the list.

Initialize your list and read in the value of n followed by n lines of commands where each command will be of the 7 types listed above. Iterate through each command in order and perform the corresponding operation on your list.

Input Format

The first line contains an integer, n, denoting the number of commands.
Each line i of the subsequent n lines contains one of the commands described above.

Constraints

The elements added to the list must be integers.

Output Format

For each command of type print, print the list on a new line.

Sample Input 0
12
insert 0 5
insert 1 10
insert 0 6
print
remove 6
append 9
append 1
sort
print
pop
reverse
print

Sample Output 0
Output:
[6, 5, 10] [1, 5, 9, 10] [9, 5, 1]
I wrote the code to match this specific sample input/output0 (with N=12) and it passed.
Upon submitting and running the code on platform's test cases, there was a test case with
N=29, where append and insert were basically repeated a few more times to
get the total 29 number of commands with different integers.
There are no indications on how these integers to populate the list should be chosen.
My non-working solution would be:

if __name__ == '__main__':
    import random, sys
    N = int(input())
    print(N)
    arr = []
    e = random.randint(0, sys.maxsize)
    for i in range(1,N+1):
         random.choice([arr.insert(i, e), print(arr), arr.remove(e), arr.append(e), arr.sort(), arr.pop(), arr.reverse()])
as using or keyword doesn't select any one of the 7 commands (or other objects), but selects only the first one preceding the keyword.

If "everything in Python is an object", why is it not possible to pass the return objects of function calls as arguments for another function (i.e. random.choice or list())?
Is there a solution, using only list operations and some loops, for this idiotic task?
Reply
#2
This problem is far from idiotic, it asks you to read, parse and run a small programming language.
anata2047 Wrote:There are no indications on how these integers to populate the list should be chosen.
I think the commands should be read in a file or in the standard input. I give you the beginning of a program where the commands are read in a memory file (StringIO). You can replace the file with sys.stdin if you prefer to read from standard input
import io, sys


file = io.StringIO('''\
12
insert 0 5
insert 1 10
insert 0 6
print
remove 6
append 9
append 1
sort
print
pop
reverse
print
''')

for line in file:
    print(line.split())
Output:
['12'] ['insert', '0', '5'] ['insert', '1', '10'] ['insert', '0', '6'] ['print'] ['remove', '6'] ['append', '9'] ['append', '1'] ['sort'] ['print'] ['pop'] ['reverse'] ['print']
The next step for your program is to understand the commands in the "for" loop and execute an action for each line read.
Reply
#3
I see. The tutorial on HackerRank mentions only a set of operations on lists, and no imports of any other modules.
Still why do assigning the output of any arr.insert(i, e), arr.remove(e), arr.append(e), arr.sort(), arr.pop(), arr.reverse() to a new variable gives the type None, instead of a copy of a modified arr list with the name of that variable?
Reply
#4
Inserting an element in a list modifies the list in place. It does not create a new list and the insert() method returns None.
>>> L = [10, 3, 47, 8, 9, 6]
>>> L.insert(2, 222)
>>> L
[10, 3, 222, 47, 8, 9, 6]
 
So insert() is a «procedure», a function that performs some action but does not return anything interesting.

See the Python tutorial for help about lists.
anata2047 Wrote:The tutorial on HackerRank mentions only a set of operations on lists, and no imports of any other modules.
A way to read from standard input without importing any module is through the input() function. That being said, using a memory file is convenient in the developing phase of a program.
Reply
#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


Forum Jump:

User Panel Messages

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