11 Things to Review Before a Programming Competition

    Seattle is a popular place for programming competitions, and it's easy to forget important concepts. Here are some things to review before you participate in one. Some good competitions are TeamsCode and PSCSTA.

    1. Opening A File

    Even though this is pretty basic, it's good to remember how to open files in case you run into technical difficulties at the competition. I open files using:
    f=open('filename.dat')
    file=f.readlines()

    2. Stripping Strings

    The strings you get from the file usually have junk at the end, such as \n. This can really mess up your program. To get rid of this, use the .strip() method (it will strip particular characters if you give it arguements). Strip() will also get rid of spaces, but .rstrip() and .lstrip() don't.
    s='ai don't like newlines or a/b\n'
    s=s.strip()
    #s is now 'ai don't like newlines or a/b'
    s.strip('ab')
    #s is now 'i don't like newlines or a/'

    3. Objects Are Passed By Reference

    This means when you make a variable equal to an object, such as a list, it will just be a pointer to the object. Here's an application:
    
    def foo(a):
      a = 1
    a=[5]
    foo(a)
    print(a) #this will print 1, not 5
    
    

    4. Strings Are Immutable

    You have to set a string to a new string instead of modifying it.
    
    s='abcde'
    s.reverse() #this does nothing
    s=s.reverse() #this reverses s
    
    

    5. Lists/Dictionaries Are Mutable

    
    a=[1,2,3,4]
    a.sort() #a is now sorted
    a=a.sort() #a is now None
    
    

    6. Sort Dictionary By Its Keys

    
    a={'b':2,'a':1}
    for k in sorted(list(a.keys())):
    	print(k,a[k])
    
    

    7. Sort Dictionary by Its Values

    
    a={'b':2,'a':1}
    pairs=[(k,v) for k,v in a.items()]
    pairs.sort(key=lambda x: x[1])
    print(pairs)
    # output: [('a', 1), ('b', 2)]
    
    

    8. Sort List of Dicts By Key

    
    dicts= [{'b':20,'a':10},{'b':2,'a':1}]
    dicts.sort(key=lambda x:x['a'])
    
    

    9. Reverse Lists/Strings

    
    print([1,2,3][::-1])
    
    
    

    10. Int to Ascii/Ascii to Int

    
    print(chr(65))
    print(ord('A'))
    
    

    11. String to Int / Int to String

    
    a=[]
    n=123
    while n>0:
        a.append(chr(ord('0')+n%10))
        n /= 10
    print(''.join(a[::-1]))
    
    a=0
    n='123'
    while len(n)>0:
        a*=10
        a += ord(n[0])-ord('0')
        n =n[1:]
    print(a)