Skip to content

Instantly share code, notes, and snippets.

@PabloLION
Created March 1, 2023 06:20
Show Gist options
  • Save PabloLION/6b6171939d6917b6e766dc2fe8e17590 to your computer and use it in GitHub Desktop.
Save PabloLION/6b6171939d6917b6e766dc2fe8e17590 to your computer and use it in GitHub Desktop.
Refactor python double while True loop
def foo(a,b):
pass
def edit_d(a):
pass
l = 0
d= {}
# before refactor
while d:
while True:
for k in d:
bar = foo(k,l)
if bar:
break
else:
l += 1
break # if no valid bar, break while True
edit_d(bar)
# after refactor
while d:
for k in d:
bar = foo(k,l)
if bar:
edit_d(bar)
break
else:
l += 1
@PabloLION
Copy link
Author

PabloLION commented Mar 1, 2023

Not sure if this can be further improved. (PEP about labeling loops is rejected here https://peps.python.org/pep-3136/)
I found this pattern during while solving leetcode 854.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment