I was trying to speed up some nested for loops with multiple internal loops in python 3.11:
for item1 in iterable1:
for item2 in interable2:
if condition == true:
expression1
for item3 in interable3:
if condition2 == true:
expression2
# my code:
'''mustConstraint = set()
notConstraint = set()
violated = 0
satisfied = 0
for i in range(0, int(input(''))):
constraint = input('')
mustConstraint.add(frozenset(constraint.split()))
for i in range(0, int(input(''))):
constraint = input('')
notConstraint.add(frozenset(constraint.split()))'''
for i in range(0, int(input(''))): # this code block is the main foucs
group = input('')
group = set(group.split())
for x in mustConstraint:
if x & group == x:
satisfied +=1
for y in notConstraint:
if y & group == y:
violated += 1
'''violated += len(mustConstraint) - satisfied
print(violated)'''
Note that the 2nd and 3rd for loops are at the same level and NOT nested, unlike This Question
I learned that list comprehension and the map()
function is usually much faster than for
loops Here, and I’m trying to convert my nested loops into map()
function(s).
Can someone please explain how to construct such map()
functions and/or list comprehensions?
I thought I would do some research – their would surely be a answer for such a problem on the internet, but left empty handed. some resources used include:
Convert a nested for loop to a map equivalent
List comprehension in Python, how to
https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions & https://docs.python.org/3/tutorial/datastructures.html#nested-list-comprehensions
https://www.programiz.com/python-programming/list-comprehension
https://docs.python.org/3/tutorial/datastructures.html#looping-techniques
F-22 Destroyer is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.