This question already has answers here:
Counting longest occurrence of repeated sequence in Python
(5 answers)
Closed 1 year ago.
I am trying to get a length of a Small string that repeats large string continuously in Python
I Tried...
def repeats(string):
for x in range(1, len(string)):
substring = string[:x]
if substring * (len(string)//len(substring))+(substring[:len(string)%len(substring)]) == string:
return "break"
print(len(substring))
But it's long..
Plese Give me your knowledge.
You might be able to use a regex re.findall approach here:
def longest_repeat(x):
matches = re.findall(r'(.+)\1+', x)
matches.sort(key=lambda s: len(s), reverse=True)
if not matches:
return ''
else:
return matches[0]
inp = ["agtcaggtccaggtccgatcgaatac", "agtcgggggggatta", "agtctgcatgac"]
for i in inp:
output = longest_repeat(i)
print(i + ', ' + output)
This prints:
agtcaggtccaggtccgatcgaatac, caggtc
agtcgggggggatta, ggg
agtctgcatgac,
Related
This question already has answers here:
What is the pythonic way to count the leading spaces in a string?
(7 answers)
Closed last year.
Is there a way to get the first letter index of a string after an n number of spaces?
I know it is easily made with a for loop, but for sake of simplicity, is there a cleaner way?
string_1 = " Hello" # Return 4
string_2 = " Bye" # Return 8
Method strip() cuts spaces before the first and after the last charactes (and multiple inside like x y.
So:
x = ' abc'
x = x.strip()
print(x) # result -> 'abc'
You can use filter, enumerate, and next to stop whevener the condition is met:
string_1 = " Hello"
next(filter(lambda x: x[1]!=' ', enumerate(string_1)))[0]
# 4
This question already has answers here:
Removing any single letter on a string in python
(6 answers)
Closed 2 years ago.
I want to remove the first character in a string, and the white space after it, only if the first word is one character.
Like this:
input = "A fish"
output = "fish"
Is there a way to do this without turning it into a list first?
You can do this with indexing:
def remove_first(s):
if len(s) < 2:
return s
# if string is letter then a space then trim the first 2 chars
if s[0].isalpha() and s[1].isspace():
return s[2:]
return s
remove_first("A fish") # "fish"
remove_first("fish") # "fish"
Here is how:
text = "A fish"
if text[1] == ' ':
text = text[2:]
print(text)
Output:
fish
This question already has answers here:
What is the purpose of the return statement? How is it different from printing?
(15 answers)
How can I use `return` to get back multiple values from a loop? Can I put them in a list?
(2 answers)
Closed 5 days ago.
For example, if we run 5678 through the function, 25364964 will come out. So I wrote a code like this.
number = 5678
for ch in str(number):
print (int(ch)**2, end="")
And got the correct output.
25364964
However, if I put this code under a function, the expected result isn't showing up.
def square_every_number(number):
for ch in str(number):
return ((int(ch)**2))
print(square_every_number(5678))
Output:
25
I'm getting only the square for the first digit.
You are returning on the first loop. You should build up your result and return that.
def square_every_number(number):
res = ''
for ch in str(number):
res = res + str(int(ch)**2)
return res
Or a shorter function:
def square_every_number(number):
return ''.join(str(int(ch)**2) for ch in str(number))
You were returning after squaring the first character, please try squaring every character and form the resultant number in your function and return the final result as below.
def sq_every_num(number):
result = ''
for ch in str(number):
result += str(int(ch) ** 2)
return int(result)
output:
result = sq_every_num(5678)
print result, type(result)
25364964 < type 'int'>
This question already has answers here:
How to merge lists into a list of tuples?
(10 answers)
Closed 7 years ago.
My goal is to write a program which compares two strings and displays the difference between the first two non-matching characters.
example:
str1 = 'dog'
str2 = 'doc'
should return 'gc'
I know that the code which I have tried to use is bad but I am hoping to receive some tips. Here is my poor attempt to solve the exercise which leads me to nowhere:
# firstly I had tried to split the strings into separate letters
str1 = input("Enter first string:").split()
str2 = input("Enter second string:").split()
# then creating a new variable to store the result after comparing the strings
result = ''
# after that trying to compare the strings using a for loop
for letter in str1:
for letter in str2:
if letter(str1) != letter(str2):
result = result + letter
print (result)
def first_difference(str1, str2):
for a, b in zip(str1, str2):
if a != b:
return a+b
Usage:
>>> first_difference('dog','doc')
'gc'
But as #ZdaR pointed out in a comment, result is undefined (in this case None) if one string is a prefix of the other and has different length.
I changed the solution by using a single loop.
How about this:
# First, I removed the split... it is already an array
str1 = input("Enter first string:")
str2 = input("Enter second string:")
#then creating a new variable to store the result after
#comparing the strings. You note that I added result2 because
#if string 2 is longer than string 1 then you have extra characters
#in result 2, if string 1 is longer then the result you want to take
#a look at is result 2
result1 = ''
result2 = ''
#handle the case where one string is longer than the other
maxlen=len(str2) if len(str1)<len(str2) else len(str1)
#loop through the characters
for i in range(maxlen):
#use a slice rather than index in case one string longer than other
letter1=str1[i:i+1]
letter2=str2[i:i+1]
#create string with differences
if letter1 != letter2:
result1+=letter1
result2+=letter2
#print out result
print ("Letters different in string 1:",result1)
print ("Letters different in string 2:",result2)
This question already has answers here:
How do I generate all permutations of a list?
(40 answers)
Randomize a string input into all possibilities
(2 answers)
Closed 9 years ago.
So I am making a word generator that takes several inputted letters, puts them in all possible positions, and matches them with a document to find words. If I am approaching this wrong please tell me! If not how can I do this?
Thanks
to generate all permutations of a given list of letters, use the itertools module.
import itertools
for word in itertools.permutations( list_of_letters ):
print ''.join(word)
You can write your own function (:
def permutation(head, tail=''):
if len(head) == 0:
print tail
else:
for i in range(len(head)):
permutation(head[0:i] + head[i + 1:], tail + head[i])
It might be faster to run it in reverse: index your document, and for each word, see if it is a subset of your list of letters.
def allpermutationsOfString(words):
if len(words) == 1:
return [words]
result = []
for index, letter in enumerate(words):
wordWithoutLetter = words[:index] + words[index+1:]
result = result + [letter + word for word in allpermutationsOfString(wordWithoutLetter)]
return result
print allpermutationsOfString("watup") #will print all permutations of watup
Here's another way to implement the algorithm.