Home > Mobile >  How to unpack input in Leetcode
How to unpack input in Leetcode

Time:01-03

I'm a newbie to programming and have solved a few questions in codechef and hackerrank. In those platforms,generally lists or elements in a list/array are given as a string of integers with spaces in them

eg: '5 4 6 7' I can unpack them using an input().split() method in python But in leetcode, I'm given an input of type '[1,2,3,4], target=7' I'm finding it hard to unpack these values from a string into a meaningful datatype. Could someone help me out here? [Context: Two sum problem in leetcode https://leetcode.com/problems/two-sum/]

I tried appending the odd indices of the string into a list

Input: nums = [2,7,11,15], target = 9
a=input()
l=[]
for i in range(len(a)):
    if i%2!=0:
        l.append(a[i])
print(l)

But I got the following output and the following error

Stdout ['2', '7', '1', ',', '5'] Runtime error

TypeError: 'int' object is not iterable
Line 19 in _deserialize (./python3/__deserializer__.py)
    param_1 = des._deserialize(line, 'integer[]')
Line 25 in _driver (Solution.py)
    _driver()
Line 43 in <module> (Solution.py)

CodePudding user response:

I think what you're looking for is .split's sep keyword argument, which allows you to split from any character. This is usually defaulted to " " which is why you don't need to put it in every time. Also as some others mentioned, you don't need to take any inputs, as the function is already taking inputs.

nums = nums[1:-1].split(sep=",")

If you did have to process an input like nums = [2,7,11,15], target = 9 my approach would be:

inp = input() # get input
inp = inp.replace("nums = ", "").replace("target = ", "") # remove the value names
nums, target = inp.split(sep=", ") # unpack items from list: [nums, target]
nums = nums[1:-1].split(sep=", ")

or just condense it down to:

nums, target = input().replace("nums = ", "").replace("target = ", "").split(sep=", ")
nums = nums[1:-1].split(sep=",")
  • Related