educative.io

Iteration can be avoided

In the DP initialization for a handful of problems, there is an initialization loop, which is not required:

  # with only one number, we can form a subset only when the required sum is equal to the number
  for s in range(1, sum+1):
    dp[s] = 1 if num[0] == s else 0

Instead one could use a simple conditional assignment as below:

if num[0] <= sum:
  dp[num[0]] = 1