Showing posts with label Integer. Show all posts
Showing posts with label Integer. Show all posts

Python Program to Find the Fibonacci Series with defined program storage infinity

a=0 b=1 n=9999999999999999999999 # Number of terms in Fibonacci Series (sample value) # An integer giving the maximum value a variable of type Py_ssize_t can take. # It 's usually 2^31 - 1 on a 32-bit platform and 2^63 - 1 on a 64-bit platform. print(a,b,end=" ") while(n-2): c=a+b a=b b=c print("\n",c) n=n-1

Temperature Conversion Table

def Fah():
    F=int(input('Enter the temperature on Fahrenheit(F)'))
    C=(F - 32) * 5/9
    K=(F - 32) * 5/9 + 273.15
    print("Fahrenheit Value :",F)
    print("Celsius Value :",C)
    print("Kelvin Value:",K)

def Cel():
    C=int(input('Enter the temperature on Celsius(C)'))
    F=(C * 9/5) + 32
    K=C + 273.15
    print("Fahrenheit Value :",F)
    print("Celsius Value :",C)
    print("Kelvin Value:",K)

def Kel():
    K=int(input('Enter the temperature on Kelvin(K)'))
    F=(K - 273.15) * 9/5 + 32
    C=K - 273.15
    print("Fahrenheit Value :",F)
    print("Celsius Value :",C)
    print("Kelvin Value:",K)
print("\n")
print('1.Fahrenheit to Celsius & Kelvin\n2.Celsius to Fahrenheit & Kelvin\n3.Kelvin to Fahrenheit & Celsius\n4.Exit')
n=int(input('Enter the choice:'))
if n==1:
      Fah()      
elif n==2:
      Cel()   
elif n==3:
      Kel()      
elif n==4:
      exit()
else:
      print('Invalid options')

To read a coordinate point in a XY coordinate system and determine its Quadrant

x=int(input('Enter the values for X'))
 
y=int(input('Enter the values for Y'))

if x > 0 and y > 0:
  print ('x, y point lies in the First quandrant')
 
elif x < 0 and y > 0:
  print ('x, y point lies in the Second quandrant')
 
elif x < 0 and y < 0:
  print ('x, y point lies in the Third quandrant')

elif x > 0 and y < 0:
  print ('x, y point lies in the Fourth quandrant')

elif x == 0 and y == 0:
  print ('x, y point lies at the origin')

To check the number is composite number or not

n=int(input('Enter the number '))
factor=0
for i in range(1,n):
  if n%i==0:
    factor=i
if factor>1:
  print ('The number is a composite number!')
elif n==1:
  print ('The number 1 is neither prime nor composite!')
else:
  print ('This is not a composite number!')

Different Set Operations

A = {1,2,3,4,5,6,7,8};
B = {5,10,15,20,25,30,35,40};
   
print("Union of A and B is",A | B)

print("\nIntersection of A and B is",A & B)

print("\nDifference of A and B is",A - B)

print("\nSymmetric difference of A and B is",A ^ B)

Check wheather a number is composite or not

#Credits to NPTEL MOOC, Programming, Data Structures & Algorithms in 
#Python by Madhavan Mukund, Chennai Mathematical Institute 
 
def composite(n):
      for i in range(2,n):
        if n%i == 0:
          return(True)
      return(False)

Greatest common divisor program using euclids algorithms

#Credits to NPTEL MOOC, Programming, Data Structures & Algorithms in 
#Python by Madhavan Mukund, Chennai Mathematical Institute 
 
def gcd(m,n):
    if m < n:
        (m,n) = (n,m)
    if (m%n) == 0:
        return(n)
    else:
        diff = m-n
        return(gcd(max(n,diff),min(n,diff)))

print(gcd(12,3))

Greatest common divisor program with looping

#Credits to NPTEL MOOC, Programming, Data Structures & Algorithms in 
#Python by Madhavan Mukund, Chennai Mathematical Institute 


def gcd(m,n):
  i = min(m,n)
  while i > 0:
    if (m%i) == 0 and (n%i) == 0:
      return(i)
    else:
      i = i-1

Greatest common divisor program without list Implementation

#Credits to NPTEL MOOC, Programming, Data Structures & Algorithms in 
#Python by Madhavan Mukund, Chennai Mathematical Institute 

def gcd(m,n):
  for i in range(1,min(m,n)+1):
    if (m%i) == 0 and (n%i) == 0:
      mrcf = i
  return(mrcf)

Greatest common divisor program - A shorter Implementation

#Credits to NPTEL MOOC, Programming, Data Structures & Algorithms #in Python by Madhavan Mukund, Chennai Mathematical Institute

def gcd(m,n):
  cf = []
  for i in range(1,min(m,n)+1):
    if (m%i) == 0 and (n%i) == 0:
      cf.append(i)
  return(cf[-1])

Greatest common divisor program

#Credits to NPTEL MOOC, Programming, Data Structures & Algorithms in 
#Python by Madhavan Mukund, Chennai Mathematical Institute 

def gcd(m,n):
  fm = []
  for i in range(1,m+1):
    if (m%i) == 0:
      fm.append(i)
  fn = []
  for j in range(1,n+1):
    if (n%j) == 0:
      fn.append(j)
  cf = []
  for f in fm:
    if f in fn:
      cf.append(f)
  return(cf[-1])

Calculation of Gross and Net Calorific Value

#  Credits   Name: ANUPRIYA R

#  HCV - Higher and Gross Calorific Value
#  LCV -  Lower or Net Calorific Value
# Compatible with python 3.x.x

c=float(input("enter value of carbon in %: "))
h=float(input("enter value of hydrogen in %: "))
s=float(input("enter value of sulphur in %: "))
o=float(input("enter value of oxygen in %: "))
HCV=(8080*c+34500*(h-o/8)+2240*s)*1/100
LCV=(HCV-0.09*h*587)
print ("Higher calorific value of sample is ",HCV)
print("Lower calorific value of sample is ",LCV)
     

Chemistry Problem Solver

# Credits  Name: Abhijith P   Email: abhijithp64@gmail.com
# Compatible with python 3.x.x 

# Program for problems related to chemistry
# 1. Spectroscopy Problems
# 2. Hardness of solution or water

# 3. Calorific value
# 4. Viscosity index 

#   Abhijith P
#   Roll number 2
#
import os
import sys
import math

def clear():#Function for clearing screen
    os.system('cls')

def error(txt):#Function to quit the program by showing an error
    print(txt + "\n\t  Program will terminate now.")
    input("\t  Press ENTER to continue...")
    exit()

def getint(txt):#Function for geeting integer as input. Shows error if input is not int type
    str = input(txt)
    if str.isdigit():
        return int(str)
    else:
        error("\n\tError : Invalid input \"" + str + "\".")
       
def getfloat(txt): #Function for getting float number as input. Shows error if input is not float type
    str = input(txt)
    partition = str.partition('.')
    if str.isdigit():
        return float(str)
    elif (partition[0].isdigit() and partition[1]=='.' and partition[2].isdigit()) or (partition[0]=='' and partition[1]=='.' and partition[2].isdigit()):
        return float(str)
    else:
        error("\n\tError : Invalid input \"" + str + "\".")

#Main function starts from here!
choice = None
while choice !=5:
    choice1 = None
    choice2 = None
    choice3 = None
    clear()
    print("\tProgram for problems related to chemistry")
    print("\t-----------------------------------------")
    print("\n\t1. Spectroscopy Problems\n\t2. Hardness of solution or water\n\t3. Calorific value\n\t4. Viscosity index\n\t5. EXIT")
    choice = input("\n\tEnter your choice : ")
    if choice == "1":
        choice1 = None
        while choice1 != 5:
            clear()
            print("\tSpectroscopy Problems")
            print("\t---------------------")
            print("\n\tAbsorbance")
            print("\n\t1. Calculate Absorbance using intensities of\n\t   incident and transmitted light")
            print("\t2. Calculate Absorbance using concentration,\n\t   cell lenght and molar absorbance coefficient")
            print("\t3. Calculate Absorbance using transmittance")
            print("\n\tTransmittance")
            print("\n\t4. Calculate Transmittance using intensities of\n\t   incident and transmitted light\n\t5. Go to main menu")
            choice1 = input("\n\tEnter your choice : ")
            if choice1 == "1":
                t1 = getfloat("\n\t  Enter intensity of incident light : ")
                t2 = getfloat("\t  Enter intensity of transmitted light : ")
                if t1 <= 0.0 or t2 <= 0.0:
                    error("\n\t  Intensity of incident light or transmitted light cannot be\n\t  zero or negative.")
                print("\t  Absorbance is "+ str(math.log10(t1/t2)) +" .")
                input("\t  Press ENTER to conitnue...")
            elif choice1 == "2":
                conc = getfloat("\n\t  Enter concentration of solution : ")
                x = getfloat("\t  Enter cell length : ")
                coeff = getfloat("\t  Enter molar absorbance coefficient : ")
                if conc < 0.0 or x < 0.0 or coeff < 0.0:
                    error("\n\t  Concentration, cell lenght or molar absorbance coefficient\n\t cannot be negative!")
                print("\t  Absorbance is " + str(coeff*x*conc) + " .")
                input("\t  press ENTER to continue...")
            elif choice1 == "3":
                trans = getfloat("\n\t  Enter transmittance : ")
                if trans < 0:
                    error("\t  Transmitance cannot be negative!")
                print("\t  Absorbance is " + str(-1 * math.log10(trans)) + " .")
                input("\t  Press ENTER to continue...")
            elif choice1 == "4":
                t1 = getfloat("\n\t  Enter intensity of incident light : ")
                t2 = getfloat("\t  Enter intensity of transmitted light : ")
                if t1 <= 0.0 or t2 <= 0.0:
                    error("\n\t  Intensity of incident light or transmitted light cannot be\n\t  zero or negative.")
                print("\t  Transmittance is " + str(t2/t1) + " .")
                input("\t  Press ENTER to continue...")
            elif choice1 == "5":
                choice1 = 5
            else:
                print("\n\tWrong choice")
                input("\tPress ENTER to continue...")
    elif choice == "2":
        choice2 = None
        while choice2 != 4:
            clear()
            print("\tHardness ofsolution or water")
            print("\t----------------------------")
            print("\n\t1. Calculate using normality ")
            print("\t2. Calculate using molarity")
            print("\t3. Calculate using mass")
            print("\t4. Go to main menu")
            choice = str(input("\tEnter your choice : "))
            if choice == "1":
                norm = getfloat("\n\t  Enter normality : ")
                if norm < 0:
                    error("\n\t  Normality cannot be negative!")
                print("\tHardness of " + str(norm)+"N solution is "+ str(norm*50*100)+" mg/l!")
                input("\tPress ENTER to continue...")
            elif choice == "2":
                mol = getfloat("\n\t  Enter molarity : ")
                if mol < 0:
                    error("\n\t  Molarity cannot be negative!")
                print("\tHardness of " + str(mol)+"M solution is "+ str(mol*100*100)+" mg/l!")
                input("\tPress ENTER to continue...")
            elif choice == "3":
                massp = []
                print("\n\t  Note:- Enter zero if their is no ion")
                ph = getint("\t  Enter total number of chloride and sulphide of Ca and Mg : ")
                if ph < 0:
                    error("\n\t  Number of ions cannot be negative!")
                for i in range(ph):
                      massp.append([])
                      m = getfloat("\t  Enter mass of ion " + str(i+1) + " : ")
                      if m <= 0:
                          error("\n\t  Mass cannot be zero or negative!")
                      w = getfloat("\t  Enter molecular weight of ion " + str(i+1) + " : ")
                      if w<=0:
                          error("\n\t  Molecular weight cannot be zero or negative!")
                      massp[i].append(m)
                      massp[i].append(w)
                masst = []
                print("\n\t  Note:- Enter zero if their is no ion")
                th = getint("\t  Enter total number of carbonates and bicarbonates of Ca and Ma : ")
                if th < 0:
                    error("\n\t  Number of carbonates or bicarbonates cannot be negative!")
                for i in range(th):
                      masst.append([])
                      m = getfloat("\tEnter mass of carbonate/bicarbonate " + str(i+1) + " : ")
                      if m <= 0:
                          error("\n\t  Mass cannot be zero or negative!")
                      w = getfloat("\tEnter molecular weight of carbonate/bicarbonate " + str(i+1) + " : ")
                      if w<=0:
                          error("\n\t  Molecular weight cannot be zero or negative!")
                      masst[i].append(m)
                      masst[i].append(w)
                perh = 0.0
                for i in range(len(massp)):
                      perh = perh + ((massp[i][0]*100)/massp[i][1])
                temh = 0.0
                for i in range(len(masst)):
                      temh = temh + ((masst[i][0]*100)/masst[i][1])
                print("\n\tPermamnent hardness is " + str(perh) + " ppm.")
                print("\tTemporary hardness is " + str(temh) + " ppm.")
                print("\tTotal hardness is " + str(perh + temh) + " ppm!")
                input("\tPress ENTER to continue...")
            elif choice == "4":
                choice2 = 4
            else:
                print("\n\tWrong choice!")
                input("\tPress ENTER to continue...")
    elif choice == "3":
        choice3 = None
        HCV = None
        LCV = None
        while choice3 != 3:
            clear()
            print("\tCalorific Value")
            print("\t---------------")
            print("\n\t1. Calculate HCV ")
            print("\t2. Calculate LCV")
            print("\t3. Go to main menu")
            choice3 = input("\n\tEnter your choice : ")
            if choice3 == "1":
                W = getfloat("\n\t  Enter mass of water taken in calorimeter : ")
                if W<=0:
                    error("\n\t  Mass of water cannot be zero or negative!")
                w = getfloat("\t  Enter water equvalent of calorimeter : ")
                if w<=0:
                    error("\n\t  Water equvalent of calorimeter cannot be zero or negative!")
                x = getfloat("\t  Enter mass of fuel taken : ")
                if x<=0:
                    error("\n\t  Mass of fuel cannot be zero or negative!")
                t1 = getfloat("\t  Enter initial temperature of water : ")
                t2 = getfloat("\t  Enter final temperature of water : ")
                cc = getfloat("\t  Enter cooling correction (zero if their is no correction) : ")
                ac = getfloat("\t  Enter acid correction (zero if their is no correction) : ")
                fc = getfloat("\t  Enter fuse correction (zero if their is no correction) : ")
                HCV = ((W+w)*(t2-t1+cc)-(ac+fc))/x
                print("\t  HCV is " + str(HCV))
                input("\t  Press ENTER to continue...")
            elif choice3 == "2":
                if HCV != None:
                    print("\n\t  Last calculated value of HCV is " + str(HCV),"\n")
                    tHCV = float(input("\t  Enter HCV (input -1 to use last calculated value) : "))
                    if tHCV == -1.0:
                        tHCV = HCV
                else:
                    tHCV = float(input("\n\t  Enter HCV : "))
                ph = float(input("\t  Enter percentage of hydrogen : "))
                lhs = float(input("\t  Enter latent heat of steam (-1 to use default value) : "))
                if lhs == -1.0:
                    lhs = 587
                LCV = tHCV-0.09*ph*lhs
                print("\t  LCV is " + str(LCV))
                input("\t  Press ENTER to continue...")
            elif choice3 == "3":
                choice3 = 3
            else:
                print("\n\tWrong choice!")
                input("\tPress ENTER to continue...")
    elif choice == "4":
        choice4 = None
        while choice4 != 2:
            clear()
            print("\tViscosity Index")
            print("\t---------------")
            print("\t1. Calculate viscosity index")
            print("\t2. Go to main menu")
            choice4 = input("\n\tEnter your choice : ")
            if choice4 == "1":
                u = getfloat("\n\t  Enter viscosity of sample oil : ")
                h = getfloat("\t  Enter viscosity of High Viscosity Standard oil : ")
                l = getfloat("\t  Enter viscosity of Low Viscosity Standard oil : ")
                if l == h:
                    error("\t  High viscosity standard oil and low viscosity standard oil cannot have same viscosity!")
                if u < 0 or h < 0 or l < 0:
                    error("\t  Viscosity cannot be zero!")
                print("\t  Viscosity index of sample is " + str(((l-u)/(l-h))*100) + " .")
                input("\t  Press ENTER to continue...")
            elif choice4 == "2":
                choice4 = 2
            else:
                print("\n\tWrong choice!")
                input("\tPress ENTER to continue...")
    elif choice == "5":
        choice = 5
    else:
        print("\n\tWrong choice!")
        input("\tPress ENTER to continue...")


Character Classification based on ASCII value

SingleCharacter = input("Enter a character:",)
Character = ord(SingleCharacter)
# ord --> Convert a string to ASCII value
if Character > 0 and Character <= 31:
    print("ASCII value", Character," is a control character")
elif Character >= 48 and Character <= 57:
    print("ASCII value", Character,"  is a character is a digit")
elif Character >= 65 and Character <= 90:
    print("ASCII value", Character,"  is a uppercase letter")
elif Character >= 97 and Character <= 122:
    print("ASCII value", Character,"  is a lowercase letter")
else:
    print("ASCII value", Character," is a Symbol")

To find the distance between two points, given by the coordinates (x1, y1) and (x2, y2) by Pythagorean theorem using functions

def pt(x1,y1,x2,y2):
      x=x2-x1
      y=y2-y1
      x=x**2
      y=y**2
      d=(x+y)**(0.5)
      return d
     
x1=int(raw_input('Enter the coordinate x1: '))
x2=int(raw_input('Enter the coordinate x2: '))
y1=int(raw_input('Enter the coordinate y1: '))
y2=int(raw_input('Enter the coordinate y2: '))
k=pt(x1,y1,x2,y2)
print 'Distance between two points is : ', k
     

Converting a for loop to corresponding while loop

for count in range(0,100,2):
   print 'For:',count

count1 =0
while(count1<100):
  print 'While:',count1
  count1=count1+2

Evaluating expression in Python

x=2
y=3
z=2

print x**y**z  #Answer 512

print (x**y)**z  #Answer 64

print x**(y**z)  #Answer 512


Program to check the Perfect Number or Not

num=input("Enter the number:")
i=1
while i<=num/2:
 s=i**2
 if s==num:
  print "perfect square"
  break
 i+=1
else:
 print "Not a perfect square"

Sum of digits of the a given number

n=int(raw_input('Enter the number: '))
sum=0
while n>0:
      rem=n%10
      sum=sum+rem
      n=n/10
print 'Sum of digits of the number is: ',sum

Decimal Number to Binary number conversion

n=int(raw_input('Enter the Number'))
h=" "
while n>0:
  n1=n%2
  print 'R',n1
  n=n/2
  print 'V=',n
  h=h+str(n1)
print 'Binary Number is:',h[::-1]