Posts

Showing posts from December, 2021

BUBBLE SORT

 Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order. Example:   First Pass:   ( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1.  ( 1 5 4 2 8 ) –>  ( 1 4 5 2 8 ), Swap since 5 > 4  ( 1 4 5 2 8 ) –>  ( 1 4 2 5 8 ), Swap since 5 > 2  ( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them. Second Pass:   ( 1 4 2 5 8 ) –> ( 1 4 2 5 8 )  ( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2  ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )  ( 1 2 4 5 8 ) –>  ( 1 2 4 5 8 )  Now, the array is already sorted, but our algorithm does not know if it is completed. The algorithm needs one whole pass without any swap to know it is sorted. Third Pass:   ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )  ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )  ( 1 2 4 5 8 ) –> ( 1 2 4

Python Program to Find HCF or GCD

  Python Program to Find HCF or GCD In this example, you will learn to find the GCD of two numbers using function and loop. The highest common factor (H.C.F) or greatest common divisor (G.C.D) of two numbers is the largest positive integer that perfectly divides the two given numbers. For example, the H.C.F of 12 and 14 is 2. Source Code: Using Loops    # Python program to find H.C.F of two numbers # define a function def compute_hcf(x, y): # choose the smaller number if x > y: smaller = y else: smaller = x for i in range(1, smaller+1): if((x % i == 0) and (y % i == 0)): hcf = i return hcf num1 = int(input("Enter the first number: ")) num2 = int(input("Enter the second number: ")) print("The H.C.F. is", compute_hcf(num1, num2))    Output: D:\PROGRAMMING\PYTHON>python Hcf.py Enter the first number: 8 Enter the second number: 12 The H.C.F. is 4 D:\PROGRAMMING\PYTHON>python Hcf.py Enter the fi

Python Program to Find the Factors of a Number

  Python Program to Find the Factors of a Number   # Python Program to find the factors of a number # This function computes the factor of the argument passed l=[] # To store values list is used def print_factors(x): print("The factors of",x,"are:") for i in range(1, x + 1): if x % i == 0: l.append((i,x/i)) return l num = int(input("Enter the number: ")) print(print_factors(num))   Output: Enter the number: 320 The factors of 320 are: [(1, 320.0), (2, 160.0), (4, 80.0), (5, 64.0), (8, 40.0), (10, 32.0), (16, 20.0), (20, 16.0), (32, 10.0), (40, 8.0), (64, 5.0), (80, 4.0), (160, 2.0), (320, 1.0)]  Note: To find the factors of another number, change the value of num . In this program, the number whose factor is to be found is stored in num , which is passed to the print_factors() function. This value is assigned to the variable x in print_factors() . In the function, we use the for loop to iterate from i equal to x . If x is perfectly divisi