Skip to content

Instantly share code, notes, and snippets.

@subins2000
Last active November 25, 2017 19:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save subins2000/fe2ac89c99fd4ee530d1c5848a114db1 to your computer and use it in GitHub Desktop.
Save subins2000/fe2ac89c99fd4ee530d1c5848a114db1 to your computer and use it in GitHub Desktop.

Python Programs

August 2017

  • Write a program to calculate nCr with a functions for finding out factorial (2)

    • Answer

      # Python3
      def fact(n):
          if fact == 0:
              return 1
          # return will end the function call. So no need of elif here
          return n * fact(n - 1)
      
      n = int(input('Enter value of n :'))
      r = int(input('Enter value of r :'))
      
      nCr = fact(n) / (fact(r) * fact(n - r))
      
      print(nCr)
  • Write a program to generate all prime numbers in a given range (8)

    • Answer

      # Python3
      # Check if a gived number is prime or not. Returns a boolean
      def isPrime(n):
          # Assume number is prime
          prime = True
      
          for i in range(2, n):
              if n % i == 0:
                  # Our assumption is wrong. The number is divisible by a number other than 1 and the same number
                  prime = False
      
                  # No need to continue checking if it is found to be divisible once. So stop the loop
                  break
      
          return prime
      
      start = int(input('Enter start of range : '))
      end = int(input('Enter end of range : '))
      
      # end + 1 because we want to include the ending number too
      for i in range(start, end + 1):
          if isPrime(i):
              print(i)
  • Write a Python program to find the roots of a quadratic equation. (4)

    • Answer

      # Python3
      import math
      
      a = int(input('Enter value of a : '))
      b = int(input('Enter value of b : '))
      c = int(input('Enter value of c : '))
      
      # Calculate discriminant = b^2 - 4*a*c
      discriminant = math.sqrt(b ** 2 - (4 * a * c))
      
      if discriminant < 0:
          print('Only imaginary solutions')
      else:
          x1 = (-b + discriminant) / 2 * a
          x2 = (-b - discriminant) / 2 * a
      
          if discriminant == 0:
              print('Unique solution = ', x1)
          else:
              print('Solution 1 = ', x1)
              print('Solution 2 = ', x2)
  • Write a Python program to calculate the area of a circle, given the centre and a point on the perimeter. Use a function to find radius as the distance between two points. (5)

    • Answer

      # Python3
      import math
      
      # Return coordinates of the point as a tuple where first value is x coordinate and the other, y coordinate
      def getPoint():
          x = int(input('Enter x coordinate : '))
          y = int(input('Enter y coordinate : '))
      
          # Return a tuple
          return (x, y)
      
      # Find the distance between two points
      def findDistance(centre, point):
          # centre and point is a tuple.
          # centre[0] and point[0] will have x coordinate
          xDiff = centre[0] - point[0]
          yDiff = centre[1] - point[1]
      
          distance = math.sqrt((xDiff ** 2) + (yDiff ** 2))
      
          return distance
      
      print('Enter coordinates of centre :')
      centre = getPoint()
      
      print('Enter coordinates of point on perimeter :')
      point = getPoint()
      
      radius = findDistance(centre, point)
      
      area = math.pi * radius * radius
      
      print('Area of circle : ', area)
  • Write a program to replace a substring with a new substring in the given string (7)

    • Answer

      s = input('Enter a string : ')
      find = input('Enter string to replace : ')
      replace = input('Enter string to replace to : ')
      
      findLength = len(find)
      newS = ''
      
      i = 0
      while i < len(s):
          # The position from current until the end of 
          until = i + findLength
          
          # Check if characters from 'i'th position to 'until' is the substring we want to replace
          if s[i : until] == find:
              newS += replace
      
              i += findLength
          else:
              newS += s[i]
              i += 1
      
      print(newS)
  • Write a program that reads a file and writes out a new file with the lines in reversed order. (7)

    • Answer

      #Python3
      file = open('file.txt', 'r')
      out = open('out.txt', 'a')
      
      # Get a list of each lines
      contents = file.readlines()
      # Reverse the list
      reversedContents = reversed(contents)
      
      for s in reversedContents:
          # Append each line to the output file
          out.write(s)
      
      file.close()
      out.close()

January 2017

  • Write a python program to find the sum of all odd terms in a group of n numbers entered by the user (3)

    • Answer

      # Python3
      s = 0
      
      print('Enter the numbers. Type "done" when finished entering numbers.')
      while True:
          number = input('Enter number : ')
      
          if number == 'done'
              break
      
          number = int(number)
      
          # If odd number
          if number % 2 != 0 :
              s += number
      
      print(s)
  • Write a program to find the quadrant of a given point (x,y) (5)

    • Answer

      # Python 3
      x = int(input('Enter x coordinate of point : '))
      y = int(input('Enter y coordinate of point : '))
      
      if x == 0 or y == 0:
          print('Point is on an axis')
      else:
          if x > 0:
              if y > 0:
                  print('First Quadrant')
              else:
                  print('Fourth Quadrant')
          else:
              if y > 0:
                  print('Second Quadrant')
              else:
                  print('Third Quadrant')
  • Write a program that reads an integer N from the keyboard and then calls a user defined function to compute and displays the sum of the numbers from N to (2N) if N is non-negative. If N is negative, then displays the sum of the numbers from (2N) to N.The starting and ending points are included in the sum. (4)

    • Answer

      # Python 3
      def sumOfRange(start, end):
          s = 0
      
          # end + 1 because ending point needs to be included in the sum
          for i in range(start, end + 1):
              s += i
      
          return s
      
      n = int(input('Enter number : '))
      
      # Non-negative
      if n > 0:
          print(sumOfRange(n, 2*n))
      else:
          # 2*n will be negative
          print(sumOfRange(2*n, n))
  • Write a program to compute the sum of first n positive integers using a recursive function. (4)

    • Answer

      # Python 3
      # Get the 'n'th term in the series of sum of positive numbers
      def recurseSum(n):
          # 1st term and the 2nd term in the series is the term number itself
          if n == 0 or n == 1:
              return n
      
          return n + recurseSum(n - 1)
      
      n = int(input('Enter a positive number : '))
      print(recurseSum(n))
  • Write a menu driven program to calculate area of circle, triangle, rectangle and square. Use a separate function to implement each operation. (5)

    • Answer

      # Python3
      def circle():
          r = int(input('Enter radius : '))
          print('Area of circle : ', 3.14 * r * r)
      
      def triangle():
          b = int(input('Enter base : '))
          h = int(input('Enter height : '))
      
          print('Area of triangle : ', 0.5 * b * h)
      
      def rectangle():
          l = int(input('Enter length : '))
          b = int(input('Enter breadth : '))
      
          print('Area of rectangle : ', l * b)
      
      def square():
          a = int(input('Enter length of square : '))
          print('Area of square : ', a * a)
      
      print('Find Area (c = circle, t = triangle, r = rectangle, s = square)')
      op = input('Enter operation : ')
      if op == 'c':
          circle()
      elif op == 't':
          triangle()
      elif op == 'r':
          rectangle()
      else:
          square()
  • Write a program to check if a given string is a palindrome or not, without reversing the original string (7)

    • Answer

      # Python 3
      s = input('Enter string : ')
      
      # Assume to be palindrome
      palindrome = True
      
      for i in range(0, len(s)):
          # Check if character at position from beggining and ending are the same. If not, it's not a palindrome
          if s[i] != s[ -(i+1) ]:
              palindrome = False
              break
      
      if palindrome == True:
          print('Palindrome')
      else:
          print('Not palindrome')
  • Write a python program to create a dictionary of phone numbers and names of five persons. Display the contents of the dictionary in alphabetical order of names.

    • Answer

      # Python 3
      phonebook = {}
      
      for i in range(0, 5):
          name = input('Enter name : ')
          # Phone may contain +, so receiving as string
          phone = input('Enter phone number : ')
      
          # Add item to dictionary
          phonebook[name] = phone
      
      # Sort the phonebook in order of names
      sortedPhonebook = sort(phonebook)
      
      for name, phone in sortedPhonebook:
          print(name, ' - ', phone)

June 2016

  • Write a python code to find transpose of a matrix using list. (4)

    • Answer

      # Python 3
      matrix = []
      
      size = int(input('Enter size of square matrix : '))
      
      for i in range(0, size):
          matrix.append([])
          for j in range(0, size):
              matrix[i].append(int(input('Enter value in ' + str(i + 1) + 'th row and ' + str(j + 1) + 'th column : ')))
      
      transpose = []
      
      for i in range(0, size):
          transpose.append([])
          for j in range(0, size):
              transpose[i].append(matrix[j][i])
      
      for i in range(0, size):
          for j in range(0, size):
              print(transpose[i][j], end=' ')
          print()
  • Write a python program that opens a file for input and prints the count of four letter words in it. (5)

    • Answer

      #Python3
      fp = open('file.txt', 'r')
      contents = fp.read()
      
      count = 0
      # Get words by splitting string by a space
      words = contents.split(' ')
      
      for word in words:
          if len(word) == 4:
              count += 1
      
      fp.close()
      
      print('Number of 4 letter words: ', count)
  • Write a Python code to search an element in a list (3)

    • Answer

      # Python 3
      li = []
      
      s = input('Enter element to be searched : ')
      
      for i in range(0, len(li)):
          if li[i] == s:
              print('Found element at position ', i)
  • Write a Python program using function to check the type of a triangle (Scalene, Isosceles, Equilateral) by getting vertices from the user (8)

    • Answer

      # Python3
      def getPoint():
          x = int(input('Enter x coordinate : '))
          y = int(input('Enter y coordinate : '))
      
          # Return a tuple
          return (x, y)
      
      # Find the distance between two points
      def findDistance(centre, point):
          # centre and point is a tuple.
          # centre[0] and point[0] will have x coordinate
          xDiff = centre[0] - point[0]
          yDiff = centre[1] - point[1]
      
          distance = math.sqrt((xDiff ** 2) + (yDiff ** 2))
      
          return distance
      
      print('Enter first point')
      point1 = getPoint()
      point2 = getPoint()
      point3 = getPoint()
      
      a = findDistance(point1, point2)
      b = findDistance(point2, point3)
      c = findDistance(point1, point3)
      
      if a == b and b == c and a == c:
          print('Equilateral')
      elif (a == b) or (b == c):
          print('Isosceles')
      else:
          print('Scalene')

January 2016

  • Write a Python program to compute nth fibonacci number. Use a recursive function. (2)

    • Answer

      # Python 3
      def fibo(n):
          # First and second term of fibonacci series is the term numberi tself
          if n == 0 or n == 1:
              return n
          return n + fibo(n-1)
      
      n = int(input('Enter number of terms : '))
      for i in range(0, n):
          print(fibo(n))
  • Write a Python program to display all Armstrong numbers in a given range (5)

    • Answer

      # Python 3
      def isArmstrong(n):
          s = 0
          n = str(n)
          l = len(n)
      
          for digit in n:
              s += int(digit) ** l
      
          if int(n) == s:
              return True
          return False
      
      start = int(input('Enter starting range : '))
      end = int(input('Enter ending range : '))
      
      for i in range(start, end):
          if isArmstrong(i):
              print(i)
  • Write a Python program to count number of vowels, consonants, words and questionmarks in a given string (6)

    • Answer

      # Python 3
      s = input('Enter a string :')
      
      vowels = 0
      consonants = 0
      qm = 0
      
      for l in s:
          if l.isalpha():
              if l == 'a' or l == 'e' or l == 'i' or l == 'o' or l == 'u':
                  vowels += 1
              else:
                  consonants += 1
          elif l == '?':
              qm += 1
      
      words = len(s.split(' '))
      
      print('Number of vowels : ', vowels)
      print('Number of consonants : ', consonants)
      print('Number of words : ', words)
      print('Number of questionmarks : ', qm)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment