In: Computer Science
Question 3
You should form the list of integers with your student ID. The numbers are generated as follows:
Number |
Based on your student ID number, formed by its … |
a |
1 st and 2nd digits |
b |
2 nd and 3rd digits |
c |
3rd and 4th digits |
d |
4th and 5th digits |
e |
5th and 6th digits |
f |
6th and 7th digits |
g |
7th and 8th digits |
For example, the student ID is 19563755A.
Values of a to g are: 19, 95, 56, 63, 37, 75, 55
Sort them using insertion sort. Show all the steps.
#Note:
For this problem using Python language.
All work has done it creates number only alphabets never assign.
Theory
List:
The list is a collection of element which is ordered also unordered and changeable. It also allow duplicate values.
Solution:
Algorithm:
1. Start
2. Get input from user
3. Seperate the user id and store into list namely values.
4. Create function for concate the adjecent numbers in values list.
5. After concatenation add this numbers in numbers list.
6. display numbers list
6. Create function for insertion sort of numbers list
7. After sorting display sorting list.
8. End
Code:
#get input from user
studentID=input("Enter student id ")
# Its seperate the user id and
values=[int(i) for i in studentID]
numbers=[]
i=0
j=1
# function for concate numbers
def numConcat(num1, num2):
# find number of digits in num2
digits = len(str(num2))
# add zeroes to the end of num1
num1 = num1 * (10 ** digits)
#condition check for first element
if(num1==0):
pass
# add num2 to num1
else:
num3= num1 + num2
#add concated numbers in numbers list
numbers.append(num3)
# function for insertion sorting of numbers list
def insertionSort(arr):
# Traverse through 1 to len(arr)
for i in range(1, len(arr)):
key = arr[i]
# Move elements of arr[0..i-1], that are
# greater than key, to one position ahead
# of their current position
j = i - 1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
#print sorted list
print("Sorted list is:")
print(arr)
#i is for first and j is for next element
while(i<j and j<len(values)):
first=values[i]
second=values[j]
#pass adjecent numbers to function
numConcat(first, second)
i=i+1
j=j+1
print("The values are:")
print(numbers)
#call insertionSort() method
insertionSort(numbers)
Output: