How can I optimize this code for large amount of input? - python

How can I optimize this code for large amount of input? Out of 5, 3 test case are failing because code is taking too long to execute.
n = int(input())
phonebook=dict([map(str,raw_input().split()) for x in range(n)])
while True:
try:
name = raw_input()
except EOFError as e:
break
if name not in phonebook.keys():
print("Not found")
else:
print(name +"="+phonebook[name])

You can turn the phonebook's keys into a set, sets are faster at lookup than lists

last 4 line in one
print(name +"="+phonebook[name]) if phonebook.get(name) else print("Not found")

This line is probably taking too much time:
if name not in phonebook.keys():
Because you are going over all the keys in the dictionary and compare it with input. You can use in keyword to check if a key exists directly without iterating over keys
n = int(input())
phonebook=dict([map(str,raw_input().split()) for x in range(n)])
while True:
try:
name = raw_input()
except EOFError as e:
break
if name not in phonebook:
print("Not found")
else:
print(name +"="+phonebook[name])
Or you can use exception handling on key error like so, it is better practice:
n = int(input())
phonebook=dict([map(str,raw_input().split()) for x in range(n)])
while True:
try:
name = raw_input()
print(name +"="+phonebook[name])
except EOFError as e:
break
except KeyError as e:
print ("Not found")

Related

Using Exception Handling in Python

Using exception handling inside a loop in python, I'm receiving inputs from a user and adds it to a list but if the user types 'done' the loop terminates and sums up the list. If the user types any other non numeric data it would print 'Wrong Data' and continue the loop. My issues are: Adding the list. Converting the user data from number to string. Reading a string data first from the user. And terminating the loop with 'done'.
total = 0
user_list = []
while True:
try:
user_entry = int(input('(\'done\' is your terminator.)\nEnter any number only! >> '))
user_list.append(user_entry)
total = total + user_list
except ValueError:
if str(user_entry) == 'done':
break
else:
print('Wrong Data')
continue
There's lots of code in the try block that should go before or after the try statement.
total = 0
user_list = []
while True:
user_entry = input('(\'done\' is your terminator.)\nEnter any number only! >> ')
if user_entry == 'done':
break
try:
user_entry = int(user_entry)
except ValueError:
print('Wrong Data')
continue
user_list.append(user_entry)
total += user_entry
Note that instead of keeping running total, you can simply wait until after the loop to call total = sum(user_list).

Exception In Python Doesn't Do Anything

I am beginner to python and I have doubt in one program when using try except part
I try to take input from user and add that number by 1 like if you enter 5 then 6 will be printed but if you enter string then except would come in role and print enter only number
I've written code but except is not working there, code is working like if I enter 5 then 6 gets printed but except statement is not working
Here is the code that I've written
def increment(num):
try:
return num + 1
except Exception as e:
print("ufff error occured :", e)
n = int(input("enter your num: "))
a = increment(n)
print(a)
You would have to change to the following:
def increment(num):
try:
return int(num) + 1
except Exception as e:
print("ufff error occured :", e)
n = input("enter your num: ")
a = increment(n)
print(a)
The reason for that is that the exception was raised by the int() functions, because it couldn't convert your input to int. The call to int() was before the increment function. Therefore the exception was unhandled.
You tried converting the input to int before going into the try/except block. If you just put it in the try block it will work.
def increment(num):
try:
num = int(num)
return num + 1
except Exception as e:
print("ufff error occured :", e)
n = input("enter your num: ")
a = increment(n)
print(a)
You have to use the type conversion within the try block so that if num is not a number, the controller would move to expect portion.
The problem here is you are using type conversion outside of try-catch block.
Another point to note, convert e to string as a good practice.
Third point to note,the last line print(a) will itself cause trouble in cases of exception as you have returned nothing from the exception part and directly printed the error. Use a return statement in there else it would return None type and which itself will mess up the flow.
def increment(num):
try:
return int(num) + 1 #Updated Line
except Exception as e:
return "ufff error occurred :" + str(e) #Updated Line
n = input("enter your num: ")
a = increment(n)
print(a)
Might I recommend the following?
def increment(num):
try:
return int(num) + 1
except Exception as e:
print("ufff error occurred:", e)
n = input("enter your num: ")
a = increment(n)
print(a)
The only difference here is that the attempt to convert the user's input to an int occurs within the try-except block, rather than outside. This allows the type conversion error to be caught and your message ("ufff error occurred: ...") to be displayed.
Edit: regarding your comment:
yes it worked out thanks everyone, but can anyone tell what should i have to do if i use int with input line what changes i've to make
Optionally, you could do the following:
def increment(num):
return num + 1
try:
n = int(input("enter your num: "))
a = increment(n)
print(a)
except Exception as e:
print("ufff error occurred:", e)
In this case, I would recommend removing the try-except block in the increment function, because you can safely assume that all values passed to that function will be numeric.
The only code that would raise an exception is the int(...) conversion - and it is not protected under a try/except block. You should put it under the try:
def increment():
try:
return int(input("enter your num: ")) + 1
except ValueError as e:
return f"ufff error occured: {e}"
print(increment())
You should always try to catch the narrowest exception. In this case, a ValueError.

Why can't I call a function here?

Hi guys I was working on a shoppinglist-creator code but at the end I faced with a surprise.
My code:
import time
import math
import random
dict_of_lists={}
def addlist():
while True:
try:
listname=str(raw_input("=>Name of the list:\n"))
dict_of_lists[listname]={}
break
except ValueError:
print "=>Please enter a valid name.\n"
print "=>You added a new list named %s.\n" % (listname)
def printlists():
for lists in dict_of_lists:
return "-"+lists
def addproduct():
while True:
try:
reachlistname=input("=>Name of the list you want to add a product,Available lists are these:\n %s \nPlease enter one:\n" % (printlists()))
break
except ValueError:
print "=>Please enter a valid list name.\n"
while True:
try:
productname=raw_input("=>Name of the product:\n")
break
except ValueError:
print "=>Please enter a valid name.\n"
while True:
try:
productprice=input("=>Price of the product:\n")
if isinstance(float(productprice),float):
break
except ValueError:
print "=>Please enter a valid number.\n"
while True:
try:
productcount=input("=>Amount of the product:\n")
if isinstance(int(productcount),int):
break
except ValueError:
print "=>Please enter a valid number.\n"
dict_of_lists[reachlistname][productname]={"price":productprice,"count":productcount}
dict_of_lists[reachlistname]={productname:{"price":productprice,"count":productcount}}
allevents="1-Add a list"+" 2-Add a product to a list"
def eventtochoose():
while True:
try:
event=raw_input("=>What would you like to do? Here are the all things you can do:\n %s\nPlease enter the number before the thing you want to do:" % (allevents))
if not isinstance(int(event),int):
print "\n=>Please enter a number.\n"
else:
if event==1:
addlist()
break
elif event==2:
addproduct()
break
except ValueError:
print "\n=>Please enter a valid input.\n "
while True:
print "%s" % ("\n"*100)
eventtochoose()
So, the problem is (I suggest you run the code) it says "=>What would you like to do? Here are the all things you can do:
1-Add a list 2-Add a product to a list
Please enter the number before the thing you want to do:" and when i put an answer it simply doesn't call the fucntion.
If I put 1 It should have called the fucntion addlist but I think it doesn't. There is nothing to explain I think just look at the code and find the problem if you want to help crocodiles. Thx
When you do int(event), that returns an int if possible, and raises a ValueError if not. So, testing the type of the result doesn't do you any good—if your code gets that far, the type has to be an int.
You already have code to handle the ValueError, so you don't need any other test for the same problem.
Meanwhile, you want to start the number that you got from int(event). That's the thing that can be == 1; the original string '1' will never be == 1.
So:
while True:
try:
event=raw_input("=>What would you like to do? Here are the all things you can do:\n %s\nPlease enter the number before the thing you want to do:" % (allevents))
event = int(event)
if event==1:
addlist()
break
elif event==2:
addproduct()
break
except ValueError:
print "\n=>Please enter a valid input.\n "
You are not converting your input to an integer before comparing, so the comparisons are always false:
'1' == 1 # false
Try:
event = raw_input("=>What would you like to do? Here are the all things you can do:\n %s\nPlease enter the number before the thing you want to do:" % (allevents))
try:
event = int(event)
if event == 1:
addlist()
elif event == 2:
addproduct()
break
except ValueError:
print('Please enter a valid input')

Datetime module - ValueError try/except won't work python 3

I have a programming homework assignment. Everything went smoothly until I reached a problem using Try/Except. If I type a valid datetime, the program will take it and it will move on, but if I use a valid datetime format, the exception won't react.
Here is my code:
import datetime
import csv
def get_stock_name(prompt,mode):
while True:
try:
return open(input(prompt) + ".csv")
except FileNotFoundError:
print("File not found. Please try again.")
except IOError:
print("There was an IOError opening the file. Please try again.")
def get_stock_date(prompt):
while True:
try:
return (input(prompt))
except TypeError:
print("Try again.")
except ValueError:
print("Try again.")
def get_stock_purchased(prompt):
while True:
try:
return (input(prompt))
except ValueError:
print("Try again.")
except TypeError:
print("try again.")
stock_name = get_stock_name("Enter the name of the file ==> ", "w")
stock_date = datetime.datetime.strptime(get_stock_date("Enter the stock purchase date ==> " , "%m/%d/%Y"))
stock_sold = datetime.datetime.strptime(get_stock_date("Enter the date you sold the stock ==>" , "%m/%d/%Y"))
stock_purchased = get_stock_purchased("How many stocks were purchased on start date ==>")
To clarify Tigerhawk's initial comment: in order for the try-catch to handle TypeError or ValueError, you need to cast the input to datetime in the try statement.
import datetime
def get_stock_date(prompt):
while True:
try:
return datetime.datetime.strptime(input(prompt), "%m/%d/%Y")
except (ValueError, TypeError):
print("Try again.")
stock_date = get_stock_date("Enter the stock purchase date ==> ")
Additionally, your initial post had strange indentation that made it look like you were making a recursive call to get_stock_date, which caused confusion.
Lastly, you will need to use raw_input if you're using Python 2.
You currently have a loop that will immediately end the function and return a string in any situation I can think of off the top of my head, exceptions that (as just mentioned) I don't think will happen, a call to strptime with the wrong number of arguments, and a recursive call to your function with the wrong number of arguments. And you never save or return a meaningful value. Maybe the recursive call just has wrong indentation? Anyway, you'll have to completely restructure your code, as most of it makes little sense:
import datetime
def get_stock_date(prompt):
while True:
d = input(prompt)
try:
d = datetime.datetime.strptime(d, "%m/%d/%Y")
except (ValueError, TypeError):
print("Try again.")
else:
return d
stock_date = get_stock_date("Enter the stock purchase date ==> ")
I think this is what you are looking for:
def get_stock_date(prompt):
try:
stock_date = datetime.datetime.strptime(prompt, "%m/%d/%Y")
return(stock_date)
except:
print("Try Again.")
prompt = input("Enter the stock purchase date ==> ")
get_stock_date(prompt)
get_stock_date(input("Enter the stock purchase date ==> " ))

Python: Can I combine these functions together to shorten my python code?

Can I combine these functions together to shorten my python code? I'm creating a quick program!
Here are the functions:
def try1():
try:
num1=input("Enter num 1: ")
return num1
except ValueError:
print("incorrect!")
return #value
def try2():
try:
num2=input("Enter num 2: ")
return num2
except ValueError:
print ("incorrect!")
return #value
def try3():
try:
num3=input("Enter num 3: ")
return num3
except ValueError:
print ("incorrect!")
return #value
def try4():
try:
num4=input("Enter num 4: ")
return num4
except ValueError:
print ("incorrect!")
return #value
Please post your suggestions and answers below.
As you can see from my reputations, I am a new programmer hoping to find kind people on Stackoverflow.
(This answer is based on the original revision of the question which is no longer accessible but showed a different problem, where the user is keep being asked until a valid number is entered. And the code showed some skill game system or something, so that’s why my questions are longer and more specific too.)
Something like this?
def getInt(name, target):
while True:
try:
return int(input('Please enter {0} for {1}: '.format(name, target)))
except ValueError:
print('Incorrect!')
strength0 = getInt('strength', 'character 1')
skill0 = getInt('skill', 'character 1')
strength1 = getInt('strength', 'character 2')
skill1 = getInt('skill', 'character 2')
In general, when you have multiple functions that approximately do the same thing, then yes, there is a lot potential to refactor it so you don’t repeat yourself. In this case, what was different is the question the user was being asked, so if we parameterize that, we are good to use just a single function to handle it all.
The function can be generalised to ask for the input of any number, for example:
def try_num(n):
num = int(input("Enter num {} : ".format(n)))
while num != n:
print ("incorrect!")
num = int(input("Enter num {} : ".format(n)))
return num
Use it like this:
try_num(10)
Enter num 10 : 9
incorrect!
Enter num 10 : 10
10
def safe_int(x):
try:
return int(x)
except ValueError:
return 0
[safe_int(raw_input("Number %d:"%i)) for i in range(4)]
I would create a validation method and simply pass in the strings.
def validate(question):
while True:
try:
print question,
input = raw_input()
if input.isdigit():
return int(input)
else:
print "Not a valid integer"

Categories