Recursion happens too many times and list is not iterable - python-3.x

I'm trying to make a secret santa programm. The input is in form of the list of names of people g. ["John", "Bob", "Alice"] and the list of emials ["John#gmail.com", "Bob#gmail.com", "Alice#outlook.com"]. I need to generate pairs of email adress and a random name which doesn't belong to the said email adress. For this I have written the function compare.
def compare(list_of_names, list_of_emails):
zipped_lists = zip(list_of_emails, list_of_names)
random.shuffle(list_of_emails)
zipped_shuffled_lists = zip(list_of_emails, list_of_names)
for pair in zipped_lists:
for shuffle_pair in zipped_shuffled_lists:
if shuffle_pair == pair:
return compare(list_of_names, list_of_emails)
return zipped_shuffled_lists
But instead of shuffling like it should it just creates a recursion. i still can't find out why. After a finite amount of time it should create two different lists that work. Also the shuffled_list_of_emails is not iterable, why?
EDIT:changed the code with shuffle because it works in place

zip is lazy!
I'm not sure why, but I'm too excited about this right now, so the answer might be a bit messy. Feel free to ask for clarification)
Let's step through your code:
def compare(list_of_names, list_of_emails):
# the `zip` object doesn't actually iterate over any of its arguments until you attempt to iterate over `zipped_lists`
zipped_lists = zip(list_of_emails, list_of_names)
# modify this IN-PLACE; but the `zip` object above has a pointer to this SAME list
random.shuffle(list_of_emails)
# since the very first `zip` object has `list_of_emails` as its argument, AND SO DOES THE ONE BELOW, they both point to the very same, SHUFFLED (!) list
zipped_shuffled_lists = zip(list_of_emails, list_of_names)
# now you're iterating over identical `zip` objects
for pair in zipped_lists:
for shuffle_pair in zipped_shuffled_lists:
# obviously, this is always true
if shuffle_pair == pair:
# say "hello" to infinite recursion, then!
return compare(list_of_names, list_of_emails)
return zipped_shuffled_lists
Let's recreate this in the Python interpreter!
>>> List = list(range(5))
>>> List
[0, 1, 2, 3, 4]
>>> zipped_1 = zip(List, range(5))
>>> import random
>>> random.shuffle(List)
>>> zipped_2 = zip(List, range(5))
>>> print(List)
[4, 2, 3, 0, 1]
>>> zipped_1, zipped_2 = list(zipped_1), list(zipped_2)
>>> zipped_1 == zipped_2
True
You see, two different zip objects applied to the same list at different times (before and after that list is modified in-place) produce the exact same result! Because zip doesn't do the zipping once you do zip(a, b), it will produce the zipped... uh, stuff... on-the-fly, while you're iterating over it!
So, to fix the issue, do not shuffle the original list, shuffle its copy:
list_of_emails_copy = list_of_emails.copy()
random.shuffle(list_of_emails_copy)
zipped_shuffled_lists = zip(list_of_emails_copy, list_of_names)

There's correct answer from #ForceBru already. But a will contribute a little.
You should avoid zip's lazy evaluation and unfold zips with, for example, list:
def compare(list_of_names, list_of_emails):
zipped_lists = list(zip(list_of_emails, list_of_names)) # eager evaluation instead of lazy
random.shuffle(list_of_emails) # shuffle lists
zipped_shuffled_lists = list(zip(list_of_emails, list_of_names)) # eager again
for pair in zipped_lists:
for shuffle_pair in zipped_shuffled_lists:
if shuffle_pair == pair:
return compare(list_of_names, list_of_emails)
return zipped_shuffled_lists
But I guess you need no recursion and can achieve your task easier:
def compare(list_of_names, list_of_emails):
zipped_lists = list(zip(list_of_emails, list_of_names))
random.shuffle(zipped_lists) # shuffle list of emails and names
result = []
shuffled_emails = [i[0] for i in zipped_lists]
for i, _ in enumerate(shuffled_emails):
result.append(zipped_lists[i-1][1]) # shift email relatively one position to the right
return list(zip(result, shuffled_emails))
This code links an name with an email of a previous name, which is randomly selected, and it guaranteed does not match.
There's no recursion, works fine for lists with two or more elements.

Related

How to subtract adjacent items in list with unknown length (python)?

Provided with a list of lists. Here's an example myList =[[70,83,90],[19,25,30]], return a list of lists which contains the difference between the elements. An example of the result would be[[13,7],[6,5]]. The absolute value of (70-83), (83-90), (19-25), and (25-30) is what is returned. I'm not sure how to iterate through the list to subtract adjacent elements without already knowing the length of the list. So far I have just separated the list of lists into two separate lists.
list_one = myList[0]
list_two = myList[1]
Please let me know what you would recommend, thank you!
A custom generator can return two adjacent items at a time from a sequence without knowing the length:
def two(sequence):
i = iter(sequence)
a = next(i)
for b in i:
yield a,b
a = b
original = [[70,83,90],[19,25,30]]
result = [[abs(a-b) for a,b in two(sequence)]
for sequence in original]
print(result)
[[13, 7], [6, 5]]
Well, for each list, you can simply get its number of elements like this:
res = []
for my_list in list_of_lists:
res.append([])
for i in range(len(my_list) - 1):
# Do some stuff
You can then add the results you want to res[-1].

Math-like way to define a set in Python: technical name [duplicate]

Can someone explain the last line of this Python code snippet to me?
Cell is just another class. I don't understand how the for loop is being used to store Cell objects into the Column object.
class Column(object):
def __init__(self, region, srcPos, pos):
self.region = region
self.cells = [Cell(self, i) for i in xrange(region.cellsPerCol)] #Please explain this line.
The line of code you are asking about is using list comprehension to create a list and assign the data collected in this list to self.cells. It is equivalent to
self.cells = []
for i in xrange(region.cellsPerCol):
self.cells.append(Cell(self, i))
Explanation:
To best explain how this works, a few simple examples might be instructive in helping you understand the code you have. If you are going to continue working with Python code, you will come across list comprehension again, and you may want to use it yourself.
Note, in the example below, both code segments are equivalent in that they create a list of values stored in list myList.
For instance:
myList = []
for i in range(10):
myList.append(i)
is equivalent to
myList = [i for i in range(10)]
List comprehensions can be more complex too, so for instance if you had some condition that determined if values should go into a list you could also express this with list comprehension.
This example only collects even numbered values in the list:
myList = []
for i in range(10):
if i%2 == 0: # could be written as "if not i%2" more tersely
myList.append(i)
and the equivalent list comprehension:
myList = [i for i in range(10) if i%2 == 0]
Two final notes:
You can have "nested" list comrehensions, but they quickly become hard to comprehend :)
List comprehension will run faster than the equivalent for-loop, and therefore is often a favorite with regular Python programmers who are concerned about efficiency.
Ok, one last example showing that you can also apply functions to the items you are iterating over in the list. This uses float() to convert a list of strings to float values:
data = ['3', '7.4', '8.2']
new_data = [float(n) for n in data]
gives:
new_data
[3.0, 7.4, 8.2]
It is the same as if you did this:
def __init__(self, region, srcPos, pos):
self.region = region
self.cells = []
for i in xrange(region.cellsPerCol):
self.cells.append(Cell(self, i))
This is called a list comprehension.

Recursion for generating subsets of a list

I would like to know for this function, why does after it runs and returns [[],[1]] which is the last line of the function? Then it would run the line smaller = genSubset(L[:-1]) again and again. I visualized the code from pythontutor. However, i do not understand why it works this way. Someone please enlighten me. Thank You.
This function generates all the possible subsets of a given list, so, for example, input list is [1,2,3]. It would return [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]].
def genSubsets(L):
res = []
if len(L) == 0:
return [[]] #list of empty list
smaller = genSubsets(L[:-1]) # all subsets without last element
extra = L[-1:] # create a list of just last element
new = []
for small in smaller:
new.append(small+extra) # for all smaller solutions, add one with last element
return smaller+new # combine those with last element and those without
print(genSubsets([1,2,3]))
This function is recursive, that means - it calls itself. when it finishes one recursion iteration - it returns to where it stopped. This is exactly at the line smaller = getSubsets(L[:-1]) but notice that it wont run it again, but instead continue until it finishes the call. This recursion happens n times (where n is the list's length), and you will see this behavior exactly n times before the function finally returns the subsets.
I hope i understood correctly the question and managed to answer it :)

Simple way to remove duplicate item in a list [duplicate]

This question already has answers here:
How do I remove duplicates from a list, while preserving order?
(30 answers)
Closed 4 years ago.
the program says "TypeError: 'int' object is not iterable"
list=[3,3,2]
print(list)
k=0
for i in list:
for l in list:
if(l>i):
k=l
for j in k:
if(i==j):
del list[i]
print(list)
An easy way to do this is with np.unique.
l=[3,3,2]
print(np.unique(l))
Hope that helps!
Without using any numpy the easiest way I can think of is to start with a new list and then loop through the old list and append the values to the new list that are new. You can cheaply keep track of what has already been used with a set.
def delete_duplicates(old_list):
used = set()
new_list= []
for i in old_list:
if i not in used:
used.add(i)
new_list.append(i)
return new_list
Also, a couple tips on your code. You are getting a TypeError from the for j in k line, it should be for j in range(k). k is just an integer so you can't iterate over it, but range(k) creates an iterable that will do what you want.
Just build another list
>>> list1=[3,2,3]
>>> list2=[]
>>> for i in list1:
... if i in list2:
... pass
... else:
... list2.append(i)
...
>>> list2
[3, 2]
You can always add list1 = list2 at the end if you prefer.
You can use set()
t = [3, 3, 2]
print(t) # prints [3, 3, 2]
t = list(set(t))
print(t) # prints [2, 3]
To remove a duplicate item in a list and get list with unique element, you can always use set() like below:
example:
>>>list1 = [1,1,2,2,3,3,3]
>>>new_unique_list = list(set(list1))
>>> new_unique_list
>>>[1, 2, 3]
You have the following line in your code which produces the error:
for j in k:
k is an int and cannot be iterated over. You probably meant to write for j in list.
There are a couple good answers already. If you really want to write the code yourself however, I'd recommend functional style instead of working in place (i.e. modifying the original array). For example like the following function which is basically a port of Haskell's Data.List.nub.
def nub(list):
'''
Remove duplicate elements from a list.
Singleton lists and empty lists cannot contain duplicates and are therefore returned immediately.
For lists with length gte to two split into head and tail, filter the head from the tail list and then recurse on the filtered list.
'''
if len(list) <= 1: return list
else:
head, *tail = list
return [head] + nub([i for i in tail if i != head])
This is—in my opinion—easier to read and saves you the trouble associated with multiple iteration indexes (since you create a new list).

Creating a function that shuffles a deck of cards

So the problem is as follows:
simpleSHuffle(D) takes as input list of elements. It should step through the list, at each point exchanging the current element with an element chosen at random from the remainder of the list (including the present element). In other words, if we are considering the third element of aten element list, we select an index between 3 and 9, inclusive, and exchange list[3] with list[0] before advancing to the fourth element of the list and repeating the process. Note that yo will need to use the randint() function, which has been imported for you from the random module at the top of this file
def simpleShuffle(D):
n=len(D)-1
for i in range(n):
r=randin(i,n)
temp=D[r]
D[r]=D[i]
D[i]=temp
return D
Above is what I got. Are there any other ways of doing this? Any improvements?
random.shuffle should get you what you want
>>> from random import shuffle
>>> a = [1,2,3,4]
>>> shuffle(a)
>>> a
[4, 2, 1, 3]
Note that shuffle shuffles the sequence in place and does not return anything.

Resources