Python Tutorial

Showing posts with label SPOJ. Show all posts
Showing posts with label SPOJ. Show all posts

Tuesday, January 15, 2013

Problem solving using python : Candy I


Candy I: https://www.spoj.com/problems/CANDY/
All source code available on github

n=input()
while n != -1:
    a=[]
    s =0
    for i in range(0,n):
        d=input()
        s  += d
        a.append(d)
    avg = int(s/n)
    if avg*n != s:
        print -1
    else:
        r=0
        for i in range(0,n):
            if a[i]<avg:
                r += (avg - a[i])
        print r
    n = input()

Tuesday, December 11, 2012

Problem solving using python: Count on Cantor


Count on Cantor: https://www.spoj.com/problems/CANTON/
All source code available on github

import math

def solution(n):
    t = float(math.sqrt(1+8*(n-1)))
    k = int((t+1)/2)
    a = int((k*(k-1))/2)
    b = n - a
    if k%2==0:
        return b,(k+1)-b
    return (k+1)-b, b

case = input()
while case>0:
    n=input()
    case = case -1
    a, b = solution(n)
    print "TERM %d IS %d/%d" % (n,a,b)

Problem solving using python: Adding Reversed Numbers


Adding Reversed Numbers: http://www.spoj.com/problems/ADDREV/


All source code available on github

# python 2.7
n=input()
while n>0:
    a, b = [int(x) for x in raw_input().split()]
    sa, sb=str(a)[::-1],str(b)[::-1]
    sr =str( int(sa)+int(sb) )
    sr = sr[::-1]
    print int(sr)
    n=n-1

Wednesday, December 5, 2012

Problem solving using python: Small factorials


Small factorials: https://www.spoj.pl/problems/FCTRL2/

All source code available on github

# python 2.7
def fact(n):
    if n==0:
        return 1
    return n*fact(n-1)

n = input()
while n>0:
    n=n-1
    k=input()
    print fact(k)

Problem solving using python


Currently I am starting to solve online programming problems using python. Spoj support python as well as other's language. Here I post some of my solved problems code of Spoj site, so that you can find how to solve programming problems in python. Lets have fun ....
Life, the Universe, and Everything :
https://www.spoj.pl/problems/TEST/
All source code available on github

# python 2.7
num=input()
while num!=42:
    print num
    num=input()