Write a program to sort the elements of the array - Python

Categories:
Viewed: 4 - Published at: a few seconds ago

Write a program to sort the elements of the array

``````arr = [5, 2, 8, 7, 1];
temp = 0;
print("Elements of original array: ");
for i in range(0, len(arr)):
print(arr[i], end=" ");

for i in range(0, len(arr)):
for j in range(i+1, len(arr)):
if(arr[i] > arr[j]):
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;

print();

print("Elements of array sorted in ascending order: ");
for i in range(0, len(arr)):
print(arr[i], end=" ");
``````

Write a program to check if the given number is a disarium number

``````def calculateLength(n):
length = 0;
while(n != 0):
length = length + 1;
n = n//10;
return length;

num = 175;
rem = sum = 0;
len = calculateLength(num);

n = num;

while(num > 0):
rem = num%10;
sum = sum + int(rem**len);
num = num//10;
len = len - 1;

if(sum == n):
print(str(n) + " is a disarium number");
else:
print(str(n) + " is not a disarium number");
``````

Write a program to print all disarium numbers between 1 and 100

``````def calculateLength(n):
length = 0;
while(n != 0):
length = length + 1;
n = n//10;
return length;

def sumOfDigits(num):
rem = sum = 0;
len = calculateLength(num);

while(num > 0):
rem = num%10;
sum = sum + (rem**len);
num = num//10;
len = len - 1;
return sum;

result = 0;

print("Disarium numbers between 1 and 100 are");
for i in range(1, 101):
result = sumOfDigits(i);

if(result == i):
print(i),
``````
``````
``````

Write a program to add two matrices using nested loop

``````X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]

Y = [[5,8,1],
[6,7,3],
[4,5,9]]

result = [[0,0,0],
[0,0,0],
[0,0,0]]

# iterate through rows
for i in range(len(X)):
# iterate through columns
for j in range(len(X[0])):
result[i][j] = X[i][j] + Y[i][j]

for r in result:
print(r)
``````

Write a program to transpose a matrix using a nested loop

``````X = [[12,7],
[4 ,5],
[3 ,8]]

result = [[0,0,0],
[0,0,0]]

# iterate through rows
for i in range(len(X)):
# iterate through columns
for j in range(len(X[0])):
result[j][i] = X[i][j]

for r in result:
print(r)
``````