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 :: how to see if something is in a class in python 
Python :: asyncio RuntimeError: Event loop is closed 
Python :: python extract words from string with format 
Python :: python which packages depend on package 
Python :: i have installed python modules but pycharm cannot run 
Python :: run exe for python and wait until finish 
Python :: flask lazy response style with `make_response` 
Python :: run all jupyter notebooks in project folder 
Python :: How to make bot commands case insensitive in discord.py 
Python :: check check writability of the file 
Python :: micropython free space esp32 esp2866 
Python :: iris data pandas scatterplot 
Python :: tb to pb with python calculator 
Python :: num = [7,8, 120, 25, 44, 20, 27] newnum = [] def remove_even(num): for i in num: if i%2 != 0: newnum.append(i) return newnum print("get_unevens") test(remove_even(num), [7,25,27]) 
Python :: python zip function 
Python :: divide array into equal parts/slices python 
Python :: how to set conditionlally keys in python 
Python :: python lane angle detection 
Python :: rolling call on one column and groupby second pandas 
Python :: how to make an app like word in python 
Python :: ternary operator using dictionary in Python 
Python :: least square fit straight line python 
Python :: how to loadh5 file in python 
Python :: where are spacy models stored 
Python :: get value of a list of dictionary matching key 
Python :: python loop list backwards 
Python :: how to comment in python 
Python :: age calculator python 
Python :: python label 
Python :: how to plot using pyplot 
ADD CONTENT
Topic
Content
Source link
Name
3+4 =