Python

coding java programming

How is competitive programming different from real-life programming?

Adapted from Anthony Moh:

In competitive programming, you just have to choose the first algorithm that comes to mind that you think will work and then code it. The aim while coding is to just get it down and make minimal mistakes. You do not have to worry about maintenance  documenting etc. No need to to think much about how to name the variables, split the code into functions and so on. Also, competitive coding is short. You will not have to spend more than a few days on it. And most of your time is spent coding.

While competitive programming gives you important knowledge of algorithms and how to implement them, you will find that in most jobs, coders just use libraries of algorithms. So, the most useful part of competitive coding is learning which algorithm to use for the problem at hand. At office, you will spend only a small amount of your time writing code. Most of your time is spent in deciding what to code, testing, documenting and …

You are in thprogramming bug jokee jungle. You have a pocket-knife. Someone asks you to kill a mountain lion. Anyone but a programmer would be asking “WTF is a MOUNTAIN lion doing in a JUNGLE?!”, but that’s not what you have been trained to do as a programmer. You are here to solve problems, not to question them.

Years of training has taught you well. You use your knife to sharpen a stick. You cut vines to lash sharp stones on one end. Maybe you’re from a top university, and you’ve learned to extract essential ingredients from plant and insect life around you to fashion a poison to tip your weapon with.

Convinced that you have an effective and efficient way to kill the lion, you set forth to accomplish your task. Maybe your stick is too short, or your poisons don’t work. It’s okay – you live to refine your method and try again another day.

Then someone figures out a way to fashion a low-grade explosive from harvesting chemicals in the jungle. Your method of fashioning a spear to kill the lion is now far from the best way to accomplish your task. Nevertheless, it’s still a simple way, and will continue to be taught in schools. Every lion-killer will be taught how to build his tools from scratch.

That’s “real-life” programming.

In competitive programming, you start out with the same resources (a pocket-knife), except you have 2 minutes to kill the lion.

As a beginner, you will stare at the lion and do nothing.

Soon, you learn that if you kill a squirrel, sometimes the judge thinks it’s a lion and you’re good to go.

A more experienced programmer just keeps stabbing the lion and hopes that the lion dies in time. Soon, you learn that there are certain spots on a lion that are damage immune. You learn to not even bother stabbing those spots. Sometimes, the lion doesn’t expose those spots, so you get really good at killing squirrels. (more…)

Advertisements
coding java programming

How do you keep your programming skills sharp?

Short answer: ABC: Always Be Coding.

1. The more you code, the better you’ll get — it’s that simple. By coding, you’re practicing. But the best practice is focused practice. Have goals in mind, explore new areas, and challenge yourself. Over time, you should develop a portfolio of both unfinished and finished projects. GitHub is a great place to put this portfolio on display, but just having an eclectic body of work is huge.

2. Re-build the wheel. You should implement the most common data structures in the language you’re trying to learn. Do not rely on common libraries. Implement the following and write tests for them: vector (dynamic array), linked list, stack, queue, circular queue, hash map, set, priority queue, binary search tree, etc. You should be able to implement them quickly as you get more comfortable with the language. (more…)

python script logo

What are the main weaknesses of Python as a programming language?

Answer by Jesse Tov:

The essence of my complaints with Python boils down to two things:

  • Much of the language consists of special cases rather than general features that combine in orthogonal ways. This results in infelicities and weird corner cases.
  • Guido van Rossum has a history of getting the language design really wrong (e.g., http://neopythonic.blogspot.com/2009/04/tail-recursion-elimination.html), which means that we might expect him to continue to get things wrong in the future.

Some examples:

  • Python has perpetual scope confusion. As far as I can tell, this is because van Rossum didn’t understand lexical scope initially, so he got it wrong. (This isn’t a problem unique to Python. It seems pretty common among early versions of scripting languages.) Originally, Python was dynamically scoped, which everyone but RMS agrees is wrong. Then they did away with the dynamic scope, but made it so that inner scopes couldn’t even see variables from outer scopes, which is bizarre in a supposedly block-structured language. Now inner scopes can see outer scopes but can’t mutate them, which is bizarre in a supposedly object-oriented language. Some may claim this is a feature, but it’s an accident of implementation. I’m sure when he fixes that, he’ll break something else.
  • David Parnas invented information hiding more than three decades ago, but it’s “unPythonic,” so Python is missing probably the biggest advance in programming since FORTRAN 2.
  • eval

    breaks alpha-equivalence — that is, you can’t arbitrarily change the names of variables, because some variable occurrences can hide in strings, which makes the binding structure of Python undecidable.

  • Python is untyped, which means that a whole bunch of errors that are easily detected ahead of time aren’t detected in Python until they happen. Some people like it that way — and more power to them! — but it’s always worth considering whether it’s a misfeature for your particular application
  • Syntactic whitespace can be nice, but it makes code generation harder than it has to be. This isn’t a difficult problem to solve. Haskell lets you use either syntactic whitespace or an equivalent syntax involving curly braces and semicolons. One is good for people and the other for metaprogramming, and there’s no good reason not to support both. It doesn’t help that when people have requested this, Python’s implementors have been really snotty about it. (Try
    from 
    __future__ 
    import 
    braces

    .)

  • Limiting the bodies of
    lambda

    s to be expressions rather than statements is arbitrary and annoying. That variable declarations and assignments are statements rather than expressions is arbitrary and annoying. The statement/expression distinction is arbitrary and annoying.

  • “The [hash table] is a stark data structure.” Python, like the other table-based languages, encourages you to use “mappings” for many things where sum-of-products (algebraic) datatypes would be more appropriate. This is inefficient, but more importantly, it’s error-prone. To continue quoting Perlis, “Programmers are not to be measured by their ingenuity and their logic but by the completeness of their case analysis.” Python’s lack of support for appropriate data structures encourages program structure that hides case analysis.

All that said, I’d still rather work with Python than PHP or C++. But that’s like saying I’d rather eat Jack in the Box than McDonald’s. It might be slightly more palatable, but it’s still pretty bad.

View Answer on Quora

python script logo

What are the best Python scripts you’ve ever written?

Answer by Akshit Khurana:

Thanking my 500+ friends who wished me on my birthday on Facebook:

It was my 21st birthday and there were three stories that made the day memorable. This was the last one of the day.

I prefer to comment on the wishes individually and personally, but using python to do that was going to be better.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# Thanking everyone who wished me on my birthday
import requests
import json

# Aman's post time
AFTER = 1353233754
TOKEN = ' <insert token here> '

def get_posts():
    """Returns dictionary of id, first names of people who posted on my wall
    between start and end time"""
    query = ("SELECT post_id, actor_id, message FROM stream WHERE "
            "filter_key = 'others' AND source_id = me() AND "
            "created_time > 1353233754 LIMIT 200")

    payload = {'q': query, 'access_token': TOKEN}
    r = requests.get('https://graph.facebook.com/fql', params=payload)
    result = json.loads(r.text)
    return result['data']

def commentall(wallposts):
    """Comments thank you on all posts"""
    #TODO convert to batch request later
    for wallpost in wallposts:

        r = requests.get('https://graph.facebook.com/%s' %
                wallpost['actor_id'])
        url = 'https://graph.facebook.com/%s/comments' % wallpost['post_id']
        user = json.loads(r.text)
        message = 'Thanks %s :)' % user['first_name']
        payload = {'access_token': TOKEN, 'message': message}
        s = requests.post(url, data=payload)

        print "Wall post %s done" % wallpost['post_id']

if __name__ == '__main__':
    commentall(get_posts())

To make this work, you need a token which you can obtain from Graph API Explorer with the appropriate permissions. The script assumes all posts after certain timestamp are birthday wishes.

With a small change in the comments function, I also liked each post.

The screen after I ran the script:

(This screenshot makes things look much cooler than they are.)

Watching the ticker go boom with my likes and comments and the structure of the comments, Shashwat Lal Das | Facebook quickly identified I had done something like this.

Probably not my best python script but this was simple, quick and fun!

The idea came up in a discussion with Sandesh Agrawal in Networks Lab. Thanks for not working on the lab assignments and wasting time with me!

View Answer on Quora