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
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)
Here is the question:
Write a program to accept 2 inputs from user, a string and a list of letters. It should then display True if the entered string consists of all the letters in a given list.
And here is the solution I wrote:
def guess(secword,thelist):
for letter in thelist:
if letter not in secword:
return False
return True
word=str(input("Please enter a word"))
print("The length of your word is",len(word))
aList=[]
for i in word:
x=input("Please enter a character to add to the list")
aList.append(x)
print(aList)
print(guess(word,aList))
This solution I wrote works, however, if I change the code as such (adding an else statement):
def guess(secword,thelist):
for letter in thelist:
if letter not in secword:
return False
else:
return True
It does not work anymore.
Can anyone please provide an explanation?
Thanks for your time
Any return statement ends the function right there. In your broken code example
def guess(secword, thelist):
for letter in thelist:
if letter not in secword:
return False
else:
return True
(which is a quite typical beginner's gotcha) you return from the first iteration og the loop in every case. That means you are only examining the first element of the thelist.
def guess(secword, thelist):
for letter in thelist:
if letter not in secword:
return False
return True # you only know for sure after all are examined
def guess(secword,thelist):
for letter in thelist:
if letter not in secword:
return False
else:
return True
Think about what this is doing; it will check the first letter of the list, and if that letter is not present in secword it will correctly return false. If the letter is in secword, however, it will return true instantly without checking the rest of the letters in the word.
If I understand the question correctly, your initial function should be correct. That one will return false if any letter in the list is not in the word, and true otherwise.
Putting the "return True" inside the for-loop changes how it will work compared to the first solution. It will just check the first letter and return either False or True and exit from the function without looking at the rest of the letters.
I have a function that checks if a given string is in a list of strings using a for and while loop. I’m not supposed to use the ‘in’ operator. Here’s my code using a for loop:
def word_in_list(words, word):
for strings in words:
if len(words) > 0 and strings == word:
return True
else:
return False
However, it is not returning True unless the single string is the first element of the list. The list should return False in case the list is empty. And how can I solve the same problem using a while loop (and without 'in' operator)?
Don’t return False the moment you find one mismatch, return False when you are done checking all possibilities and not finding any match:
def word_in_list(words, word):
for strings in words:
if strings == word:
return True
return False
Also, no need to check the length of list every time, if it's zero, you don't run the loop at all and directly return False.
Your code is wrong because of the else statement. Your function must return False only after checking the whole list, not just the first element. Whenever a function gets to a "return" instruction, it stops, so it just checked the first one. This is the correct solution:
def word_in_list(words, word):
i = 0
while i < len(words):
if words[i] == word:
return True
i += 1
return False
simly use this code
def word_in_list(words, word):
if word in words:
return True
else
return False
Your else block kicks-in without finishing the iteration on complete list.
def word_in_list(list_of_words, word_to_search):
found = False
for word in list_of_words:
if word == word_to_search:
found = True
break # breaks iff the word is found
return found
Any particular reason you are adamant not to use the 'in' operator?
Also, please be careful about the indentation in the code you paste.
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
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