opurag

Untitled

Jan 10th, 2023
1,140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 16.14 KB | None | 0 0
  1. #1. Python program to evaluate Values, expressions, and statements, Conditional execution, and Functions Iterations
  2. #a. prompt the user to enter an integer and reverse it. And print the sum of the reversed integer.
  3. num=int(input("enter a number containing more than 1 integer "))
  4. revnum = 0
  5. while num!=0:
  6.     digit = num % 10
  7.     revnum = revnum * 10 + digit
  8.     num //= 10
  9. print("the reversed of given number is ",revnum)
  10. sum = 0
  11. for i in str(revnum):
  12.     sum = sum + int(i)
  13. print("the sum of the reversed numbers is ",sum)
  14.  
  15.  
  16.  
  17. #b. Write a python program to find whether a number (num1) is a factor of 255.
  18. num1=int(input("enter a number "))
  19. if 255%num1==0:
  20.     print("the given number is a factor of 255")
  21. else:
  22.     print("the given number is not a factor of 255")
  23.  
  24.  
  25.  
  26. #d. Write a program to find the sum of the following series:
  27. #i. 1 + 1/3 + 1/5 + 1/7 + .... up to ‘N’ terms.
  28. sum = 0
  29. numofterms=int(input("enter number of elements "))
  30. for i in range(1, numofterms + 1):
  31.         sum = sum + 1.0 / (2 * i - 1)    
  32. print(sum)
  33.  
  34. #ii. 1 + x/1! + x3/2! + x5/3! + x7/4 + .... x2n-1/n!
  35. def factorial(num):
  36.     fact=1
  37.     for i in range(1,num+1):
  38.         if num==1:
  39.             return fact
  40.         else:
  41.             fact=fact*i
  42.     return fact
  43. x=int(input("enter the value of x\n"))
  44. n=int(input("enter the value of n\n"))
  45. final_result=1
  46. for i in range(1,n+1):
  47.     g=factorial(i)
  48.     final_result=final_result+((x**((2*n)-1))/g)
  49.  
  50. print("the sum is=",final_result)
  51.  
  52. """- [ ] 2. Python program to evaluate Python Collections
  53. a. Write a Python Program to demonstrate the inbuilt functions of Strings, List,and sets.
  54. """
  55. # string reversal
  56. a=input("Enter the word to be reversed:")
  57. print(a[::-1])
  58.  
  59. a=input("Enter the word to reverse:")
  60. b=len(a)
  61. for i in range(-1,-b-1,-1):
  62.     print(a[i],end="")
  63.    
  64. a=input("Enter the word to reverse:")
  65. b=len(a)
  66. i=-1
  67. while(i!=-b-1):
  68.     print(a[i],end="")
  69.     i=i-1
  70.    
  71. # abrreviation
  72. a=input("Enter the word:")
  73. l=a.split()
  74. n=[]
  75. for i in range(0,len(l)):
  76.     print(l[i][0].upper(),end="")
  77.    
  78. # accept nos till done and sum and avr
  79. l=[]
  80. while 1:
  81.     a=input("Enter the number:")
  82.     if(a.lower()=='done'):
  83.         break
  84.     else:
  85.         l.append(int(a))
  86.        
  87. c=sum(l)
  88. f=len(l)
  89.  
  90. average=c/f
  91. print("Average:",average)
  92.  
  93. #
  94.    
  95. b. Write a Python program for counting a specific letter 'o' in a given string; the
  96. number of times vowel ‘o’ appears.
  97.  
  98.     str1= "Hello World,"
  99.  
  100.  
  101. """d. Store the following for ‘n’ countries, using a dictionary:
  102. i. Name of a country, country’s capital, per capita income of the
  103. Write a Python Program to find the frequency of each word in given
  104. strings/strings
  105. country.
  106. ii. Write a program to display details of the country with the highest and second lowest per capita income."""
  107. countries_dictn=dict()
  108. countries_dictn
  109. n=int(input("Enter the number of entries"))
  110. i=1
  111.  
  112. while(i<=n):
  113.     country=input("Enter Country")
  114.     cap=input("Enter Capital")
  115.     capInc=input("Enter per capita income")
  116.     countries_dictn[country]=(cap,capInc)
  117.     i=i+1
  118.    
  119. dict_keys=list(countries_dictn.keys())
  120. print("\nCountry\t\tCapital\t\tPer Capita Income")
  121. for ckey in dict_keys:
  122.     details=countries_dictn[ckey]
  123.     print("\n",ckey,'\t\t',end='')
  124.     for val in details:
  125.         print(val, end='\t\t')
  126.     perCaptaInc=[]
  127.    
  128. for ckey in dict_keys:
  129.     details=countries_dictn[ckey]
  130.     print(details[1])
  131.     perCaptaInc.append(details[1])
  132.    
  133. indmin=perCaptaInc.index(min(perCaptaInc))
  134. print("The country with Minimum per capita income is:",dict_keys[indmin])
  135.  
  136. indmax=perCaptaInc.index(max(perCaptaInc))
  137. print("The country with Maximum per capita income is:",dict_keys[indmax])
  138.        
  139.  
  140. """
  141.  
  142. #-[ ] 3. Write a python program to create two classes “Python” and “Java” having data members “Version” and “name” and a member function “display()”. With the help of the object, print the appropriate messages.
  143. #Prog 3
  144.  
  145. class Python:
  146.    version = 3.3
  147.    name = "Python"
  148.    def display(self):
  149.        print("Python name and version is",self.name,self.version)
  150.        
  151.      
  152.    
  153. class Java:
  154.    version = 1.8
  155.    name = "JDK"
  156.    def display(self):
  157.          print("Java name and version is",self.name,self.version)
  158.        
  159.    
  160. a=Python()
  161. b=Java()
  162.  
  163. a.display()
  164. print("-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-")
  165. b.display()
  166.  
  167. #- [ ] 4. Create a class “Employee” with _init_ method to initialize data members: Name, Designation, Ph. No., and a member function display(). Create an instance for the class and display the details of the employee
  168. #Prog 4
  169.  
  170. class Employee:
  171.    def __init__(self,name='',designation='',phone=0):
  172.        self.name=name
  173.        self.designation=designation
  174.        self.phone=phone
  175.    
  176.    def display(self):
  177.        print("Name:",self.name ,"\n")
  178.        print("Designation:",self.designation, "\n")
  179.        print("Phone No:",self.phone ,"\n")
  180.        
  181.    
  182. emp1=Employee("Raj","Technical Advisor",8325772891)
  183. emp2=Employee("Sanju","Financial Advisor",6983762781)
  184. emp3=Employee("Rachit","Customer Support Advisor",8746587362)
  185.  
  186.  
  187.  
  188.  
  189. emp1.display()
  190. print("---------------------")
  191. emp2.display()
  192. print("---------------------")
  193. emp3.display()
  194.  
  195.  
  196. """
  197. - [ ] 5. Write an interactive calculator! User input is assumed to be a formula that consist of a number, an operator (at least + and -), and another number, separated by white space (e.g. 1 + 1). Split user input using str.split(), and check whether the resulting list is valid:
  198. a. If the input does not consist of 3 elements, raise a FormulaError, which is a custom Exception.
  199. b. Try to convert the first and third input to a float (like so: float_value = float(str_value)). Catch any ValueError that occurs, and instead raise a FormulaError
  200. c. If the second input is not '+' or '-', again raise a FormulaError
  201. d. If the input is valid, perform the calculation and print out the result. The user
  202. is then prompted to provide new input, and so on, until the user enters quit.#/
  203. """
  204.  
  205. class FormulaError(Exception):
  206.    pass
  207.  
  208. while True:
  209.    try:
  210.        formula = input("Enter a formula (e.g. 1 + 1): ")
  211.        if formula.lower() == "quit":
  212.            break
  213.        
  214.        elements = formula.split()
  215.        if len(elements) != 3:
  216.            raise FormulaError("Formula must consist of three elements: number, operator, number")
  217.        
  218.        try:
  219.            x = float(elements[0])
  220.            y = float(elements[2])
  221.        except ValueError:
  222.            raise FormulaError("Number must be a valid float")
  223.        
  224.        if elements[1] == "+":
  225.            result = x + y
  226.        elif elements[1] == "-":
  227.            result = x - y
  228.        elif elements[1] == "*":
  229.            result = x * y
  230.        elif elements[1] == "/":
  231.            result = x / y
  232.        elif elements[1] == "%":
  233.            result = x % y
  234.        else:
  235.            raise FormulaError("Operator must be '+' or '-' or '*' or '/' or '%'")
  236.        
  237.        print(f"Result: {result}")
  238.    except FormulaError as e:
  239.        print(e)
  240.        
  241. """
  242. class FormulaError(Exception):
  243.     pass
  244.  
  245. def parse_input(user_input):
  246.     input_list = user_input.split()
  247.     if len(input_list)!=3:
  248.         raise FormulaError("input doesn't consist of three elements")
  249.     n1,op,n2=input_list
  250.     try:
  251.         n1=float(n1)
  252.         n2=float(n2)
  253.     except ValueError:
  254.         raise FormulaError("the first and third input value must be numbers")
  255.     return n1,op,n2
  256. def calculate(n1,op,n2):
  257.     if op=='+':
  258.         return n1+n2
  259.     if op=='-':
  260.         return n1-n2
  261.     if op=='*':
  262.         return n1*n2
  263.     if op=='/':
  264.         return n1/n2
  265.    
  266.     raise FormulaError('(0) is not a valid operator'.format(op))
  267. while True:
  268.     user_input=input('>>>>')
  269.     if user_input=='quit':
  270.         break
  271.     n1,op,n2=parse_input(user_input)
  272.     result=calculate(n1,op,n2)
  273.     print(result)
  274. """
  275.  
  276. """
  277. 6. Write a Python program to count the number of lines in a text file and read the file line by line and store it into a list as well as find the longest word in the file.
  278. """
  279.  
  280. # Write a Python program to count the number of lines in a text file
  281. f=open("test.txt","w")
  282. f.write("hello world123\n")
  283. f.write("hello world456\n")
  284. f.write("hello world789\n")
  285. f.write("hello world101010110\n")
  286. f.close()
  287.  
  288. f=open("test.txt","r")
  289.  
  290. def count_lines(f):
  291.    count=0
  292.    for i in f:
  293.        count+=1
  294.    return count
  295. print("the number of lines is ",count_lines(f))
  296.  
  297. f=open("test.txt","r")
  298. for i in f:
  299.    print(i)
  300.  
  301. f.close()
  302.  
  303. f=open("test.txt","r")
  304.  
  305. a=[]
  306. print("the list elemens are:")
  307. for i in f:
  308.    a.append(i)
  309. print(a)
  310. f.close()
  311. # find the longest word in the file and print it
  312. def longest_word():
  313.    with open('test.txt') as f:
  314.        words = f.read().split()
  315.        print("the longest word is",max(words, key=len))
  316. longest_word()
  317.  
  318. """
  319. - [ ] 7. Write a Python program to create a list of student details: usn, name dob and email {using dictionary} and write a list to a file.
  320. """
  321. dict={}
  322. while True:
  323.    roll = input("Enter the roll no. of the student(enter Q to quit)=")
  324.    if roll=='Q' or roll=='q':
  325.        break
  326.        
  327.    else:
  328.        usn=input('Enter the USN of the Student:')
  329.        name=input('Enter the Name of the Student:')
  330.        dob=input('Enter the DOB of the Student:')
  331.        email=input('Enter the Email of the Student:')
  332.        dict[roll]={usn,name,dob,email}
  333.    print(dict)
  334.    
  335.    filename="samplefile.txt"
  336.    with open(filename,'w') as givenfilecontent:
  337.        for key,value in dict.items():
  338.            givenfilecontent.write('%s:%s\n'%(key,value))
  339.            
  340. """
  341. - [ ] 8. Generate one-hot encodings for an array in numpy.
  342. """
  343. import numpy as np
  344. def OHE(array):
  345.    n = np.max(array) + 1
  346.    return np.eye(n)[array]
  347.  
  348. array = np.array([1,4,5,6,7])
  349. print(OHE(array))
  350.  
  351. """
  352. - [ ] 9. Write a Pandas program to import excel data into a Pandas dataframe and find a list of
  353. employees where hire_date is between two specific month and year.
  354. """
  355. import pandas as pd
  356.  
  357. df = pd.read_excel('empl.xlsx')
  358.  
  359. df.set_index('emp_id', inplace=True)
  360.  
  361. df['hire_date'] = pd.to_datetime(df['hire_date'])
  362.  
  363. req = df[(df['hire_date'].dt.month >= 1) & (df['hire_date'].dt.month <= 3) & (df['hire_date'].dt.year == 2022)]
  364.  
  365. print(req)
  366.  
  367.  
  368. """1.   Write a python program to create two classes “Python” and “Java” having data members “Version” and “name” and a member function “display()”. With the help of the object, print the appropriate messages."""
  369.  
  370. class Python:
  371.    '''This is a class explaining about python'''
  372.    Version = "3.9"
  373.    Name = "Python"    #data members
  374.  
  375.    def display_Python(self):
  376.        print("Hello Python")
  377.        
  378. class Java(Python):
  379.    '''This is a class explaining about Java'''
  380.    Version = "15.1"
  381.    Name = "Java"
  382.  
  383.    def display_Java(self):
  384.        print("Hello Java")
  385.  
  386. Obj_1 = Python()
  387. Obj_2 = Java()
  388.  
  389. Obj_2.display_Python()
  390.  
  391.  
  392. "2. Write a python program to demonstrate the usage of the __init__ method and self parameter"
  393.  
  394. class Python:
  395.    """This is the class about
  396.         Python Programming Lanugage"""
  397.    def __init__(self,Version,Name):
  398.        self.Version = Version
  399.        self.Name = Name
  400.    
  401.    def display(self):
  402.        print("This is display Fun", self.Name)
  403.  
  404. P1 = Python(3.9,"Python")
  405. print(P1.Version)
  406. del P1.Version
  407. print(P1.Version)
  408. P1.display()
  409.  
  410.  
  411. "3. Create a class “Employee” with data members Name, Designation, Ph.No, and member function display(). Create an instance for the class and display the details of the employee"
  412.  
  413. class Employee:
  414.    "Employee class containing the details"
  415.    def __init__(self, Name, Designation, PhNo):
  416.        self.Name = Name
  417.        self.Designation = Designation
  418.        self.PhNo = PhNo
  419.        
  420.    def display(self):
  421.        print("The Name of employee is", self.Name)
  422.        print("The Designation of employee is", self.Designation)
  423.        print("The Ph.No of employee is", self.PhNo)
  424.  
  425. Emp1 = Employee("Joey","Manager",9999888888)
  426. Emp1.display()
  427.  
  428. "4. Write a Python program to demonstrate single inheritance."
  429.  
  430. class Person:
  431.  def __init__(self, fname, lname):
  432.    self.firstname = fname
  433.    self.lastname = lname
  434.  
  435.  def printname(self):
  436.    print(self.firstname, self.lastname)
  437.  
  438. class Student(Person):
  439.  def __init__(self, fname, lname, year):
  440.    super().__init__(fname, lname)
  441.    self.graduationyear = year
  442.  
  443. y = Person("John","nike")
  444.  
  445. x = Student("Mike", "Olsen", 2019)
  446. print(x.graduationyear)
  447. print("isinstance", isinstance(y,Student))
  448. print("Value is ",x = Person)
  449.  
  450. "5. Write a Python Program to demonstrate the concept of Classes and Objects."
  451.  
  452.   def diffcar(self, name, make, model):
  453.    self.name=name
  454.    self.make=make
  455.    self.model=model
  456.    Car.car_count+=1
  457.  
  458. car_a=Car()
  459. car_a.diffcar("Camry", "Toyota", 2021)
  460. print(car_a.car_count)
  461.  
  462. car_b=Car()
  463. car_b.diffcar("Altima", "Nissan", 2020)
  464. print(car_a.car_count)
  465.  
  466. "6. Write a Python Program to demonstrate Inheritance"
  467.  
  468. class Person:
  469.  def __init__(self, fname, lname):
  470.    self.firstname = fname
  471.    self.lastname = lname
  472.  
  473.  def printname(self):
  474.    print(self.firstname, self.lastname)
  475.  
  476. class Student(Person):
  477.  def __init__(self, fname, lname, year):
  478.    Person.__init__(self, fname, lname)
  479.    self.year=year
  480.  
  481.  
  482. x = Student("Mike", "Olsen", 2021)
  483. x.printname()
  484. print(x.year)
  485.  
  486. "7. Write Python Program to demonstrate Inheritance."
  487.  
  488. class Calculation1:  
  489.    def Summation(self,a,b):  
  490.        return a+b;  
  491. class Calculation2:  
  492.    def Multiplication(self,a,b):  
  493.        return a*b;  
  494. class Calculation3(Calculation1,Calculation2):  
  495.    def Divide(self,a,b):  
  496.        return a/b;  
  497. d =Calculation3()  
  498. print(d.Summation(10,20))  
  499. print(d.Multiplication(10,20))  
  500. print(d.Divide(10,20))
  501.  
  502. "8. Write a Python Program to demonstrate Single Inheritance "
  503.  
  504. class Animal:
  505.  def speak(self):
  506.    print("Animal is speaking")
  507.  
  508. class Dog(Animal):
  509.  def bark(self):
  510.     print("Dog is barking")  
  511. xyz=Dog()
  512. xyz.bark()
  513. xyz.speak()
  514.  
  515. "9. Write a Python Program to demonstrate Multilevel Inheritance"
  516.  
  517. class Animal:
  518.  def speak(self):
  519.    print("Animal is speaking")
  520.  
  521. class Dog(Animal):
  522.  def bark(self):
  523.     print("Dog is barking")
  524.  
  525. class Dogchild(Dog):
  526.  def drink(self):
  527.    print("Dog is drinking")
  528.  
  529. xyz=Dogchild()
  530. xyz.drink()
  531. xyz.bark()
  532. xyz.speak()
  533.  
  534.  
  535. "10.    Write a Python Program to demonstrate Multiple Inheritance"
  536.  
  537. class Calculator1:
  538.  def sum(self, a, b):
  539.    return a+b
  540. class Calculator2:
  541.  def mul(self, a, b):
  542.    return a*b
  543. class Derived(Calculator1, Calculator2):
  544.  def div(self, a, b):
  545.    return a/b
  546. a=Derived()
  547. a.sum(4,2)
  548. a.mul(4,2)
  549. a.div(4,2)
  550.  
  551.  
  552. "11.    Write a Python Program to demonstrate accessing attributes of class"
  553.  
  554.  
  555. class emp:
  556.    
  557. name = 'sumukh'
  558.     salary = '25000'
  559.     def show(self):
  560.         print(self.name)
  561.         print(self.salary)
  562. e1 = emp()
  563. # Use getattr instead of e1.name
  564. print(getattr(e1, 'name'))
  565. # returns true if object has attribute
  566. # delete the attribute
  567. delattr(emp, 'salary')
  568. print(hasattr(e1, 'name'))
  569. # sets an attribute
  570. setattr(e1, 'height', 152)
  571. # returns the value of attribute name height
  572. print(getattr(e1, 'height'))
  573.  
  574. "12.    Write a Python Program to demonstrate Single Inheritance"
  575.  
  576. class A:
  577.   def feature1(self):
  578.       print("feature 1 is working")
  579.   def feature2(self):
  580.       print("feature 2 is working")
  581. a1 = A()
  582. a1.feature1()
  583. a1.feature2()
  584. class B(A):
  585.   def feature3(self):
  586.       print("feature 3 is working")
  587. b1 = B()
  588. b1.feature3()
  589.  
  590.  
  591.  
  592.  
  593.  
  594. "13.    Create a Bus class that inherits from the Vehicle class. Give the capacity argument of Bus.seating_capacity() a default value of 50."
  595.  
  596. class Vehicle:
  597.    def __init__(self, name, max_speed, mileage):
  598.        self.name = name
  599.        self.max_speed = max_speed
  600.        self.mileage = mileage
  601.  
  602.    def seating_capacity(self, capacity):
  603.        return f"The seating capacity of a {self.name} is {capacity} passengers"
  604.  
  605. class Bus(Vehicle):
  606.    # assign default value to capacity
  607.    def seating_capacity(self, capacity=50):
  608.        return super().seating_capacity(capacity=50)
  609.  
  610. School_bus = Bus("School Volvo", 180, 12)
  611. print(School_bus.seating_capacity())
  612.  
  613.  
  614.  
  615.  
Advertisement
Add Comment
Please, Sign In to add comment