This has not much to do with dynamic programming itself.
n, S = map(int, input().split())
will query the user for input, and then split it into words, convert these words in integers, and unpack it into two variables n and S. This thus will succeed when the user enters two numbers (not more, not less).
It works as follows:
input()will query the user for input, and read one line of user input;.split()will split that input into a list of "words";map(int, ...)will callinton each word, it will to that lazily (although that is not important here); andn, S = ...will unpack the expression into two elements, and assign the first one tonand the second one toS.
For example:
>>> n, S = map(int, input().split())
14 25
>>> n
14
>>> S
25
But it will error if you pass only one number, three numbers, etc. like:
>>> n, S = map(int, input().split())
14
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: not enough values to unpack (expected 2, got 1)
>>> n, S = map(int, input().split())
14 25 37
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 2)
>>> n, S = map(int, input().split())
foo bar
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'foo'
The line:
w = list(map(int, input().split()))
does more or less the same thing, but instead takes as input from the user a sequence of numbers. There can be zero, one or more numbers. w will store a list of numbers. The list(..) part forces Python to evaluate the map(..) eagerly.
dp = [0] * (S + 1)
Here we will construct a list with S + 1 zeros. In Python, you can multiply a list (and tuple) with an integer n. The result is a list (or tuple) that is n times as large as the original list, and it repeats the elements. For example:
>>> [1,4,2,5] * 3
[1, 4, 2, 5, 1, 4, 2, 5, 1, 4, 2, 5]
Since here the given list contains one zero, it will thus produce a list that contains S+1 zeros.
Finally
dp[0] = 0
will set the first element to zero. But since that was already the case, this line is not very useful.
Answer from willeM_ Van Onsem on Stack OverflowWhat does list(map(int,input().split())) do in python? Can please anyone explain what this line does.
I am creating a dynamic array using the following code: (PYTHON 3)
arr = map(int, input().split()) print(arr)
I am actually trying to print the array. But the print statement is returning a value as:
<map object at 0x00000265D78A4400>
I want to print the array and also access each element separately. How can I implement that ?
I am a new python learner need some help....
Thank you
You don't create an array this way, you create an object that will provide you the objects once you iterate over them. Meaning as in a for loop
for v in arr:
do something with v
or when you would create another sequence from it, like with list()
my_list = list(arr)
the point is that with a list you create a structure in RAM that will hold all the items upfront, which is often not what you actually need per se, so map allows you to simply define what you want (that takes no CPU or extra storage space) and only performs the actions when needed. If you do you need this as a list then a comprehension is preferable over map:
mylist = [int(n) for n in input.split()]
Sidenote: Python doesn't have a regular 'array', it has lists for ordered sequences that can be indexed. It does have specialized array for numerical values of a specific type but that's more oriented for low-level applications or for interfacing to other systems that need those kind of statically typed arrays.
Python has acquired a lot of "lazy" functions that don't fully evaluate everything until you need them. This can save memory and time, but you have to understand what is happening. map() is one of those functions that return a lazy object. To get a list that you can play with, do this:
arr = map(int, input().split())
print(list(arr))
Use input() in Python 3. raw_input has been renamed to input in Python 3 . And map now returns an iterator instead of list.
score = [int(x) for x in input().split()]
or :
score = list(map(int, input().split()))
As a general rule, you can use the 2to3 tool that ships with Python to at least point you in the right direction as far as porting goes:
$ echo "score = map(int, raw_input().split())" | 2to3 - 2>/dev/null
--- <stdin> (original)
+++ <stdin> (refactored)
@@ -1,1 +1,1 @@
-score = map(int, raw_input().split())
+score = list(map(int, input().split()))
The output isn't necessarily idiomatic (a list comprehension would make more sense here), but it will provide a decent starting point.
- map(function, iterable) Return an iterator that applies function to every item of iterable, yielding the results.
- int(x) Return an integer object constructed from a number or string x.
Therefore, it will return an iterable where it applied the int() function to each substring from .split(), meaning it casts every substring to int.
Example:
arr = map(int, "12 34 56".split())
arr = list(arr) # to convert the iterable to a list
print(arr) # prints: [12, 34, 56]
# This is equivalent:
arr = [int("12"), int("34"), int("56")]
Other example with custom function instead of int():
def increment(x):
return x + 1
arr = map(increment, [1, 2, 3, 4, 5])
arr = list(arr)
print(arr) # prints: [2, 3, 4, 5, 6]
Let's say I type 5 and then enter at the first prompt:
n = int(input())
Would take the input "5" and make it into the integer 5. So we are going from a string to an int
Then we will get another input prompt because we have input() again in the next line:
This time I'll type 123 324 541 123 134 and then enter.
the .split() will split this into "123", "324", "541", "123", "134" which is a list (well a map) of strings. Then we'll map int onto them to give ourselves a map of ints rather than strings. int converts the strings to integers.
When checking out code it is often helpful to try things in a REPL (read execute print, looper). In your command promt just type python or python3 if you have it installed or use replt.it. Type a = "123" + "321" then try `a = int("123") + int("321")
Wrap this with list(map(int, input().split())) to get a list rather than a map.
In python 3.x
list(map(int, input().split()))
In python 2.x
map(int, raw_input().split())
x = [int(part) for part in input().split()]
In 2.x, use raw_input() instead of input() - this is because in Python 2.x, input() parses the user's input as Python code, which is dangerous and slow. raw_input() just gives you the string. In 3.x, they changed input() to work that way as it is what you generally want.
This is a simple list comprehension that takes the split components of the input (using str.split(), which splits on whitespace) and makes each component an integer.
The question about whether you would like to store the data as a dict or a list of tuples depends on whether you want the user to overwrite existing values or not. If you store the values in a dict, the input of
id 1230
hi 16
id 99
will produce a dictionary like {"id": 99, "hi":16} because the second input id overwrites the first. A list of tuples approach would produce [("id", 1230), ("hi", 16), ("id", 90)].
How to parse the values has already been suggested by other people, but for completion I will add it to my answer as well.
Dict approach
d = dict()
var = input('Enter input: ')
key, value = var.split()
d[key] = int(value)
List approach
L = list()
var = input('Enter input: ')
key, value = var.split()
L.append((key, int(value)))
You do not need map here. You can use str.split to split by whitespace and then create a dictionary explicitly:
var = input('Enter input: ') # 'id 1230'
key, value = var.split()
d = {key: int(value)} # {'id': 1230}
You can add some checks to ensure the format is input correctly before proceeding with creating the dictionary:
while True:
try:
var = input('Enter input: ') # 'id 1230'
key, value = var.split()
d = {key: int(value)} # {'id': 1230}
break
except ValueError:
print('Incorrect format supplied, type "id 1230" expected. Please try again.')