python matching list of lists - list

def compare_two_lists(list1,list2):
i=0
j=0
while i < len(list2) :
if i%2 == 0:
j == 0
else:
j == 1
for sublist2 in list2[i:] :
for sublist in list1[j:]:
#sublist.intersection(sublist2)
intersect = [x for x in sublist if x in sublist2]
print('from set ',sublist, len(intersect),' matched number(s): ', intersect)
i=i +1
compare_two_lists([[1,2,3,4,5],[20,30]],[[5,3,7,8,1],[20,10],[4,10,1,7,8],[30,20]])
I am trying to get list 0 and 1 of list 1 to compare appropriately list 0, 1, 2 and 3 of list 2 and return matches. The program almost works in the sense that it does return matches for the lists amongst other iterations. I cannot seem to be able to get the iteration to occur twice and return [1,3,5],[20], [1,4],[20,30]. Please help. I am going quite mad trying to understand how to space functions correctly and use loops logically!!

def compare_two_lists(list1,list2):
lRet = [] #a
for i in range(len(list2)): #b
j= i%2 #c
sublist1 = list1[j]
sublist2 = list2[i]
lRet.append([x for x in sublist1 if x in sublist2])
return lRet
compare_two_lists([[1,2,3,4,5],[20,30]],[[5,3,7,8,1],[20,10],[4,10,1,7,8],[30,20]])
This seems to do the trick. Here's an explanation (see line labels above):
a: lRet is initialised. We are doing to build up a list of lists in this variable
b: i runs through every index of list2
c: if i is even then j is zero, otherwise j is one. you had j==1 and j==0 in your code. These operators don't change any operand values. you meant j=1 etc. but this way is quicker
For explaining the rest I'll just talk through the actual iteration with your example input lists:
i = 0 (the first iteration)
j=0
sublist1 = [1,2,3,4,5]
sublist2 = [5,3,7,8,1]
intersection is [1,3,5]. we APPEND this to lRet.
thus lRet = [[1,3,5],]
i=1
j=1
sublist1 = [20,30]
sublist2 = [20,10]
the intersection is [20,]
thus lRet = [[1,3,5],[20]]
i=3
j=0
sublist1 = [1,2,3,4,5]
sublist2 = [4,10,1,7,8]
etc

Related

Why it's printing different for this two loops

So i have for example t=[1.0, 1.0, 1.6, 1.125, 1.5]
I want to print the indices for the elements that have the minimum value min(t) but i want them to start from 1
So for this example i want to print 1 2
It's working when i do this:
for j in range(len(t)):
if t[j]==min(t):
print j+1,`
Output :
1 2
But it's not working with this:
for j in t:
if j==min(t):
a=t.index(j)
print a+1,`
Output :
1 1
Why is that?
Your error is here
a = t.index(j)
t.index(j) is going to give you the first index of that value.
You can make this:
m = min(t)
cont = 0
for j in t:
if j == m:
print cont+1,
cont += 1
Or
for idx, val in enumerate(t):
if val == m:
print idx + 1,

How many times a number in list 1 appears in list 2 without using count()

trying to write this code to see how many times the numbers in list 1 appear in the list two, can use a nested for or while loop but I came up with this it doesn't work. I don't want to use count.
list1 = [4,7,2]
list2 = [2,3,4,2,5,6,3,2,6,7,3,4]
def compare(list1, list2):
freq = ([i for i in list1 if i == num])
return
print('The number 4 occurs in list2', freq, 'times')
print('The number 7 occurs in list2', freq, 'times')
print('The number 2 occurs in list2', freq, 'times')
I'm not completely sure that I understand the question,
but this code seems to work, though if it may be slow if you need it for an interactive program.
Hope this helps!
list1 = [4,7,2]
list2 = [2,3,4,2,5,6,3,2,6,7,3,4]
occurrences = [0,0,0]
for i in range(len(list1)):
for j in list2:
if list1[i] == j:
occurrences[i]+=1
print occurrences
try this:
list1 = [4,7,2]
list2 = [2,3,4,2,5,6,3,2,6,7,3,4]
occurrences = [0,0,0]
for i in range(len(list1)):
for j in list2:
if list1[i] == j:
occurrences[i]+=1
print occurrences

List of Tuples remove error

ExpenseL is my list of tuples and I try to remove from the list starting from start to stop but I just get this error: in removeFromAtoB
expenseL.pop(i)
TypeError: 'tuple' object cannot be interpreted as an integer
Please help me!!! :)
def removeFromAtoB():
aux = copy.deepcopy(expenseL)
print(expenseL, "\n")
start = int(input("Starting point: "))
stop = int(input("Ending point: "))
j = 0
for i in expenseL:
if j >= start and j <= stop:
expenseL.pop(i)
j += 1
print(expenseL)
You're iterating over your list of tuples:
for i in expenseL
That means i will be one of those tuples. Then you try to use it in list.pop:
expenseL.pop(i)
This won't work, because list.pop expects an index. Just enumerate your list:
for index, tpl in enumerate(expenseL):
...
expenseL.pop(index)
But this breaks, too, because the indices change when you remove an element. You could circumvent that by not increasing j in that case, but the simpler way is just assigning an empty list to the slice:
def removeFromAtoB():
start = int(input("Starting point: "))
stop = int(input("Ending point: "))
expenseL[start:stop+1] = []

Compress Python code

How can I write the following loop in one line? Or is this not possible because of the if-statement?
a = listWithFancyIntegers
for i in range(len(a)):
if a[i] < 0:
a[i] = 0
else:
a[i] = 1
What I do not want to have is a list of booleans.
I have already searched the web to check if I can use something like a Lambda expression but I didn't find anything that helped me. (Or I didn't understand it :D)
Thank you for your support.
a = [0 if n < 0 else 1 for n in listWithFancyIntegers]
EDIT
I prefer the code I wrote above, but here's another way:
a = [int(n >= 0) for n in listWithFancyIntegers]
or if you prefer map to list comprehension:
a = map(lambda n: int(n >= 0), listWithFancyIntegers)
This can be done in a single line in Python
a = [0 if i < 0 else 1 for i in a]

Understanding Recursive Function

I'm working through the book NLP with Python, and I came across this example from an 'advanced' section. I'd appreciate help understanding how it works. The function computes all possibilities of a number of syllables to reach a 'meter' length n. Short syllables "S" take up one unit of length, while long syllables "L" take up two units of length. So, for a meter length of 4, the return statement looks like this:
['SSSS', 'SSL', 'SLS', 'LSS', 'LL']
The function:
def virahanka1(n):
if n == 0:
return [""]
elif n == 1:
return ["S"]
else:
s = ["S" + prosody for prosody in virahanka1(n-1)]
l = ["L" + prosody for prosody in virahanka1(n-2)]
return s + l
The part I don't understand is how the 'SSL', 'SLS', and 'LSS' matches are made, if s and l are separate lists. Also in the line "for prosody in virahanka1(n-1)," what is prosody? Is it what the function is returning each time? I'm trying to think through it step by step but I'm not getting anywhere. Thanks in advance for your help!
Adrian
Let's just build the function from scratch. That's a good way to understand it thoroughly.
Suppose then that we want a recursive function to enumerate every combination of Ls and Ss to make a given meter length n. Let's just consider some simple cases:
n = 0: Only way to do this is with an empty string.
n = 1: Only way to do this is with a single S.
n = 2: You can do it with a single L, or two Ss.
n = 3: LS, SL, SSS.
Now, think about how you might build the answer for n = 4 given the above data. Well, the answer would either involve adding an S to a meter length of 3, or adding an L to a meter length of 2. So, the answer in this case would be LL, LSS from n = 2 and SLS, SSL, SSSS from n = 3. You can check that this is all possible combinations. We can also see that n = 2 and n = 3 can be obtained from n = 0,1 and n=1,2 similarly, so we don't need to special-case them.
Generally, then, for n ≥ 2, you can derive the strings for length n by looking at strings of length n-1 and length n-2.
Then, the answer is obvious:
if n = 0, return just an empty string
if n = 1, return a single S
otherwise, return the result of adding an S to all strings of meter length n-1, combined with the result of adding an L to all strings of meter length n-2.
By the way, the function as written is a bit inefficient because it recalculates a lot of values. That would make it very slow if you asked for e.g. n = 30. You can make it faster very easily by using the new lru_cache from Python 3.3:
#lru_cache(maxsize=None)
def virahanka1(n):
...
This caches results for each n, making it much faster.
I tried to melt my brain. I added print statements to explain to me what was happening. I think the most confusing part about recursive calls is that it seems to go into the call forward but come out backwards, as you may see with the prints when you run the following code;
def virahanka1(n):
if n == 4:
print 'Lets Begin for ', n
else:
print 'recursive call for ', n, '\n'
if n == 0:
print 'n = 0 so adding "" to below'
return [""]
elif n == 1:
print 'n = 1 so returning S for below'
return ["S"]
else:
print 'next recursivly call ' + str(n) + '-1 for S'
s = ["S" + prosody for prosody in virahanka1(n-1)]
print '"S" + each string in s equals', s
if n == 4:
print '**Above is the result for s**'
print 'n =',n,'\n', 'next recursivly call ' + str(n) + '-2 for L'
l = ["L" + prosody for prosody in virahanka1(n-2)]
print '\t','what was returned + each string in l now equals', l
if n == 4:
print '**Above is the result for l**','\n','**Below is the end result of s + l**'
print 'returning s + l',s+l,'for below', '\n','='*70
return s + l
virahanka1(4)
Still confusing for me, but with this and Jocke's elegant explanation, I think I can understand what is going on.
How about you?
Below is what the code above produces;
Lets Begin for 4
next recursivly call 4-1 for S
recursive call for 3
next recursivly call 3-1 for S
recursive call for 2
next recursivly call 2-1 for S
recursive call for 1
n = 1 so returning S for below
"S" + each string in s equals ['SS']
n = 2
next recursivly call 2-2 for L
recursive call for 0
n = 0 so adding "" to below
what was returned + each string in l now equals ['L']
returning s + l ['SS', 'L'] for below
======================================================================
"S" + each string in s equals ['SSS', 'SL']
n = 3
next recursivly call 3-2 for L
recursive call for 1
n = 1 so returning S for below
what was returned + each string in l now equals ['LS']
returning s + l ['SSS', 'SL', 'LS'] for below
======================================================================
"S" + each string in s equals ['SSSS', 'SSL', 'SLS']
**Above is the result for s**
n = 4
next recursivly call 4-2 for L
recursive call for 2
next recursivly call 2-1 for S
recursive call for 1
n = 1 so returning S for below
"S" + each string in s equals ['SS']
n = 2
next recursivly call 2-2 for L
recursive call for 0
n = 0 so adding "" to below
what was returned + each string in l now equals ['L']
returning s + l ['SS', 'L'] for below
======================================================================
what was returned + each string in l now equals ['LSS', 'LL']
**Above is the result for l**
**Below is the end result of s + l**
returning s + l ['SSSS', 'SSL', 'SLS', 'LSS', 'LL'] for below
======================================================================
This function says that:
virakhanka1(n) is the same as [""] when n is zero, ["S"] when n is 1, and s + l otherwise.
Where s is the same as the result of "S" prepended to each elements in the resulting list of virahanka1(n - 1), and l the same as "L" prepended to the elements of virahanka1(n - 2).
So the computation would be:
When n is 0:
[""]
When n is 1:
["S"]
When n is 2:
s = ["S" + "S"]
l = ["L" + ""]
s + l = ["SS", "L"]
When n is 3:
s = ["S" + "SS", "S" + "L"]
l = ["L" + "S"]
s + l = ["SSS", "SL", "LS"]
When n is 4:
s = ["S" + "SSS", "S" + "SL", "S" + "LS"]
l = ["L" + "SS", "L" + "L"]
s + l = ['SSSS", "SSL", "SLS", "LSS", "LL"]
And there you have it, step by step.
You need to know the results of the other function calls in order to calculate the final value, which can be pretty messy to do manually as you can see. It is important though that you do not try to think recursively in your head. This would cause your mind to melt. I described the function in words, so that you can see that these kind of functions is are descriptions, and not a sequence of commands.
The prosody you see, that is a part of s and l definitions, are variables. They are used in a list-comprehension, which is a way of building lists. I've described earlier how this list is built.