Regarding string methods - python

I'm currently working through Automate the Boring Stuff with Python book and run into curious issue on chapter 7.
When trying to execute the following code:
def isPhoneNumber(text):
if len(text) != 12:
return False
for i in range(0, 3):
if not text[i].isdecimal():
return False
if text[3] != "-":
return False
for i in range(4, 7):
if not text(i).isdecimal():
return False
if text[7] != "-":
return False
for i in range(8, 12):
if not text[i].isdecimal():
return False
return True
print("415-555-4242 is a phone number:")
print(isPhoneNumber("415-555-4242"))
print("Moshi moshi is a phone number:")
print(isPhoneNumber("Moshi moshi"))
I get the following error message:
Traceback (most recent call last):
File "automation.py", line 27, in <module>
print(isPhoneNumber("415-555-4242"))
File "automation.py", line 13, in isPhoneNumber
if not text(i).isdecimal():
TypeError: 'str' object is not callable
Switching the str.isdecimal() method for str.isdigit() method allows me to execute the code properly, but I would like to know why the isdecimal() method will not work?

The error has nothing to do with isdecimal(). You have a typo in how you extract the character from text. The
if not text(i).isdecimal():
should read
if not text[i].isdecimal():
(note the square brackets.)

File "automation.py", line 13, in isPhoneNumber
if not text(i).isdecimal():
TypeError: 'str' object is not callable
The typeError is on line 13, where you are calling a string object. Use [] not ()

Related

Pset7 numb3r; failed check50

I am doing problem set 7; my code output True or False as per instruction but it didn't pass check50.
check50 returned:
Traceback (most recent call last):
File "/tmp/tmp2vk2c_gh/test_correct_ipv4_localhost/testing.py", line 3, in \<module\>
print(validate(input("IPv4 Address: ")))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/tmp/tmp2vk2c_gh/test_correct_ipv4\_...
Kindly assist.
Here is my code
import re
def main():
# prompting use for IPV4
ip = input("IPv4 Address: ")
numbers = get_num(ip)
print(validate(numbers))
def get_num(ip):
# search for a valid IPV4 sequence in a string
m = re.search(r"^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$", ip)
if m:
# convert each group in a sequence to an int
number1 = int(m.group(1))
number2 = int(m.group(2))
number3 = int(m.group(3))
number4 = int(m.group(4))
# return a list of numbers
return [number1, number2, number3, number4]
# if no match found return None
else:
return None
# validate ip address
def validate(numbers):
# if there was a match
if numbers:
for number in numbers:
# check if each number in
if 0 <= number <= 255:
number = number
else:
return False
return True
else:
return False
if __name__ == "__main__":
main()
Now that I look at the traceback more closely and compare to the code above, I see why the error occurs. I will explain.
The last line of the traceback displays the line with the error. It is:
Traceback (most recent call last):
...
print(validate(input("IPv4 Address: ")))
This is what the Python interpreter was trying to execute when the error occurs. It also tells you this is line 3 in file testing.py. So, the error isn't in your code (per se), but when testing.py calls your code.
Now, look at your main() function (code snippet below):
ip = input("IPv4 Address: ")
numbers = get_num(ip)
print(validate(numbers))
Notice how input() returns ip. You then call get_num(ip) which returns numbers, and THEN it calls print(validate(numbers)). You have an extra step between input() and validate() that is not in the testing code. That's not how your program is supposed to work. You should get the input and call validate() directly -- no intermediate functions. That's why it doesn't work when called from testing.py.
I assume you fixed the error by migrating get_num() into the validate() function?

HackerRank Runtime Error in Simple Python 3 if statement

def findNumber(arr, k):
if k in arr:
print( "YES" )
else:
print( "NO" )
if __name__ == '__main__':
arr_count = int(input().strip())
arr = []
for _ in range(arr_count):
arr_item = int(input().strip())
arr.append(arr_item)
k = int(input().strip())
result = findNumber(arr, k)
fptr.write(result + '\n')
fptr.close()
While this runs just fine on Pycharm, on HackerRank i get the error:
Traceback (most recent call last):
File "Solution.py", line 42, in <module>
fptr.write(result + '\n')
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'
Would really appreciate if you could point out what the error might be.
Your function def findNumber(arr, k): does not return anything, so it returns None implicitly.
These lines
result = findNumber(arr, k)
fptr.write(result + '\n')
then try to add None and a string together - which does not work.
Instead of printing inside your function, return "Yes" or "No".
findNumber returns Nothing, so it automatically returns None. You have to replace the "print" in your function with return statements.

Why do I get the error "'function' object is not subscriptable'

This is my code block
import json
import difflib
from difflib import get_close_matches
definitions = json.load(open("data.json"))
def thesaurus(words):
if words in definitions:
return definitions[words]
elif len(get_close_matches(words, definitions.keys())) > 0:
yn = input("Did you mean %s instead? Enter 'Y' if yes or 'N' if no: " % get_close_matches(words,definitions.keys()) [0])
if yn == "Y":
return thesaurus[get_close_matches(words, definitions.keys())]
elif yn == "N":
return "None found"
else:
return "Please check word again"
words = input("Look Up: ").lower()
print(thesaurus(words))
I expected to receive the meaning of the word "Grief". However, I kept receiving the error : function object is not subscriptable.
Here is the terminal log, just in case it might help:
My-MacBook-Pro:Python Adwok$ python3 dictionary.py
Look Up: GRERFAG
Did you mean grief instead? Enter 'Y' if yes or 'N' if no: Y
Traceback (most recent call last):
File "dictionary.py", line 22, in <module>
print(thesaurus(words))
File "dictionary.py", line 13, in thesaurus
return thesaurus[get_close_matches(words, definitions.keys())]
TypeError: 'function' object is not subscriptable
Please point out even the smallest details, I would appreciate that very much.
As stated by the error stack, in line 13 you are accessing thesaurus as if it was a list/dictionary (or any subscriptable object). Since thesaurus is a function (which is not subscriptable), you get an error. Thus, you need to invoke the function (instead of accessing it):
thesaurus(get_close_matches(words, definitions.keys()))
Also, you should notice:
At the end of your code you are correctly invoking the thesaurus function by calling print(thesaurus(words))
Consider reusing the result of get_close_matches to avoid multiple calls to the same function (which can lead to performance degradation if the call is resource consuming).
I suggest you the following solution:
import json
import difflib
from difflib import get_close_matches
definitions = json.load(open("data.json"))
def thesaurus(words):
if words in definitions:
return definitions[words]
else:
close_matches = get_close_matches(words, definitions.keys())
if len(close_matches) > 0:
yn = input("Did you mean %s instead? Enter 'Y' if yes or 'N' if no: " % get_close_matches(words,definitions.keys()) [0])
if yn == "Y":
return thesaurus(close_matches)
elif yn == "N":
return "None found"
else:
return "Please check word again"
words = input("Look Up: ").lower()
print(thesaurus(words))

python error need explanations

I have this error when running the following program and I don't understand why:
Traceback (most recent call last):
line 18
main() line 13, in main
nombre=condition(nombre)
line 3, in condition
if (nombre % 2) == 1:
TypeError: unsupported operand type(s) for %: 'NoneType' and 'int'
Here is my program:
def condition(nombre):
if (nombre % 2) == 1:
nombre=(nombre*3)+1
else:
nombre=(nombre/2)
def main():
nombre=int(input())
print(nombre)
while nombre!=1:
nombre=condition(nombre)
print(nombre)
main()
This error occurring because you doest returning value from condition function and in second iteration of your while != 1 value of nombre was equal to def. try this to fix your code:
def condition(nombre):
if (nombre % 2) == 1:
nombre=(nombre*3)+1
else:
nombre=(nombre/2)
return nombre
if you want that condition return integer value you should use // instead of / :
def condition(nombre):
if (nombre % 2) == 1:
nombre=(nombre*3)+1
else:
nombre=(nombre//2)
return nombre
You are getting NoneType from condition function since it doesn't return anything.

palindrome or not practice program using user input

def reverse(string):
return string[::-1]
def isPalindrome(string):
temp=reverse(string)
if temp==string:
return True
else:
return False
string='tanmay' # input('enter a word')
ans=isPalindrome(string)
if ans==1:
print' Yes palindrome'
else:
print' no its not a palindrome'
if I ask for an input from the user the error what I got was Traceback (most recent call last):
File "C:/Python27/prac06-2.py", line 10, in <module>
string=input('enter a word')
File "<string>", line 1, in <module>
NameError: name 'tanmay' is not defined
but when I enter a string by myself the program is executed successfully
in python 2.7 input() evaluates the given input, you should use raw_input() to read in the data as a string. On another note, temp==string evaluates to a boolean so you do not need to put it in an if statement you can simply return temp==string
def reverse(string):
return string[::-1]
def isPalindrome(string):
temp=reverse(string)
return temp==string
string=raw_input('enter a word')
if isPalindrome(string):
print(' Yes palindrome')
else:
print(' no its not a palindrome')
You can simplify isPalindrome() further by removing reverse() to:
def isPalindrome(string):
return string == string[::-1]
You are returning a boolean True or False and you are trying to compare the result with a value 1. Here is how you should invoke it.
ans = isPalindrome(string)
if ans: # you can also do (if ans == True)
print 'Yes, it is a palindrome'
else:
print 'No, it is not a palindrome'

Categories