write a function that validates password - if-statement

I have to write a function that validates a password and returns true or false. It is only true if it is 8 characters, contains a number, a upper case letter, and a symbol.
This is what I have for my function file.
def validatepassword(pswd):
for char in pswd:
if char in '01234567890':
containsnumber = True
I have no idea how to incorporate the other variables, any help is appreciated.
Thanks

def validatepassword(pswd):
## Declare the flags and set them to False
containsNumber = False
containsUpper = False
containsSymbol = False
for char in pswd: ## Loop through the characters of the password
if char in '0123456789': ## Check if the character's a number
containsNumber = True
elif char in "ABCEDFGHIJKLMNOPQRSTUVWXYZ": ## Otherwise check if the character's an uppercase letter
containsUpper = True
elif char not in "0123456789ABCEDFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz": ## Otherwise check if the letter isn't an alphanumeric character (i.e. a symbol)
containsSymbol = True
if containsNumber and containsUpper and containsSymbol and len(pswd) == 8: ## Were all of the checks passed?
return True
return False ## No need for an 'else' as the program will only reach this stage if it hasn't returned anything yet

Use regular expression and check the password matching as below in python.
Check python documentation for more help https://docs.python.org/2/howto/regex.html
import re
def validatePassword(pswd):
P=re.compile('[\d\D]')
if(P.match(pswd)):
print('TRUE')
else:
print('FALSE')
validatePassword('super')

Related

how to extract elements from a string with a trasversal loop

I have this little code:
> def names():
prefixes='JKLMNOPQ'
suffix='ack'
for letter in prefixes:
if letter == 'O'or 'Q' in prefixes:
print letter +'u' +suffix
else:
print letter+suffix
And I would like to achieve the following format after printing it:
Jack
Kack
Lack
Mack
Nack
Ouack
Pack
Quack
However I get this one:
Juack
Kuack
Luack
Muack
Nuack
Ouack
Puack
Quack
For any reason I cannot see the if statement is not work. How can I manage to make it work?
You probably might want to change your code to:
def names():
prefixes='JKLMNOPQ'
suffix='ack'
for letter in prefixes:
if letter == 'O' or letter == 'Q':
print letter +'u' +suffix
else:
print letter+suffix
Your problem is you have a "always" True condition:
def names():
prefixes='JKLMNOPQ'
suffix='ack'
for letter in prefixes:
if letter == 'O'or 'Q' in prefixes: # here
print letter +'u' +suffix
else:
print letter+suffix
'Q' is always in prefixes - the condition is alwas True.
Use if letter in 'O Q': instead.

For a given string check if matches the pattern [scala]

I am beginner in Scala and I was wondering how I can build a function to check if it matches a definite pattern or not?
For example:
def patternFound(s:String): Boolean = (s) match {
case s matches xyxy pattern => true //where x,y are two consecutive characters in the string
case s matches xxyy pattern => false //where x, y are two characters in that string
case (_) => false //default
}
//Here x,y are not definite characters but the string s should match a pattern
//which consist a string of pattern containing characters in alternating positions
patternFound("babab")//true because pattern of xyxy found in it
patternFound("baabba")//false because pattern of xxyy found in it
Can anyone show with an example how I can achieve this?
Looking for a solution which returns true for any occurrence of xyxyxy pattern in a string, but returns false when the pattern is xxyy in that string.
Example: The function should return true if the string is "babab" or
"ababa" (which has pattern xyxy in it), but returns false for "aabba"
or "bbaab" (which has the pattern xxyy in it)
Any help is appreciated! Thank you in advance.
For the two examples you've posted, these two Regex patterns will cover it.
def patternFound(s:String): Boolean = {
val ptrn1 = "(.)(.)\\1\\2".r
val ptrn2 = "(.)\\1(.)\\2".r
s match {
case ptrn1(_,_) => true
case ptrn2(_,_) => true
case _ => false
}
}
proof:
patternFound("rrgg") // res0: Boolean = true
patternFound("hqhq") // res1: Boolean = true
patternFound("cccx") // res2: Boolean = false
But I suspect that your requirements, as stated, are not specific enough to cover exactly what you're looking for.
UPDATE
You're 2nd requirement now makes no sense. Everything that doesn't match the 1st pattern will return false so there's no point in testing for a specific pattern to return false.
def patternFound(s:String): Boolean = {
val ptrn = "(.)(.)\\1\\2".r.unanchored
s match {
case ptrn(_,_) => true
case _ => false
}
}
patternFound("babab") //true because pattern of xyxy found in it
patternFound("baabba") //false because it doesn't match the target pattern
The syntax is not correct.
You need to remove "s matches" from the body of the function, it is already in the method definition line "(s) match".
See also https://docs.scala-lang.org/tour/pattern-matching.html
This might be possible with regular expressions and look arounds, but I just created a helper function:
/**
* Checks for recurring pattern in a String
* #param s The input String to check
* #param patternSize The size of the expected pattern. For example in the String "aabbaabbaabb" the pattern is "aabb" which is a length of 4
*/
def checkPattern(s: String, patternSize: Int): Boolean = {
val grouped = s.grouped(patternSize)
grouped.toSet.size == 1 // everything should be the same
}
Some example usage of that function:
checkPattern("abababab", 2) // true
checkPattern("aabbaabbaabb", 2) // false
checkPattern("aabbaabbaabb", 4) // true
checkPattern("abcabcabc", 3) // true
So for your code you could do use it with some guard statements:
def patternFound(s: String): Boolean = s match {
case "" => false // empty Strings can't have patterns
case s if checkPattern(s, 2) => true
case s if checkPattern(s, 4) => true
case _ => false
}
patternFound("ababababab") // true
patternFound("aabbaabb") // true
patternFound("aabbzz") // false
Edit: I think the other answer is better for what you are looking for, but here is my updated answer for you updated question:
def patternFound(s: String): Boolean = s match {
s.nonEmpty && checkPattern(s, 2)
}

Why condition returns True using regular expressions for finding special characters in the string?

I need to validate the variable names:
name = ["2w2", " variable", "variable0", "va[riable0", "var_1__Int", "a", "qq-q"]
And just names "variable0", "var_1__Int" and "a" are correct.
I could Identify most of "wrong" name of variables using regex:
import re
if re.match("^\d|\W|.*-|[()[]{}]", name):
print(False)
else:
print(True)
However, I still become True result for va[riable0. Why is it the case?
I control for all type of parentheses.
.match() checks for a match only at the beginning of the string, while .search() checks for a match anywhere in the string.
You can also simplify your regex to this and call search() method:
^\d|\W
That basically checks whether first character is digit or a non-word is anywhere in the input.
RegEx Demo
Code Demo
Code:
>>> name = ["2w2", " variable", "variable0", "va[riable0", "var_1__Int", "a", "qq-q"]
>>> pattern = re.compile(r'^\d|\W')
>>> for str in name:
... if pattern.search(str):
... print(str + ' => False')
... else:
... print(str + ' => True')
...
2w2 => False
variable => False
variable0 => True
va[riable0 => False
var_1__Int => True
a => True
qq-q => False
Your expression is:
"^\d|\W|.*-|[()[]{}]"
But re.match() matches from the beginning of the string always, so your ^ is unnecessary, but you need a $ at the end, to make sure the entire input string matches, and not just a prefix.

Terminating raw_input based on the ascii value of the string

I am new to python.
My Issue- need to terminate the raw_input if no input is passed
I am basically asking user for number of key-value pairs to be added to dictionary. Then adding the key-value pairs in dictionary. Later querying the dictionary which should result value if key exist, else print Not found.
I searched the Stack Overflow and found solution in terms of timer but I am trying to use ord function to get ascii value of string and check it against null that is ascii value of 0. My code does not seem to terminate, please advice on necessary changes in code.
Please find the code that I am using in the program:
def convert_to_ascii(text):
return "".join(str(ord(char)) for char in text)
n=int(raw_input().rstrip())
phonebook = dict(raw_input().split() for i in range(n))
print phonebook
list1=[]
while True:
choice = raw_input()
temp=convert_to_ascii(choice)
print temp
if temp != '0':
list1.append(choice)
else:
break
for word in list1:
if word in phonebook :
print '{0}={1}'.format(word,phonebook[word])
else:
print 'Not found'
You should have the empty string '' instead of '0' as your check. This code worked for me. I also added some prints in the raw_inputs to help me look through your code, but the only change that matters is the '0' to '':
def convert_to_ascii(text):
return "".join(str(ord(char)) for char in text)
n=int(raw_input('How many entries in your phonebook?\n').rstrip())
phonebook = dict(raw_input('Please enter "[name] [number]" for entry '+str(i+1)+':\n').split() for i in range(n))
print phonebook
list1=[]
while True:
choice = raw_input('Who do you want to choose?\n')
temp=convert_to_ascii(choice)
if temp != '': #<-- changed to empty string from '0'
list1.append(choice)
else:
break
for word in list1:
if word in phonebook :
print '{0}={1}'.format(word,phonebook[word])
else:
print word,'was not found'

Python: The code disobeys the conditional depending on the input

I'm making a hang man game. When I made the code with out a conditional and classes, it worked fine. Basically my issues with the code below are:
Only the letter "t" will match. I can't get any other letter to match.
If I enter "t" on the first try, then purposely get the next 4 letters wrong, it won't end until after 7 turns. Yet if I enter any other letter first, it will end after 4 wrong turns, like it should.
My questions....
How can I get it to match with the other letters that are in the self.word index?
Why is it not obeying the condition I set with the while loop in the main method if I enter "t" on my first try and get every other letter wrong thereafter?
class Hang():
def __init__(self):
self.turns = 0
self.word = ['t', 'h', 'i', 's']
self.empty = ["__", "__", "__", "__"]
self.wrong = []
def main(self):
while self.turns < 4:
for i in self.word:
choice = raw_input("Enter a letter a-z: ")
if choice == i:
index = self.word.index(i)
self.empty.pop(index)
self.empty.insert(index, i)
print self.empty
else:
print "Wrong"
self.wrong.append(choice)
print self.wrong
print self.empty
self.turns += 1
char1 = Hang()
char1.main()
In the game of hangman you can guess any character in the phrase in any order. But you're using a for loop to go through each character in order and it is only correct if the player correctly guesses the characters in order
Try this instead
while self.turns < 4:
choice = raw_input("Enter a letter a-z: ")
# optional, if user enters more than a single letter
if len(choice) > 1:
print "invalid choice"
continue # loop again from start
index = self.word.index(choice)
if index != -1:
# -1 indicates character in not int the string
# so this block is only executed if character is
# in the string
self.empty[index] = choice # no need to pop, you can simply change the value of the list at a given index
else:
print "wrong"
self.turns += 1
print self.empty