R20 DATA STRUCTURES LAB

DATA STRUCTURES LAB

Data Structures LAB

Exercise-1
  • a) Write C program that use both recursive and non recursive functions to perform Linear search for a Key value in a given list.
//non recursive functions to perform Linear search
#include<stdio.h>
void main()
{
    int n,a[100],se,i;
    void linear(int ,int [],int);
    printf("Enter searching element:");
    scanf("%d",&se);
    printf("Enter no of elements:");
    scanf("%d",&n);
    printf("Enter elements into the array:");
    for(i=0;i<n;i++)
    {
        scanf("%d",&a[i]);
    }
    linear(n,a,se);
}
void linear(int n,int a[100],int se)
{
    int i,flag=0;
    for(i=0;i<n;i++)
    {
        if(a[i]==se)
        {
            flag=1;
            printf("Element %d found at %d",se,i);
        }
    }
    if(flag==0)
    {
        printf("%d was not found",se);
    }
}

  • b) Write C program that use both recursive and non recursive functions to perform Binary search for a Key value in a given list.
//Binary search without recursion
#include<stdio.h>
void main()
{
    int n,a[100],se,i;
    void binarysearch(int ,int [],int);
    printf("Enter the no of elements:");
    scanf("%d",&n);
    for(i=0;i<n;i++)
    {
        printf("Enter %d elements:",i+1);
        scanf("%d",&a[i]);
    }
    printf("Enter searching elements");
    scanf("%d",&se);
    binarysearch(n,a,se);

}
void binarysearch(int n,int a[100],int se)
{
    int low,high,mid,flag=0;
    low=0;
    high=(n-1);
    mid=(low+high)/2;
    while(low<high)
    {
        if(se==a[mid])
        {
            flag=1;
            printf("The element %d is found at %d",se,mid);
            break;
        }
        else if(se<a[mid])
        {
            low=0;
            high=mid-1;

        }
        else if(se<a[mid])
        {
            low=mid+1;
            high=high;
        
        }
    }
    if(flag==0)
    {
        printf("Element %d is not found",se);
    }
}

Exercise-2(Sorting-I)
  • a) Write C program that implement Bubble sort, to sort a given list of integers in ascending order.
//Bubble sort
#include<stdio.h>
void main()
{
    int i,n,a[100],j,temp;
    printf("Enter size:");
    scanf("%d",&n);
    printf("Enter elements into the array:");
    for(i=0;i<n;i++)
    {
        scanf("%d",&a[i]);
    }
    for(i=0;i<n-1;i++)
    {
        for(j=0;j<n-1-i;j++)
        {
            if(a[j]>a[j+1])
            {
                temp=a[j];
                a[j]=a[j+1];
                a[j+1]=temp;

            }
        }
    }
    printf("Elements after sorting are:");
    for(i=0;i<n;i++)
    {
        printf("%d,",a[i]);
    }
}

  • c) Write C program that implement Insertion sort, to sort a given list of integers in ascending order
//Insertion sort
#include<stdio.h>
void main()
{
    int n,a[100],i,j,temp;
    printf("Enter size:");
    scanf("%d",&n);
    printf("Enter elements into the array:");
    for(i=0;i<n;i++)
    {
        scanf("%d",&a[i]);
    }
    for(i=1;i<n;i++)
    {
        temp=a[i];
        j=i-1;
        while((j>=0)&&(temp<a[j]))
        {
            a[j+1]=a[j];
            j--;

        }
        a[j+1]=temp;
    }
    printf("Elements after sorting:");
    for(i=0;i<n;i++)
    {
        printf("%d,",a[i]);
    }
}

Exercise - 3
  • b) Write C program that implement merge sort, to sort a given list of integers in ascending order.
//Merge sort
#include<stdio.h>
void mergesort(int a[],int lb,int ub);
void merge(int a[],int lb,int mid,int ub);
void main()
{
    int a[100],i,n;
    printf("Enter array size:");
    scanf("%d",&n);
    printf("Enter elements into the array:\n");
    for(i=0;i<n;i++)
    {
        printf("Enter %d element:",i+1);
        scanf("%d",&a[i]);
    }
    mergesort(a,0,n-1);
    printf("The array elements after sorting are:");
    for(i=0;i<n;i++)
    {
        printf("%d,",a[i]);
    }
}
void mergesort(int a[],int lb,int ub)
{
    int mid;
    if(lb<ub)
    {
        mid=(lb+ub)/2;
        mergesort(a,lb,mid);
        mergesort(a,mid+1,ub);
        merge(a,lb,mid,ub);
    }
}
void merge(int a[],int lb,int mid,int ub)
{
    int i,j,k;
    int b[100];
    i=lb;
    j=mid+1;
    k=lb;
    while (i<=mid&&j<=ub)
    {
        if(a[i]<a[j])
        {
            b[k]=a[i];
            i++;
            k++;
        }
        else
        {
            b[k]=a[j];
            j++;
           k++;
        }
    }
    if(i>mid)
    {
        while(j<=ub)
        {
            b[k]=a[i];
            i++;
            k++;
        }
    }
    else
    {
        while(i<=mid)
        {
            b[k]=a[i];
            i++;
            k++;
        }
    }
    for(i=lb;i<=ub;i++)
    {
        a[i]=b[i];
    }
    
}


Exercise - 4(Singly Linked List)
  • a) Write a C program that uses functions to create a singly linked list
  • b) Write a C program that uses functions to perform insertion operation on a singly linked list
  • c) Write a C program that uses functions to perform deletion operation on a singly linked list
 #include<stdio.h>
#include<stdlib.h>
struct node
{
    int data;
    struct node *next;
};
struct node *head=NULL;
void insert_begin();
void insert_end();
void insert_loc();
void delete_begin();
void delete_end();
void delete_loc();
void search();
void display();

void main()
{
    int ch;
    while(1)
    {
        printf("1.Insert at beginning");
        printf("\n2.Insert at end");
        printf("\n3.Insert at location");
        printf("\n4.delete at beginning");
        printf("\n5.delete at end");
        printf("\n6.delete at location");
        printf("\n7.search");
        printf("\n8.display");
        printf("\n9.exit");
        printf("\nEnter your choice:");
        scanf("%d",&ch);
    
    switch(ch)
    {
        case 1:
                insert_begin();
                break;
        case 2:
                insert_end();
                break;
        case 3:
                insert_loc();
                break;
        case 4:
                delete_begin();
                break;
        case 5:
                delete_end();
                break;
        case 6:
                delete_loc();
                break;
        case 7:
                search();
                break;
        case 8:
                display();
                break;
        case 9:
                exit(0);
                break;
        default:
                printf("No choice found");
                break;
    
    }
    }

}

void insert_begin()
{
    int data;
    struct node *newnode=(struct node*)malloc(sizeof(struct node*));
    printf("Enter a value to insert:");
    scanf("%d",&data);
    if(newnode==NULL)
        printf("Memmory is full");
    else if(head==NULL)
    {
        newnode->data=data;
        newnode->next=NULL;
        head=newnode;
    }
    else
    {
        newnode->data=data;
        newnode->next=head;
        head=newnode;
    }
    

    
    
}
void insert_end()
{
        int data;
        struct node *newnode=(struct node*)malloc(sizeof(struct node*));
        printf("Enter value to insert:");
        scanf("%d",&data);
        if(newnode==NULL)
                printf("Memory is full");
        else if(head==NULL)
        {
                newnode->data=data;
                newnode->next=NULL;
                head=newnode;
        }
       else
       {
                newnode->data=data;
                newnode->next=NULL;
                struct node *temp;
                temp=head;
                while(temp->next!=NULL)
                {
                        temp=temp->next;

                }
                temp->next=newnode;
       }
}
void insert_loc()
{
        int data,loc;
        struct node *newnode=(struct node*)malloc(sizeof(struct node*));
        printf("Enter a value to enter:");
        scanf("%d",&data);
        if(newnode==NULL)
                printf("Memory is full");
        else if(head==NULL)
        {
                newnode->data=data;
                newnode->next=NULL;
                head=newnode;
        }
        else
        {
                printf("Enter a location:");
                scanf("%d",&loc);
                struct node *temp;
                temp=head;
                while(temp->next!=loc)
                {
                        temp=temp->next;
                }
                newnode->data=data;
                newnode->next=temp->next;
                temp->next=newnode;

        }
        
        
}
void delete_begin()
{
        if(head=NULL)
                printf("Linked List is empty");
        else
        {
                struct node*temp;
                temp=head;
                head=head->next;
                temp->next=NULL;
                free(temp);
        }
}
void delete_end()
{
        if(head==NULL)
                printf("Linked List is empty");
        else
        {
                struct node *temp;
                struct node *prev;
                prev=head;
                temp=head->next;
                while(temp->next!=NULL)
                {
                        temp=temp->next;
                        prev=prev->next;
                }
                prev->next=NULL;
                free(temp);
        }
}
void delete_loc()
{
        int loc;
         if(head=NULL)
                printf("Linked List is empty");
        else
        {
                struct node *temp;
                struct node *prev;
                prev=head;
                temp=head->next;
                printf("Enter a location:");
                scanf("%d",&loc);
                while(temp->next!=loc)
                {
                        temp=temp->next;
                        prev=prev->next;
                }
                prev->next=temp->next;
                temp->next=NULL;
                free(temp);
                
        }
}
void search()
{
        int se,count=0;
        if(head==NULL)
                printf("Linked List is empty");
        else
        {
                printf("Enter a searching element");
                scanf("%d",&se);
                struct node *temp;
                temp=head;
                while(temp->next!=NULL)
                {
                        if(se==temp->data)
                                count++;
                }
                temp=temp->next;
                if(count==0)
                        printf("Element is not found");
                else
                        printf("Element is found %d times",count);

        }
}
void display()
{
        if(head==NULL)
                printf("Linked List is empty");
        else
        {
                struct node *temp;
                temp=head;
                while(temp->next!=NULL)
                {
                        printf("%d->",temp->data);
                        temp=temp->next;
                }
                printf("%d\n",temp->data);
        }
}
        



netaji gandi Tuesday, May 16, 2023
PYTHON PROGRAMMING PREVIOUS QUESTION PAPERS

PYTHON PROGRAMMING PREVIOUS QUESTION PAPERS

PYTHON PROGRAMMING PREVIOUS QUESTION PAPERS

Regulation Month & Year Download File
R20 August -2022-Regular 4 Sets
R20 March -2022-Supply 1 Set
R20 Sep -2021-Regular 1 Set
R19 March -2021-Regular 4 Sets
R16 Oct/Nov-2017-Regular 4 Sets
R16 Oct/Nov-2018-Regular 4 Sets
R16 May-2018-Supply 1 Set
R16 Oct/Nov-2019-Regular 4 Sets
R16 May-2019-Supply 1 Set
R16 Oct/Nov-2020-Supply 1 Set
Online Quiz

netaji gandi
JNTUK R20 PYTHON PROGRAMMING LAB

R20 PYTHON PROGRAMMING LAB
  1. 1. Write a program that asks the user for a weight in kilograms and converts it to pounds. There are 2.2 pounds in a kilogram.
  2. weight = float(input("enter ur weight: "))
    
    pound = (2.2 * weight)
    
    print("After coverting Kgs into pounds is %0.2f" %pound)
    


  3. 2. Write a program that asks the user to enter three numbers (use three separate input statements). Create variables called total and average that hold the sum and average of the three numbers and print out the values of total and average.
  4.  
    a=int(input("enter value of a: "))
    b=int(input("enter value of b: "))
    c=int(input("enter value of c: "))
    Total = (a+b+c) 
    Average = Total/3 
    print("sum of three numbers is ", Total)
    print("Avg of three numbers is ", Average)
    print("sum of three numbers is %d and Avg of three numbers is %0.2f " %(Total,Average))
    


  5. 3. Write a program that uses a for loop to print the numbers 8, 11, 14, 17, 20, . . . , 83, 86, 89.
  6.  
    for i in range(8,90,3):
        print(i,end=' ')
    


  7. 4. Write a program that asks the user for their name and how many times to print it. The program should print out the user's name the specified no of times
  8. username=input("enter ur name")
    n=int(input("how many no of times to print"))
    c=1
    while c<=n:
        print("u r name is ",username)
        c=c+1
    


  9. 5. Use a for loop to print a triangle like the one below. Allow the user to specify how high the triangle should be.
  10. n=15
    for i in range(0,n):
        for j in range(0,i+1):
            print("*",end='')
        print()
    

    or

    for i in range(1,15):
        print(i*"*")
    


  11. 6. Generate a random number between 1 and 10. Ask the user to guess the number and print a message based on whether they get it right or not.
  12. import random as ra 
    random_num = ra.randint(1, 10) 
    guess=int(input('Guess a number between 1 and 10 until you get it right :'))
    while random_num != guess:
              print("try again ")
              guess = int(input('Guess a number between 1 and 10 until you get it right : ')) 
    print('Well guessed!')
    
    


  13. 7. Write a program that asks the user for two numbers and prints Close if the numbers are within .001 of each other and Not close otherwise.
  14. num1 = float(input("Enter the first number: "))
    num2 = float(input("Enter the second number: "))
    
    if abs(num1 - num2) <= 0.001:
        print("Close")
    else:
        print("not close")
     


  15. 8. Write a program that asks the user to enter a word and prints out whether that word contains any vowels.
  16. vowels = ['A', 'E', 'I', 'o', 'U', 'a', 'e', 'i', 'o', 'u']
    a=input("enter word") 
    c=0 
    for i in a: 
        if(i in vowels):
            c=c+1 
    if(c!=0):
        print("string contains vowels")
    


  17. 9. Write a program that asks the user to enter two strings of the same length. The program should then check to see if the strings are of the same length. If they are not, the program should print an appropriate message and exit. If they are of the same length, the program should alternate the characters of the two strings. For example, if the user enters abcde and ABCDE the program should print out AaBbCcDdEe.
  18. a=input("enter string 1: ")
    b=input("enter string 2: ")
    #result=''
    if(len(a)==len(b)):
        for i in range(len(a)):
            result=a[i]+b[i]
            print(result,end='')
    else:
        print("please enter equal length strings") 
    


  19. 10. Write a program that asks the user for a large integer and inserts commas into it according to the standard American convention for commas in large numbers. For instance, if the user enters 1000000, the output should be 1,000,000.
  20. n=int(input()) 
    print("{:,}".format(n))
    
  21. 11. In algebraic expressions, the symbol for multiplication is often left out, as in 3x+4y or 3(x+5). Computers prefer those expressions to include the multiplication symbol, like 3*x+4*y or 3*(x+5). Write a program that asks the user for an algebraic expression and then inserts multiplication symbols where appropriate.
  22. n=input()
    l=list(n)
    print("list is",l)
    res=''
    i=0
    while(i<len(l)):
        if l[i]=='(':
            ind=l.index(')')
            str=''.join(l[i:ind+1])
            res=res+'*'+str
            i=i+len(str)
        elif l[i].isalpha():
            res=res+'*'+l[i]
            i=i+1
        else:
            res=res+l[i]
            i=i+1
    print(res)
     


  23. 12. Write a program that generates a list of 20 random numbers between 1 and 100. (a) Print the list. (b) Print the average of the elements in the list. (c) Print the largest and smallest values in the list. (d) Print the second largest and second smallest entries in the list (e) Print how many even numbers are in the list.
  24. import random as ra
    list=[]
    for i in range(20):
        list.append(ra.randint(1, 100))
    print(list)
    #print the average of the elements in the list
    sum=0
    for i in range(20):
        sum=sum+list[i]
    print("average of all the elements in the list is ", sum/len(list))
    #Print the second largest and second smallest entries in the list
    lar=lar2=small=small2=list[0]
    for i in list[1:]:
        if i > lar:
            lar2 = lar
            lar = i 
        elif lar2 < i: 
            lar2 = i 
        if i < small: 
            small2 = small
            small = i 
        elif small2 > i: 
            small2 = i 
    print("Largest element is : ", lar)
    print("Second Largest element is : ", lar2)
    print("Smallest element is : ", small)
    print("Second Smallest element is : ", small2)
    #Print the even numbers in the list
    for num in list:
        if num%2==0:
            print(num,end=' ')
    #list comprehension 
    even = [num for num in list if num % 2 != 0]
    print(even)
    


  25. 13. Write a program that asks the user for an integer and creates a list that consists of the factors of that integer.
  26. x=int(input("enter any number: "))
    list1=[]
    for i in range(1, x + 1):
        if x % i == 0:
            list1.append(i)
    print(list1)
    
    #list comprehension
    list=[i for i in range(1, x + 1) if x % i == 0]
    print(list)
    


  27. 14. Write a program that generates 100 random integers that are either 0 or 1. Then find the longest run of zeros, the largest number of zeros in a row. For instance, the longest run of zeros in [1,0,1,1,0,0,0,0,1,0,0] is 4.
  28. import random as ra
    list=[]
    for i in range(100):
        list.append(ra.randint(0, 1))
    print(list)
    c=0
    maxc=0
    for i in list:
        if i == 0:
            c += 1
        else:
            if c > maxc:
                maxc = c
            c = 0
    print("the longest run of zeros",maxc)
    


  29. 15. Write a program that removes any repeated items from a list so that each item appears at most once. For instance, the list [1,1,2,3,4,3,0,0] would become [1,2,3,4,0].
  30. list=[1,1,2,3,4,3,0,0]
    list1=[]
    for i in list:
        if i not in list1:
            list1.append(i)
    
    print(list1)
    


  31. 16. Write a program that asks the user to enter a length in feet. The program should then give the user the option to convert from feet into inches, yards, miles, millimeters, centimeters, meters, or kilometers. Say if the user enters a 1, then the program converts to inches, if they enter a 2, then the program converts to yards, etc. While this can be done with if statements,it is much shorter with lists and it is also easier to add new conversions if you use lists.
  32. n=float(input("Enter Feet"))
    list=[]
    list.append(n*12)
    list.append(n* 0.33333)
    list.append(n*0.00018939)
    list.append(n*304.8,2)
    list.append(n*30.48)
    list.append(n/ 3.2808)
    list.append(n/ 3280.8)
    print(list)
    print("0.Convert Feet to Inches")
    print("1.Convert Feet to Yards")
    print("2.Convert Feet to Miles")
    print("3.Convert Feet to millimeters")
    print("4.Convert Feet to centimeters")
    print("5.Convert Feet to meters")
    print("6.Convert Feet to kilometers")
    op=int(input("Choose Options from Above"))
    print(list[op])
    

    or

    n=float(input("Enter Feet"))
    
    print("1.Convert Feet to Inches")
    print("2.Convert Feet to Yards")
    print("3.Convert Feet to Miles")
    print("4.Convert Feet to millimeters")
    print("5.Convert Feet to centimeters")
    print("6.Convert Feet to meters")
    print("7.Convert Feet to kilometers")
    op=int(input("Choose Options from Above"))
    
    
    if(op==1):
        Inches=n*12
        print("Feet to Inches value is ", Inches)
    if(op==2):
        Yards= n * 0.33333
        print("Feet to Yards value is ", Yards)
    if(op==3):
        Miles= n * 0.00018939
        print("Feet to Miles value is ", Miles)
    if(op==4):
        MM= n * 304.8
        print("Feet to millimeters value is ", MM)
    if(op==5):
        CM= n * 30.48
        print("Feet to centimeters value is ", CM)
    if(op==6):
        meters= n / 3.2808
        print("Feet to meters value is ", round(meters,3))
    if(op==7):
        KM= n / 3280.8
        print("Feet to kilometers value is ", KM)
    


  33. 17. Write a function called sum_digits that is given an integer num and returns the sum of the digits of num.
  34.  def sum_digits(n):
        sum=0
        while n>0:
            m=n%10
            sum=sum+m
            n=n//10
        return sum
    
    n=int(input("enter value: "))
    print("sum of digits is: ", sum_digits(n))
    

    or

    def Sum(n): 
         
        sum = 0
        for i in n:  
          sum += int(i)       
        return sum
        
    n = input("enter value: ")
    print("sum of digist is: ",Sum(n))
    


  35. 18. 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.
  36. def first_diff(str1,str2):
        if str1 == str2:
            return -1 
        else:
            return str1.find(str2)
        
    str1=input("enter string 1: ")
    str2=input("enter string 2: ")
    
    print(first_diff(str1,str2))
    


  37. 19. Write a function called number_of_factors that takes an integer and returns how many factors the number has.
  38. def number_of_factors(n):
        list=[i for i in range(1, n + 1) if n % i == 0]
        return len(list)
        
    print("number has %d factors" %number_of_factors(20))
    


  39. 20. Write a function called is_sorted that is given a list and returns True if the list is sorted and False otherwise.
  40. def is_sorted1(list2):
        c = 0
        list1=list2[:]
        list1.sort()
        if(list2 != list1):
            c = 1
        if(not c):
            return True
        else:
            return False
            
    list2 = [121, 14, 15, 82, 100]    
    print(is_sorted1(list2))
    


  41. 21. 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.
  42. import math
    #Method 1
    def root(x,n):
        return pow(x,1/n)
    
    n=2
    x=int(input("enter value"))
    print("Method 1 using pow ", root(x,n), "
          Method 2, If n value is 2 only using sqrt function ",math.sqrt(x))
    


  43. 22. 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.
  44. def primes(n):
        list=[]
        for num in range(n+1):
            if num > 1:
                for i in range(2, num):
                    if (num % i) == 0:
                        break
                else:
                    list.append(num)
        return list
    
    n=int(input("enter n value: "))
    print("list of n prime numbers are :", primes(n))
    


  45. 23. Write a function called merge that takes two already sorted lists of possibly different lengths, and merges them into a single sorted list. (a) Do this using the sort method. (b) Do this without using the sort method.
  46. #Without sort Method
    def merge(list1,list2):
        list3=list1+list2
        print(list3)
        for i in range (len(list3)):
            for j in range(i + 1, len(list3)):
                if(list3[i] > list3[j]):
                    temp = list3[i]
                    list3[i] = list3[j]
                    list3[j] = temp
        print(list3)
    
    list1=[1,2,3,5,6]
    list2=[3,5,9,10]
    merge(list1,list2)
    
    #sort Method
    def merge(list1,list2):
        list3=list1+list2
        list3.sort()
        print("After merging two list in sorted order",list3)
    
    list1=[1,2,3,5,6]
    list2=[3,5,9,10]
    merge(list1,list2)
    


  47. 24. 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 occurances of the letter in the user's word.
  48. from itertools import permutations
    s=input('Enter a word:::')
    for i in range(2,len(s)):
        for p in permutations(s,i):
            print(''.join(p),end=' ')
    


  49. 25. 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
  50. import re
    
    fo = open("sample.txt", "r+")
    
    str = fo.read()
    print ("Read String is : ", str)
     
    lst = re.findall('\S+@\S+', str)     
    
    print(";"+lst[0]+";")
    fo.close()
    


  51. 26. 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.
  52. fo = open("temps.txt")
    f1= open("ftemps.txt","w+")
    for i in fo:
        c=float(i)
        F=(9*c + (32*5))/5
        f1.write(str(F)+"\n")
    f1.close()
    fo.close()
    


  53. 27. 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.
  54. class Product:
        def __init__(self,name,amount,price):
            self.name=name
            self.amount=amount
            self.price=price
            
        def get_price(self,number_items):
            if number_items<10:
                return self.price*number_items
            elif 10 <=number_items < 100:
                return 0.9*self.price*number_items
            else:return 0.8*self.price*number_items
        
        def make_purchase(self, quantity):
            self.amount -= quantity
    
    name, amount, price = 'shoes', 200, 1200
    
    shoes = Product(name, amount, price)
    
    q1 = 4
    print(f'cost for {q1} {shoes.name} = {shoes.get_price(q1)}')
    shoes.make_purchase(q1)
    print(f'remaining stock: {shoes.amount}\n')
    
    q2 = 12
    print(f'cost for {q2} {shoes.name} = {shoes.get_price(q2)}')
    shoes.make_purchase(q2)
    print(f'remaining stock: {shoes.amount}\n')
    
    q3 = 112
    print(f'cost for {q3} {shoes.name} = {shoes.get_price(q3)}')
    shoes.make_purchase(q3)
    print(f'remaining stock: {shoes.amount}\n')
    


  55. 28. 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.
  56. class Time():
       # constructor
       def __init__(self, seconds):
           self.seconds = seconds
      
       # function to convert and return a string of minutes and seconds
       def convert_to_minutes(self):
           mins = self.seconds//60 # get the total minutes in the given seconds
           secs = self.seconds - (mins*60) # get the remaining seconds
           print("{}:{} minutes".format(self.seconds//60,self.seconds%60))
           # return the string of minutes:seconds
           return "%d:%d minutes" %(mins,secs)
      
       # function to convert and return string of hours, minutes, and seconds
       def convert_to_hours(self):
           secs = self.seconds
           hours = secs//3600 # get the total hours in the given seconds
           secs = secs - (hours*3600) # get the remaining seconds
           mins = secs//60 # get the total minutes in the remaining seconds
           secs = secs - (mins*60) # get the remaining seconds
           print("{:.2f} Hors".format(self.seconds/3600))
           # return the string of hours:minutes:seconds
           return "%d:%d:%d" %(hours,mins,secs)
          
    time = Time(365)
    print(time.convert_to_minutes())
    time = Time(4520)
    print(time.convert_to_hours())
    


  57. 29. 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.
  58.  class Converter:
        def __init__(self, n,name):
            self.value = n
            self.name=name
        
        def FeettoInches(self):
            Inches=self.value*12
            print("Feet to Inches value is ", Inches)
            
        def milestokm(self):
            km=self.value/0.62137
            print("miles to KM  is ", km)
                
        def FeettoYards(self):
            Yards= self.value * 0.3333
            print("Feet to Yards value is ", Yards)
        
        def FeettoMiles(self):
            Miles= self.value * 0.00018939
            print("Feet to Miles value is ", Miles)     
            
    n=float(input("enter feet/inches/cm/mm/km/miles: "))
    x=Converter(n,'inches')
    
    x.FeettoInches()
    x.milestokm()
    x.FeettoYards()
    x.FeettoMiles()
    


  59. 30. Write a Python class to implement pow(x, n).
  60. class power:
        
        def pow1(self, x, n):
            if x==0 or x==1 or n==1:
                return x 
    
            if x==-1:
                if n%2 ==0:
                    return 1
                else:
                    return -1
            if n==0:
                return 1
            if n<0:
                return 1/self.pow1(x,-n)
            val = self.pow1(x,n//2)
            if n%2 ==0:
                return val*val
            return val*val*x
    
    x=power()
    print(x.pow1(2, -2))
    print(x.pow1(3, 5))
    print(x.pow1(100, 0))
    


  61. 31. Write a Python class to reverse a string word by word.
  62. class py_solution:
        def reverse_words(self, s):
            return ' '.join(reversed(s.split()))
    
    
    print(py_solution().reverse_words('hello .py'))
    

    or

    string = "I am a python programmer"
    words = string.split()
    words = list(reversed(words))
    print(" ".join(words))
    
  63. 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.
  64. from tkinter import *
    from tkinter.filedialog import *
    from tkinter.scrolledtext import ScrolledText
    #lab program 2 type
    root = Tk()
    root.title('File dialog') 
    textbox = ScrolledText()
    textbox.grid()
    
    filename=askopenfilename(initialdir='C:\Python_Code\examples',filetypes=[('Text files', '.txt'),('All files', '*')])
    s = open(filename).read()
    textbox.insert(1.0, s)
    mainloop()
    

    or

    from tkinter import *
    from tkinter.filedialog import *
    from tkinter import filedialog
    from tkinter.scrolledtext import ScrolledText
    #lab program 1 type
    master = Tk()
    master.title('File dialog')
    textbox = ScrolledText()
    textbox.grid()
    
    def callback():
        filename=askopenfilename()
        s = open(filename).read()
        textbox.insert(1.0, s)
     
    errmsg = 'Error!'
    bt=Button(text='File Open', command=callback)
    bt.grid(column=1, row=0)
    mainloop()
    


  65. 32. Write a program to demonstrate Try/except/else
  66. try:
        x=int(input('Enter a number upto 100: '))
        if x > 100:
            raise ValueError(x)
    except ValueError: 
        print(x, "is out of allowed range")
    else:
        print(x, "is within the allowed range")
    
    
  67. Write a program to demonstrate try/finally and with/as.

  68. try/finally
    try:
        print('try block')
        x=int(input("Enter a number:"))
        y=int(input("Enter another number:"))
        z=x/y
    except ZeroDivisionError:
        print("except ZeroDivisionError block") 
        print("Division by not accepted")
    else:
        print("else block")
        print("Division = ", z)
    finally:
        print("finally block")
        
    print ("Out of try, except, else and finally blocks." )
    
    Output1:
    try block
    Enter a number:100
    Enter another number:10
    else block
    Division =  10.0
    finally block
    Out of try, except, else and finally blocks.
    
    
    Output2:
    try block
    Enter a number:100
    Enter another number:0
    except ZeroDivisionError block
    Division by not accepted
    finally block
    Out of try, except, else and finally blocks.
    

    with/as
    # file handling
    
    #1)without using with statement
    file=open('123.txt','w')
    file.write('hello world')
    file.close()
    
    #2)with try and finally
    file=open('123.txt','w')
    try:
    	file.write('hello world')
    finally:
    	file.close()
    
    #3)using with statement
    with open('123.txt','w') as file:
    	file.write('hello world') 
    

netaji gandi Thursday, May 11, 2023
JNTUK R20 R PROGRAMMING LAB

R PROGRAMMING LAB

ADDON Experiment - 01

Download and Install R and R Studio


Exercise-1
  • Write a R program to take input from the user (name and age) and display the values. Also print the version of R installation.
name = readline(prompt="Input your name: ")
age =  readline(prompt="Input your age: ")
print(paste("My name is",name, "and I am",age ,"years old."))
print(R.version.string)
Exercise-2
  • Write a R program to get the details of the objects in memory.
name = "Python"; 
n1 =  10; 
n2 =  0.5
nums = c(10, 20, 30, 40, 50, 60)
print(ls())
print("Details of the objects in memory:")
print(ls.str())
Exercise-3
  • Write a R program to create a sequence of numbers from 20 to 50 and find the mean of numbers from 20 to 60 and sum of numbers from 51 to 91.
print("Sequence of numbers from 20 to 50:")
print(seq(20,50))
print("Mean of numbers from 20 to 60:")
print(mean(20:60))
print("Sum of numbers from 51 to 91:")
print(sum(51:91))
Exercise - 4
  • Write a R program to create a simple bar plot of five subjects marks.
marks = c(70, 95, 80, 74)
barplot(marks,main = "Comparing marks of 5 subjects",
     xlab = "Marks", ylab = "Subject",
names.arg = c("English", "Science", "Math.", "Hist."),
				col = "darkred",horiz = FALSE)
Exercise - 5
  • Write a R program to get the unique elements of a given string and unique numbers of vector.
str1 = "Cricket is our religion and scahin is oyur god."
print("Original vector(string)")
print(str1)
print("Unique elements of the said vector:")
print(unique(tolower(str1)))
nums = c(1, 2, 2, 3, 4, 4, 5, 6)
print("Original vector(number)")
print(nums)
print("Unique elements of the said vector:")
print(unique(nums))
Exercise - 18
  • Write a R program to append value to a given empty vector.
  vector = c()
values = c(0,1,2,3,4,5,6,7,8,9)
for (i in 1:length(values))
  vector[i] &lt- values[i]
print(vector)
Exercise - 19
  • Write a R program to multiply two vectors of integers type and length 3.
x = c(10, 20, 30)
y = c(20, 10, 40)
print("Original Vectors:")
print(x)
print(y)
print("Product of two Vectors:")
z = x * y
print(z)
Exercise - 20
  • Write a R program to find Sum, Mean and Product of a Vector, ignore element like NA or NaN.
x = c(10, NULL, 20, 30, NA)
print("Sum:")
#ignore NA and NaN values
print(sum(x, na.rm=TRUE))
print("Mean:")
print(mean(x, na.rm=TRUE))  
print("Product:")
print(prod(x, na.rm=TRUE))

MATRIX PROGRAMS

Exercise - 6
  • Write a R program to create three vectors a,b,c with 3 integers. Combine the three vectors to become a 3×3 matrix where each column represents a vector. Print the content of the matrix.
a&lt-c(1,2,3)
b&lt-c(4,5,6)
c&lt-c(7,8,9)
m&lt-cbind(a,b,c)
print("Content of the said matrix:")
print(m)
Exercise - 7
  • Write a R program to create a 5 x 4 matrix , 3 x 3 matrix with labels and fill the matrix by rows and 2 × 2 matrix with labels and fill the matrix by columns.
m1 = matrix(1:20, nrow=5, ncol=4)
print("5 × 4 matrix:")
print(m1)
cells = c(1,3,5,7,8,9,11,12,14)
rnames = c("Row1", "Row2", "Row3")
cnames = c("Col1", "Col2", "Col3")
m2 = matrix(cells, nrow=3, ncol=3, byrow=TRUE, 
			dimnames=list(rnames,cnames))
print("3 × 3 matrix with labels, filled by rows: ")
print(m2)
print("3 × 3 matrix with labels, filled by columns: ")
m3 = matrix(cells, nrow=3, ncol=3, byrow=FALSE, 
			dimnames=list(rnames,cnames))
print(m3)
Exercise - 15
  • Write a R program to create a matrix from a list of given vectors.
l = list()
for (i in 1:5)
  	l[[i]] &lt- c(i, 1:4)
print("List of vectors:")
print(l)
result = do.call(rbind, l)
print("New Matrix:")
print(result)
Exercise - 16
  • Write a R program to concatenate two given matrices of same column but different rows.
x = matrix(1:12, ncol=3)
y = matrix(13:24, ncol=3)
print("Matrix-1")
print(x)
print("size of matrix x")
print(dim(x))
print("Matrix-2")
print(y)
print("size of matrix y")
print(dim(y))
result = rbind(x,y)
print("After concatenating two given matrices:")
print(result)
print("size of matrix after concatenation")
print(dim(rbind(x,y)))
Exercise - 17
  • Write a R program to find row and column index of maximum and minimum value in a given matrix.
m = matrix(c(1:16), nrow = 4, byrow = TRUE)
print("Original Matrix:")
print(m)
result = which(m == max(m), arr.ind=TRUE)
print("Row and column of maximum value of the said matrix:")
print(result)
result = which(m == min(m), arr.ind=TRUE)
print("Row and column of minimum value of the said matrix:")
print(result)

LIST PROGRAMS

Exercise - 21
  • Write a R program to list containing a vector, a matrix and a list and give names to the elements in the list.
list_data &lt-list(c("Red","Green","Black"),matrix(c(1,3,5,7,9,11),nrow=2)
					,list("Python", "PHP", "Java"))
print("List:")
print(list_data)
names(list_data) = c("Color", "Odd numbers", "Language(s)")
print("List with column names:")
print(list_data)
Exercise - 22
  • Write a R program to create a list containing a vector, a matrix and a list and give names to the elements in the list. Access the first and second element of the list.
list_data &lt-list(c("CSE","CSM","IT"),matrix(c(1,0,1,0,1,0,0,0,1),nrow =3)
				,list("", "PHP", "Java"))
print("List:")
print(list_data)
names(list_data) = c("Color", "Odd numbers", "Language(s)")
print("List with column names:")
print(list_data)
print('1st element:')
print(list_data[1])
print('2nd element:')
print(list_data[2])
Exercise - 23
  • Write a R program to create a list containing a vector, a matrix and a list and remove the second element.
list_data &lt-list(c("Red","Green","Black"),matrix(c(1,3,5,7,9,11),nrow=2)
			,list("Python", "PHP", "Java"))
print("List:")
print(list_data)
print("Remove the second element of the list:")
list_data[2] = NULL
print("New list:")
print(list_data)
Exercise - 24
  • Write a R program to select second element of a given nested list.
x = list(list(0,2), list(3,4), list(5,6))
print("Original nested list:")
print(x)
e = lapply(x, '[[', 2)
print("Second element of the nested list:")
print(e)
Exercise - 25
  • Write a R program to merge two given lists into one list
n1 = list(1,2,3)
c1 = list("Red", "Green", "Black")
print("Original lists:")
print(n1)
print(c1)
print("Merge the said lists:")
mlist =  c(n1, c1)
print("New merged list:")
print(mlist)
Exercise - 26
  • Write a R program to create a list named s containing sequence of 15 capital letters, starting from ‘E’.
l = LETTERS[match("E", LETTERS):(match("E", LETTERS)+15)]
print("Content of the list:")
print("Sequence of 15 capital letters, starting from ‘E’-")
print(l)
Exercise - 27
  • Write a R program to assign new names "a", "b" and "c" to the elements of a given list
list1 = list(g1 = 1:10, g2 = "R Programming", g3 = "HTML")
print("Original list:")
print(list1)
names(list1) = c("one", "two", "three")
print("Assign new names 'one','two' and 'three' to the elements of the said list")
print(list1)

DATA FRAME PROGRAMS

Exercise - 11
  • Write a R program to create an empty data frame.
Program-1:
df = data.frame()
print("Structure of the empty dataframe:")
print(str(df))
print(df)

Program-2:
df = data.frame(Ints=integer(),
                Doubles=double(),
                Characters=character(),
                Logicals=logical(),
                Factors=factor(),
                stringsAsFactors=FALSE)
print("Structure of the empty dataframe:")
print(str(df))
print(df)
Exercise - 12
  • Write a R program to create a data frame from four given vectors
name = c('Rohit','Rahul','Virat','Shreyas','Surya','Risabh', 
				'Iyer','bishnoi','shami','Buvi','Bumrah')
avg = c(12.5, 9, 16.5, 12, 9, 20, 14.5, 0, 13.5, 8, 19)
age = c(31, 29, 33, 27, 25, 26, 24, 21, 29, 30, 29)
bowl = c('yes','no','yes','no','no','no','yes','yes', 'yes', 'yes','yes')
print("Original data frame:")
print(name)
print(avg)
print(age)
print(bowl)
df = data.frame(name, avg, age, bowl)  
print(df)
Exercise - 13
  • Write a R program to create a data frame using two given vectors and display the duplicated elements and unique rows of the said data frame.
a = c(10,20,10,10,40,50,20,30)
b = c(10,30,10,20,0,50,30,30)
print("Original data frame:")
ab = data.frame(a,b)
print(ab)
print("Duplicate elements of the said data frame:")
print(duplicated(ab))
print("Unique rows of the said data frame:")
print(unique(ab))
Exercise - 14
  • Write a R program to save the information of a data frame in a file and display the information of the file.
cricket_data = data.frame(
  name = c('Rohit','Rahul','Virat','Shreyas','Surya','Risabh','Iyer',
  				'bishnoi','shami','Buvi','Bumrah'),
 avg = c(12.5, 9, 16.5, 12, 9, 20, 14.5, 0, 13.5, 8, 19),
 age = c(31, 29, 33, 27, 25, 26, 24, 21, 29, 30, 29),
 bowl = c('yes','no','yes','no','no','no','yes', 'yes','yes','yes','yes')
)
print("Original dataframe:")
print(cricket_data)
write.csv(cricket_data, file = "my_cricket_team1.csv")
print(paste("Please go to the locatin and open and check file contents",getwd()))

ARRAYS & FACTORS PROGRAMS

Exercise - 8
  • Write a R program to combine three arrays so that the first row of the first array is followed by the first row of the second array and then first row of the third array.
  
num1 = rbind(rep("A",3), rep("B",3), rep("C",3))
print("num1")
print(num1)
num2 = rbind(rep("P",3), rep("Q",3), rep("R",3))
print("num2")
print(num2)
num3 = rbind(rep("X",3), rep("Y",3), rep("Z",3))
print("num3")
print(num3)
a = matrix(t(cbind(num1,num2,num3)),ncol=3, byrow=T)
print("Combine three arrays, taking one row from each one by one:")
print(a)
Exercise - 9
  • Write a R program to create a two-dimensional 5x3 array of sequence of even integers greater than 50.
a &lt- array(seq(from = 50, length.out = 15, by = 2), c(5, 3))
print("Content of the array:")
print("5×3 array of sequence of even integers greater than 50:")
print(a)
Exercise - 10
  • Write a R program to create an array using four given columns, three given rows, and two given tables and display the content of the array.
array1 =  array(1:30,dim=c(3,4,2))
print(array1)
Exercise - 28
  • Write a R program to find the levels of factor of a given vector.
v = c(1, 2, 3, 3, 4, NA, 3, 2, 4, 5, NA, 5)
print("Original vector:")
print(v)
print("Levels of factor of the said vector:")
print(levels(factor(v)))
Exercise - 29
  • Write a R program to create an ordered factor from data consisting of the names of months.
mons_v = c("March","April","January","November","January",
           "September","October","September","November","August","February",
           "January","November","November","February","May","August","February",
           "July","December","August","August","September","November","September",
           "February","April")
print("Original vector:")
print(mons_v)
f = factor(mons_v)
print("Ordered factors of the said vector:")
print(f)
print(table(f))
Exercise - 30
  • Write a R program to concatenate two given factor in a single factor.
f1 &lt- factor(sample(LETTERS, size=6, replace=TRUE))
f2 &lt- factor(sample(LETTERS, size=6, replace=TRUE))
print("Original factors:")
print(f1)
print(f2)
f = factor(c(levels(f1)[f1], levels(f2)[f2]))
print("After concatenate factor becomes:")
print(f)

ADDITIONAL PROGRAMS

1. Write R program to find whether number is positive(simple if)

data &lt- as.integer(readline(prompt = "Enter a number: "))

if (data &gt 0) {
  print("Positive number")
}


2. Write  R program to find whether given number is positive or negative(if-else)

data &lt- as.integer(readline(prompt = "Enter a number: "))

if (data &gt 0) {
  print("Positive number")
} else {
  print("negative number")
}


3. Write R program to find whether given number is positive, negative or zero(else-if-ladder)
data &lt- as.integer(readline(prompt = "Enter a number: "))

if (data &gt 0) {
  print("Positive number")
} else if (data == 0) {
  print("zero")
} else {
  print("Negative number")
}


4. Write R program to print "R programming lab" ten times using while, for, repeat.until
For loop

for (x in 1:10) {
  print("R_programming_lab”)
}
While 
i &lt- 1
while (i &lt 10) {
 print("R_programming_lab”)
       i = i + 1
}
Repeat
i &lt- 1
  repeat {
  
   print("R programming lab")
     
   i &lt- i + 1
   if(i &gt5) {
      break
   }
}



5. Write R program to find factorial of given number using while, for, repeat until

FOR LOOP 
num = as.integer(readline(prompt="Enter a number: "))
factorial = 1
if(num &lt 0) {
  print("Sorry, factorial does not exist for negative numbers")
} else if(num == 0) {
  print("The factorial of 0 is 1")
} else {
  for(i in 1:num) {
    factorial = factorial * i
  }
  print(paste("The factorial of", num ,"is",factorial))
}
WHILE LOOP 
n= as.integer(readline(prompt="Enter a number: "))
factorial = 1
  if(n==0 | n==1){
    factorial &lt- 1
  } else{
    while(n &gt= 1){
      factorial &lt- factorial * n
      n &lt- n-1
    }
  }
print(paste("The factorial of", num ,"is",factorial))
REPEAT UNTILL 

n= as.integer(readline(prompt="Enter a number: "))
factorial =1
  if(n==0 | n==1){
    factorial &lt- 1
  } else{
    repeat{
  factorial &lt- factorial * n
      n &lt- n-1
      if(n &lt 1) {
        break
      }
    }
  }
print(paste("The factorial of", num ,"is",factorial))



6. Write R program to find sum of digits of a number using while, for, repeat until.
While loop
n = as.integer(readline(prompt = "Enter a number :"))
s = 0

while (n &gt 0) {
  r = n %% 10
  s = s + r
  n = n %/% 10
}
print(paste("Sum of the digits is :", s))

For loop 
n = as.integer(readline(prompt = "Enter a number :"))
s = 0

for(i in 1:n) {
  r = n %% 10
  s = s + r
  n = n %/% 10
}
print(paste("Sum of the digits is :", s))

REPEAT UNTILL 
n= as.integer(readline(prompt="Enter a number: "))
factorial = 1
  if(n==0 | n==1){
    factorial &lt- 1
  } else{
    repeat{
  factorial &lt- factorial * n
      n &lt- n-1
      if(n==1) {
        break
      }
    }
  }
print(paste("The factorial of", num ,"is",factorial))

7. Write R program to read number and print corresponding day name in a week
A) IF ELSE IF LADDER 
B) SWITCH CASE 
A) IF ELSE IF LADDER 
week= as.integer(readline(prompt="Enter a number: "))
if(week == 1)
{
  print("Monday");
}else if(week == 2){
  print("Tuesday");
}else if(week == 3){
  print("Wednesday");
}else if(week == 4){
  print("Thursday");
}else if(week == 5){
  print("Friday");
}else if(week == 6){
  print("Saturday");
}else if(week == 7){
  print("Sunday");
}else{
  print("Invalid Input! Please enter week number between 1-7.");
}

b) switch case 


val &lt- switch(as.integer(readline(prompt = "Enter a number :"))
              ,
              "MONDAY",
              "TUESDAY",
              "WENDESDAY",
              "THURSDAY",
              "FRIDAY",
              "SATURDAY",
              "SUNDAY"
)
print(val)

ADDITIONAL PROGRAMS


PIE CHARTS IN R

netaji gandi

NPTEL Programming in Java Jan 2024 Week 11

  Week 11 : Programming Assignment 1 Due on 2024-04-11, 23:59 IST The following code is missing some information needed to run the code. Add...