Python: Check if tuple contain only integers with while - python-3.x

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

Related

returning true if numbers are duplicated in a list

Here's my code. I've seen many sophisticated codes I don't understand so I'm trying to use the basics I've learned.
def containsDuplicate(nums):
table = set()
for num in nums:
if num not in table:
table.addend(num)
else:
return TRUE
return FALSE
It messes up in the return line. It says it's outside the function
Your indentation is incorrect.
It has to be True and False, not TRUEand FALSE.
The method set.addend() does not exist. You probably meant set.add().
It should look like this:
def containsDuplicate(nums):
table = set()
for num in nums:
if not num in table:
table.add(num)
else:
return True
return False
if you already understand indentation stuffs from the first answer,let me show you another way of doing the same task in python:
def checkIfDuplicates(nums):
if len(nums) == len(set(nums)):
return False
else:
return True

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.

The return value at recursive fun at Python

im trying to write a function that takes as a value a dict,
and return if the key is exists at the dict.
i debugged the function and i fount out that even if the function
enter a code where it should return True, it is still calling the other recursive calls,
and return none instead of the initial True value.
the function:
def checkIfKeyExsists(self,searchKey,passingValue):
if searchKey in passingValue:
return True
else:
for value in passingValue.values():
if type(value) == dict:
if searchKey in value.keys():
print("yes")
return True
else:
self.checkIfKeyExsists(searchKey,value)
elif type(value) == list:
for dicInLst in value:
self.checkIfKeyExsists(searchKey,dicInLst)
dict that i used:
thisdict = {
"brand": "Ford",
"model": {"Mustang":{"car":"motti","car123":"34"}},
"year": [{"a":"test"},{"c":"er"}] }
jn = JsonNode(thisdict)
x = jn.checkIfKeyExsists("car",jn.getJsonDic())
**this function is a part of class that calls JsonNode
There are three issues with your recursive function.
First you don't return anything at the end of your function. So what does happen if you don't fall in the different branches of your code? Then the function will return None as you experienced. So first you should terminate your function with return False.
Second you don't do anything of the value returned by your recursive calls. Hence this value is just ignored. So this why even when the key is found, you keep performing recursive calls. You should do something like this instead: replace
self.checkIfKeyExsists(searchKey,dicInLst)
by
if(self.checkIfKeyExsists(searchKey,dicInLst)):
return True
Last, it does not affect the correctness of your function but your check if searchKey in value.keys() is actually useless as it's already performed as the first test (if searchKey in passingValue) when performing a recursive call. Hence this case will be covered by your recursive call (self.checkIfKeyExsists(searchKey,value)).

How to fix multiple boolean values being printed

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)

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)

Resources