I have to use a for loop to write a function has that consumes a nonempty string and determines whether or not there is at least one digit in the string, producing True if so and False otherwise.
I tried this code but it is incorrect.
string = input()
def has_digit(string):
for character in string:
if character.isdigit():
print("True")
else:
print("False")
What is the point of doing a for loop in this case? And, to do a loop, would I call on the string or something else?
Confused beginner, thanks.
You can use a loop to go through each character and test it. Try this code:
def contains_digit(string):
for character in string:
if character.isdigit():
return True #String contains digit, stop here
return False #None of the characters were digits
You can try with this:
string = input()
result = False
for char in string:
if char.isdigit():
result = True
return result
Of course you need to change return with something else if the loop is not in a function.
Try this code, just pass a string to this function and it returns true or false based on the your condition.
def has_digit(string):
nodigit=1
for character in string:
if character.isdigit():
nodigit=nodigit*0
else:
nodigit=nodigit*1
if nodigit==1:
print (False)
else:
print (True)
or if you want shorter code use this
def has_digit(string):
for character in string:
if character.isdigit():
return True
break
return False
Related
I need to determine if there are alphabetic and numeric characters in a string. My code for testing the alphabetic one seems to work fine, but numeric is only working if all of the characters are a digit, not if any.
The alphabetic code that works:
from curses.ascii import isalnum, isalpha, isdigit
password = input("Enter your password: ")
def contains_alphabetic():
for i in password:
if isalpha(i):
print("Valid")
return True
else:
print("Invalid")
return False
contains_alphabetic()
This returns "Valid" if at least one of the characters is alphabetic, and "Invalid" if none of them are, which is what I want.
def contains_numeric():
for j in password:
if isdigit(j):
print("Valid")
return True
else:
print("Invalid")
return False
contains_numeric()
This only returns "Valid" if all of the characters are numeric, not if at least one is. How do I fix this?
Also, I tried using is.numeric() instead of is.digit() and it wouldn't even import.
As the comments have pointed out, both your contains_alphabetic and contains_numeric functions don't do what you think they're doing, because they terminate prematurely - during the very first iteration. You start a loop, inspect the current character (which will be the first character of the string during the first iteration of the loop), and immediately return something from the function based on that single character, which of course terminates the loop and the function.
Other suggestions: There's no need to import things from curses. Strings already have isalpha and isdigit predicates available. Additionally, it's probably a good idea to have your functions accept a string parameter to iterate over.
If the idea is to return True if any of the characters in a string satisfy a condition/predicate, and False otherwise (if none of the characters satisfy the condition), then the following would be a working implementation:
def contains_alpha(string):
for char in string:
if char.isalpha():
return True # return True as soon as we see a character that satisfies the condition
return False # Notice the indentation - we only return False if we managed to iterate over every character without returning True
Alternatively:
def contains_alpha(string):
found = False
for char in string:
if char.isalpha():
found = True
break
return found
Or:
def contains_alpha(string):
for char in string:
if char.isalpha():
break
else: # Notice indentation - special for-else syntax: If we didn't break out of the loop, execute the else
return False
return True
Or:
def contains_alpha(string):
return any(char.isalpha() for char in string)
I'm trying to write something that shows whether or not a letter in a list is in a string and for some reason what I've written always returns false. Where am I going wrong?
def is_word_guessed(secret_word, letters_guessed):
for char in secret_word:
if char not in letters_guessed:
guess = False
break
else:
guess = True
return guess
print(is_word_guessed("python", ["o"]))
The issue you have is that you are checking whether a letter isn't in the string so let's say you have the following data:
letters = ["p", "g", "a"]
word = "python"
with this data the code will return False since the last letter you are checking, "n", isn't in the list of letters.
Same goes for the data you gave:
letters = ["o"]
word = "python"
since the first letter checked, "p", isn't in the list then the code returns False since the loop breaks.
So basically, unless all the letters in the word are in the list of letters your code will simply just return False.
This is the code you should be using:
def is_word_guessed(secret_word, letters_guessed):
for char in secret_word:
if char in letters_guessed:
return True
return False
print(is_word_guessed("python", ["o"]))
The difference here is that instead of checking whether a character is NOT in the list it will check whether it is so instead of having to have a list with all the characters the list can have any character that is in the word. The reason we use return True directly in the loop in the if statement is because the return statement stops the execution of the function so if there aren't any matching characters then the function won't execute the return True so the function won't stop there and will go execute return False which will only execute if none of the characters are in the list.
I think you would like to test it the other way around and break out if you find the first matching character.
def is_word_guessed(secret_word, letters_guessed):
for ch in secret_word:
if ch in letters_guessed:
return True
return False
You can try this. because you are breaking from the loop you exited your function early.
def is_word_guessed(secret_word, letters_guessed):
guess = None. #Note you have to declare the variable guess before assigning below, since you are returning the guess in your function
for char in secret_word:
if char not in letters_guessed:
guess = False
else:
guess = True
return guess
#Option2:
I do not think you need to loop through since your string is an iterable. you can just check for their value and return the result
def is_word_guessed(secret_word, letters_guessed):
if char not in letters_guessed:
return False
else:
return True
How to check if a string is strictly contains both letters and numbers?
Following does not suffice?
def containsLettersAndNumber(input):
if input.isalnum():
return True
else:
return False
isAlnum = containsLettersAndNumber('abc') # Should return false
isAlnum = containsLettersAndNumber('123') # Should return false
isAlnum = containsLettersAndNumber('abc123') # Should return true
isAlnum = containsLettersAndNumber('abc123$#') # Should return true
Please note that It MUST contain both letters and numerals
Simplest approach using only string methods:
def containsLetterAndNumber(input):
return input.isalnum() and not input.isalpha() and not input.isdigit()
input.isalnum returns true iff all characters in S are alphanumeric,
input.isalpha returns false if input contains any non-alpha characters, and
input.isdigit return false if input contains any non-digit characters
Therefore, if input contains any non-alphanumeric characters, the first check is false. If not input.isalpha() then we know that input contains at least one non-alpha character - which must be a digit because we've checked input.isalnum(). Similarly, if not input.isdigit() is True then we know that input contains at least one non-digit character, which must be an alphabetic character.
You can loop through and keep track of if you've found a letter and if you've found a number:
def containsLetterAndNumber(input):
has_letter = False
has_number = False
for x in input:
if x.isalpha():
has_letter = True
elif x.isnumeric():
has_number = True
if has_letter and has_number:
return True
return False
Alternatively, a more pythonic but slower way:
def containsLetterAndNumber(input):
return any(x.isalpha() for x in input) and any(x.isnumeric() for x in input)
You can also use regexes bool(re.match('^[a-zA-Z0-9]+$', 'string'))
My python function is supposed to take an input that is a string (of only letters and only lowercase letters). The function should output true if there are no repeating letters ( regardless of whether they are consecutive letters or not) and it's suppose to return false if there are repeating letters. My code only checks if the first letter is repeating or not, but doesn't check any other letter in the string. What is the issue?
Try this
def is_isogram(string):
for x in string:
if string.count(x) > 1:
return False
return True
You want to return True only if you pass through all the for loop
the following should rectify.
def is_isogram(s: str):
# loop through all unique chars
for x in set(s):
if s.count(x) > 1:
return True
# terminate after looping through all chars
return False
additionally convert string to a set to eliminate iterating over same char twice.
You're not making it past the first character because in the first iteration of the for loop, your "else" exits the function if the if statement returns false.
My solution
def is_isogram(x):
if len(str(x)) > len(set(x)):
return False
else:
return True
An isogram is a word that has no repeating letters, consecutive or non-consecutive. Implement a function that determines whether a string that contains only letters is an isogram. Assume the empty string is an isogram. Ignore letter case.
is_isogram("Dermatoglyphics" ) == true
is_isogram("aba" ) == false
is_isogram("moOse" ) == false # -- ignore letter case
Here is my code:
def is_isogram(string):
string = string.lower()
for char in string:
if string.count(char) > 1:
return False
else:
return True
And when I tried to run the test code Test.assert_equals(is_isogram("moOse"), False, "same chars may not be same case" ) It failed, but I thought I did convert everything into lowercase. Can someone help?
Try this:
def is_isogram(string):
string = string.lower()
for char in string:
if string.count(char) > 1:
return False
return True
In your code when is_isogram("moose") is called, it will see that the first character's ('m') count is not greater than 1. So it will return True. Once it hits the return statement, it will stop the execution for the rest string. So you should really write return True only after for-loop to make sure that the function checks for the whole string.
If however, at any point, it finds a character's count to be greater than 1, then it will simply return False and stop executing because there's no point of checking any more when one point is found where condition does not hold.
How about using sets? Casting the string into a set will drop the duplicate characters, causing isograms to return as True, as the length of the set won't differ from the length of the original string:
def is_isogram(s):
s = s.lower()
return len(set(s)) == len(s)
print is_isogram("Dermatoglyphics")
print is_isogram("aba")
print is_isogram("moOse")
print is_isogram("")
This outputs:
True
False
False
True
Try this :
def is_isogram(s):
string = s.lower()
if len(s) == len(set(string)):
return True
return False
Try this out:
def is_isogram(string):
return len(string) == len(set(string.lower()))
"Implement a function that determines whether a string that contains only letters is an isogram."
By using sets, you can create unique elements. So if there are any repeating numbers, it will only select one. By calling len() on these strings, you can compare the length to the original.
Sorry if I explained it poorly. I am working on this.
let us define an isogram well:
according to wikipedia An Isogram is a word in which no letter occurs more than once.
check here for more about an isogram
just remind letter
I write this code and it works for me :
def is_isogram(argument):
print(len(argument))
if isinstance(argument,str):
valeur=argument.lower()
if not argument:
return False
else:
for char in valeur:
if valeur.count(char)>1 or not char.isalpha():
return False
return True
else:
raise TypeError("need a string ")
NB: the hidden test is the fact that you must check if the char in the string is a alpha character a-z, when i add this it pass all the hiddens tests
up vote if this help
I reckon this might not be the best solution in terms of maximizing memory space and time. This answer is just for intuition purposes using a dictionary and two for loops:
def is_isogram(string):
#your code here
#create an empty dictionary
m={}
#loop through the string and check for repeating characters
for char in string:
#make all characters lower case to ignore case variations
char = char.lower()
if char in m:
m[char] += 1
else:
m[char] = 1
#loop through dictionary and get value counts.
for j, v in m.items():
#if there is a letter/character with a count > 1 return False
if v > 1:
return False
#Notice the scope of the "return True" command. It is outside.
return True