Fix EOF error when taking list as input and checking if sorted? - python-3.3

Here is my code:
lstInput = input('Type here: ')
lst = list(lstInput)
def is_sorted(lst):
if len(lst) == 1:
return True
else:
for x in range(len(lst)):
if lst[x] > lst[x+1]:
return False
return True
is_sorted(lst)
When I try to run it in zybooks, my class textbook, I get an EOF error for lstinput = input("Type here: "). I do not get an error in IDLE. Please help. Thanks

Related

Codeforces : Correct submmision giving a runtime error

I am attempting to solve this question with the following code.
# --- Algorithm --- #
def function(p):
n = int(p[0])
for i in range(n):
tot = 0
for num_list in p[1:len(p)]:
num_list = num_list.split()
number = int(num_list[i])
tot += number
if tot != 0:
return "NO"
return "YES"
# --- Run --- #
p = []
while True:
line = input()
if line:
p.append(line)
else:
break
ans = function(p)
print(ans)
However I keep getting "Runtime error on test 1". I self-tested the input myself and it was right.
The full codeforces submission data is here.

Is there any better way to do User Input validation in Python3.x ? or Improve this block of code

I'm trying to validate multiple user inputs, can be of diff. data types.
Is there any better way to do User Input validation in Python3 ? or Improve this block of code.
def validate_number(message):
i = 0
while i < 4:
try:
userInput = int(input(message))
except ValueError:
i += 1
if i == 4:
print('Max try reached !!!')
return False
else:
print("Not an integer! Try again.")
continue
else:
return userInput
break
#------------------------------------------
a = validate_number('Enter 1st No: ')
if a:
b = validate_number('Enter 2nd No: ')
if a and b:
sum = a + b
print('Result is : %s' %(sum))
print('Result is : {} '.format(sum))
print(f'Result is : {sum}')
this is my suggestion:
def validate_number(message):
for i in range(4):
try:
return int(input(message))
except ValueError:
print("Not an integer! Try again.")
print("Max try reached !!!")
a simple for loop in order to count the number of tries.
as it is the function will return None if no valid input is given. you may have to tweak that according to your needs.

Validation of Enter Fields

Interactively validating Entry widget content in tkinter
the link above explains how to do validation.
I am trying to do the same thing. But somehow i am not able to do it.
It is a 10 digit string. The first two being alphabets, the next two numbers then again the next two will be alphabets and then the rest all numbers.
for example MH02UH2012.
Other question which i have is when i run this the print of S and i is coming for the first three inputs only after that there is no print. and sometimes it prints only the first entered variable. I am not able to understand what is the issue
import tkinter
tk=tkinter.Tk()
def only_numeric_input(P,S,i):
i = int(i)
print (i, S)
if S == " ":
return False
elif i < 2:
if not S.isdigit():
return True
elif i > 5:
if S.isdigit():
return True
else:
return False
elif i > 9:
return False
e1=tkinter.Entry(tk)
e1.grid(row=0,column=0)
c=tk.register(only_numeric_input)
e1.configure(validate="key",validatecommand=(c,'%P', "%S", "%i"))
tk.mainloop()
There are issues in the condition statements of the only_numeric_input function. Try the below only_numeric_input function instead.
def only_numeric_input(P,S,i):
i = int(i)
print (i, S)
if S == " ":
return False
if i < 2 or (i>3 and i<6):
if S.isalpha() and S.isupper():
return True
else:
return False
elif i<10:
if S.isdigit():
return True
else:
return False
elif i > 9:
return False

Python: TypeError: 'int' object is not iterable

I'm tackling this following question:
Write a function is_fib(n) that returns True if n is a Fibonacci number, and False otherwise.
This is my code:
def is_fib(n):
def fib(x):
if x == 0:
return 0
elif x == 1:
return 1
else:
return fib(x-1) + fib(x-2)
for a in n:
if fib(a) == n:
result = True
break
else:
result = False
return result
Running this give rise to:
TypeError: 'int' object is not iterable.
I have been staring at the code for half an hour. Any help is greatly appreciated.
I think you mean
for a in range(n)
not
for a in n
As jozefg said you are missing range(n)
also notice that you need range(n+2) to cover all cases
def is_fib(n):
def fib(x):
if x == 0:
return 0
elif x == 1:
return 1
else:
return fib(x-1) + fib(x-2)
for a in range(n+2):
if fib(a) == n:
return True
return False
print(is_fib(3))
Firstly thanks to the two guys that helped me.
However, for Yoav's edition, python will run into an error when n is a really big number.
This is my new and improved version.
def is_fib(n):
if n < 0:
return False
else:
fib_0 = 0
fib_1 = 1
if n == fib_0 or n == fib_1:
return True
else:
for a in range(2,n+2):
fib = fib_0 + fib_1
fib_0,fib_1 = fib_1,fib
if fib >= n:
break
return fib == n

Return to main function in python

Working on Python 3.4.3
Let's say I have created three fuctions:
def choosing(mylist=[]):
print("We will have to make a list of choices")
appending(mylist)
done = False
while(done == "False"):
confirm = input("Is your list complete?[Y/N]")
if(confirm == "Y"):
print("Yaay! Choices creation complete."
"{} choices have been added successfully".format(len(mylist)))
done = True
elif(confirm == "N"):
action = input("What do you want to do? [Append/Delete]")
if(action == "Append"):
appending(mylist)
done = False
elif(action == "Delete"):
removing(mylist)
done = False
def appending(mylist1 = []):
print("Please type EOF when you want to stop!")
while True:
c = input("Please enter EOF to stop adding. Please enter a choice: ")
if(c=="EOF"):
break
else:
mylist1.append(c)
print("You have inserted {} choices".format(len(mylist1)))
print("Please verify them below: ")
for x in range(0, len(mylist1)):
print(mylist1[x])
def removing(mylist2 = []):
print("Following are choices: ")
r = input("What do you want to remove? ")
mylist2.remove(r)
print("{} successfully removed!".format(r))
Now problem is I can't just call choices() in append or remove function as choices() function will call append again and again infinitely.
So how do I get back in choices after appending or removing data in list?
As suggested by tobias_k, you should add the contents of choices() into a while loop.
I also found
some other problems:
False does not equal "False", so your while loop never runs.
You use terms like mylist, mylist1, and mylist2 - it's better to rename these to choosing_list, appending_list, and removing_list, so it's clearer.
You also shouldn't use False to define a while loop - instead, make a variable, then set it to True. When you have to stop, set it to False.
Here is the code with those problems fixed:
def appending(appending_list = []):
print("Please type EOF when you want to stop!")
while True:
c = input("Please enter EOF to stop adding. Please enter a choice: ")
if(c=="EOF"):
break
else:
appending_list.append(c)
print("You have inserted {} choices".format(len(appending_list)))
print("Please verify them below: ")
for x in range(0, len(appending_list)):
print(appending_list[x])
return appending_list
def removing(removing_list = []):
print("Following are choices: ")
r = input("What do you want to remove? ")
removing_list.remove(r)
print("{} successfully removed!".format(r))
return removing_list
print("We will have to make a list of choices")
choosing_list = appending()
list_incomplete = True
while list_incomplete:
confirm = input("Is your list complete?[Y/N]")
if(confirm == "Y"):
print("Yaay! Choices creation complete."
"{} choices have been added successfully".format(len(choosing_list)))
list_incomplete = False
elif(confirm == "N"):
action = input("What do you want to do? [Append/Delete]")
if(action == "Append"):
choosing_list = appending(choosing_list)
elif(action == "Delete"):
choosing_list = removing(choosing_list)
Let me know if there's any problems with this code.

Resources