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-07-15 07:39 pm (UTC)
From: [identity profile] joev.livejournal.com
You're missing the colon at the end of the conditional. I.e., it should be "if line2[0] == '\+':". I think missing colons are my most frequent python syntax error.

Date: 2013-07-15 07:45 pm (UTC)
From: [identity profile] rmd.livejournal.com
oh! thanks!
it was a stupid error but not the one I was expecting! :)

Date: 2013-07-16 01:57 pm (UTC)
From: [identity profile] achinhibitor.livejournal.com
Conveniently, the parser doesn't tell you anything about what it is expecting you to write there, just that it doesn't like what you *did* write.

Date: 2013-07-17 02:35 pm (UTC)
From: [identity profile] charleshaynes.livejournal.com
BTW I recommend pyCharm from JetBrains. Free 30 day trial, and it would have pointed out your error immediately.

Date: 2013-07-17 02:41 pm (UTC)
From: [identity profile] rmd.livejournal.com
Thanks - I may check it out. I'm poking my way through 'Think Python' at the moment. (I haven't even gotten to the chapter on lambdas, yet.)

Date: 2013-07-17 03:09 pm (UTC)
From: [identity profile] charleshaynes.livejournal.com
Free tools to check out - pylint, pychecker, and pyFlakes. Of the three I prefer pylint but it does compile your code - so watch out if your code has side effects!

Date: 2013-07-15 08:13 pm (UTC)
From: [identity profile] miss-chance.livejournal.com
Do pythons have colons?

(the reptile, not the language)

Date: 2013-07-15 08:44 pm (UTC)
From: [identity profile] rmd.livejournal.com
See, *that*, google can help me with. yes! (http://en.wikivet.net/Snake_Digestive_System)

Date: 2013-07-16 03:50 am (UTC)
muffyjo: (conscience)
From: [personal profile] muffyjo
I am amused. I wish I were also helpful, but it's not in my toolset. So I can only sit here on the sidelines, reading, and being so very, very amused.

Date: 2013-07-15 09:04 pm (UTC)
irilyth: (Only in Kenya)
From: [personal profile] irilyth
> also, man, python is weird!

I've been learning it recently, and I like it a lot.

Date: 2013-07-16 02:17 am (UTC)
From: [identity profile] kirkcudbright.livejournal.com
I've recently been on a project that's a mix of Python and C++. Of the two, I vastly prefer Python, but it still has its quirks. Like, if whitespace is syntactically meaningful, there's no real need for the colon. But there it is.

Date: 2013-07-16 02:25 am (UTC)
annathepiper: (Default)
From: [personal profile] annathepiper
Python is DEFINITELY weird. I've been writing a crapton of automation in at work for the last couple of years, and it's very much one of the weirder languages I've ever done anything in!

I STILL haven't really managed to bend my brain around lambda statements. :D

Date: 2013-07-16 02:45 pm (UTC)
From: [identity profile] charleshaynes.livejournal.com
print reduce(lambda x, y: x + y.lstrip('+'), sys.stdin.read().split('\n'))

Date: 2013-07-17 03:18 am (UTC)
annathepiper: (Default)
From: [personal profile] annathepiper
I rest my case. :D

Date: 2013-07-17 02:31 pm (UTC)
From: [identity profile] charleshaynes.livejournal.com
you can think of a lambda as a shorthand for an anonymous function (I'm sure you know this) so the lambda in my example (lambda x, y: x+y.lstrip('+')) is really just

def fn(x,y): return x + y.lstrip('+')

Date: 2013-07-18 03:25 am (UTC)
annathepiper: (Default)
From: [personal profile] annathepiper
Yep! I've played with them just a little bit in code at work. They're still just damned weird to me. ;)

Date: 2013-08-04 10:21 am (UTC)
From: [identity profile] charleshaynes.livejournal.com
Ok, partially prompted by this thread, I decided to write a Sieve of Erathosthenes in python using lambdas and generators. If you like puzzles, here it is:
__author__ = 'chaynes'

from itertools import chain, count, cycle, ifilter, repeat

def primes():
    sieve = []
    for p in ifilter(lambda _: reduce(lambda x, isntMultipleOf: isntMultipleOf.next() and x, sieve, True), count(2)):
        sieve.append(cycle(chain(repeat(True, p-1), (False,))))
        yield p


def main():
    for p in primes():
        print p


if __name__ == "__main__":
    main()

the sieve list holds a list of generators, one for each prime, that generates "False" if a number is not a multiple of that prime, and "True" if it is. It really just generates the sequence (True, True, ... True, False) with a period the length of the prime, over and over.

It has to use reduce(lambda x, y: f(x) and y) instead of "all()" because any/all do lazy/short-circuit evaluation and the generators depend on being called for each integer. That's also why the "isMultipleOf" comes before the "and" and/or also short circuit.

Happy to explain further if anyone is interested.

Edited Date: 2013-08-04 10:45 am (UTC)

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)

Date: 2013-07-16 02:37 pm (UTC)
From: [identity profile] charleshaynes.livejournal.com
I <3 python. Not sure what you mean by "merge them" but how about

print sys.stdin.readline()[:-1] + sys.stdin.readline()[:-1].lstrip('+')

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 03:01 pm
Powered by Dreamwidth Studios