def countOne(s): mx=0;cnt=0; for i in s: if i==1: cnt+=1 else: if mx<cnt: mx=cnt cnt=0 if mx<cnt: mx=cnt return mx Here s is a list s=[0,1,0,1,1,1,0]
Find all distinct palindrome sub string for a given string
def check_palin(word): if word==word[::-1]: return True else: return False def all_palindromes(string): result=list() st1="" for i in range(0,len(string)): st1 += string[i] result.append(string[i]) for j in range(i+1,len(string)): st1+=string[j] if check_palin(st1)==True: result.append(st1) st1="" return list(set(result))
Counting consecutive characters in a string python 2
from itertools import groupby sm='aabccaaddbb' print [[k, len(list(g))] for k, g in groupby(sm)] output: [['a', 2], ['b', 1], ['c', 2], ['a', 2], ['d', 2], ['b', 2]]
All possible substrings of a string in Python 2
st="abcde" li=list() for i in range(0,len(st)): for j in range(i,len(st)): substring = "" for k in range(i,j+1): substring+=st[k] li.append(substring) print li output: ['a', 'ab', 'abc', 'abcd', 'abcde', 'b', 'bc', 'bcd', 'bcde', 'c', 'cd', 'cde', 'd', 'de', 'e']
Generating combination of a list in python 2
import itertools li,l= [1, 3, 3],2 for subset in itertools.combinations(li, l): print subset l is the length of subsequent of element from the input iterable
Check if all elements in a list are same(identical)
def checkAll_same(li): set1=set(li) if len(set1)==1: print "List Element Are Same" else: print "List Element Are Not Same" checkAll_same([1,1,1,1])
Python program to find GCD
def gcd(a,b): if b==0: return a else: return gcd(b,a%b)
Remove a specific element from a string
string=’pandey’
string=list(string)
string.remove(‘p’)
print ”.join(str(e) for e in string)
Repeat string certain length python 2
from itertools import cycle, islice
def srepeat(string, n):
return ''.join(islice(cycle(string), n))
Remove a specific element from list python 2
li=[0,2,3,8,10,0]
li=[x for x in li if x!=0]
print li
[2,3,8,10]