How to get list of palindrome in text? [closed] - python

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 10 months ago.
Improve this question
I have the following interview question that may require traversing through the entire string.
Problem I searched about find Problem and most people do it like this def palindrome(s): return s==s[::-1] But this task is diffrent?
palindrome is a word the can read from both directions like 'mam', 'dad'. Your task is to get a list of palindrome in a given string.
def palindrome(s):
stack = []
return ['aaa']
exampls
palindrome('aaa') #['aaa']
palindrome('abcbaaaa') #['abcba','aaaa']
palindrome('xrlgabccbaxrlg') #['abccba']
palindrome('abcde') #['']

Let's try to avoid checking all the possible combinations :). My idea is, start from the extremities and converge:
def palindrome(s):
out = [''] #we need the list to not be empty for the following check
for main_start in range(len(s) - 1):
for main_end in range(len(s) - 1, main_start, -1):
start = main_start
end = main_end
while (end - start) > 0:
if s[start] == s[end]: ##may be palindrome
start += 1
end -= 1
else:
break
else:
if s[main_start:main_end + 1] not in out[-1]: #ignore shorter ("inner") findings
out.append(s[main_start:main_end + 1])
return out[1:] #skip the dummy item

Related

Function to find a continuous sub-array which adds up to a given number in python [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last month.
Improve this question
I want to know what's wrong in the below code. Will it consume more time to in some certain scenarios?
Expected time complexity: O(n)
def subArraySum(self,arr, n, s):
if sum(arr[0:n]) == s:
return [1, n]
if sum(arr[0:n]) < s:
return [-1]
start = 0
i =1
sum_elements = 0
while i < n:
sum_elements = sum(arr[start:i+1])
if sum_elements == s:
return [start+1, i+1]
if sum_elements < s:
i += 1
continue
if sum_elements > s:
start += 1
continue
if sum_elements < s:
return [-1]
Instead of running sum(arr[start:i+1]) in each iteration of the while loop, you should use a variable and add or subtract the respective value that is included or excluded from the subarray in each iteration. That way you can avoid the O(n^2) complexity and stay within O(n).
Currently there is a lot of overhead for calculating the sum of a (potentially large) subarray that has only changed by one single value at the beginning or the end during each iteration.

How do I make a function read a row and a column with only zeros without using libraries [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 12 months ago.
This post was edited and submitted for review 12 months ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
I'm new to programming in general... I have to check all the rows and columns of an matrix and in case any of them are complete with zeros, return a True value. I made this code in a silly attempt but it doesn't work for the purpose of the question itself. The matrix will always be a square and a list of lists.
def determinanteEhNulo(matriz):
contador = 0
for i in matriz:
for j in range(len(matriz)):
if i[j] == 0:
contador += 1
if contador >= int(len(matriz)):
return True
return False
This seems to do what you need.
def determinanteEhNulo(matriz):
for i in matriz:
if all(x==0 for x in i):
return True
for i in zip(*matriz):
if all(x==0 for x in i):
return True
return False
count = 0
def determinanteEhNulo(matrix):
global count
for i in matrix:
if all([j ==0 for j in i]):
count += 1
if count == len(matrix):
return True
else:
return False

How can I generate all possible words with a specified set of characters? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I play to HackNet game and i have to guess a word to bypass a firewall.
The key makes 6 characters long and contains the letters K,K,K,U,A,N.
What is the simplest way to generate all possible combinations either in bash or in python ? (bonus point for bash)
Here is a backtracking-based solution in Python:
db = {"K" : 3, "U" : 1, "A" : 1, "N" : 1}
N = 6
def possibilities(v):
l = []
for k in db.keys():
if v.count(k) < db[k]:
l.append(k)
return l
def generateImpl(a):
if len(a) < N:
lst = []
for c in possibilities(a):
lst += generateImpl(a+[c])
return lst
else:
return [''.join(a)]
def generate():
return generateImpl([])
Just run generate() to obtain a list of possible words.
You have 6 letters and need to find a combination of 6 letters. If you are not using the same character in ['K','K','K','U','A','N'] again and again, then there is only 1 permutation.
If you can use the same character again and again, you can use the following code to generate all possible combinations.
import itertools
y = itertools.combinations_with_replacement(['K','U','A','N'],6)
for i in list(y):
print(i)

In Python how do I extract all substrings that cross a certain index in a longer string? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Say I have a string (mystring). I want to extract all possible substrings of mystring so long as the substrings are lengths 8-15. I've been able to do that with no problem (see code below). However, what if I want to only extract these substrings if they overlap a certain part of mystring? The overlap is defined by the position in mystring rather than a certain letter of mystring, as the letters are not unique across mystring.
In the example below, I might want my substrings to include zero-based index 11.
mystring = "JACKANDJILLRANUPTHEHILLFORWATER"
substrings = set()
for i in range(0, len(mystring)):
for length in range(8,16):
ss = mystring[i:i+length]
if len(ss) == length:
substrings.add(ss)
Simple answer
You could check that 11 is included in [i, i + length) by checking i <= 11 < i + length:
mystring = "JACKANDJILLRANUPTHEHILLFORWATER"
substrings = set()
for i in range(0, len(mystring)):
for length in range(8,16):
ss = mystring[i:i+length]
if len(ss) == length and i <= 11 < i + length:
substrings.add(ss)
As set comprehension
You could do it like this:
substrings = {mystring[i:j]
for i in range(0, len(mystring))
for j in range(i + 8, min(i + 16, len(mystring)))
if i <= 11 < j}

Python: how to display all possible cases to place brackets [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Given a number of brackets pairs. I want to display all correct combinations of these brackets. By correct I mean each bracket should be opened before closing in each combination. For example, if the number of brackets is 2 the output should be:
(())
()()
For 3:
((()))
()()()
(()())
(())()
()(())
The order of the output lines doesn't matter.
How can I do it with Python?
Try this code, please:
def __F(l, r, pref):
if r < l or l < 0 or r < 0:
return
if r == 0 and l == 0:
print(pref)
return
__F(l - 1, r, pref + "(")
__F(l, r - 1, pref + ")")
def F(n):
__F(n, n, "")
F(2)
F(3)

Categories