Find length of a string that includes its own length?
I want to get the length of a string including a part of the string that represents its own length without padding or using structs or anything like that that forces fixed lengths.
So for example I want to be able to take this string as input:
"A string|"
And return this:
"A string|11"
Asked by: Marcus356 | Posted: 30-11-2021
Answer 1
On the basis of the OP tolerating such an approach (and to provide an implementation technique for the eventual python answer), here's a solution in Java.
final String s = "A String|";
int n = s.length(); // `length()` returns the length of the string.
String t; // the result
do {
t = s + n; // append the stringified n to the original string
if (n == t.length()){
return t; // string length no longer changing; we're good.
}
n = t.length(); // n must hold the total length
} while (true); // round again
The problem of, course, is that in appending n
, the string length changes. But luckily, the length only ever increases or stays the same. So it will converge very quickly: due to the logarithmic nature of the length of n
. In this particular case, the attempted values of n
are 9, 10, and 11. And that's a pernicious case.
Answer 2
A simple solution is :
def addlength(string):
n1=len(string)
n2=len(str(n1))+n1
n2 += len(str(n2))-len(str(n1)) # a carry can arise
return string+str(n2)
Since a possible carry will increase the length by at most one unit.
Examples :
In [2]: addlength('a'*8)
Out[2]: 'aaaaaaaa9'
In [3]: addlength('a'*9)
Out[3]: 'aaaaaaaaa11'
In [4]: addlength('a'*99)
Out[4]: 'aaaaa...aaa102'
In [5]: addlength('a'*999)
Out[5]: 'aaaa...aaa1003'
Answered by: Hailey379 | Posted: 01-01-2022
Answer 3
Here is a simple python port of Bathsheba's answer :
def str_len(s):
n = len(s)
t = ''
while True:
t = s + str(n)
if n == len(t):
return t
n = len(t)
This is a much more clever and simple way than anything I was thinking of trying!
Suppose you had s = 'abcdefgh|
, On the first pass through, t = 'abcdefgh|9
Since n != len(t)
( which is now 10 ) it goes through again : t = 'abcdefgh|' + str(n)
and str(n)='10'
so you have abcdefgh|10
which is still not quite right! Now n=len(t)
which is finally n=11
you get it right then. Pretty clever solution!
Answer 4
It is a tricky one, but I think I've figured it out.
Done in a hurry in Python 2.7, please fully test - this should handle strings up to 998 characters:
import sys
orig = sys.argv[1]
origLen = len(orig)
if (origLen >= 98):
extra = str(origLen + 3)
elif (origLen >= 8):
extra = str(origLen + 2)
else:
extra = str(origLen + 1)
final = orig + extra
print final
Results of very brief testing
C:\Users\PH\Desktop>python test.py "tiny|"
tiny|6
C:\Users\PH\Desktop>python test.py "myString|"
myString|11
C:\Users\PH\Desktop>python test.py "myStringWith98Characters.........................................................................|"
myStringWith98Characters.........................................................................|101
Answered by: Leonardo393 | Posted: 01-01-2022Answer 5
Just find the length of the string. Then iterate through each value of the number of digits the length of the resulting string can possibly have. While iterating, check if the sum of the number of digits to be appended and the initial string length is equal to the length of the resulting string.
def get_length(s):
s = s + "|"
result = ""
len_s = len(s)
i = 1
while True:
candidate = len_s + i
if len(str(candidate)) == i:
result = s + str(len_s + i)
break
i += 1
Answered by: Marcus916 | Posted: 01-01-2022
Answer 6
This code gives the result.
I used a few var
, but at the end it shows the output you want:
def len_s(s):
s = s + '|'
b = len(s)
z = s + str(b)
length = len(z)
new_s = s + str(length)
new_len = len(new_s)
return s + str(new_len)
s = "A string"
print len_s(s)
Answered by: Fenton859 | Posted: 01-01-2022
Answer 7
Here's a direct equation for this (so it's not necessary to construct the string). If s
is the string, then the length of the string including the length of the appended length will be:
L1 = len(s) + 1 + int(log10(len(s) + 1 + int(log10(len(s)))))
The idea here is that a direct calculation is only problematic when the appended length will push the length past a power of ten; that is, at 9
, 98
, 99
, 997
, 998
, 999
, 9996
, etc. To work this through, 1 + int(log10(len(s)))
is the number of digits in the length of s
. If we add that to len(s)
, then 9->10
, 98->100
, 99->101
, etc, but still 8->9
, 97->99
, etc, so we can push past the power of ten exactly as needed. That is, adding this produces a number with the correct number of digits after the addition. Then do the log again to find the length of that number and that's the answer.
To test this:
from math import log10
def find_length(s):
L1 = len(s) + 1 + int(log10(len(s) + 1 + int(log10(len(s)))))
return L1
# test, just looking at lengths around 10**n
for i in range(9):
for j in range(30):
L = abs(10**i - j + 10) + 1
s = "a"*L
x0 = find_length(s)
new0 = s+`x0`
if len(new0)!=x0:
print "error", len(s), x0, log10(len(s)), log10(x0)
Answered by: Roman762 | Posted: 01-01-2022
Similar questions
Large Python Includes
I have a file that I want to include in Python but the included file is fairly long and it'd be much neater to be able to split them into several files but then I have to use several include statements.
Is there some way to group together several files and include them all at once?
python - Put bar at the end of every line that includes foo
I have a list with a large number of lines, each taking the subject-verb-object form, eg:
Jane likes Fred
Chris dislikes Joe
Nate knows Jill
To plot a network graph that expresses the different relationships between the nodes in directed color-coded edges, I will need to replace the verb with an arrow and place a color code at the end of each line, thus, somewhat simplified:
Jane -> Fred r...
python - Global includes in Django
I want to create a module containing different utility functions and classes to use across different apps. It's not going to define any models or views. What's the best way to do this?
python - How do I return a string that includes new lines?
I have a question that requires I use return and I do not know how to return on multiple lines. I need to be able to get an output that looks like this
Dear so and so,
kjhagjkahgsdhgl;dslhglk
jkasdhgjkdshkglhds;g
kjdghksadjglkdjslkg
kjgahkjsdhlgkdsjg;lsd
where the gibberish are strings that I have
Python For Loop includes the end of the range
I'm on checkio.org trying to solve this problem:
You are given a two or more digits number N. For this mission, you should find the smallest positive number of X, such that the product of its digits is equal to N. If X does not exist, then return 0.
Let's examine the example. N = 20. We can factorize this number as 2*10, but 10 is not a digit. Also we can factorize it as 4*5 or 2*2*5. The smallest number for 2*2*5 ...
Find min value in a CSV and print every row that includes it in Python
Thanks so much in advance for any help. I'm trying to write a script that will go through a folder of csv files, find the minimum value in the second column and print every row that contains it. The csv files the script looks through looks like this:
TPN,12010,on this date,25,0.00005047619239909304377497309619
TPN,12011,on this date,23,0.00003797836224092152019127884704
TPN,12012,on this date,78,0.00011304...
python - How to build exe file which includes cv module
I am writing a simple security camera program.
I used that code for accessing camera:
import cv
camera = cv.CaptureFromCAM(0)
I tried .py file. It worked. But, when I compiled and ran exe file, I could not access camera. Program didn't react. On .py file, I could choose the camera from a window which has title named 'Video Source'.
I think that this problem about accessing ...
python - How to Format Includes List for Py2app?
I have an app organized across several folders:
models
views
controllers
data_and_execution.
I'm trying to build the app using Py2app, however, I'm getting import errors when running the app such as:
"4/27/16 9:52:29.252 PM main[63983]: ImportError: No module named controllers.available_balances_controller"
I believe it's because I ha...
How to read a file whose name includes '/' in python?
Now I have a file named Land/SeaMask and I want to open it, but it cannot be recognized as a filename by programme, but as a directory, how to do it?
python - How to change a word if it includes a certain letter
This question already has answers here:
Large Python Includes
I have a file that I want to include in Python but the included file is fairly long and it'd be much neater to be able to split them into several files but then I have to use several include statements.
Is there some way to group together several files and include them all at once?
import - Python includes, module scope issue
I'm working on my first significant Python project and I'm having trouble with scope issues and executing code in included files. Previously my experience is with PHP.
What I would like to do is have one single file that sets up a number of configuration variables, which would then be used throughout the code. Also, I want to make certain functions and classes available globally. For example, the main file would i...
python - Put bar at the end of every line that includes foo
I have a list with a large number of lines, each taking the subject-verb-object form, eg:
Jane likes Fred
Chris dislikes Joe
Nate knows Jill
To plot a network graph that expresses the different relationships between the nodes in directed color-coded edges, I will need to replace the verb with an arrow and place a color code at the end of each line, thus, somewhat simplified:
Jane -> Fred r...
python - How to check if phone number entered by user includes country code?
Is there an easy way to check whether a phone number entered by the user includes country code and to validate that the number is correct? I don't use any specific formats, the number itself must be only digits, no ('s, -'s and the like. Is such validation possible without asking user for a country? The trick is that I want to work with all numbers world-wide.
I guess it can't be done with regex (googled a bit and...
python - PyCUDA: C/C++ includes?
Something that isn't really mentioned anywhere (at least that I can see) is what library functions are exposed to inline CUDA kernels.
Specifically I'm doing small / stupid matrix multiplications that don't deserve to be individually offloaded to the GPU but am offloading a larger section of the algorithm which includes this multiplication. Noone ever liked using their own linalg functions since someone has always ...
python - Something wrong without any error - Includes Tkinter
I'm not getting any error but the code doesn't do what I want so there must be somewhere in the code where I have made a mistake. What I want to do is if the words match then the words must be a pair and the two chosen cells should remain "self.hidden = False" and therefore the cells should still show the words behind the two cells. Else if the words doesn't match then the cells should be "self.hidden = True" and the two c...
python - Global includes in Django
I want to create a module containing different utility functions and classes to use across different apps. It's not going to define any models or views. What's the best way to do this?
python - my post method returns (u'') and django saves includes the (u'') string when saving it
This is how I retrieve the post data from the webpage. The person models can be saved but it includes the "(u'')" string. For example if change the firstname to "Alex", it gets the raw value u('Alex') and saves it.
def submit_e(req, person_id=None):
if(req.POST):
try:
person_id = req.POST['driver']
person = Person.objects.get(pk=person_id)
...
python - How do I return a string that includes new lines?
I have a question that requires I use return and I do not know how to return on multiple lines. I need to be able to get an output that looks like this
Dear so and so,
kjhagjkahgsdhgl;dslhglk
jkasdhgjkdshkglhds;g
kjdghksadjglkdjslkg
kjgahkjsdhlgkdsjg;lsd
where the gibberish are strings that I have
python - Celery beat queue includes obsolete tasks
I'm using periodic celery tasks with Django. I used to have the following task in my app/tasks.py file:
@periodic_task(run_every=timedelta(minutes=2))
def stuff():
...
But now this task has been removed from my app/tasks.py file. However, I keep seeing call to this task in my celery logs:
[2013-05-21 07:08:37,963: ERROR/MainProcess] Received unregistered task of type u'ap...
Still can't find your answer? Check out these communities...
PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python