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
I am looking for a function in Python where you give a string as input where a certain word has been repeated several times until a certain length has reached.
The output would then be that word. The repeated word isn't necessary repeated in its whole and it is also possible that it hasn't been repeated at all.
For example:
"pythonpythonp" => "python"
"hellohello" => "hello"
"appleapl" => "apple"
"spoon" => "spoon"
Can someone give me some hints on how to write this kind of function?
You can do it by repeating the substring a certain number of times and testing if it is equal to the original string.
You'll have to try it for every single possible length of string unless you have that saved as a variable
Here's the code:
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:
print(substring)
return "break"
print(string)
repeats("pythonpytho")
Start by building a prefix array.
Loop through it in reverse and stop the first time you find something that's repeated in your string (that is, it has a str.count()>1.
Now if the same substring exists right next to itself, you can return it as the word you're looking for, however you must take into consideration the 'appleappl' example, where the proposed algorithm would return appl . For that, when you find a substring that exists more than once in your string, you return as a result that substring plus whatever is between its next occurence, namely for 'appleappl' you return 'appl' +'e' = 'apple' . If no such strings are found, you return the whole word since there are no repetitions.
def repeat(s):
prefix_array=[]
for i in range(len(s)):
prefix_array.append(s[:i])
#see what it holds to give you a better picture
print prefix_array
#stop at 1st element to avoid checking for the ' ' char
for i in prefix_array[:1:-1]:
if s.count(i) > 1 :
#find where the next repetition starts
offset = s[len(i):].find(i)
return s[:len(i)+offset]
break
return s
print repeat(s)
Related
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 days ago.
Improve this question
def spell(txt):
txt = input()
spell(txt)
Given a string as input, use recursion to output each letter of the strings in reverse order, on a new line.
Sample Input
HELLO
Sample Output
O
L
L
E
H
I used recursion to get output in reverse order, but didn't get exactly.
Working of spell() function:
The function works by first checking if the length of the string is 1. If it is, the function simply prints the string (since it's the last letter of the original string, and therefore the first one to be printed in reverse order). If the length of the string is greater than 1, the function prints the last letter of the string (which is the next letter to be printed in reverse order), and then calls itself recursively with the string sliced to exclude the last letter.
Code:
def spell(txt):
if len(txt) == 1:
print(txt)
else:
print(txt[-1])
spell(txt[:-1]) #sliced the last character and spell function is call again.
spell(input("Input:\n"))
Output:
Input:
HELLO
O
L
L
E
H
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 23 days ago.
The community reviewed whether to reopen this question 23 days ago and left it closed:
Original close reason(s) were not resolved
Improve this question
There is a list with duplicate word elements with a number at the end of them. I want to sum the duplicate's numbers, remove the duplicates and print words with sum of numbers but I don't know how...
Input:
a = ["mango3", "apple2", "kiwi1", "kiwi2", "mango2"]
Output:
mango5
apple2
kiwi3
Here's a solution, first using regex to split the fruit/numbers in your list's elements, building a dictionary of fruit:total_number pairs, and finally recreating a list from the dictionary:
import re
a=["mango3","apple2","kiwi1","kiwi2","mango2"]
b={}
for element in a:
fruit, number = re.findall('\D+',element)[0], re.findall('\d+', element)[0]
b[fruit] = b.get(fruit,0) + int(number)
c=[fruit + str(number) for fruit,number in b.items()]
print(c)
# ['mango5', 'apple2', 'kiwi3']
Explanation about the regex: \d stands for digit, so \d+ will return (in this case where there's only one digit sequence) the longest succession of (at least 1) digits; similarly, \D stands for non-digit.
Note that you could use a single regex with catching groups this way:
fruit, number = re.findall('(\D+)(\d+)', element)[0]
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 4 years ago.
Improve this question
def rev(one, two, three):
print("Reverse of the third string is",three[::-1])
# returning concatenation of first two strings
return one+two
def main():
# Taking user input of 3 strings
first = input("Enter first string:")
second = input("Enter second string:")
third = input("Enter third string:")
# calling function, passing three arguments
print("Reverse of third string is",rev(first, second, third))
main()
Assignment
Write a Python function that will accept as input three string values
from a user. The method will return to the user a concatenation of the string values in reverse order. The function is to be called from the main method.
In the main method, prompt the user for the three strings.
If the input of the strings is Hello, World, and Car, then the output should be raCdlroWolleH
Your rev function could contain just one line of code (you should call it in the main function). It is as simple as :
return three[::-1]+two[::-1]+one[::-1]
I think the problem is that you're doing two separated prints, one for the first two words and other to the third word. If what you pretende is to join all of the three words and return that, then all you have to do is
New = one + two + three
return New[::-1]
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I have a string:
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
I need to print the strings with the characters present at odd and even position in the above string.
For example:
for odd position, output should be:
'ACEGIKMOQSUWY'
for even position, output should be
'BDFHJLNPRTVXZ'
You need to use string slicing. For example:
>>> my_str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
# For odd
>>> my_str[::2]
'ACEGIKMOQSUWY'
# For even
>>> my_str[1::2]
'BDFHJLNPRTVXZ'
General syntax of string slicing is string[start:end:jump] where:
start: is the starting index for slicing the string. Empty value means start of the string i.e. index 0
end: is the index till which you want to slice the string. Empty value means end of the string
jump: is used to jump the elements from start such that you'll get values in the order start, start+jump, start+2*jump, so on till your string reaches end. Empty value means 1
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 8 years ago.
Improve this question
Suppose I have a list of strings
['elvis','elo','eels','acdc']
Is there a function that accept this string and returns a unique character for each of the strings? For example, in this case, I expect to get
['e','l','s','a']
Edit: To clarify my meaning.
I want a function that will return an identifier character or string that is based on the input list members. jme answer and bonit's one are a good example.
I think I see your point. There is no built-in for this.
Correct me if I am wrong, but it seems like you want to take the first not already taken character in each string and take one only.
Here is some code to do that
def get_first_not_know(l):
chars = []
for word in l:
for letter in word:
if letter not in chars:
chars.append(letter)
break
return chars
If you don't care about order of letters you take, you can do something quicker using sets.
Assuming BenoƮt Latinier's interpretation of your question is right (which, it looks like it is), then there will be some cases where a unique letter can't be found, and in these cases you might throw an exception:
def unique_chars(words):
taken = set()
uniques = []
for word in words:
for char in word:
if char not in taken:
taken.add(char)
uniques.append(char)
break
else:
raise ValueError("There are no unique letters left!")
return uniques