Python - Finding all non alpha-numeric characters in a string - python

I'm designing a system that allows users to input a string, and the strength of the string to be determined by the amount of non alphanumeric characters. Points should be awarded like so: +1 for every non-alnum character to a maximum of 3 non-alnum characters.
def non_alnum_2(total,pwd):
count = 0
lid = 3
number = 0
if pwd[count].isalnum():
if True:
print "Nope"
if False:
print "Good job"
count = count + 1
number += 1
if number > lid:
number = lid
return number
total = 0
number = 0
pwd = raw_input("What is your password? ")
non_alnum_2(total, pwd)
print total
total += number
I've only just started coding, so I'm sorry if this seems like a very junior question.

You can simply try:
bonus = min(sum(not c.isalnum() for c in pwd), 3)

If you want to count the number of non-alpha strings you could say
def strength(string):
'''Computes and returns the strength of the string'''
count = 0
# check each character in the string
for char in string:
# increment by 1 if it's non-alphanumeric
if not char.isalpha():
count += 1
# Take whichever is smaller
return min(3, count)
print (strength("test123"))

There are multiple problems with this code.
First, if True: is always true, so the "Nope" will always happen, and if False: is never true, so none of that stuff will ever happen. I think you wanted this:
if pwd[count].isalnum():
print "Nope"
else:
print "Good job"
count = count + 1
number += 1
Also, I think you want to increment count always, not just if it's a symbol, so:
if pwd[count].isalnum():
print "Nope"
else:
print "Good job"
number += 1
count = count + 1
Meanwhile, you need some kind of loop if you want this to happen over and over. For example:
while count < len(pwd):
if pwd[count].isalnum():
# etc.
However, you really don't need to maintain count yourself and keep doing pwd[count]; you can use a for loop for this:
for ch in pwd:
if ch.isalnum():
# etc.
Meanwhile, while you do return a value from the end of the function, you don't do anything with that returned value when you call the function. What you need is:
number = non_alnum_2(total, pwd)
Also, there's no reason to pass total to non_alnum_2 here. In fact, it doesn't do anything useful at all.
So, putting it all together:
def non_alnum_2(pwd):
lid = 3
number = 0
for ch in pwd:
if ch.isalnum():
print "Nope"
else:
print "Good job"
number += 1
if number > lid:
number = lid
return number
pwd = raw_input("What is your password? ")
number = non_alnum_2(pwd)
print number

def non_alnum(s):
temp=[]
for i in s:
if i.isalnum():
continue
else:
temp.append(i)
if temp==[]:
print("The string doesn't contain any non_alphanumeric chars")
else:
print("The string contains non_alphanumeric chars: ",temp)
str1="ABCDEFabcdef123450"
str2="ABCDEF;abcdef'1234!50"
str3="*&%#!}{"
non_alnum(str1)
non_alnum(str2)
non_alnum(str3)

Related

how to check repeating Vowels

I'm pretty new to python and I'm having trouble with my
if then else statements and I only get is "no repeating vowels" which mean my rep_vowel is still returning 0
so the program rules are as follows.
if no vowel appears next to itself (e.g. hello), then print:
no vowel repeats
if exactly one vowel is repeated in sequence at least once (e.g. committee) then print a message that indicates which vowel repeats:
only vowel e repeats
if more than one vowel repeats (e.g. green door) then print:
more than one vowel repeats
ignore upper case - lower case differences: assume all the input is always lowercase
answer = input("Enter a string: ")
rep_vowel = 0
i = 0
length_Answer = len(answer)
next_string = 1
curChar = answer[0+rep_vowel]
for i in range(0,length_Answer):
if answer[0 + i] in ["a","e","i","o","u"]:
i =+ 1
next_string = answer[0+i+i]
if next_string == answer:
rep_vowel =+ 1
if rep_vowel == 0:
print("no repeating vowles")
elif rep_vowel > 1:
print("more than 1 repeating vowels")
else:
print ("the letter "+ str(curChar) +" repeats")
You have a few mistakes so i'll try to address several of them:
You do a lot of [0 + something] indexing, which is useless, since 0 + something always equals to something, so yo should just do indexing with [something]
Changing the value of i with i += 1 is bad because you are already increasing it as part of the loop
All you have to do to find a match is simply match the current letter to the next one, if both are the same and they are also vowels, you've found a match.
You are initializing unnecessary variables such as i = 0 only to have them overridden in the next lines
Adding all of those together:
answer = input("Enter a string: ")
vowels = "aeiou"
repeats = [] # this list will hold all repeats of vowels
for i in range(len(answer) - 1): # i'll explain the -1 part at the end
if answer[i] in vowels and answer[i] == answer[i + 1]:
repeats.append(answer[i])
if len(repeats) == 0:
print("no repeating vowles")
elif len(repeats) > 1:
print("more than 1 repeating vowels")
else:
print("the letter " + repeats[0] + " repeats")
This still doesn't take every possible input into account, but it should get you started on a final solution (or perhaps that's enough). For example, input of teest will give the correct result but the input of teeest doesn't (depends on your definition of correct).
About the len(answer-1) range, that's only to make sure we don't go out of bounds when doing answer[i + 1], so we're stopping on the next to last letter instead.
Firstly, you have to indent your code.
to say if (condition) then do print('hello') you write it this way:
if condition:
print('hello')
Secondly, you are using i =+ 1 which is the same as i=1
I think you meant i +=1 which is i = i+1
Finally, I suggest this code:
answer = input("Enter a string: ")
vowel_repeated_count = 0
length_Answer = len(answer)
i=0
while (i <length_Answer-1):
#we check if it's a vowel
if answer[i] in ["a","e","i","o","u"]:
#we check if it's followed by the same vowel
if answer[i+1] == answer[i]:
#increment the vowel_repeated_count
vowel_repeated_count +=1
#we save the vowel for the display
vowel = answer[i]
#we skip the other same repeated vowels
#example: abceeed, we skip the third e
while (answer[i] == vowel and i < length_Answer-1):
i +=1
#we add this incrementation because we're in a while loop
i +=1
if vowel_repeated_count == 0:
print("no repeating vowles")
elif vowel_repeated_count == 1:
print("the letter "+ str(vowel) +" repeats")
else:
print ("more than 1 repeating vowels")
You have some logical errors. It's time consuming to edit that. You can try this, I have modified your code. Hope it will work for you. I have commented beside every important line.
answer = input("Enter a string: ")
is_found = {} #a dictionary that will hold information about how many times a vowel found,initially all are 0
is_found["a"]=0
is_found["e"] = 0
is_found['i']=0
is_found['o']=0
is_found['u']=0
vowels =["a","e","i","o","u"]
for i in range(0,len(answer)):
if answer[i] in vowels:
is_found[answer[i]] = is_found[answer[i]]+1 # if a vowel found then increase its counter
repeated=0 #let 0 repeated vowel
previously_repeated=False #to trace whether there is a previously repeated character found
curChar=None
for key,value in is_found.items(): #iterate over dictionary
if previously_repeated and value>1: #if a vowel found and previously we have another repeated vowel.
repeated=2
elif previously_repeated==False and value>1: # we don't have previously repeated vowel but current vowel is repeated
curChar=key
previously_repeated=True
repeated=1
if repeated== 0:
print("no repeating vowles")
elif repeated> 1:
print("more than 1 repeating vowels")
else:
print ("the letter "+ str(curChar) +" repeats")
There is no need to increment your counter i. In your for loop, it will increment itself each time it goes through the for loop. Also, you need a variable to keep track of how many times the vowel repeats.
answer = input("Enter a string: ")
rep_vowel = 0
length_Answer = len(answer)
vowelList=["a","e","i","o","u"]
vowelRepeated = []
#this will go from i=0 to length_Answer-1
for i in range(length_Answer):
if (answer[i] in vowelList) and (answer[i+1] in vowelList):
if (answer[i] == answer[i+1]):
vowelRepeated.append(answer[i])
repVowel += 1
if rep_vowel==0:
print("no repeating vowels")
elif rep_vowel==1:
print("only one vowel repeated:")
print(vowelRepeated)
else:
print("multiple vowels repeated:")
print(vowelRepeated)
for such counting, I will prefer to use a dictionary to keep the counting number. Your code has been modified for your reference
answer = input("Enter a string: ")
length_Answer = len(answer)
count = dict()
for i in range(length_Answer):
if answer[i] in ["a","e","i","o","u"]:
if answer[i+1] == answer[i]:
if answer[i] in count:
count[answer[i]] += 1
else:
count[answer[i]] = 1
rep_vowel = len(count)
if rep_vowel == 0:
print("no repeating vowles")
elif rep_vowel > 1:
print("more than 1 repeating vowels")
else:
for k in count:
vowel = k
print("the letter " + vowel + " repeats")
You have a few issues with your solution :
1) You never use curChar, i'm guessing you wanted to enter the next_string value into it after the '==' statement.
2) You compare your next_string to answer, this will always be a false statement.
3) Also no need to use [0+i], [i] is good enough
Basically what you want to do is this flow :
1) Read current char
2) Compare to next char
3) If equal put into a different variable
4) If happens again raise a flag
Optional solution :
vowel_list = ["a","e","i","o","u"]
recuring_vowel_boolean_list = [answer[index]==answer[index+1] and answer[index] in vowel_list for index in range(len(answer)-1)]
if not any(recuring_vowel_boolean_list ):
print("no repeating vowels")
elif (recuring_vowel_boolean_list.count(True) > 1):
print("More then 1 repeating vowels")
else:
print("The letter {} repeats".format(answer[recuring_vowel_boolean_list.index(True)]))

Python String Handling Functions

Is there a specific function that returns true if characters in the string are special characters (ex: #. #. $)? Like, the isalpha() function returns true if all the characters in a string are letters.
I have to create a program where I need to ask a user for a string and then my program must print the length of the string, the number of letters, the number of digits and the number of characters that are not letters.
counter = 0
num = 0
extra = 0
wrd = raw_input("Please enter a short sentence.")
for i in wrd:
if i.isalpha():
counter = counter + 1
print "You have " + str(counter) +" letters in your sentence."
for n in wrd:
if n.isnumeric():
num = num + 1
print "You have " + str(num) + " number(s) in your sentence"
for l in wrd:
extra = extra + 1
print "You have " + str(extra) + " characters that are not letters or numbers."
I got the first two parts figured out albeit I'm stuck on the last...I know its easier to just create one while loop but since I already started, I want to stick with three four loops.
You don't need another function. Since you've already counted the other characters, subtract them from the total:
print "You have", len(wrd) - counter - num, "characters that are not letters or numbers."
Is there a specific function that returns true if characters in the string are special characters (ex: #. #. $)? Like, the isalpha() function returns true if all the characters in a string are letters.
No, but its pretty easy to create your own:
import string
def has_special_chars(s):
return any(c in s for c in string.punctuation)
Test:
>>> has_special_chars("ab#tjhjf$dujhf&")
True
>>> has_special_chars("abtjhjfdujhf")
False
>>>
In your case, you would use it like:
for l in wrd:
if has_special_chars(l)
extra=extra+1
But as #TigerHawkT3 has already beat me to saying, you should simply use len(wrd) - counter - num instead. Its the most canonical and obvious way.
Just to log a generic answer that will apply beyond this context -
import string
def num_special_char(word):
count=0
for i in word:
if i in string.punctuation:
count+=1
return count
print "You have " + str(num_special_char('Vi$vek!')) + " characters that are not letters or numbers."
Output
You have 2 characters that are not letters or numbers.
Use one for loop with if, elif and else:
sentence = raw_input("Please enter a short sentence.")
alpha = num = extra = 0
for character in sentence:
if character.isspace():
pass
elif character.isalpha():
alpha += 1
elif character.isnumeric():
num += 1
else:
extra += 1
print "You have {} letters in your sentence.".format(alpha)
print "You have {} number(s) in your sentence".format(num)
print "You have {} characters that are not letters or numbers.".format(extra)

Write a program that lets the user enter a string and displays the character that appears most frequently in the string

I am currently working on python, and I do not understand this much. I am looking for help with this question, before the dictionaries. This question is to be completed without any dictionaries. The problem is I do not know much about the max function.
So Far I have:
AlphaCount = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
Alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
for ch in text:
ch = ch.upper()
index=Alpha.find(ch)
if index >-1:
AlphaCount[index] = AlphaCount[index]+1
You can use Counter
from collections import Counter
foo = 'wubalubadubdub'
Counter(list(foo))
To get the most frequent letter
Counter(list(foo)).most_common(1)
You can use set which will get only unique characters from the input. Then iterate over them and count how many times it occurs in the input with count. If it occurs more often then the max and isalpha (not a space) then set max to the count.
text='This is a test of tons of tall tales'
un=set(text.upper())
max=0
fav=''
for u in un:
c=text.upper().count(u)
if c>max and u.isalpha():
max=c
fav=u
print(fav) # T
print(max) # 6
EDIT
To do this from your code: fix capitalization(for, if) and then find and print/return the most common letter. Also AlphaCount has an extra 0, you only need 26.
text='This is a test of tons of tall talez'
AlphaCount=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
Alpha='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
for ch in text:
ch= ch.upper()
index=Alpha.find(ch)
if index >-1:
AlphaCount[index]+=1
print(AlphaCount) # the count of characters
print(max(AlphaCount)) # max value in list
print(AlphaCount.index(max(AlphaCount))) # index of max value
print(Alpha[AlphaCount.index(max(AlphaCount))]) # letter that occurs most frequently
def main():
string = input('Enter a sentence: ')
strings=string.lower()
counter = 0
total_counter = 0
most_frequent_character = ""
for ch in strings:
for str in strings:
if str == ch:
counter += 1
if counter > total_counter:
total_counter = counter
most_frequent_character = ch
counter = 0
print("The most frequent character is", most_frequent_character, "and it appears", total_counter, "times.")
main()

python password checker: numbers and symbols

I'm new to python and I'm having a problem. I need to check a password on its upper, lower, numbers and symbols. It needs 1 of each class and the whole password needs to be longer then 6 characters. I have upper and lower case so far. raw_input inputs as a string so how can I then check for numbers and symbols in that string?
My code so far:
p = raw_input(("plz enter a password to check it's strength"))
if len (p) <= 6:
if p.isupper() or p.islower() or int(p):
print"This is a weak password "
elif len(p) > 6 and len(p) <26:
if p.isupper() or p.islower() or isdigit():
print "wea2k"
else:
print "good"
So what I need to know is how to check the input for numbers and symbols.
Try taking the requirements one at a time.
has_upper = False
for char in p:
if char.isupper():
has_upper = True
break
Repeat this for lower case and digits.
For special characters, use the same type of loop, but change the if to something like this:
if not (char.isupper() or char.islower() or char.isdigit()):
At the end, if all four flags are true, then you have a strong password; otherwise, it's weak.
Can you finish the coding from there?
Just so you know, there are ways to code this that are far more "Pythonic" -- that use the language's style much better. For instance:
has_upper = reduce(lambda a, b: a or b.isupper(), [_ for _ in p], False)
... replaces the entire 5-line block that I gave you.
Try this:
p = raw_input(("plz enter a password to check it's strength"))
upper_case = 0
lower_case = 0
number = 0
symbol = 0
for i in p:
if i.isupper():
upper_case += 1
elif i.islower():
lower_case += 1
elif i.isdigit():
number += 1
else:
symbol += 1
if len (p) <= 6:
print"This is a weak password "
elif upper_case > 0 and lower_case > 0 and number > 0 and symbol > 0:
print "Good"
else:
print "Too Weak"

Loop Issue with Local Variable

I'm using Python (3.x) to create a simple program for an assignment. It takes a multiline input, and if there is more than one consecutive whitespace it strips them out and replaces it with one whitespace. [That's the easy part.] It must also print the value of the most consecutive whitespaces in the entire input.
Example:
input = ("This is the input.")
Should print:
This is the input.
3
My code is below:
def blanks():
#this function works wonderfully!
all_line_max= []
while True:
try:
strline= input()
if len(strline)>0:
z= (maxspaces(strline))
all_line_max.append(z)
y= ' '.join(strline.split())
print(y)
print(z)
if strline =='END':
break
except:
break
print(all_line_max)
def maxspaces(x):
y= list(x)
count = 0
#this is the number of consecutive spaces we've found so far
counts=[]
for character in y:
count_max= 0
if character == ' ':
count= count + 1
if count > count_max:
count_max = count
counts.append(count_max)
else:
count = 0
return(max(counts))
blanks()
I understand that this is probably horribly inefficient, but it seems to almost work. My issue is this: I would like to, once the loop is finished appending to all_lines_max, print the largest value of that list. However, there doesn't seem to be a way to print the max of that list without doing it on every line, if that makes sense. Any ideas on my convoluted code?
Just print the max of all_line_max, right where you currently print the whole list:
print(max(all_line_max))
but leave it at the top level (so dedent once):
def blanks():
all_line_max = []
while True:
try:
strline = input()
if strline:
z = maxspaces(strline)
all_line_max.append(z)
y = ' '.join(strline.split())
print(y)
if strline == 'END':
break
except Exception:
break
print(max(all_line_max))
and remove the print(z) call, which prints the maximum whitespace count per line.
Your maxspaces() function adds count_max to your counts list each time a space is found; not the most efficient method. You don't even need to keep a list there; count_max needs to be moved out of the loop and will then correctly reflect the maximum space count. You also don't have to turn the sentence into a list, you can directly loop over a string:
def maxspaces(x):
max_count = count = 0
for character in x:
if character == ' ':
count += 1
if count > max_count:
max_count = count
else:
count = 0
return max_count

Categories