Reputation: 23
I'm quite new with coding. I need your help. I did an exercise and hit the error. The code is like this:
def isAnagram(s,t):
if len(s)!=len(t):
return False
else:
list_t = sorted(list(set(t))
list_s = sorted(list(set(s))
if list_s != list_t:
return False
else:
i=0
j=[]
k=[]
for i in range len(list_s):
j.append(list_s.count(list_s[i]))
k.append(list_t.count(list_t[i]))
i=i+1
if j!=k:
return False
else:
return True
And I get this error
File "<ipython-input-43-5ac86c9b9c40>", line 7
list_s = sorted(list(set(s))
^
SyntaxError: invalid syntax
If I put a comma at the end of 5th line, then I receive a new error:
File "<ipython-input-44-6a66b63cb96e>", line 8
if list_s != list_t:
^
SyntaxError: invalid syntax
Help me to understand why I made those two errors.
Upvotes: 0
Views: 42
Reputation: 21
**First you miss ')' for sorted function and second you have whitespace on range function and you miss '()' for that **
def isAnagram(s,t):
if len(s)!=len(t):
return False
else:
list_t = sorted(list(set(t)))
list_s = sorted(list(set(s)))
if list_s != list_t:
return False
else:
i = 0
j = []
k = []
for i in range(len(list_s)):
j.append(list_s.count(list_s[i]))
k.append(list_t.count(list_t[i]))
i=i+1
if j!=k:
return False
else:
return True
Upvotes: 0
Reputation: 2159
You're missing parentheses in your code:
sorted
- it should be list_t = sorted(list(set(t)))
As @Dan D. mentioned, your program is looking for a closing parentheses. When it got another letter instead, it returns a series of syntax errorsrange
is a function, so you need for i in range (len(list_s)):
This code should compile correctly:
def isAnagram(s,t):
if len(s)!=len(t):
return False
else:
list_t = sorted(list(set(t))) # add missing parenthesis
list_s = sorted(list(set(s))) # add missing parenthesis
if list_s != list_t:
return False
else:
i=0
j=[]
k=[]
for i in range(len(list_s)): # add missing parenthesis
j.append(list_s.count(list_s[i]))
k.append(list_t.count(list_t[i]))
i=i+1
if j!=k:
return False
else:
return True
Upvotes: 0
Reputation: 74645
Your code is basically:
(1
The parser is looking for )
and doesn't find it and instead reports a number of different errors depending on what it finds instead.
Upvotes: 1