JNTUK R19 Python Programming Lab

  1. Write a function called first_diff that is given two strings and returns the first location in which the strings differ. If the strings are identical, it should return -1.
    Click Here of Solutions
    def first_diff(str1,str2):
      if str1==str2:
        return -1
      else:
        i=0
        while i<len(str1) or i<len(str2):
          if str1[i]!=str2[i]:
            break
          i+=1
        return i

    str1=input("Enter first string: ")
    str2=input("Enter second string: ")
    if first_diff(str1,str2)==-1:
      print("Strings are identical.")
    else:
      print("Strings are differ at ",first_diff(str1,str2))
  2. Write a function called number_of_factors that takes an integer and returns how many factors the number has.
    Click Here of Solutions
    def number_of_factors(num):
      count=0
      for i in range(1,num+1):
        if num%i==0:
          count+=1
      return count

    num=int(input("Enter number: "))
    print("Number of factors of {} is {}".format(num,number_of_factors(num)))
  3. Write a function called is_sorted that is given a list and returns True if the list is sorted and False otherwise.
    Click Here of Solutions
    def is_sorted(numList):
      if numList==sorted(numList) or numList==sorted(numList,reverse=True):
        return True
      else:
        return False

    num = int(input("Enter number of elements to be insert: "))
    numList=[]
    print("Enter {} elements".format(num))
    for i in range(num):
      numList.append(int(input()))
    if is_sorted(numList):
      print("List is in sorted order.")
    else:
      print("List is in unsorted order.")
  4. Write a function called root that is given a number x and an integer n and returns x1/n. In the function definition, set the default value of n to 2.
    Click Here of Solutions
    def root(x,n=2):
      return x**(1/n)

    x=int(input("Enter number: "))
    print("Root of {} is {}".format(x,root(x)))
  5. Write a function called primes that is given a number n and returns a list of the first n primes. Let the default value of n be 100.
    Click Here of Solutions
    def primes(n=100):
      primesList=[]
      i=2
      while True:
        count=0
        for j in range(1,i//2+1):
          if i%j==0:
            count+=1
        if count==1:
          primesList.append(i)
        i+=1
        if len(primesList)==n:
          break
      return primesList

    n = int(input("Enter number of terms:"))
    primesList=primes(n)
    print(primesList)
  6. Write a function called merge that takes two already sorted lists of possibly different lengths, and merges them into a single sorted list.
    1. Do this using the sort method.
      Click Here of Solutions
      def merge(list1,list2):
        i=j=0
        list3=[]
        while i<len(list1) and j<len(list2):
          if list1[i]<list2[j]:
            list3.append(list1[i])
            i+=1
          else:
            list3.append(list2[j])
            j+=1
        while i<len(list1):
          list3.append(list1[i])
          i+=1
        while j<len(list2):
          list3.append(list2[j])
          j+=1
        print(list3)

      n1=int(input("Enter list1 size: "))
      n2=int(input("Enter list2 size: "))
      list1=[]
      list2=[]
      print("Enter {} elements for list1:")
      for i in range(n1):
        list1.append(int(input()))
      print("Enter {} elements for list2:")
      for i in range(n2):
        list2.append(int(input()))
      list1.sort()
      list2.sort()
      merge(list1,list2)
    2. Do this without using the sort method.
      Click Here of Solutions
      def merge(list1,list2):
        i=j=0
        list3=[]
        while i<len(list1) and j<len(list2):
          if list1[i]<list2[j]:
            list3.append(list1[i])
            i+=1
          else:
            list3.append(list2[j])
            j+=1
        while i<len(list1):
          list3.append(list1[i])
          i+=1
        while j<len(list2):
          list3.append(list2[j])
          j+=1
        print(list3)

      n1=int(input("Enter list1 size: "))
      n2=int(input("Enter list2 size: "))
      list1=[]
      list2=[]
      print("Enter {} elements for list1:".format(n1))
      for i in range(n1):
        list1.append(int(input()))
      print("Enter {} elements for list2:".format(n2))
      for i in range(n2):
        list2.append(int(input()))
      for i in range(n1-1):
        for j in range(i+1,n1):
          if list1[i]>=list1[j]:
            list1[i],list1[j]=list1[j],list1[i]
      for i in range(n2-1):
        for j in range(i+1,n2):
          if list2[i]>=list2[j]:
            list2[i],list2[j]=list2[j],list2[i]
      merge(list1,list2)
  7. Write a program that asks the user for a word and finds all the smaller words that can be made from the letters of that word. The number of occurrences of a letter in a smaller word can’t exceed the number of occurrences of the letter in the user’s word.
    Click Here of Solutions
  8. Write a program that reads a file consisting of email addresses, each on its own line. Your program should print out a string consisting of those email addresses separated by semicolons.
  9. Click Here of Solutions
    fp = open("mails.txt","r")
    data = fp.read()
    fp.close()
    data = data.split('\n')
    mails=""
    for line in data:
      words = line.split()
      for word in words:
        if '@' in word and '.' in word and word.find('@') < word.rfind('.'):
          if mails=="":
            mails=word
          else:
            mails=mails + ";" + word
    print(mails)
  10. Write a program that reads a list of temperatures from a file called temps.txt, converts those temperatures to Fahrenheit, and writes the results to a file called ftemps.txt.
    Click Here of Solutions
    fp = open("temps.txt","r")
    temps=fp.read()
    fp.close()
    temps = list(map(float,temps.split(',')))
    fp = open("ftemps.txt","w")
    for i in range(len(temps)):
      f = temps[i] * 1.8 + 32.00
      fp.write(str(f))
      if i<len(temps)-1:
        fp.write(",")
    fp.close()
  11. Write a class called Product. The class should have fields called name, amount, and price, holding the product’s name, the number of items of that product in stock, and the regular price of the product. There should be a method get_price that receives the number of items to be bought and returns a the cost of buying that many items, where the regular price is charged for orders of less than 10 items, a 10% discount is applied for orders of between 10 and 99 items, and a 20% discount is applied for orders of 100 or more items. There should also be a method called make_purchase that receives the number of items to be bought and decreases amount by that much.
    Click Here of Solutions
    class Product:
      def __init__(self, name, amount, price):
        self.name = name
        self.amount = amount
        self.price = price

      def get_price(self, numOfItems):
        if numOfItems < 10:
          return self.price
        elif numOfItems >=10 and numOfItems < 99:
          return self.price * 0.1
        elif numOfItems >= 100:
          return self.price * 0.2

      def make_purchase(self, numOfItems):
        print("Total amount is",numOfItems*self.get_price(numOfItems))

    name = input("Enter product name: ")
    amount = int(input("Enter quantity: "))
    price = float(input("Enter price of product: "))
    p = Product(name, amount, price)
    p.make_purchase(amount)
  12. Write a class called Time whose only field is a time in seconds. It should have a method called convert_to_minutes that returns a string of minutes and seconds formatted as in the following example: if seconds is 230, the method should return '5:50'. It should also have a method called convert_to_hours that returns a string of hours, minutes, and seconds formatted analogously to the previous method.
    Click Here of Solutions
    class Time:
      def __init__(self, time):
        self.time = time

      def convert_to_minutes(self):
        return str(self.time//60) + " : " + str(self.time%60)

      def convert_to_hours(self):
        return str((self.time//60)//60) + " : " + str((self.time//60)%60) + " : " + str(self.time%60)

    time = int(input("Enter time in seconds: "))
    t = Time(time)
    print("Time in minutes and seconds ",t.convert_to_minutes())
    print("Time in hours, minutes and seconds ",t.convert_to_hours())
  13. Write a class called Converter. The user will pass a length and a unit when declaring an object from the class—for example, c = Converter(9,'inches'). The possible units are inches, feet, yards, miles, kilometers, meters, centimeters, and millimeters. For each of these units there should be a method that returns the length converted into those units. For example, using the Converter object created above, the user could call c.feet() and should get 0.75 as the result.
    Click Here of Solutions
  14. Write a Python class to implement pow(x, n).
    Click Here of Solutions
    class Power:
      def __init__(self, x, n):
        self.x = x
        self.n = n

      def power(self):
        return self.x ** self.n

    x = int(input("Enter base value: "))
    n = int(input("Enter exponent value: "))
    p = Power(x,n)
    print("pow({},{}) is {}".format(x,n,p.power()))
  15. Write a Python class to reverse a string word by word.
    Click Here of Solutions
  16. Write a program that opens a file dialog that allows you to select a text file. The program then displays the contents of the file in a textbox.
    Click Here of Solutions
  17. Write a program to demonstrate Try/except/else.
    Click Here of Solutions
  18. Write a program to demonstrate try/finally and with/as.
    Click Here of Solutions