I have a function that have to return True if and only if all the ints in L1 are the lengths of the strings in L2 at the corresponding positions. and the Precondition: len(L1) == len(L2).
EXAMPLE:
>>> are_lengths_of_strs([4, 0, 2], ['abcd', '', 'ef'])
True
Below is the function:
def are_lengths_of_strs(L1, L2):
result = True
for i in range(len(L1)):
if i in len(L1) != len(L2):
result = False
return result
It result in a error. The line if i in len(L1) != len(L2): is the wrong . Can someone help me in this line ??
Obs : I have to use !=
-
5"Something rotten in the state of Danmark"sehe– sehe2012年11月17日 20:04:08 +00:00Commented Nov 17, 2012 at 20:04
-
+1 to sehe's comment, please use descriptive titles for your questions.Lev Levitsky– Lev Levitsky2012年11月17日 20:08:44 +00:00Commented Nov 17, 2012 at 20:08
3 Answers 3
Corrected version of your code:
def are_lengths_of_strs(L1, L2):
result = True
for i in range(len(L1)):
if L1[i] != len(L2[i]):
result = False
return result
Note that this is not pythonic, because you don't in fact need an index here:
def are_lengths_of_strs(L1, L2):
result = True
for i, l in zip(L1, L2)
if i != len(l):
result = False
return result
Even shorter:
def are_lengths_of_strs(L1, L2):
return all(i == len(l)
for i, l in zip(L1, L2))
Comments
Your if condition is probably the problem:
if i in len(L1) != len(L2):
This checks if i in len(L1), but len(L1) is an integer, which can't "contain" another number.
You have to iterate over the elements of each list:
def are_lengths_of_strs(L1, L2):
result = True
for i in range(len(L1)):
if L1[i] != len(L2[i]):
result = False
return result
Also, get rid of result. A simple return statement will work just fine:
def are_lengths_of_strs(L1, L2):
for i in range(len(L1)):
if L1[i] != len(L2[i]):
return False
return True
If you want to get even more Pythonic, use zip:
def are_lengths_of_strs(L1, L2):
for a, b in zip(L1, L2)
if a != len(b):
return False
return True
Comments
use the built-in all() along with zip():
In [5]: all(x==len(y) for x,y in zip([4, 0, 2], ['abcd', '', 'ef']))
Out[5]: True
or if != is compulsory use any():
In [7]: not any(x != len(y) for x,y in zip([4, 0, 2], ['abcd', '', 'ef']))
Out[7]: True
or improving your code:
def are_lengths_of_strs(L1, L2):
for x,y in zip(L1,L2):
if x!=len(y):
return False
return True
In [12]: are_lengths_of_strs([4, 0, 2], ['abcd', '', 'ef'])
Out[12]: True