How to convert any word into an integer in Python [closed] - python

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
Is there a possible way to convert any word, which is obviously in form of a string to an integer in python.
That might seem utterly stupid and impossible at first, but if you take a look at it, it's a good problem to work on that I have been struggling with so long.
And yes, I have tried many other ways such as using a list to store different integers to their corresponding letters, however; it didn't go very well.

You could create a mapping between primes (2,3,5,7,... ) to all characters in your alphabet (a,b,c,d,e,...). Then you map the position of the character inside your word to the next bigger primes.
Then you multiply your character value with your positional value and sum all up:
Example:
alphabet = {"a":2, "b":3, "1":5, "2":7 }
position = [11,13,17,19,23,29,31]
text = "aabb12a"
def encode(t):
"""Throws error when not map-able"""
return sum(alphabet[x] * position[pos] for pos,x in enumerate(t))
for i in alphabet:
print(i,"=>",encode(i))
print(encode(text))
Output:
('a', '=>', 22)
('1', '=>', 55)
('2', '=>', 77)
('b', '=>', 33)
536
To reverse the number, you would have to do a prime factorisation, order the resuling summands by theire bigger number ascending, then reverse the mapping of your alphabet.
In this case you would get :
536 = 2*11 + 2*13 + 3*17 + 3*19 + 5*23+ 7*29 + 2*31
and you can lookup position and character to reconstruct your word.
Give, with 128 characters (ascii) and words up to 50 characters you would get big numbers....

You can use built-in hash function:
>>> hash('hello')
-8733837932593682240

Related

How do I convert a list of strings to integers in Python [closed]

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 1 year ago.
Improve this question
I need help on how to convert a list to integers, for example
lst = ["1", "2", "3"]
Desired output:
123
I think I explain myself, I do not speak English so I use a translator, I hope it is understood.
You need to do two things: 1. concatenate the elements of the array together into a single string, and 2. convert that string to a number.
You can do #1 with the join string method. Normally, you call join on some other string that you want to put in between the ones you're joining, but since you don't want one of those here, you can just use the empty string:
>>> lst=["1","2","3"]
>>> "".join(lst)
'123'
Since that's still a string, not a numeric value, this is where step 2 comes in. You can convert it to an integer with the int function:
>>> int("".join(lst))
123
Join the strings, then convert to an integer:
int(''.join(lst))
The alternative of converting to integer and then joining is much more complicated, and will drop any leading zeros you have:
from math import floor, log10
result = 0
for x in lst:
n = int(x)
result *= 10**((x and floor(log10(x))) + 1)
result += n
Because of how Python's and operator works, the expression x and ... returns x immediately if it is zero, and the right hand side if not, which is what you want when taking logarithms.

create list of increasing number of repeated 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'm trying to create this kind of output in Python
["k", "kk", "kkk", "kkkk", ...]
["rep", "reprep", "repreprep", ...]
That is a list of n elements, made of the same character (or small group of characters) repeated X times, X being increased by one for each element.
I can't find a way to do this easily, without loops..
Thanks,
Here you have a generator using itertools.count, remember the property of "multiplying" strings in python by a number, where they will be replicated and concatenated nth times, where for example "a"*3 == "aaa" :
import itertools
def genSeq(item):
yield from (item*i for i in itertools.count())
Here you have a live example
repeating_value = "k" #Assign the value which do you want to be repeated
total_times=5 #how many times do you want
expected_list=[repeating_value*i for i in range(1,total_times+1)]
print(expected_list)
character = 'k'
_range = 5
output = [k*x for k in character for x in range(1, _range + 1)]
print(output)
I would multiple my character by a specified number in the range, and then I would simply iterate through the range in a list comprehension. We add 1 to the end of the range in order to get the full range.
Here is your output:
['k', 'kk', 'kkk', 'kkkk', 'kkkkk']
The following is by far the easiest which I have built upon the comment by the user3483203 which eliminates initial empty value.
var = 'rep'
list = [var * i for i in range(1,x,1)]
print(list)

How to slice a string to fetch characters at odd and even position [closed]

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

python find repeated substring in string [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
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)

shortest repeated substring [PYTHON] [closed]

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 6 years ago.
Improve this question
Is there a quick method to find the shortest repeated substring and how many times it occurs? If there is non you only need to return the actual string ( last case ).
>>> repeated('CTCTCTCTCTCTCTCTCTCTCTCT')
('CT', 12)
>>> repeated('GATCGATCGATCGATC')
('GATC', 4)
>>> repeated('GATCGATCGATCGATCG')
('GATCGATCGATCGATCG', 1)
Because some people think it's 'homework' I can show my efforts:
def repeated(sequentie):
string = ''
for i in sequentie:
if i not in string:
string += i
items = sequentie.count(string)
if items * len(string) == len(sequentie):
return (string, items)
else:
return (sequentie, 1)
Your method unfortunately won't work, since it assumes that the repeating substring will have unique characters. This may not be the case:
abaabaabaabaabaaba
You were somewhat on the right track, though. The shortest way that I can think of is to just try and check over and over if some prefix indeed makes up the entire string:
def find_shorted_substring(s):
for i in range(1, len(s) + 1):
substring = s[:i]
repeats = len(s) // len(substring)
if substring * repeats == s:
return (substring, repeats)
It's not very efficient, but it works. There are better ways of doing it.

Categories