Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to work with very long strings in Python?

Tags:

python

I'm tackling project euler's problem 220 (looked easy, in comparison to some of the others - thought I'd try a higher numbered one for a change!)

So far I have:

D = "Fa"

def iterate(D,num):
    for i in range (0,num):
        D = D.replace("a","A")
        D = D.replace("b","B")
        D = D.replace("A","aRbFR")
        D = D.replace("B","LFaLb")
    return D

instructions = iterate("Fa",50)

print instructions

Now, this works fine for low values, but when you put it to repeat higher then you just get a "Memory error". Can anyone suggest a way to overcome this? I really want a string/file that contains instructions for the next step.

like image 379
Rich Bradshaw Avatar asked Dec 09 '08 15:12

Rich Bradshaw


People also ask

How do you handle a long string in Python?

The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. If necessary, you can add an extra pair of parentheses around an expression, but sometimes using a backslash looks better. Make sure to indent the continued line appropriately.

What if a line is too long in Python?

If you have a very long line of code in Python and you'd like to break it up over over multiple lines, if you're inside parentheses, square brackets, or curly braces you can put line breaks wherever you'd like because Python allows for implicit line continuation.

What is the maximum length of a string in Python?

On a 32 bit system it's around 2 billion or 500 million characters.

How do you break a long line in Python?

To break a line in Python, use the parentheses or explicit backslash(/). Using parentheses, you can write over multiple lines. The preferred way of wrapping long lines is using Python's implied line continuation inside parentheses, brackets, and braces.


1 Answers

The trick is in noticing which patterns emerge as you run the string through each iteration. Try evaluating iterate(D,n) for n between 1 and 10 and see if you can spot them. Also feed the string through a function that calculates the end position and the number of steps, and look for patterns there too.

You can then use this knowledge to simplify the algorithm to something that doesn't use these strings at all.

like image 139
xahtep Avatar answered Oct 22 '22 01:10

xahtep