I know it sounds like a duplicate question- I know because I've clicked on like 10 SO posts labeled the same thing, but hear me out.
I have a function like below
class Solution:
def confusingNumberII(self, N: int) -> int:
valid = {0: 0, 1: 1, 6: 9, 8: 8, 9: 6}
count = [0]
def dfs(n, rotate, digit):
if n != rotate:
count[0] =1
for num in valid:
cur = n * 10 num
if cur > N: return
dfs(cur, valid[num] * digit rotate, digit * 10)
for num in valid:
if num != 0:
dfs(num, valid[num], 10)
return count[0]
And I feel like setting a len-1-list to keep track of count which will be incremented in dfs
is bad practice.
What I've tried:
- I've read like 10 different stackoverflow posts that say "just declare
global
variableName in the function that will update it" but it seems to be a past-time solution. I get an error that saysunsupported operand type(s) for : 'type' and 'int'
- I've also read a post that says I should increment count = 0 not by
count =1
but bycount = count 1
. This doesn't work either and throws the same error. - I've also tried passing count in as a variable to update it- it doesn't do anything and the entire function ends up returning 0.
Is there a clean way of updating a single int
variable? I really feel like it shouldn't be this clunky to update a variable.
CodePudding user response:
You can avoid the global variable by letting dfs
calculate the count for its own given input only, and return that. The caller is then responsible of accumulating the counts that are returned from the recursive calls:
class Solution:
def confusingNumberII(self, N: int) -> int:
valid = {0: 0, 1: 1, 6: 9, 8: 8, 9: 6}
def dfs(n, rotate, digit):
count = int(n != rotate)
for num in valid:
cur = n * 10 num
if cur > N:
break
count = dfs(cur, valid[num] * digit rotate, digit * 10)
return count
count = 0
for num in valid:
if num != 0:
count = dfs(num, valid[num], 10)
return count
For what it's worth, you can rewrite the above code in a more function programming style, like this:
from itertools import takewhile
class Solution:
def confusingNumberII(self, N: int) -> int:
valid = {0: 0, 1: 1, 6: 9, 8: 8, 9: 6}
def dfs(n, rotate, digit):
return int(n != rotate) sum(
dfs(n * 10 num, valid[num] * digit rotate, digit * 10)
for num in takewhile(lambda num: n * 10 num <= N, valid)
)
return sum(
dfs(num, valid[num], 10)
for num in valid
if num != 0
)
CodePudding user response:
I agree with the @trincot answer. Though, there is one thing I want to add: there is always a way to avoid global variables being used inside functions. Even in the recursive functions. So avoid them as much as you can, since they make your code less flexible and harder to maintain.