I need to define a function receives a string that is made of numbers and checks the following requirement:
the string isnt empty
the first character is in range (1,10)
every character besides the first is in range (0,10)
if the string answers all the requirements return True, else return False.
What ive tried is if in for loops and vice versa.
I've also tried moving the return function in the following code to different indentations which didn't help
def is_positive_int(st):
n = len(st)
if n > 0:
if st[0]>= 0 and st[0]<= 9:
for i in range(1,n):
if st[i]>= 0 and st[i]<= 9
return True
I've also tried:
def is_positive_int(st):
n = len(st)
for n > 0:
if st[0] >= 1 and st[0]<=9:
for i in range (1,n):
if st[i]>=1 and st[i]<= 9
return True
else:
return False
which returns: invalid syntax for n > 0 (I'm not sure why)
For example:
print(is_positive_int("123"))
should return True
Where as
print(is_positive_int("123.0"))
should return False
And
print(is_positive_int("0"))
should return False
You can also just iterate over the string:
for character in st:
# your conditionals
Then use character in place of st[i]
But also note, that with the conditionals you can not compare a string with a number. So what you should do is either make a set of the digits or use the isdigit() method for strings.
Taking it all together your function should be something like this:
def is_positive_int(st):
if not (st and st[0] != '0'):
return False
for character in st:
if not character.isdigit():
return False
return True
I can suggest 2 alternative approaches:
Option 1: iterate directly over the string and compare each char to allowed chars for each position (do not compare chars to numbers).
import string
def func(input_str):
if len(input_str) == 0:
return False
for i, c in enumerate(input_str):
if i == 0:
allowed_chars = string.digits[1:] # exclude '0'
else:
allowed_chars = string.digits
if c not in allowed_chars:
return False
return True
Option 2: use regular expressions; I know that they aren't always a solution, but in this case they allow for a really short code solution.
import re
def func(input_str):
if re.match(r'^[1-9][0-9]*$', input_str):
return True
return False
Does this help?
Try this
If you input something that isnt a string that can convert to int, it will run the except condition. len(input)>1 just confirms that there is a second digit
def is_positive_int(input):
try:
if int(input[0]) in range(1,10) and int(input) and len(input)>1:
return True
else:
return False
except:
print('invalid input')
Use range(len(iterable)) to iterate over the indexes of an iterable:
def is_positive_int(string):
positive_ints = {1, 2, 3, 4, 5, 6, 7, 8, 9}
if len(string) == 0:
return False
if int(string[0]) not in positive_ints:
return False
for i in range(1, len(string)):
if int(string[i]) not in (positive_ints | {0}):
return False
return True
Note the use of sets to define accepted numbers, since it's an efficient data structure for this purpose, and could also be constructed dynamically with positive_ints = set(range(1,10)).
The int() calls are there because the elements of the string (string[i]) will be strings, and would always compare to false since 1 == "1" is False.
Lastly, the cascading style of returns is often preferred as it skips parts of the function that won't be relevant and only returns True if nothing else stops it until the end.
Instead of operating on indexes, you can iterate on the characters of the string themselves:
def is_positive_int(string):
positive_ints = set(range(1, 10))
if len(string) == 0:
return False
if int(string[0]) not in positive_ints:
return False
for character in string:
if int(character) not in (positive_ints | {0}):
return False
return True
Note that both of these will raise an exception if a character in the string cannot be converted to int. This can be prevented by converting the numbers to string instead:
def is_positive_int(string):
positive_ints = set(str(x) for x in range(1, 10))
if len(string) == 0:
return False
if string[0] not in positive_ints:
return False
for i in range(1, len(string)):
if string[i] not in (positive_ints | {"0"}):
return False
return True
You need to convert the entries in your string to int, otherwise your conditional statements will throw an error:
your code:
def is_positive_int(st):
n = len(st)
if n > 0:
if (st[0]>= 0) and (st[0]<= 9):
for i in range(1,n):
if st[i]>= 0 and st[i]<= 9:
return True
Should throw an error. At least it does when I run it on '123'
TypeError: '>=' not supported between instances of 'str' and 'int'
So, you could change to:
def is_positive_int(st):
n = len(st)
if n > 0:
if (int(st[0])>= 0) and (int(st[0])<= 9):
for i in range(1,n):
if int(st[i])>= 0 and int(st[i])<= 9:
return True
Since nowhere in this function it is asserted if there are non-digit characters, it cannot return False when encountering those. Contrary, it will throw an error, when it tries the conversion. So you could do:
def is_positive_int(st):
entries = list(st) # create a list of all items in the string
if entries: # assert this list has length > 0
output = True # initialise output
for e in entries:
output *= e.isdigit() # update outputs : a single False will convert output to 0.
return bool(output) # convert output to boolean
else: # if the string is empty, return False.
return False
if you have to check only for positive integers you can use .is.isdigit
def is_positive_int(st):
return st.isdigit() and int(st) > 0
>>>is_positive_int('123')
True
>>>is_positive_int('123.0')
False
>>>is_positive_int('0')
False
>>>is_positive_int('#$%')
False
>>>is_positive_int('-123')
False
>>>is_positive_int('')
False
You can use the str.isdigit function to check if a string is a digit between 0 and 9, and we can utilize it here as follows.
def is_positive_int(st):
#Get the length of the string
n = len(st)
#Flag to capture result
result = True
#If the string is empty, result is False
if n == 0:
result = False
#If the string has only one character, if the character is not 0, result is False
elif n == 1:
if st[0] == '0':
result = False
else:
#Otherwise iterate through all characters in the string
for i in range(1, n):
#If we find a character which is not a digit, result is False
if not st[i].isdigit():
result = False
break
#Return the final result
return result
The outputs for the function above then will be
print(is_positive_int(""))
#False
print(is_positive_int("0"))
#False
print(is_positive_int("1"))
#True
print((is_positive_int("123.0")))
#False
print((is_positive_int("123")))
#True
Using the builtin function all() and a list comprehension, just to add to the many options.
def test_num(num):
# check for empty string
if len(num) == 0:
return False
# check all numbers are digits,
# if so, is the first digit > 0
return all(i.isdigit() for i in num) and int(num[0]) > 0
if __name__ == '__main__':
for num in ['', '0', '1', '123.0', '123', '+123', '-123']:
print(f'\'{num}\' is positive: {test_num(num)}')
# '' is positive: False
# '0' is positive: False
# '1' is positive: True
# '123.0' is positive: False
# '123' is positive: True
# '+123' is positive: False
# '-123' is positive: False
Related
I want say there is a string in the list with only one mismatch
def check(list, s):
n = len(list)
# If the array is empty
if (n == 0):
return False
for i in range(0, n, 1):
# If sizes are same
if (len(list[i]) != len(s)):
continue
diff = False
for j in range(0, len(list[i]), 1):
if (list[i][j] != s[j]):
# If first mismatch
if (diff == False):
diff = True
# Second mismatch
else:
diff = False
break
if (diff):
return True
return False
This code is okay but it works slowly. How can I make it faster using a dictionary?
You can use zip() to pair up each character of two strings and sum() to count the number of mismatches. The any() function will allow you to check for a match over every item in the list:
def check(sList,string):
return any(len(string)==len(s) and sum(a!=b for a,b in zip(s,string))==1
for s in sList)
check(["abcd","cdef","efgh"],"xfgh") # True
check(["abcd","cdef","efgh"],"abdc") # False
This translates to the following basic for-loop:
def check(sList,string):
for s in sList:
if len(string) !=len(s): continue
if sum(a!=b for a,b in zip(s,string)) == 1:
return True
return False
[EDIT] to make this go a bit faster, the string comparisons can use zip() as an iterator so that the comparison doesn't need to go to the end of every string:
def check(sList,string):
for s in sList:
if len(string) !=len(s): continue
mismatch = (a!=b for a,b in zip(s,string)) # non-matching iterator
if not any(mismatch): continue # at least one
if any(mismatch): continue # no more after that
return True
return False
prompt for isValidSubsequence
def isValidSubsequence(array, sequence):
index = -1
# issue is with initialising the index variable
if len(sequence)<=len(array):
for i in range(len(sequence)):
# i refers to the i in the sequence
if sequence[i] in array:
# causing a problem for repetitions such as array = [1,1,1,1,1] and subsequence = [1,1,1]
# array.index(sequence[i]) would call the first 1 instead of the second 1
if array.index(sequence[i]) > index:
index = array.index(sequence[i])
else:
return False
else:
return False
return True
else:
return False
How to solve this repeating 1s issue using my code?
The reason array.index(sequence[i]) calls the first 1 is because sequence[i] is 1 in your case, and that is the same as if you called array.index(1). The index function searches your array for 1 and as soon as it finds it, it returns its index, so it always finds the first 1 first and then stops looking and returns its index.
Try something like this, this should work:
def isValidSubsequence(array, sequence):
lastIndex = -1
if not len(array) >= len(sequence):
return False
for i in range(len(sequence)):
containsInt = False
for j in range(lastIndex + 1, len(array)):
if array[j] == sequence[i]:
containsInt = True
lastIndex = j
break
if not containsInt:
return False
return True
You are using lists, not arrays. list.index(x[, start[, end]]) can take positionals from where to where search - you could rewrite your algo to remember the last found position for each value and look for new values from that position.
BUT: this is irrelevant, you only need to concern yourself with how many of each element are in original and sequence and if one has at most equal of them...
The correct way to solve this ist to count the occurences of elements in the original, subtract the amount of occurences in the `sequence`` and evaluate your numbers:
If sequence is empty, contains elements not in original or contains more elements then inside original it can not be a subsequence:
from collections import Counter
def isValidSubsequence(array, sequence):
# check empty sequence
if not sequence:
return False
original = Counter(array)
# check any in seq that is not in original
if any(i not in original for i in sequence):
return False
# remove number of occurences in sequence from originals
original.subtract(sequence)
# check if too many of them in sequence
if any(v < 0 for v in original.values()):
return False
return True
Testcode:
source = [1,2,3,4]
test_cases = [[1], [2,4], [1,2,4] ]
neg_test_case = [[2,5], [9], []]
for tc in test_cases:
print(isValidSubsequence(source,tc), "should be True")
for ntc in neg_test_case:
print(isValidSubsequence(source,ntc), "should be False")
Output:
True should be True
True should be True
True should be True
False should be False
False should be False
False should be False
If you are not allowed to import, count yourself (expand this yourself):
# not efficient
counted = {d:original.count(d) for d in frozenset(original)}
# remove numbers
for d in sequence:
counted.setdefault(d,0)
counted[d] -= 1
This would be another way to answer the question.
def isValidSubsequence(array,sequence):
if len(array) >= len(sequence):
iter_sequence = iter(sequence)
last = next(iter_sequence)
total = 0
for i in array:
if i + total == last:
total += i
try:
last += next(iter_sequence)
except StopIteration:
return True
break
return False
I've been doing a good amount of studying and practicing algorithms, and I ran into one that asked the question (summarizing here) "Given two strings, return True if the strings are one edit away (either by removing, inserting, or replacing a character). Return False if not."
I went about this problem by comparing two strings and counting the amount of letters that are in string1, but not in string2. If there is more than one letter missing, then it will return False.
Here is my Python code:
def oneAway(string1, string2):
string1 = string1.lower()
string2 = string2.lower()
# counts the number of edits required
counter = 0
for i in string1:
if i not in string2:
counter += 1
if counter > 1:
return False
else:
return True
I'd like to hear other people's approaches to this problem, and please point out if I have oversimplified this concept.
Why call .lower() on both strings? Based on the question, oneAway('abc', 'ABC') should be False.
Building off of the other comments, how about this:
def oneAway(s1, s2):
i, j = 0, 0
mistake_occurred = False
while i < len(s1) and j < len(s2):
if s1[i] != s2[j]:
if mistake_occurred:
return False
mistake_occurred = True
i += 1
j += 1
if mistake_occurred and (i != len(s1) or j != len(s2)):
return False
if i < len(s1) - 1 or j < len(s2) - 1:
return False
return True
You have to check each editing action specifically:
def isOneEdit(A,B):
# replacing one char
if len(A) == len(B) and sum(a!=b for a,b in zip(A,B)) == 1:
return True
# inserting one char in A to get B
if len(A) == len(B)-1 and any(A==B[:i]+B[i+1:] for i in range(len(B))):
return True
# removing one char (like inserting one in B to get A)
if len(A) == len(B)+1:
return isOneEdit(B,A)
return False
print(isOneEdit("abc","abd")) # True - replace c with d
print(isOneEdit("abd","abcd")) # True - insert c
print(isOneEdit("abcd","abd")) # True - delete c
print(isOneEdit("abcde","abd")) # False
Alternatively, you can compare the size of the common prefix and suffix of the two strings to the length of the longest one:
def isOneEdit(A,B):
if abs(len(A)-len(B))>1: return False
commonPrefix = next((i for i,(a,b) in enumerate(zip(A,B)) if a!=b),len(A))
commonSuffix = next((i for i,(a,b) in enumerate(zip(reversed(A),reversed(B))) if a!=b),len(B))
editSize = max(len(A),len(B)) - (commonPrefix+commonSuffix)
return editSize <= 1
To find two consecutive digits(D) in a given integer(N) without using any built-in functions and returning True or False, the following code seems to be exiting when coming across one D, however it works if there are two Ds. Why is it not working as it is and how to fix it? Thanks!
def double_digits(n, d):
"""Return True if N has two Ds in a row otherwise return False.
int, int -> Boolean
>>> double_digits(91019, 1)
False
>>> double_digits(88, 8)
True
>>> double_digits(2772, 7)
True
>>> double_digits(88108, 0)
False
>>> double_digits(12345, 4)
False
>>> double_digits(81811081, 1)
True
"""
while n > 0:
remainder = n % 10
n = n // 10
if remainder == d:
if n % 10 == d:
return True
else:
remainder, n = n % 10, n // 10
return False
The last return statement should be out of the loop.
Below is the correct code:
def double_digits(n, d):
while n > 0:
remainder = n % 10
n = n // 10
if remainder == d:
if n % 10 == d:
return True
else:
remainder, n = n % 10, n // 10
return False
You must de-indent the last statement : return False, 4 spaces to the left. That must help you.
Alternatively you can convert the input to a string and then the character matching would be easy.
def double_digits(n: int, d: int)->bool:
n = str(n)
d = str(d)
i = 0
while i < len(n)-1:
if n[i] == d and n[i+1] == d:
return True
i+=1
return False
Here I have used some builtin fuctions like len and str, but if you explicitly
want to avoid using them, just go with your original approach and just de-indent the return statement once
I need to compare the return value of a recursive function with an integer.
Doing recursively the sum of all elements of a list , I have to compare the final sum with an integer "n" giving back TRUE if sum == n , FALSE if sum != n . In addiction to the function have to return FALSE if i'm giving an empty list .
Here I report the code to clarify the situation :)
def function(list_of_numbers,int):
if not list:
return false # I have to return false if list is empty.
if len(l) > 0:
return l[0] + function(list_of_numbers[1:],int) # recursive sum of element
# and here i'm stuck !
when not l we either got passed an empty list or have reached our base case so compare n to our test number, if you want an empty list to return True change test=-1 to test=0 :
def function(l, n=0, test=-1):
if not l:
return n == test
else:
n += l[0]
return function(l[1:], n, test)
In [2]: function([1,2,3],test=6)
Out[2]: True
In [3]: function([1,2,3],test=5)
Out[3]: False
In [4]: function([1,2,3])
Out[4]: False
In [5]: function([])
Out[5]: False
If you want an empty list to return False you can check how many times the function has been called and either compare n to test or return False :
def function(l, n=0, test=0, calls=0):
if not l:
return n == test if calls > 0 else False
else:
n += l[0]
calls += 1
return function(l[1:], n, test,calls)
If you just want to pass a single argument the number to test against:
def function(l, test, n=0, calls=0):
if not l and calls == 0: # changed for jython
return False
if not l:
return n == test
else:
n += l[0]
calls += 1
return function(l[1:],test,n, calls)