Tuesday 26 April 2011

Script to find if a number is prime or not

Below script will find if the number entered is prime or not

while True:
    try:
        input = int(input("Enter a number: "))
        break
    except Exception, e:
        print e

a = []
if input == 0:
    print input, "is  not a valid number"
elif input == 1:
    print input, "is not a prime number"
else:
    for i in range(input):
        if i == 0:
            pass
        else:
            a.append(input % i)
    if a.count(0) > 1:
        print input, "is not a prime number"
    else:
        print input, "is a prime number"

Output:
[madhu@localhost tmp]$ python prime.py
Enter a number: 2
2 is a prime number
[madhu@localhost tmp]$ python prime.py
Enter a number: 10
10 is not a prime number

pallindrome script

I wrote the below python script to find if the string is pallindrome or not.

while True:
try:
input_string = str(input("Enter a string: "))
if input_string.isdigit():
pass
else:
break
except Exception, e:
print e
a = []
b = []
for i in input_string:
a.append(i)
a.reverse()

for i in input_string:
b.append(i)
if a == b:
print input_string, "is a pallindrome"
else:
print input_string, "is not a pallindrome"

Output:
[madhu@localhost tmp]$ python pallindrome.py
Enter a string: "elle"
elle is a pallindrome
[madhu@localhost tmp]$ python pallindrome.py
Enter a string: "malayalam"
malayalam is a pallindrome
[madhu@localhost tmp]$ python pallindrome.py
Enter a string: "pallindrome"
pallindrome is not a pallindrome