In: Computer Science
1. Write a Python program that performs the following: 2. Defines an array of integers from 1 to 10. The numbers should be filled automatically without the need for user inputs 3. Find the sum of the numbers that are divisible by 3 (i.e., when a number is divided by 3, the remainder is zero) 4. Swap the positions of the maximum and minimum elements in the array. First, you need to find the maximum element as shown in the class, then find the minimum element, finally perform the swap operation(don't assume the first element is the smallest and the last element is the largest). 5. Create a main() function to call your defined functions and print your results.
Source Code:
Output:
Code in text format (See above images of code for indentation):
#function to fill array
def fill_array():
a=[]
#fill array with 1 to 10
for i in range(10):
a.append(i+1)
#return a
return a
#function to calculate sum
def sumOf3(a):
sum=0
for i in range(10):
#check for divisible by 3
if(a[i]%3==0):
#calculate sum
sum+=a[i]
#return sum
return sum
#function to swap maximum and minimum
def swap(a):
max=0
maxind=0
minind=0
min=11
#find max min and their indexes
for i in range(len(a)):
if(max<a[i]):
max=a[i]
maxind=i
if(min>a[i]):
min=a[i]
minind=i
#swapping
t=a[maxind]
a[maxind]=a[minind]
a[minind]=t
return a
#main function
def main():
#fuctioncalls and print results
a=fill_array()
print("The array is: ",a)
s=sumOf3(a)
print("The sum of the numbers that are divisible by 3 is:
",s)
a=swap(a)
print("The array after swapping: ",a)
#function call to main
main()