Python double for loop over finite iterable running indefinitely [duplicate] - python

This question already has answers here:
How to get all possible combinations of a list’s elements?
(32 answers)
How to calculate a Cartesian product of a list with itself [duplicate]
(2 answers)
Closed 2 years ago.
In my code below, 'single' refers to a finite list. I then need to get all possible pairs from this list; however, the program didn't finish executing.
After messing around with some print statements, for some reason, despite 'single' having a finite number of elements (13122; I checked with len()) the for loop was running forever, until I but a break statement in which forcibly ends the loop when the index gets too high. Initially I thought this was because I was referencing over 'single' twice; however, even when I replaced 'single' with copy.deepcopy(single), the same problem occurred, and my fix no longer worked.
If it is of any help, the elements of 'single' are themselves lists.
'''
for index1, i in enumerate(single):
for index2, j in enumerate(single):
return_list.append([i,j])
if (index1 > length):
break
'''

By iterating through the list twice, you are having to append to that return_list 13122*13122=172186884 times. That will take ages, there are much better and more performant ways of calculating that list if that is really what you want to do (will take up an enormous amount of memory).
Take a look at itertools.combinations.
list(itertools.combinations(single, 2))

Related

Can I use values from an array to complete an if statement? [duplicate]

This question already has answers here:
How do I do a case-insensitive string comparison?
(15 answers)
Closed last year.
import time
while True:
npc=input("Josuke\n\nJotaro Kujo (Part 4)\n\nChoose NPC to talk to.")
if npc=="Josuke" or npc=="josuke":
confirm=input("[Press E to interact.]")
elif npc=="jp4" or npc=="JP4" or npc=="Jp4
Within this code you can see that there are 2 NPCs to interact to. Because there are many ways of addressing the name Jotaro Kujo (Part 4), the if statement has many "or"s, but I want to be able to condense it. Could I use an array to be able to put the possibilities in and then have the if statement identify if the value is within the array? (I haven't completed the code yet, but the problem doesn't require the full code to be completed.)
Yes, you can do it easily using the in operator to check if a particular string is in the list.
as an example:
lst = ["bemwa", "mike", "charles"]
if "bemwa" in lst:
print("found")
And if all the possibilities you want to cover are related to case-insensitivity you can simply convert the input to lower-case or upper-case and compare it with only one possibility.

order of evaluation of boolean expression in python [duplicate]

This question already has answers here:
Python. Will TWO condition checked, If `ONE == True`? [duplicate]
(3 answers)
Closed 5 years ago.
I have a multi-part boolean expression in a piece of python code, part of which involves a call to a random number generator and evaluating an expoenential of a sum of a 2d array. Since this is buried deep in nested loops I want to avoid checking that last part if at all possible, since it's computationally expensive.
if self.B == 0 or (np.sign(self.B) == -sign) or (np.random.rand() < np.exp(-2*sign*self.B*np.sum(cluster))):
do stuff
If either of the first two expression are true, will the random number generator still be called? Or is it guaranteed to evaluate those parts in order and stop once it finds one that is true?
I can always make it explicit by breaking it up, but it seems like something I should probably know anyway.
In if A or B, B is only evaluated if A is false.
This concept is called short circuiting, and you can read a little about it here.
The idea is that you go from left to right until a result is determined. Once that's the case, you stop.

Can we insure the for loop iteration order when we loop over a list by "for item in list:"? [duplicate]

This question already has answers here:
Is a Python list guaranteed to have its elements stay in the order they are inserted in?
(7 answers)
Closed 5 years ago.
for a in mylist:
print(a)
I am wondering whether the item in the for loop iteration will always print the item in order?
I know "for i in (len(mylist))" can ensure the order but not sure about whether "for a in mylist" can ensure the order.
I tried on my computer it seems like it prints out the items in order. But not sure whether it is true everywhere
Thanks
In a word - yes. To quote Python's wiki (bolding added for emphasis):
The Python for statement iterates over the members of a sequence in order, executing the block each time.

Test if two lists are equal [duplicate]

This question already has answers here:
Check if two unordered lists are equal [duplicate]
(8 answers)
Closed 7 years ago.
I'm trying to write tests for my Django app and I need to check many times
if 2 lists have the same objects (i.e. that every object in A is also in B and vice versa).
I read on the assertLists/Sequence/Equal etc but for what I saw if the lists
have the same objects but in a different order (A = [a,b,c], B = [b,c,a]) then it returns an error, which I don't want it to be an error because they both have the same objects.
Is there a way to check this without looping the lists?
You can use assertCountEqual in Python 3, or assertItemsEqual in Python 2.
From the Python 3 docs for assertCountEqual:
Test that sequence first contains the same elements as second, regardless of their order. When they don’t, an error message listing the differences between the sequences will be generated.
Duplicate elements are not ignored when comparing first and second. It verifies whether each element has the same count in both sequences. Equivalent to: assertEqual(Counter(list(first)), Counter(list(second))) but works with sequences of unhashable objects as well.
If you are staying with list() datatype then the cleanest way if your lists are not too large would be :
sorted(list_1) == sorted(list_2)
Have a look at this Question (which is the same):
Check if two unordered lists are equal

Length of the longest sublist? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Python’s most efficient way to choose longest string in list?
I have a list L
L = [[1,2,3],[5,7],[1,3],[77]]
I want to return the length of the longest sublist without needing to loop through them, in this case 3 because [1,2,3] is length 3 and it is the longest of the four sublists. I tried len(max(L)) but this doesn't do what I want. Any way to do this or is a loop my only way?
max(L,key=len) will give you the object with the longest length ([1,2,3] in your example) -- To actually get the length (if that's all you care about), you can do len(max(L,key=len)) which is a bit ugly -- I'd break it up onto 2 lines. Or you can use the version supplied by ecatamur.
All of these answers have loops -- in my case, the loops are implicit which usually means they'll be executed in optimized native machine code. If you think about it, How could you know which element is the longest without looking at each one?
Finally, note that key=function isn't a feature that is specific to max. A lot of the python builtins (max,min,sorted,itertools.groupby,...) use this particular keyword argument. It's definitely worth investing a little time to understand how it works and what it typically does.
Try a comprehension:
max(len(l) for l in L)

Categories

Resources