rmd: (sweeney)
[personal profile] rmd
ETA: solved!

Very basic python question for folks what know python.

So, I'm messing about with python a bit (rev 2.7.3), and I'm doing some very basic just-above-hello-world stuff. I want to take two lines of input and merge them, but if the second line starts with a + (like some text clients do when inserting a line break), I want to delete the +. But this:
import sys
line1 = sys.stdin.readline()[:-1]
line2 = sys.stdin.readline()[:-1]
if line2[0] == '\+'
 line1 = line1 + line2[1:]
print line1


fails with this error message:
  File "foo.py", line 4
    if line2[0] == '\+'
                      ^
SyntaxError: invalid syntax


I tried using " quotes and with and without the \ escape character. What's the right syntax, here? (google was unhelpful, or at least I had too much trouble distilling the results down to things that were relevent.)
also, man, python is weird!

Date: 2013-08-05 11:16 pm (UTC)
From: [identity profile] rmd.livejournal.com
... interesting! i'm going to have to stare at that for a while and maybe read up more on python before I come back to it again.

Thanks!

Date: 2013-08-13 01:14 am (UTC)
From: [identity profile] charleshaynes.livejournal.com
You're welcome. It's a horrible algorithm though. N^2. This one is based on priority queues and is a better sieve:
__author__ = 'chaynes'

from heapq import heappushpop, heappush
from itertools import count

def primes():
    """
    generate a list of primes

    sieve contains a heap of tuples, (nextLargestMultipleOfPrime, prime)
    top of the heap is the smallest composite bigger or equal to our last prime
    we repeatedly update top of heap until either:
        we find our candidate, in which case it isn't a prime so we increment the candidate
        or the smallest composite is bigger than our candidate
            in which case we push the new prime and its next multiple
    """
    sieve = []
    yield 2
    p = 3
    while True:
        heappush(sieve, (p * p, p))
        yield p
        p += 2
        while sieve[0][0] <= p:
            if (sieve[0][0] == p): p += 2
            heappushpop(sieve, (sieve[0][0] + sieve[0][1], sieve[0][1]))


def main():
    """
    print a generated list of primes
    """
    for (p, _) in zip(primes(), xrange(10000)):
        print p


if __name__ == "__main__":
    main()
Enjoy! and as always happy to answer questions. BTW I just installed Python and Emacs on my phone! I love living in the future.
Edited Date: 2013-08-13 01:18 am (UTC)

Profile

rmd: (Default)
rmd

June 2025

S M T W T F S
1234567
89 1011121314
15161718192021
22232425262728
2930     

Most Popular Tags

Style Credit

Expand Cut Tags

No cut tags
Page generated Jan. 18th, 2026 11:10 pm
Powered by Dreamwidth Studios