PYTHON ASSIGNMENT 4: NUMBER TRIANGLES




Write program to generate the following NUMBER / STAR arrangements






















PYTHON ASSIGNMENT 10 - LIST COMPREHENSION





Write a list comprehension that prints a list of the cubes of the numbers 1 through 10.

Write a list comprehension that prints out the possible results of two coin flips (example -  one result would be ’ht’)

Write a function that takes in a string and uses a list comprehension to return all the vowels in the string.

Run this list comprehension in your prompt:
[x+y for x in [10, 20, 30] for y in [1, 2, 3]]

Write a function that takes in a list of elements of different types and uses a list comprehension to return all the elements of the list of type int. (Note: Use the python isinstance function)

Write a list comprehension which solves the equation y = x2+1. The solution should print out a list of [x, y] pairs; use the domain x ∈ [−5, 5] and the range y ∈ [0, 10].

Write a list comprehension that finds the integer solutions [x, y] for a circle of radius 5.

PYTHON - EXTRA ASSIGNMENT PROGRAMS





Control Structure

Check if a given number is divisible by 5

Sum of N different numbers

Sum and average of N different numbers

Sum of numbers between 1 and 50 which are divisible by 3 and not by 5

First N even numbers

First N numbers divisible by 4


Functions

Area and circumference of a circle

Simple and Compound Interest

Smallest and largest digit in a number

Sum of digits of a number until single number is obtained

Sum of even and odd digits of a number

Sum of squares of individual digits of a number

Sum of cubes of individual digits of a number

Digits in odd position of a number

Digits in even position of a number

Factorial of first N numbers

Read a name and display a welcome message

Menu driven Calculator program


Lists

Create a list and perform the following operations on the list

Display content of list

Display length of list

Display element in given position in the list

Add elements to the list

Remove elements from the list:

Slice

Sort

Reverse

Replace elements

Join two lists

Membership test

Nested lists


Lists and Functions

Smallest number from a set of numbers

Largest number from a set of numbers

Sum of even and odd numbers from a set of numbers

Sort the elements of a matrix

Read an N x N matrix. Check if the last element of each row is the sum of the all other elements in that row


String

Two words form a metathesis pair, if you can transform one into the other by swapping two letters. Example – conserve and converse. Write a program to find all the metathesis pair in a dictionary.

Read a word and check if all the letters are in alphabetical order

Two words are anagrams if you can rearrange the letters from one to spell the other. Write a program that displays all lists of anagrams from the word list. Example:
[‘silent’, ‘listen’]
[‘deltas’,’desalt’,’lasted’,’salted’,’slated’,’staled’]

Two words are reverse pair, if each is the reverse of the other. Example: was and saw. Write a program that finds all the reverse pairs in the word list.

Two words “interlock” if taking alternate letters from each forms a new word. Example, “shoe” and “cold” interlock to form “schooled”. Write a program that finds all pairs of words that interlock.

Dictionary

Creating a Dictionary and perform the following operations:

Get the values in a Dictionary

Looping over dictionary

Add elements to a dictionary

combine two dictionaries

Delete elements of a dictionary

Test the presence of a key

Write a program to generate a dictionary containing the list of customers and their telephone numbers. Write functions to find the telephone number of a given customer and to find the customer details if the telephone number is specified.

Files

Read a file and display all words containing all 5 vowels atleast once. Example – automobile

Write a program called cross reference that creates a dictionary of all words in a document, and for each word, a list of the line numbers on which it occurs. Remove noise words like “the”, “and”, and so on.

Write a program to compare two files, printing the first line where they differ.

Write a program that displays the three most frequently occurring words in a file.

Write a program that displays five most frequently occurring characters in a file.

Given a file containing customer names and their phone numbers, write a program to find the telephone number of a given customer.

Write a program to read student details (Name, roll number and CGPA) and write to file. Also display the file content.





PYTHON ASSIGNMENT 9: FILES




Read from console and write to file

Read from file and display in console

Display file content with line number

Display first N lines of a file

Display nth line of a file

Display from nth line to mth line of a file

Copy file

Copy first N lines from a file to new file

Copy from nth line to mth line of a file to new file

Merge two files

Count number of characters, words and lines in a file

Search if a word exists in a file.

Count number of times a word exists in a file

Search if a word exists in a file. Display all lines in which the word exists.

Delete a word in a file

Replace a word in a file

Write a program that creates a dictionary of the frequency of all words in a file. Remove noise words like “the”, “and”, and so on. Display the three most frequently occurring words.

Write a program that creates a dictionary of the frequency of all the characters in a file. Display five most frequently occurring characters.

Given a file containing customer names and their phone numbers, write a program to find the telephone number of a given customer.

Compare two files and print the first line where they differ.




PYTHON ASSIGNMENT 8: FUNCTIONS



Check if a given number is even or odd

Find sum of two numbers

Swap two numbers

Biggest of three numbers

Find GCD of two numbers

Find distance between two points

Find square root of a number using Newton’s method

Check if a given number is an Armstrong number

Check if a given number is a prime number

Number manipulation
Number of digits
Sum of digits
Reverse of a number

Factorial of a number using (1) iteration and (2) recursion

Fibonacci series up to (1) a given limit and (2) number of terms

List
Sum of elements
Average of all numbers
Biggest element
Smallest element

Read two lists and merge without duplicates

Matrix Manipulation
Addition
Subtraction
Multiplication
Sum of diagonal element
Transpose of a matrix

PYTHON ASSIGNMENT 7: MISCELLANEOUS PROGRAMS

Operators and Control Structures

Swap two numbers

Circulate the values of n variables

Find GCD of two numbers

Distance between two points

Square root of a number using Newton’s method 

Exponentiation of a number 

First N prime numbers



List

Maximum in a given list of numbers

Sum of elements in a list

Matrix multiplication


Search

Linear search

Binary search


Sort

Insertion sort

Selection sort

Merge sort


Dictionaries : Histograms

Read a string and find the 5 most frequent characters

Read a string and find the 3 most frequent words


File operations:

File copy

Merge two files

Read a file name from command line and count the number of lines, words and characters in the file.

Read a file and create a dictionary for the frequency of words in the file

Read a file and create a dictionary for the frequency of characters in the file.

PYTHON ASSIGNMENT 6: DICTIONARIES



Write a program to generate a dictionary called phonebook containing the list of customers and their telephone numbers.
Lookup: Read a customer name and print the associated entry from the phonebook on a new line in the form name=phonenumber; If an entry for name is not found, print “Not found" instead.
Reverse Lookup: Given a phone number find the customer details. If number is not present, print “No match found”

Create a dictionary containing employee name and id (name:id). Display
Employee names, sorted in alphabetical order
Employee name and id, sorted alphabetically by name
Inverse the dictionary (id : name)

Consider two lists
NAMES = [’Alice’, ’Bob’, ’Cathy’, ’Dan’, ’Ed’, ’Frank’, ’Gary’, ’Helen’, ’Irene’, ’Jack’, ’Kelly’, ’Larry’]
AGES = [20, 21, 18, 18, 19, 20, 20, 19, 19, 19, 22, 19]
These lists match up, so Alice’s age is 20, Bob’s age is 21, and so on. Write a program that
Combines these lists into a dictionary.
Reads a name and returns the age.
Reads an age and returns the names of all the people who are that age.

Histogram: Read a string and create a dictionary containing the frequency of the characters in string.

Histogram: Read a string and create a dictionary containing the frequency of the words in string.

PYTHON ASSIGNMENT 5: LISTS



Write a program to read a set of numbers from a user and store in a list. Eliminate duplicate elements.

Given a list of N numbers, read the element to search in the list. Display the number of occurrences of the element with its position.

Anagrams. Given a list of words display the sets of anagrams.

Given a list of integers, create a new list with cumulative sum; that is a new list where the ith element is the sum of the first i elements from the original list. For example, the cumulative sum of [4, 3, 6] is [4, 7, 13].

Create a nested list containing student details (Roll number, name and 3 marks). Print the roll number, name, total and average marks of each student. 

Given two lists that are sorted in ascending order, write a program to merge the lists into a single list that contains every item from both lists in sorted order.


Matrix

Addition, subtraction and multiplication of matrices.

Transpose of a matrix.

Sum of diagonal elements of a matrix.

Largest, smallest element in matrix.

PYTHON ASSIGNMENT 3 - TUPLES



Write a program to generate the Fibonacci series up to N terms. Store the generated numbers in a tuple and display it.

Given a tuple containing city names, display the index, name and name length, Write a program to read two tuples and merge them without duplicates

Write a program to display elements from the first tuple that are not present in the second tuple

The second year of engineering offers the following subjects in two departments.
CSE = (“PQT”, “OS”, “SE”, “DPSD”)
IT = (“OS”, “PQT”, “DS”, “SE”)
Find
Number of subjects in CSE
Names of subjects in CSE only
Names of subjects in IT only
Number and names of subjects in both CSE and IT
Number and names of subjects for either CSE or IT, but not in both
Number and names of all subjects.

Read 5 student information (roll number, name and CGPA).
Find
Student having the maximum CGPA
Names of students having CGPA more than 7.5
Average CGPA of the students
Sort and display name list
Rank list

Consider the price list of various items in a retail store. A customer wants to know
Price of costliest item sold in the retail store
Display item and price list in increasing order of price
Display items in ascending order and the corresponding price
Average price of items in retail store

PYTHON ASSIGNMENT 2 - STRING


Read a string

     Check for empty string

     Display string length

     Display reverse of a string

     Character at a given position

     Index of a substring in a string

     Copy first n characters

     Copy last n character

     Copy n characters from mth position

     Convert all characters to uppercase

     Convert all characters to lower case

     Replace a character

     Delete a character

     Count number of vowels

     Split a string based on the spaces / delimiter



Write a program to read and join a list of strings

Write a program to check if a given string is a palindrome or not.

Write a program to count and display the number of capital letters in a given string.

Write a program to count the number of vowels in a string.

Write a program to display the number of times each vowel occurs in a string. (ignore case)

Write a program to remove all punctuations and special characters (~!@#$%^&*()_{}[]\:”;’<>?,./) in a given string.

Write a program to read a string and count and display the number of upper, lower, digit and special characters in a given string.

Write a Python program to accept a string and display the resultant string in a reverse order. The resultant string should contain all characters at the even position of accepted string ignoring blank spaces.
     Example:
          Given string: An apple a day keeps the doctor away
          Required output: ywrtoetpeydepaA

Given a string containing both upper and lower case letters, write a python program to count the number of repeated characters and display the maximum count of a character along with the character
     Sample input: ABaBCbGc
     Output:
          2A
          3B
          2C
          1G
          B is repeated 3 times

Consider 2 strings string1 and string2 and display the merged_string as output. The merged_string should be capital letters from both the strings in the order they appear.
     Sample Input:
     String1: I Like Java
     String2: Mary Likes Python
     merged_string: ILJMLP




PYTHON ASSIGNMENT 1 - CONTROL STRUCTURES


If – elif – else structure


Check if given number is greater than 5

Check if given number is odd or even

Check if a given number is positive, negative or zero

Check for leap year

Biggest / smallest of three numbers

Check if given number is a single, two, three or four digit number.

Check if given character is vowel or not

Read a customer name, number of items purchased and price of item. If gross amount is greater than 500, a discount of 10 % is applicable. Find the net amount to be paid by the customer.


While loop


Print numbers from 1 to 5

Read and display 5 numbers

Print numbers between two limits and type (odd / even)

Read and display 5 numbers.
     Find
          Sum of 5 numbers
          Mean of 5 numbers
          Biggest of 5 numbers
          Smallest of 5 numbers

Factorial of a given number

Fibonacci series

Number manipulation. Given a number
     Find
          Count number of digits in a given number
          Sum of digits in a given number
          Reverse of the number

Armstrong number (Sum of cubes of individual digits in a given number equal to original number)

Check if given number is a Prime number or not

Display all the prime numbers between two limits


For loop


Print numbers from 1 to 5

Read and display 5 numbers

Print numbers between two limits and type (odd / even)

Read and display 5 numbers.
     Find
          Sum of 5 numbers
          Mean of 5 numbers
          Biggest of 5 numbers
          Smallest of 5 numbers

Factorial of a given number

Fibonacci series

Number manipulation. Given a number
     Find
          Count number of digits in a given number
          Sum of digits in a given number
          Reverse of the number

Armstrong number (Sum of cubes of individual digits in a given number equal to original number)

Check if given number is a Prime number or not

Display all the prime numbers between two limits





Sliding Window Protocol


Sliding window protocol


/*


Note:

The sender sends the packets and waits for acknowledgement.

The receiver uses a random function to send / withhold acknowledgements when a packet is received.

When sender receives an acknowledgement, it calculates the number of free slots in the sending window and transmits the next frames.

The packet data is set to alphabets from ‘a’ to ‘e’ and program terminates after 15 frames are sent and acknowledged.

*/



// Sliding window protocol
// Sender.java

import java.io.*;
import java.net.*;
import java.util.*;

public class Slide_Sender
{
     Socket sender;
   
     ObjectOutputStream out;
     ObjectInputStream in;
   
     String pkt;
     char data='a';
    
     int SeqNum = 1, SWS = 5;
     int LAR = 0, LFS = 0;
     int NF;
   
     Slide_Sender()
     {
     }
   
     public void SendFrames()
     {
          if((SeqNum<=15)&&(SWS > (LFS - LAR)) )
          {
              try
              {
                   NF = SWS - (LFS - LAR);
                   for(int i=0;i<NF;i++)
                   {
                        pkt = String.valueOf(SeqNum);
                        pkt = pkt.concat(" ");
                        pkt = pkt.concat(String.valueOf(data));
                        out.writeObject(pkt);
                        LFS = SeqNum;
                        System.out.println("Sent  " + SeqNum + "  " + data);
                            
                        data++;
                        if(data=='f')
                             data='a';
                            
                        SeqNum++;
                        out.flush();
                   }
              }  
              catch(Exception e)
              {}
          }
     }
    
     public void run() throws IOException
     {
          sender = new Socket("localhost",1500);

          out = new ObjectOutputStream(sender.getOutputStream());
          in = new ObjectInputStream(sender.getInputStream());
       
          while(LAR<15)
          {       
              try
              {  
                   SendFrames();      
                  
                   String Ack = (String)in.readObject();
                   LAR = Integer.parseInt(Ack);
                   System.out.println("ack received : " + LAR);
              }       
              catch(Exception e)
              {
              }
          }
         
          in.close();
          out.close();
          sender.close();
          System.out.println("\nConnection Terminated.");  
     }
    
     public static void main(String as[]) throws IOException
     {
          Slide_Sender s = new Slide_Sender();
          s.run();
     }
}


// Sliding window protocol
// Receiver.java

import java.io.*;
import java.net.*;
import java.util.*;

public class Slide_Receiver
{
     ServerSocket reciever;
     Socket conc = null;
   
     ObjectOutputStream out;
     ObjectInputStream in;
   
     String ack, pkt, data="";
     int delay ;
    
     int SeqNum = 0, RWS = 5;
     int LFR = 0;
     int LAF = LFR+RWS;
  
     Random rand = new Random();
     
     Slide_Receiver()
     {
     }
    
     public void run() throws IOException, InterruptedException
     {
          reciever = new ServerSocket(1500,10);
          conc = reciever.accept();
           
          if(conc!=null)
              System.out.println("Connection established :");
                            
          out = new ObjectOutputStream(conc.getOutputStream());
          in = new ObjectInputStream(conc.getInputStream());
             
          while(LFR<15)
          {
              try
              {  
                   pkt = (String)in.readObject();
                   String []str = pkt.split("\\s");
                  
                   ack = str[0];
                   data = str[1];
                                                         
                   LFR = Integer.parseInt(ack);
                  
                   if((SeqNum<=LFR)||(SeqNum>LAF))
                   {
                        System.out.println("\nMsg received : "+data);
                        delay = rand.nextInt(5);
                       
                        if(delay<3 || LFR==15)
                        {  
                             out.writeObject(ack);
                             out.flush();
                             System.out.println("sending ack " +ack);
                             SeqNum++;
                        }
                        else
                             System.out.println("Not sending ack");
                   }
                   else
                   {
                        out.writeObject(LFR);
                        out.flush();
                        System.out.println("resending ack " +LFR);
                   }  
              }                 
              catch(Exception e)
              {  
              }
          }  
          in.close();
          out.close();
          reciever.close();
          System.out.println("\nConnection Terminated.");
     }
     public static void main(String args[]) throws IOException, InterruptedException
     {
          Slide_Receiver R = new Slide_Receiver();
          R.run();
     }
}





Output:

Sender Window:

>javac Slide_Sender.java
>java Slide_Sender
Sent  1  a
Sent  2  b
Sent  3  c
Sent  4  d
Sent  5  e
ack received : 3
Sent  6  a
Sent  7  b
Sent  8  c
ack received : 5
Sent  9  d
Sent  10  e
ack received : 7
Sent  11  a
Sent  12  b
ack received : 8
Sent  13  c
ack received : 10
Sent  14  d
Sent  15  e
ack received : 11
ack received : 12
ack received : 15

Connection Terminated.

>  




Receiver Window:

>javac Slide_Receiver.java
>java Slide_Receiver
Connection established :

Msg received : a
Not sending ack

Msg received : b
Not sending ack

Msg received : c
sending ack 3

Msg received : d
Not sending ack

Msg received : e
sending ack 5

Msg received : a
Not sending ack

Msg received : b
sending ack 7

Msg received : c
sending ack 8

Msg received : d
Not sending ack

Msg received : e
sending ack 10

Msg received : a
sending ack 11

Msg received : b
sending ack 12

Msg received : c
Not sending ack

Msg received : d
Not sending ack

Msg received : e
sending ack 15

Connection Terminated.
     >