Given set of numbers in a string in python - python

I want to check if a set of numbers is present in a string or not
Here is my code:
def check_no(string):
string = string.lower()
no = set(c)
s = set()
for i in string:
if i in no:
s.add(i)
else:
pass
if len(s) == len(no):
return("Valid")
else:
return("Not Valid")
c = input()
print(check_no(c))
if the given set of numbers is present in the string then it prints Valid and if not present it prints Not valid
the program works fine when the input is given as 123 and the string is like I have 12 car and 3 bikes then the output is valid
but when i give input as 254 and string as i hav25555number the output comes as valid but the actual output should be Not valid as 4 is not present in the string.
Can anyone help how to solve it in the provided code

I you want to check if all characters match then use all.
def check_no(text, check):
valid = all(character in text for character in check)
if valid:
return("Valid")
else:
return("Not Valid")
check = '254'
text = 'i hav25555number'
print(check_no(text, check))
The one-liner version
def check_no(text, check):
return 'Valid' if all(character in text for character in check) else 'Not Valid'

Your function is mostly correct, but probably because of your (terrible) choices of variable names, string and c variables were mixed up in the environment.
The solution is to add the parameters explicitly to the function definition (also avoid names like string or c as these could be pre-defined python keywords):
teststring = "254"
testc = "i hav25555number"
def check_no(mystring, myc):
string = mystring.lower()
no = set(c)
print("string is",string)
s = set()
for i in string:
if str(i) in no:
# print(i, " in ", no)
s.add(i)
else:
pass
# print("s is",s)
# print("no is",no)
if len(s) == len(no):
return("Valid")
else:
return("Not Valid")
print(check_no(teststring,testc))
gives:
print(check_no(teststring,testc))
string is 254
Not Valid
As mentioned before, you can use all to make your code more elegant, although there is nothing wrong with your implementation either.

Related

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

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

Two try statements with the same except clause

Say I want to do something in python 3 with a two character string like "A1" or "1A" but first check if it's in either form beacuse the user may type it in both ways. (I already have a way to check if a char is a letter.)
How would I implement this in the shortest and easiest way?
I would like to try one thing, and if it fails, try another before raising the exception. Like so:
x = 0
string = 'A1'
try:
x = int(string[1]) # Check that second char is a digit
# something else to check first char is a letter
else try:
x = int(string[0]) # Check that first char is a digit
# something else to check second char is a letter
except:
print('Was in neither form')
You could use a loop:
for i in range(1, -1, -1):
try:
string[i] = int(string[i])
except ValueError:
pass
else:
break
else:
print('Was in neither form')
If either conversion succeeds, the loop is broken out of with break. If you didn't use break, the else suite on the for loop is executed.
However, you cannot assign to string indices as they are immutable. A better option would be to use a regular expression:
import re
valid_pattern = re.compile('^(?:\d[A-Z]|[A-Z]\d)$')
def is_valid(string):
return valid_pattern.match(string) is not None
You could create a helper to reduce the nesting:
def letter_and_digit(identifier):
a, b = identifier
try:
return a, int(b)
except ValueError:
return b, int(a)
try:
letter, digit = letter_and_digit(string)
assert letter.isupper()
except:
print('Was in neither form')
A regular expression also works, but might be overkill:
import re
LETTER_DIGIT_PAIR = re.compile('^(?=.?([A-Z]))(?=.?([0-9]))..$')
letter, digit = LETTER_DIGIT_PAIR.match('A1').groups()
For variety, this approach does not use try/except. It simply verifies that string has exactly one digit and one letter:
if not (sum(c.isdecimal() for c in string) == 1 and sum(c.isalpha() for c in string) == 1):
print('Was in neither form')

How to check for valid sequence input?

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.")

How to check whether a str(variable) is empty or not?

How do I make a:
if str(variable) == [contains text]:
condition?
(or something, because I am pretty sure that what I just wrote is completely wrong)
I am sort of trying to check if a random.choice from my list is ["",] (blank) or contains ["text",].
You could just compare your string to the empty string:
if variable != "":
etc.
But you can abbreviate that as follows:
if variable:
etc.
Explanation: An if actually works by computing a value for the logical expression you give it: True or False. If you simply use a variable name (or a literal string like "hello") instead of a logical test, the rule is: An empty string counts as False, all other strings count as True. Empty lists and the number zero also count as false, and most other things count as true.
The "Pythonic" way to check if a string is empty is:
import random
variable = random.choice(l)
if variable:
# got a non-empty string
else:
# got an empty string
Just say if s or if not s. As in
s = ''
if not s:
print 'not', s
So in your specific example, if I understand it correctly...
>>> import random
>>> l = ['', 'foo', '', 'bar']
>>> def default_str(l):
... s = random.choice(l)
... if not s:
... print 'default'
... else:
... print s
...
>>> default_str(l)
default
>>> default_str(l)
default
>>> default_str(l)
bar
>>> default_str(l)
default
Empty strings are False by default:
>>> if not "":
... print("empty")
...
empty
For python 3, you can use bool()
>>> bool(None)
False
>>> bool("")
False
>>> bool("a")
True
>>> bool("ab")
True
>>> bool("9")
True
Some time we have more spaces in between quotes, then use this approach
a = " "
>>> bool(a)
True
>>> bool(a.strip())
False
if not a.strip():
print("String is empty")
else:
print("String is not empty")
element = random.choice(myList)
if element:
# element contains text
else:
# element is empty ''
How do i make an: if str(variable) == [contains text]: condition?
Perhaps the most direct way is:
if str(variable) != '':
# ...
Note that the if not ... solutions test the opposite condition.
if the variable contains text then:
len(variable) != 0
of it does not
len(variable) == 0
use "not" in if-else
x = input()
if not x:
print("Value is not entered")
else:
print("Value is entered")
{
test_str1 = ""
test_str2 = " "
# checking if string is empty
print ("The zero length string without spaces is empty ? : ", end = "")
if(len(test_str1) == 0):
print ("Yes")
else :
print ("No")
# prints No
print ("The zero length string with just spaces is empty ? : ", end = "")
if(len(test_str2) == 0):
print ("Yes")
else :
print ("No")
}
string = "TEST"
try:
if str(string):
print "good string"
except NameError:
print "bad string"
Python strings are immutable and hence have more complex handling when talking about its operations. Note that a string with spaces is actually an empty string but has a non-zero size.
Let’s see two different methods of checking if string is empty or not:
Method #1 : Using Len()
Using Len() is the most generic method to check for zero-length string. Even though it ignores the fact that a string with just spaces also should be practically considered as an empty string even its non-zero.
Method #2 : Using not
Not operator can also perform the task similar to Len(), and checks for 0 length string, but same as the above, it considers the string with just spaces also to be non-empty, which should not practically be true.
Good Luck!
#empty variable
myvar = ""
#check if variable is empty
if not myvar:
print("variable is empty") # variable is empty

Categories