Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

dictionary changed size during iteration

# to avoid this problem, make a copy of keys:
for i in list(d)

# Can also solve this problem here: 
# https://leetcode.com/problems/binary-trees-with-factors/

arr = [2,4,5,10]
dp = collections.defaultdict(int)

# this would create error since dp[x/i] is creating a new key with x/i
# thus dictionary changed size during iteration
# to solve this problem, dp.copy() can be used but with time complexity O(n^2)
for x in sorted(arr):
    dp[x] = sum(dp[i]*dp[x/i] for i in dp if x % i == 0) + 1
return sum(dp.values()) % (10**9 + 7)

# use `get` since it just query the dictionay without creating a new key
# time complexity: O(n)
for x in sorted(arr):
	dp[x] = sum(dp[i] * dp.get(x / i, 0) for i in dp if x % i == 0) + 1
return sum(dp.values()) % (10**9 + 7)
Comment

PREVIOUS NEXT
Code Example
Python :: python compare each item of one list 
Python :: ipython history 
Python :: seaborn modificar o tamanho dos graficos 
Python :: count number of objects django template 
Python :: create python package 
Python :: python sort comparator 
Python :: messages in django 
Python :: Python Split list into chunks using for loop 
Python :: python indentation 
Python :: from pandas to dictionary 
Python :: beautifulsoup get h1 
Python :: inpuit inf terfminal ppython 
Python :: stack program in python3 
Python :: include in flask 
Python :: python qr decomposition 
Python :: phyton 2.7 convert timedelta to string 
Python :: pandas make dataframe from few colums 
Python :: minmaxscaler transform 
Python :: python if not 
Python :: cholesky decomposition in python 
Python :: python does string contain space 
Python :: python generate dictionary in loop 
Python :: how to download file using python using progress bar 
Python :: how to delete record in django 
Python :: check if key exists in sesson python flask 
Python :: how to replace string in python 
Python :: python string to tuple 
Python :: python counter 
Python :: python check if included in list 
Python :: strip() 
ADD CONTENT
Topic
Content
Source link
Name
4+3 =