Check if string contains substring at index - python

In Python 3.5, given this string:
"rsFooBargrdshtrshFooBargreshyershytreBarFootrhj"
and the index 17 -- so, the F at the start of the second occurrence of FooBar -- how can I check that "FooBar" exists? In this case, it should return True, while if I gave it the index 13 it should return false.

There's actually a very simple way to do this without using any additional memory:
>>> s = "rsFooBargrdshtrshFooBargreshyershytreBarFootrhj"
>>> s.startswith("FooBar", 17)
True
>>>
The optional second argument to startswith tells it to start the check at offset 17 (rather than the default 0). In this example, a value of 2 will also return True, and all other values will return False.

You need to slice your original string based on your substring's length and compare both the values. For example:
>>> my_str = "rsFooBargrdshtrshFooBargreshyershytreBarFootrhj"
>>> word_to_check, index_at = "FooBar", 17
>>> word_to_check == my_str[index_at:len(word_to_check)+index_at]
True
>>> word_to_check, index_at = "FooBar", 13
>>> word_to_check == my_str[index_at:len(word_to_check)+index_at]
False

print("rsFooBargrdshtrshFooBargreshyershytreBarFootrhj"[17:].startswith('Foo')) # True
or in common
my_string[start_index:].startswith(string_to_check)

Using Tom Karzes approach, as a function
def contains_at(in_str, idx, word):
return in_str[idx:idx+len(word)] == word
>>> contains_at(s, 17, "FooBar")
>>> True

Try this:
def checkIfPresent(strng1, strng2, index):
a = len(strng2)
a = a + index
b = 0
for i in range(index, a):
if strng2[b] != strng1[i]:
return false
b = b+1
return true
s = "rsFooBargrdshtrshFooBargreshyershytreBarFootrhj"
check = checkIfPresent(s, Foobar, 17)
print(check)

Related

Isinstance function to check the elements given fits in my matrix

I want to create a function that checks if the given tab fits or not. My matrix should be a 3x3 with 3 tuples, each with 3 integers.
I want this interaction to happen:
>>> tab = ((1,0,0),(-1,1,0),(1,-1,-1))
>>> tabuleiro(tab)
True
>>> tab = ((1,0,0),(’O’,1,0),(1,-1,-1))
>>> tabuleiro(tab)
False
>>> tab = ((1,0,0),(-1,1,0),(1,-1))
>>> tabuleiro(tab)
False
All I have right now is:
def tabuleiro(tab):
return isinstance(tab, tuple) and len(tab) == 3 and \
all((isinstance( l, tuple) and len (l) == len(tab[0])) for l in tab) and len (tab[0]) == 3 and \
(....)
This is probably easier to read and reason about if you break it into one function for the group and another function for each member of the group. Then you could do something like:
def tab_is_valid(tab, valid_size=3):
''' is an individual member valid'''
return len(tab) == valid_size and all(isinstance(n, int) for n in tab)
def tabuleiro(tab):
''' is the whole structure valid '''
return all((
isinstance(tab, tuple),
len(tab) == 3,
all(tab_is_valid(t) for t in tab),
))
tabuleiro(((1,0,1),(-1,1,0),(1,-1,-1)))
# True
tabuleiro(((1,0,1.6),(-1,1,0),(1,-1,-1)))
# False
tabuleiro(((1,0),(-1,1,0),(1,-1,-1)))
#False
tabuleiro(((1,0, 1),(-1,1,0),(1,-1,-1), (1, 1, 1)))
# False
In python3.10 and above, you can use pattern matching:
def tabuleiro(tab):
match tab:
case (int(),int(),int()),(int(),int(),int()),(int(),int(),int()):
return True
case _:
return False
print(tabuleiro(((1,0,1),(-1,1,0),(1,-1,-1))))
# True
print(tabuleiro(((1,0,1.6),(-1,1,0),(1,-1,-1))))
# False
print(tabuleiro(((1,0),(-1,1,0),(1,-1,-1))))
#False
print(tabuleiro("string is not a tuple"))
# False
The line case _: does not change the value of variable _ (If I use another variable name, the value of this variable whould be the value of tab).
This line and the identation of last line return false are here not necessary, but I keep them for sake of readability.

Difference between: IF IN and IF == python

I wanted to know which condition is better to use for the following code:
Here are my two lists:
Matrix = ['kys_q1a1','kys_q1a2','kys_q1a3','kys_q1a4','kys_q1a5','kys_q1a6']
fixedlist = ['kys_q1a2', 'kys_q1a5']
Option 1:
for i, topmember in enumerate(Matrix):
for fixedcol in fixedlist:
if topmember in fixedcol:
print i
OR
Option 2:
for i, topmember in enumerate(Matrix):
for fixedcol in fixedlist:
if topmember == fixedcol:
print i
I understand that the comparison opertor is matching strings but isn't 'in' doing the same?
Thanks
topmember in fixedcol
tests if the string topmember is contained within fixedcol.
topmember == fixedcol
tests if the string topmember is equal to fixedcol.
So, 'a' in 'ab' would evaluate True. But 'a' == 'ab' would evaluate False.
I wanted to know which condition is better to use.
Since the two variants perform different operations, we cannot answer that. You need to choose the option that does the operation that you require.
Your code could be simplified quite a bit. The second option could be reduced to:
for i, topmember in enumerate(Matrix):
if topmember in fixedlist:
print i
You could also use a list comprehension to find the matching indices:
[i for i, x in enumerate(Matrix) if x in fixedlist]
If you just have to print the indices rather than store them in a list you can write it like this:
print '\n'.join([str(i) for i, x in enumerate(Matrix) if x in fixedlist])
It's a matter of taste whether you prefer the dense list comprehension one-liner, or the rather more verbose version above.
Hi in opeartor is used for membership testing and == operator is used for equality testing .
Generally we used in for membership testing in sequence object. And is able to test in dictionary, set, tuple, list, string etc. But it behaves differently based on the object types.
Dictionary:
It check for the key exists.
>>> d = {'key' : 'value'}
>>> 'key' in d
True
>>> 'k' in d
False
>>>
Set:
Under the hood it checks for key is exist, set implementation is same as dictionary with some dummy value.
>>> s = set(range(10))
>>> 1 in s
True
>>>
List and Tuple:
For the list and tuple types, x in y is true if and only if there exists an index i such that x == y[i] is true.
>>> l = range(10)
>>> 3 in l
True
>>>
String:
checking whether the substring is present inside the string eg. x in y is true if and only if x is a substring of y. An equivalent test is y.find(x) != -1
Use defined data type:
user-defined classes which define the __contains__() method, x in y is true if and only if y.__contains__(x) is true.
class Person(object):
def __init__(self,name,age):
self.name = name
self.age = age
def __contains__(self, arg):
if arg in self.__dict__.keys():
return True
else:
return False
obj_p = Person('Jeff', 90)
print 'Jeff', 'Jeff' in obj_p
print 'age', 'age' in obj_p
print 'name', 'age' in obj_p
I Hope, you will clear some what is the usage of in.
Lets rewrite your snippet:
>>> Matrix = ['kys_q1a1','kys_q1a2','kys_q1a3','kys_q1a4','kys_q1a5','kys_q1a6']
>>> fixedlist = ['kys_q1a2', 'kys_q1a5']
>>> for i in fixedlist:
... print i, i in Matrix
...
kys_q1a2 True
kys_q1a5 True
>>>
And finally lets see some of the equality test: ==:
>>> 'a' == 'b'
False
>>> 'a' == 'a'
True
>>> 'a' == 'ab'
False
>>> '' in 'ab' # empty string is treated as a sub-string for any string
True
>>> '' == 'ab' # False as they are having different values
False
>>>
>>> 1 == 'ab'
False
>>> 1 == 1
True
>>>
Going with '==' is precise if you want to match exact string.

How to check if characters in a string are alphabetically ordered

I have been trying these code but there is something wrong. I simply want to know if the first string is alphabetical.
def alp(s1):
s2=sorted(s1)
if s2 is s1:
return True
else:
return False
This always prints False and when i say print s1 or s2, it says "NameError: name 's1' is not defined"
is is identity testing which compares the object IDs, == is the equality testing:
In [1]: s1 = "Hello World"
In [2]: s2 = "Hello World"
In [3]: s1 == s2
Out[3]: True
In [4]: s1 is s2
Out[4]: False
Also note that sorted returns a list, so change it to:
if ''.join(s2) == s1:
Or
if ''.join(sorted(s2)) == s1:
You could see this answer and use something which works for any sequence:
all(s1[i] <= s1[i+1] for i in xrange(len(s1) - 1))
Example:
>>> def alp(s1):
... return all(s1[i] <= s1[i+1] for i in xrange(len(s1) - 1))
...
>>> alp("test")
False
>>> alp("abcd")
True
I would do it using iter to nicely get the previous element:
def is_ordered(ss):
ss_iterable = iter(ss)
try:
current_item = next(ss_iterable)
except StopIteration:
#replace next line to handle the empty string case as desired.
#This is how *I* would do it, but others would prefer `return True`
#as indicated in the comments :)
#I suppose the question is "Is an empty sequence ordered or not?"
raise ValueError("Undefined result. Cannot accept empty iterable")
for next_item in ss_iterable:
if next_item < current_item:
return False
current_item = next_item
return True
This answer has complexity O(n) in the absolute worst case as opposed to the answers which rely on sort which is O(nlogn).
Make sure that you are comparing strings with strings:
In [8]: s = 'abcdef'
In [9]: s == ''.join(sorted(s))
Out[9]: True
In [10]: s2 = 'zxyw'
In [11]: s2 == ''.join(sorted(s2))
Out[11]: False
If s1 or s2 is a string, sorted will return a list, and you will then be comparing a string to a list. In order to do the comparison you want, using ''.join() will take the list and join all the elements together, essentially creating a string representing the sorted elements.
use something like this:
sorted() returns a list and you're trying to compare a list to a string, so change that list to a string first:
In [21]: "abcd"=="".join(sorted("abcd"))
Out[21]: True
In [22]: "qwerty"=="".join(sorted("qwerty"))
Out[22]: False
#comparsion of list and a string is False
In [25]: "abcd"==sorted("abcd")
Out[25]: False

How to do check for a palindrome in Python?

Hi I'm working on a python function isPalindrome(x) for integers of three digits that returns True if the hundreds digit equals the ones digit and false otherwise. I know that I have to use strings here and this is what I have:
def isPal(x):
if str(1) == str(3):
return "True"
else:
return "False"
the str(0) is the units place and str(2) is the hundreds place. All I'm getting is False? Thanks!
Array access is done with [], not (). Also if you are looking for hundreds and units, remember that arrays are 0 indexed, here is a shortened version of the code.
def is_pal(num):
return num[0] == num[2]
>>> is_pal('123')
False
>>> is_pal('323')
True
You might want to take in the number as a parameter and then convert it to a string:
def is_pal(num):
x = str(num)
return x[0] == x[2]
Note that you can simply just check if string is equal to it's reverse which works for any number of digits:
>>> x = '12321'
>>> x == x[::-1]
True
str(1) will create a string of the integer value 1. Which won't equal the string value of the integer value 3 - so it's always False.
You should return True and False, rather than strings of "True" and "False"...
This is what you're aiming for taking into account the above... (which works with any length)
def pal(num):
forward = str(num)
backward = ''.join(reversed(forward))
return forward == backward
Your problem is that str(1) == '1' and str(3) == '3'. You're also returning string values reading 'True' and 'False' instead of using the actual True and False values.
Let me propose a much simpler function for you:
def isPal(x):
s = str(x) # convert int to str
return s == s[::-1] # return True if s is equal to its reverse
s[::-1] creates a reverse of the string; e.g. 'foo'[::-1] == 'oof'. This works because of extended slice notation.
Not sure why people are sticking to the string idea when division and modulo will do:
def isPal(x):
return (x/100)%10 == x%10
if the number is no larger than 999 (3 digits as the OP stated) then it simplifies to
def isPal(x):
return x/100 == x%10
str() casts a value into a str. You want to access each character. You might want to benchmark a few different techniques.
>>> t1 = timeit.Timer(stmt="""\
... def isPal(x):
... return x//100 == x%10
... isPal(434)
... isPal(438)
... """)
>>> t2 = timeit.Timer(stmt="""\
... def isPal(x):
... return str(x)[0] == str(x)[2]
... isPal(434)
... isPal(438)
... """)
>>> print "%.2f usec/pass" % (1000000 * t1.timeit(number=100000)/100000)
0.97 usec/pass
>>> print "%.2f usec/pass" % (1000000 * t2.timeit(number=100000)/100000)
2.04 usec/pass
So, it looks like the mod technique works:
def isPal(x):
return x//100 == x%10
str(1) just gives you the string representation of the number 1:
>>> x = 357
>>> str(1)
'1'
What you want is the first index of the string representation of x.
>>> x = 357
>>> str(x) #string representation of x
'357'
>>> str(x)[0] #first index of that
'3'
>>> str(x)[2] #third index of that
'7'
>>> str(x)[0]==str(x)[2] #compare 1st and last
False
>>> x = 525
>>> str(x)[0]==str(x)[2] #compare 1st and last
True
you compare number 1 and 3, but you needt to compare index of input variable.
x = 1000
def isPal(x):
return str(x[-1]) == str(x[-3]):
It looks like you still need to study Python syntax
Here is a way to achieve what you need :
>>> def isPal(x):
... x_as_str = str(x)
... if len(x_as_str) != 3:
... raise Exception("{} is not of length 3".format(x))
... return x_as_str[0] == x_as_str[2]
...
>>> isPal(42)
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "<input>", line 4, in isPal
Exception: 42 is not of length 3
>>> isPal(420)
False
>>> isPal(424)
True
str(x) delivers the string value of whatever you pass to it, so in your case the string "1" or the string "3". But what you actually want is to access the 1st and 3rd digit of the given number. So, first you want to convert that number to string (e.g. with str(num)), and then you have to consider that indices in strings begin with 0, not with 1.
So working code culd e.g. look like this:
def isPal(x):
if str(x)[0] == str(x)[2]:
return 'true'
else:
return 'false'
Output:
> isPal(101)
true
> isPal (203)
false
A smaller solution for this would be:
def isPalindrome(x):
return str(x) == str(x)[::-1]
This will work for words and integer values.
def is_palindrome() :
a=(raw_input("enter the name : "))
b=a[::-1]
if b == a:
print " it is palindarome"
else:
print " it is not palindarome"
is_palindrome()

Check if none of the multiple chars appears in string A?

I have a string, A = "abcdef", and several chars "a", "f" and "m". I want a condition to make sure none of the chars appears in A, i.e.,
if a not in A and f not in A and m not in A:
# do something
Is there a better way to do this? Thanks!
Sets are useful for this -- see the isdisjoint() method:
Return True if the set has no elements in common with other.
Sets are disjoint if and only if their intersection is the empty set.
new in version 2.6.
>>> a = "abcde"
>>> b = "ace"
>>> c = "xyz"
>>> set(a).isdisjoint(set(b))
False
>>> set(a).isdisjoint(set(c))
True
edit after comment
sets are still you friend. If I'm following you better now, you want this (or something close to it):
We'll just set everything up as sets to begin with for clarity:
>>> a = set('abcde')
>>> b = set('ace')
>>> c = set('acx')
If all of the chars in your set of characters is in the string, this happens:
>>> a.intersection(b) == b
True
If any of those characters are not present in your string, this happens:
>>> a.intersection(c) == c
False
Closer to what you need?
True in [i in 'abcdef' for i in 'afm']
gives True
and
True in [i in 'nopqrst' for i in 'afm']
gives False

Categories