How to check for valid sequence input? - python

import re
def check_input():
while True:
try:
sequence = raw_input("Please input:")
if sequence = [a,t,c,g]: # checking for valid input
continue
else:
print("invalid input, sequence coule only contain the "
"following letters (a,t,c,g)"):
check_input()
I basically want the script to check the user's input whether it contains only these four letters (a,t,c,g). If their input contains anything other than that four letters, it could print that second statement and prompt the user to input again. I saw there are similar questions and I already tried to change my script according to those posts but it still gives me the invalid syntax error at the if < sequence position. Anyone knows what's wrong here?

You need to iterate over every letter in the input and check if it is in the set of allowed letters, like this:
sequence = raw_input("Please input:")
for letter in sequence:
if letter not in "atcg":
print("invalid input, sequence coule only contain the following letters (a,t,c,g)")
When you discover that the sequence is invalid, you could choose to end the check by using a break statement after the print, or you could count how many invalid letters are allowed.

Your function must check and give user whether True or False:
def check_input(word):
result = True
for letter in sequene:
if letter in 'atcg':
continue
else:
result = False
break
return result
check_input('atgc')
Error Message:
if check_input('agct'):
continue
else:
print "error message"

You could also use the filter command:
def checkInp():
seq = raw_input("Please input sequence:")
if not filter(lambda m: m not in 'ATGC', seq) == '':
print 'Invalid input characters in sequence: ' + filter(lambda m: m not in 'ATGC', seq)
print 'Pleas'
check_input()
else: return seq

sequence, once input by the user will be a string, so you would need to iterate over each character in the sequence and use in to verify the existence of the character in the accepted characters string. String comparisons in Python are also case sensitive, so you need to match the case of the input to your expected string. I've used uppercase based on your sample input.
def check_input():
sequence = input("Please input:")
sequence.upper()
for letter in sequence:
if letter in 'ATCG':
continue
else:
print("invalid input, sequence could only contain the
following letters: a, t, c or g.")

Related

Why doesn't if any(var0) == any(var1) work?

I'm very new to programming, and more new to Python, and I'm having a hard time figuring this out. I'm trying to make a simple text hangman game, and I'm trying to validate player1's input. Here's what I have so far.
a = 0
int = ["1","2","3","4","5","6","7","8","9","0"]
while a == 0:
print("Please choose any word by typing it here:")
d = input()
d = list(d)
print(d)
if any(int) == any(d):
print("Invalid input. Please choose a non-number with no spaces or special characters.")
I can't figure why, whether I include a number in my response or not, it always meets my any(int) == any(d) condition. I know I must just be misunderstanding how any() works.
You are right: the issue is with how you use the any() function. any() returns either True or False depending on whether or not any of the elements in its iterable argument are True, in other words if they exist and are not False or an empty list or empty string or 0. This will always evaluate as True for int because int does contain an element that is True and the same will happen for d unless you do not give any input when the input() function prompts you (you hit return without typing anything). What your conditional is basically asking is the following:
if True==True
To fix this, just change your code to the following:
a = 0
int = ["1","2","3","4","5","6","7","8","9","0"]
while a == 0:
print("Please choose any word by typing it here:")
d = input()
print(d)
for letter in d:
if letter in int:
print("Invalid input. Please choose a non-number with no spaces or special characters.")
break
The easiest solution, however, does not involve the int list at all. There is actually a special method in python that can gauge whether or not a string has a number (or special character) in it, and this method, .isalpha() can be used to streamline this process even further. Here's how to implement this solution:
while True:
d = input("Please choose any word by typing it here: \n")
print(d)
if not d.isalpha():
print("Invalid input. Please choose a non-number with no spaces or special characters.")
Try this:
a = 0
ints = ["1","2","3","4","5","6","7","8","9","0"]
while a == 0:
print("Please choose any word by typing it here:")
word = input()
word_list = list(word)
if any(letter in ints for letter in word_list):
print("Invalid input. Please choose a non-number with no spaces or special characters.")

Check Python String Formatting

I can accept user's input in two formats:
123
123,234,6028
I need to write a function/a few lines of code that check whether the input follows the correct format.
The rules:
If a single number input, then it should be just a number between 1 and 5 digits long
If more then one number, then it should be comma-separated values, but without spaces and letters and no comma/period/letter allowed after the last number.
The function just checks if formatting correct, else it prints Incorrect formatting, try entering again.
I would assume I would need to use re module.
Thanks in advance
You can use a simple regex:
import re
validate = re.compile('\d{1,5}(?:,\d{1,5})*')
validate.fullmatch('123') # valid
validate.fullmatch('123,456,789') # valid
validate.fullmatch('1234567') # invalid
Use in a test:
if validate.fullmatch(your_string):
# do stuff
else:
print('Incorrect formatting, try entering again')
Another option is:
def validString(string):
listofints = [v.isdigit() for v in string.split(",") if 0 < len(v) < 6]
if not len(listofints) or not all(listofints):
print("Incorrect formatting, try entering again.")
The following code should leave the Boolean variable valid as True if the entered ibnput complies with your rules and False otherwise:
n = input("Your input: ")
valid = True
try:
if int(n) > 9999:
valid = False
except:
for character in n:
if not character in "0123456789,":
valid = False
if n[-1] == ",":
valid = False

How to check if list of strings entered are in alphabetical order?

I have a program which takes a series of strings from user input and should print "Yes" if the strings entered are in alphabetical order and "No" if not. The program ends by the user entering an empty input. I can do this when I specify the number of inputs it should have, eg 2:
finished = False
while not finished:
print("Please enter a string: ")
s = input()
x = input()
if len(s) != 0:
if s < x:
print("Yes")
else:
print("No")
else:
finished = True
However I can't seem to get my code to work when there is an indefinite amount of strings that can be entered. My current working method is to append all the strings to a list and perform the checks there, but I'm not sure exactly how to write the if statement to check this:
lst = []
i = range(len(lst))
finished = False
while not finished:
print("Please enter a string: ")
s = input()
lst.append(s)
if len(s) != 0:
if lst[i:] < lst[i: - 1]:
print("Yes")
else:
print("No")
else:
finished = True
Is there an easy way to achieve this without deviating too far from the intended structure above?
lst is a list of strings, slicing syntax on that will get you a list of strings back. But you want a string instead. Since you're appending to the list, the latest string appended will be present in the [-1] index, and the previous one will be present in [-2] index.
Change lst[i:] < lst[i: - 1] to lst[-2] < lst[-1]
There's still another problem though, in the first iteration lst[-2] does not exist, because there is only one string that has been inputted, to get rid of this - take one input and append it to the list before the loop starts-
print("Please enter a string: ")
s = input()
lst.append(s)
finished = False
while not finished:
# rest of your code
You can use the following to always compare the new item to the last item in the existing list. Therefore it always checks, if the next item is in order
new_input = input()
existing_list = ...
if sorted(existing_list[-1], new_input)[-1] == new_input
existing_list.append(new_input)
print("Yes")
else:
print("No")
That way, you don't have to enter the value to the list before checking
I have made some changes to your code. There is no need for two inputs and a master list. The code is as below.
Assumptions
Assumes that items in the list are separated by a single space
The difference between a capital case character and small case character is not important. If this is not true and ASCII ordering is important then remove ".lower()" from the third line.
while True:
print("Please enter a string: ")
s = input().lower() ## To avoid confusion between sorting ABb Abb and like strings
if not s: ## If nothing is entered break out of loop
break
SplitString = s.split(" ") ##Get elements separated by "single" space into list
SortedString = " ".join(sorted(SplitString)) ##Sort the list and then join into string
if s == SortedString: ##If the sorted and joined string is same as original then the string was already sorted when entered
print("Yes")
else: ## Else it was not sorted when entered
print("No")
The output is as below
Please enter a string:
AAA AAB ABA ABC
Yes
Please enter a string:
AAA AAB ABC ABA
No
Please enter a string:
aaa aab aba abc
Yes
Please enter a string:
aaa aab abc aba
No
Please enter a string:

Input not returning from function?

I'm making a basic text-based hangman game, and I'm stumped as to why inpLetter is returning None from letterVerify()? It's expected to return a string response so I'm unsure why it isn't.
def letterVerify(prompt):
try:
inp = input(prompt)
verify = str.count(inp)
if (verify > 1) or (verify < 1):
print("Please enter one character.")
if inp not in alphabet or alphabetCaps:
print("Please enter a letter from the English alphabet.")
else:
return inp
except:
print("Please enter a letter from the English alphabet.")
inpLetter = letterVerify("Enter a letter you think is in this word. ")
The problem is in line 4, verify = str.count(inp). count() function returns the number of times a particular character has appeared in a string. It is used as
string = 'abcabcabcabcabc'
string.count('a')
This returns 5. Your code could not find this error because of the try-except block. Whenever this error was raised, it was caught by the exception block, and hence made it difficult to debug. You can rather try using the len() function. This will do the same work you want. It will check if the length of input is 1 or not. Modifications to your code are as
def letterVerify(prompt):
inp = input(prompt)
verify = len(inp)
if verify > 1 or verify < 1:
print('Please enter 1 character')
elif not inp.isalpha():
print('Please enter a letter from English alphabet')
else:
return inp
inpLetter = letterVerify('Enter a letter you think is in this word')
Also, you did not specify what alphabet and alphabetCaps are. I have used isalpha() method, that checks only for alphabetical characters (what you needed). Hope this resolves your issue.
I made your function a little terse for better readability.
First, you should avoid naming your function in camelCase, this violates PEP8. Rather you should use snake_case while naming functions and variables.
Also, simple length checking will do the verify trick. str.count returns the number of times a letter appears in a string, you don't want that here.
You don't need the exception handler here. Python will internally make your inputs str type.
You can lower your string and make comparison with the built in string.ascii_lowercase property. This will eliminate redundant control flow logic.
Here is the function, refactored:
def letter_verify(prompt):
inp = input(prompt)
# remove extra whitespace
inp = inp.strip()
# simple length checking with len function will do the trick
if len(inp) != 1:
print("Please enter one character.")
# just make your input to lowercase and then compare
# this will help you avoid comparison with two cases
elif inp.lower() not in string.ascii_lowercase:
print("Please enter a letter from the English alphabet.")
else:
return inp

Write a function remove_duplicates in python

Write a function called remove_duplicates which will take one argument called string. This string input will only have characters between a-z.
The function should remove all repeated characters in the string and return a tuple with two values:
A new string with only unique, sorted characters.
The total number of duplicates dropped.
For example:
remove_duplicates('aaabbbac') => ('abc', 5)
remove_duplicates('a') => ('a', 0)
remove_duplicates('thelexash') => ('aehlstx', 2)
Here's my solution, and I'm new to python:
string = raw_input("Please enter a string...")
def remove_duplicates(string):
string = set(string)
if only_letters(string):
return (string, string.length)
else:
print "Please provide only alphabets"
remove_duplicates(string)
What might I be doing wrongly? This is the error I get below
THERE IS AN ERROR/BUG IN YOUR CODE
Results:
/bin/sh: 1: python/nose2/bin/nose2: not found
Thanks.
This works just fine. The output should be sorted.
def remove_duplicates(string):
new_string = "".join(sorted(set(string)))
if new_string:
return (new_string, len(string)-len(new_string))
else:
print "Please provide only alphabets"
No need to include this:
string = raw_input("Please enter a string...")
remove_duplicates(string)
As the order is not important, you can use
string = raw_input("Please enter a string...")
def remove_duplicates(string):
new_string = "".join(set(string))
if new_string:
return (new_string, len(string)-len(new_string))
else:
print "Please provide only alphabets"
remove_duplicates(string)
Please enter a string...aaabbbac
Out[27]: ('acb', 5)
set() will create a set of unique letters in the string, and "".join() will join the letters back to a string in arbitrary order.
was receiving the same error from a test I am working on, I feel the error is not from your end but the tester's end

Categories