Monday, June 6, 2016

A quick try except in python


Please use try/except for cross service or real time user input validation, its safer to throw exception rather failing the whole program

# Program to convert all given values into int

# Ex. of try except

for v in 1,2,10,'a',4,5,10,'v',"abc",1:
        try:
                print "Vint:",int(v)
        except ValueError as ex:

                print "{} cannot be converted to int: {}".format(v,ex)


Counting the vowels

There are many ways to count the vowels in python, here is one


# Program to count vowels in given sentence

count=0
vowels={'a':0,'e':0,'i':0,'o':0,'u':0}

print "Program to count vowels in given sentence"

sentence=raw_input('Enter sentence? ')

for i in sentence:
if i.lower() in vowels.keys():
count+=1
vowels[i.lower()]+=1

print "Vowel count:", count
print "Each vowel count"
for k,v in vowels.items():

print '\t',k,':',v



Tuesday, February 16, 2016

first 100 prime numbers


Using sieve of Eratosthenes method to find first 100 prime numbers..

The program might not be exact ..its learning curve will improve on.. :)


#!/usr/bin/env python
"""
  Program to list out the first 100 prime numbers
  sieve of Eratosthenes Method
"""


def getprime(n):
    ret=[]
    cancel=[]
    for i in range( 2, n+1):
        if i not in cancel:
            ret.append(i)
        for j in range (i,n+1,i):
            cancel.append(j)
    return ret


if __name__=='__main__':

print getprime(100)

Take a look: 
https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
https://en.wikipedia.org/wiki/Prime_number