How to fix multiple boolean values being printed - python-3.x

Right now I'm led to believe that my function is incorrect since I am getting more than 1 boolean output.
listOstrings = ['cat in the hat','michael meyers','mercury.','austin powers','hi']
def StringLength(searchInteger, listOstrings):
'return Boolean value if the strings are shorter/longer than the first argument'
for i in listOstrings:
if len(i) < searchInteger:
print(False)
else:
print(True)

You don't want to print True or False for each item; you want to create a single Boolean over the course of iterating over the loop. Or more simply, you can return False as soon as you find one element that fails the test, returning True only if you make it through the entire loop without returning.
def checkStringLength(searchInteger, lstStrings):
'return Boolean value if the strings are shorter/longer than the first argument'
for i in lstStrings:
if len(i) < searchInteger:
return False
return True
This is more naturally written using the all function:
def checkStringLength(searchInteger, lstStrings):
return all(len(i) >= searchInteger for i in lstStrings)

Related

function that returns `True` if a string contains exactly two instance of a substring and `False` if it doesn't

I'm trying to write a function that returns True if a string contains exactly two instance of a substring and False if it doesn't.
I'm getting an error:
return' outside function
I feel I'm very close but just can't quite get it, I'd appreciate being pointed in the right direction.
Should recursion be used?
s = ("xeroxes")
exes = str(x)
count = 0
def has_two_X(s):
count = s.count(exes)
for exes in s:
count = +1
if count ==2:
return True
else:
return False
if __name__ == "__main__":
print("string has :",count.s(exes))
If the code must return True if there is two or more instances of substring, you can create a dictionary and return True if value is there in dictionary or not.
mydict = {}
for letter in s:
if letter in mydict:
return True
else:
mydict[letter] = 0
return False #Since there is no substring (two substring can be formed only if it has two same letters in the string)
To find exactly if it has two substring, I would recommend the same approach where you can maintain the dictionary and the count of substring present. Add all the substring/count to the dictionary, this would take O(n^2) to generate all substrings and approx- O(n^2) hashmap memory.
After constructing hashmap, you can iterate over the hashmap to return True if it has exactly two occurences of substring.

Function returns inside loops?

How do return statements of a function work inside for loops? See my code below for what got me thinking about this.
It is like a game of scrabble. You get given n letters (we'll call it a hand), and the aim is to make a word out of your hand. The hand is in the form of a dictionary, like so:
yellow = {'y':1, 'e':1, 'l':2, 'o':1, 'w':1}
I have written a function called get_frequency_dict to transform a string in to this form.
I want to write a function which tells me if the word given is valid or not. I have a list of acceptable words in the variable word_list
Call the function: is_valid_word(word, hand, word_list) which takes in three inputs.
word: string
hand: dictionary (string: int)
word_list: list of lowercase strings
So, I wanted to write this function to return True if the word is valid and False if the word is invalid:
def is_valid_word(word, hand, word_list):
word_dict = get_frequency_dict(word.lower())
if word.lower() in word_list:
for char in word_dict:
if (char in hand) and (hand[char] >= word_dict[char]):
return True
else:
return False
else:
return False
This function seems to work fine with various different inputs, but I'm not quite sure I understand the logic behind the function return in the for loop?
As we loop through the keys in the dictionary (letters), we will get a True or False depending on whether or not the condition is satisfied. So, how does the function know what to return? What if one char returns False and then the next char returns True? Does it instantly return False as soon as it sees one False in the for loop?
The code below makes more sense to me:
total_false = 0
for char in word_dict:
if (char in hand) and (hand[char] >= word_dict[char]):
pass
else:
total_false += 1
if word.lower() not in word_list:
return False
elif total_false > 0:
return False
else:
return True
Does the first segment of code do this "counting" behind the scenes? As in, as soon as we see a False, it returns False?
Simply iterate over the list and if you find an error, stop:
def is_valid_word(word, hand, word_list):
word_dict = get_frequency_dict(word.lower())
if word.lower() in word_list:
for char in word_dict:
if (char in hand) and (hand[char] >= word_dict[char]):
continue
else:
return False #This will stop the function and return false
else:
return False #This will do the same
#At the end, this means that all of the criteria are met, so we return True
return True
As we see, the moment a character doesn't fit the criteria, the function stops and returns false. If it passes all the criteria, it returns true.

Python: Check if tuple contain only integers with while

I have a task to define a function contains_only_integers which takes a tuple as the argument and returns True is every element of the tuple is an integer, and false otherwise. I'm a bit stuck on why I get false every time.
I would use a for-loop, but the task asks specifically for a while loop.
def contains_only_integers(tup):
while isinstance(tup, int)==True:
return True
else:
return False
What am I missing?
Mthrsj covered your problem and how to fix it but an alternative, perhaps more pythonic, way of doing this would be to use the builtin all function.
def contains_only_integers(tup):
return all(isinstance(v, int) for v in tup)
When you do while isintance(tup,int), the function evaluates the tuple, not each element. To achieve what you want, you need to iterate over the tuple. An example below:
def contains_only_integers(tup):
for item in tup:
if not isinstance(item, int):
return False
return True
If the code find any item in the tuple that is not an integer instance it will return False. Otherwise, it will return True.
EDIT
As you said you need to use a while loop, there it is:
def contains_only_integers(tup):
i = 0
while i < len(tup):
if not isinstance(tup[i], int):
return False
i+=1
return True

How do I test if an index is a valid, non-negative index for 'mystr'?

Write a function called valid_index that takes two parameters, index and mystr. The value of index will be an integer, and mystr will be a non-empty string. The function should return True if index is a valid non-negative index for indexing into mystr, and returns False if it is not a valid non-negative index.
I tried this, which did not work:
def valid_index(index, mystr):
if index<0 or index>len(mystr-1):
return False
else:
return True
small fix on the len instruction
def valid_index(index, mystr):
if index<0 or (index>len(mystr)-1):
return False
else:
return True
You're trying to subtract from mystr, which won't work. You can only subtract from numbers, not strings.
There's no need to subtract anything, just use >= instead of >.
def valid_index(index, mystr):
if index<0 or index>=len(mystr):
return False
else:
return True
There's also no need for if, just return the result of the inverted test:
def valid_index(index, mystr):
return index >= 0 and index < len(mystr)

recursion not stopping with 'if'

I am trying to write a code which prints True if given string has at max 2 consecutive c, and at max 1 b. I am using recursion to reduce the string and check that at max 'c' is present in the same index twice.But my recursion is not stopping till it empties the whole list. Can you please suggest what's wrong with my code. Thanks!
def stringcond(N,count=0,k=0):
N=list(N)
if(N.count('b')>1):
return False
if len(N)<2:
return True
else:
for i,j in enumerate(N):
if(j=='c'):
del N[i]
count+=1
if(k==i and count>2):
return False
stringcond(N,count=count,k=i)
return True
You have several mistakes. First, why are you splitting the characters into a list? There is a perfectly good count method for strings.
Your recursion fails because you ignore the return value. You would want something like
if not stringcond(N,count=count,k=i):
return False
# I make no claim that this logic is correct.
In any case, there is no need to recur. Use count to check the quantity of "b" and many-'c' substrings:
def stringcond(s, c_max=0):
return s.count('b') <= 1 and \
s.count("c" * (c_max+1)) == 0
You have to use the result of the stringcond call. Now your function will only return whatever was determined on the top level call.

Resources