Beta
Table of Contents
The outline of your notebook will show up here. You can include headings in any text cell by starting a line with #
, ##
, ###
, etc., depending on the desired title hierarchy.
# Start coding here...
from array import *
#Creating a function that calculates the sum of an array.
def calculate_sum(arr):
result = sum(arr)
return result
#Creating a function that finds the max and min number of an array.
def find_max_min(arr):
max_num = max(arr)
min_num = min(arr)
return max_num, min_num
#Creating a function that finds the element wise sum of two arrays.
def element_wise_sum(arr1, arr2):
if len(arr1) != len(arr2):
raise ValueError("Arrays should have the same length.")
result = array('i')
for num in range(len(arr1)):
result.append(arr1[num] + arr2[num])
return result
#Creating a function that removes any repeating integers.
def remove_repeats(arr):
convert = set(arr)
array_convert = array('i', convert)
return array_convert
#Creating a function that sorts an array in ascending order.
def ascending_order(arr):
return sorted(arr)
#Creating a function that checks to see if an array is non-decreasing.
def non_decreasing(arr):
for i in range(len(arr) - 1):
if arr[i] > arr[i + 1]:
return False
return True
#Creating a function that calculates the mean of an array.
def calculate_mean(arr):
total = sum(arr)
mean = total / len(arr)
return mean
#Defining the arrays to be used in the functions.
array1 = array('i', [3,9,2,6,1,8,5])
array2 = array('i', [4,2,9,5,1,6,8])
array3 = array('i', [1,2,3,4,5])
array4 = array('i', [5,4,3,2,1])
array5 = array('i', [5,5,5,5,4])
#Printing the functions with the arrays plugged in.
print(f"Sum of array elements: {calculate_sum(array1)}")
print(f"Max and Min values are: {find_max_min(array2)}")
print(f"The elementwise sum of these two arrays are: {element_wise_sum(array3,array4)}")
print(f"Here is your array with no duplicates: {remove_repeats(array5)}")
print(f"This is the array in ascending order: {ascending_order(array2)}")
print(f"Is the array in non-decreasing order? {non_decreasing(array2)}")
print(f"The mean of the array is: {calculate_mean(array4)}")
# Function to calculate the sum of all elements in an array
def calculate_sum(arr):
total_sum = 0
for num in arr:
total_sum += num
return total_sum
# Function to find the maximum and minimum values in an array
def find_max_min(arr):
max_value = min_value = arr[0]
for num in arr[1:]:
if num > max_value:
max_value = num
if num < min_value:
min_value = num
return max_value, min_value
# Function to calculate the element-wise sum of two arrays with the same length
def calculate_elementwise_sum(arr1, arr2):
result = []
for i in range(len(arr1)):
result.append(arr1[i] + arr2[i])
return result
# Function to remove duplicate elements from an array, keeping only the unique elements
def remove_duplicates(arr):
result = []
for num in arr:
if num not in result:
result.append(num)
return result
# Function to sort the elements in an array in ascending order
def sort_array(arr):
return sorted(arr)
# Function to check if an array is sorted in non-descending order
def is_sorted(arr):
for i in range(1, len(arr)):
if arr[i] < arr[i-1]:
return False
return True
# Function to calculate the average (mean) of all elements in an array
def calculate_average(arr):
total_sum = 0
for num in arr:
total_sum += num
average = total_sum / len(arr)
return average
def main():
# Test cases
arr1 = [1, 2, 3, 4, 5]
arr2 = [6, 7, 8, 9, 10]
arr3 = [1, 2, 2, 3, 4, 4, 5]
arr4 = [5, 4, 3, 2, 1]
# Calculate sum
sum_result = calculate_sum(arr1)
print("Sum:", sum_result)
# Find maximum and minimum
max_value, min_value = find_max_min(arr1)
print("Max value:", max_value)
print("Min value:", min_value)
# Calculate element-wise sum
elementwise_sum = calculate_elementwise_sum(arr1, arr2)
print("Element-wise sum:", elementwise_sum)
# Remove duplicates
unique_elements = remove_duplicates(arr3)
print("Unique elements:", unique_elements)
# Sort array
sorted_array = sort_array(arr4)
print("Sorted array:", sorted_array)
# Check if array is sorted
is_sorted_result = is_sorted(arr1)
print("Is array sorted?", is_sorted_result)
# Calculate average
average = calculate_average(arr1)
print("Average:", average)
if __name__ == "__main__":
main()
from array import *
def calculate_sum():
arr = array('i', [])
x = int(input("Please enter the array size: "))
print("Enter %d elements: " % x)
for i in range(x):
n = int(input())
arr.append(n)
sum = 0
for element in arr:
sum += element
print("The sum of all elements in the array is: ", sum)
calculate_sum()
def find_max_min():
arr = array('i', [])
x = int(input("Please enter the array size: "))
print("Enter %d elements: " % x)
for i in range(x):
n = int(input())
arr.append(n)
print(arr)
max_value = arr[0]
min_value = arr[0]
for a in arr:
if a > max_value:
max_value = a
print("The maximum values in the array is: ", max_value)
for a in arr:
if a < min_value:
min_value = a
print("The minimum values in the array is: ", min_value)
find_max_min()
def calculate_elementwise_sum():
arr1 = array('i', [])
arr2 = array('i', [])
x = int(input("Please enter the array size for both array: "))
print("Enter %d elements in first array: " % x)
for i in range(x):
n = int(input())
arr1.append(n)
print("Enter %d elements in second array: " % x)
for i in range(x):
n = int(input())
arr2.append(n)
if len(arr1) != len(arr2):
return None
result = []
for i in range(len(arr1)):
result.append(arr1[i] + arr2[i])
print(arr1)
print(arr2)
print("The element-wise sum of both array are: ", result)
calculate_elementwise_sum()
def remove_duplicates(arr):
unique_elements = set()
result = []
for num in arr:
if num not in unique_elements:
unique_elements.add(num)
result.append(num)
return result
# Test the function with different input arrays
array1 = [3, 9, 2, 6, 1, 8, 5, 4, 2, 9, 5, 1, 6, 8]
print(array1)
print("Duplicates remove: ", remove_duplicates(array1))
def sort_array():
arr = array('i', [])
x = int(input("Please enter the array size: "))
print("Enter %d elements: " % x)
for i in range(x):
n = int(input())
arr.append(n)
print("The sorted array: ", sorted(arr))
sort_array()
def is_sorted():
arr = array('i', [])
x = int(input("Please enter the array size: "))
print("Enter %d elements: " % x)
for i in range(x):
n = int(input())
arr.append(n)
for i in range(1, len(arr)):
if arr[i] < arr[i-1]:
return False
return True
# Check if the array is sorted
if is_sorted():
print("The array is sorted in non-decreasing order.")
else:
print("The array is not sorted in non-decreasing order.")
def calculate_average():
arr = array('i', [])
x = int(input("Please enter the array size: "))
print("Enter %d elements: " % x)
for i in range(x):
n = int(input())
arr.append(n)
if not arr:
return None
total = 0
for num in arr:
total += num
average = total / len(arr)
print("The average (mean) of all the elements in the array is: ", average)
calculate_average()
import array
# Test cases.
array1 = array.array("i", [3, 9, 2, 6, 1, 8, 5])
array2 = array.array("i", [4, 2, 9, 5, 1, 6, 8])
array3 = array.array("i", [1, 2, 3, 4, 5])
array4 = array.array("i", [5, 4, 3, 2, 1])
""" 1. This function accepts an array of integers and returns the sum of the elements."""
def sum_of_arr(int_arr):
return f"The sum is {sum(int_arr)}"
print(sum_of_arr(array1))
print(sum_of_arr(array2))
print(sum_of_arr(array3))
print(sum_of_arr(array4))
"""2. This function accepts an array of integers and returns the maximum and minimum values of the elements."""
def min_max_of_arr(int_arr):
return f"The minimum value is {min(int_arr)} and the maximum value is {max(int_arr)}"
print(min_max_of_arr(array1))
print(min_max_of_arr(array2))
print(min_max_of_arr(array3))
print(min_max_of_arr(array4))
"""3. This function accepts 2 arrays of integers of equal length and returns their element-wise sum."""
def element_wise_sum_of_arr(int_arr1, int_arr2):
# Array to hold the values of the element-wise sums.
sum_arr = array.array("i", [])
# Get the index and value for each element of arr1.
for i, v in enumerate(int_arr1):
# Add the value of the current element of arr1 to the value at the same index of arr2 and append to sum_arr.
element_sum = v + int_arr2[i]
sum_arr.append(element_sum)
return f"The element-wise sums are: {sum_arr}"
print(element_wise_sum_of_arr(array1, array2))
print(element_wise_sum_of_arr(array3, array4))
"""4. This function accepts an array of integers and removes all duplicate elements."""
def remove_duplicates(int_arr):
# Array to hold the unique values.
duplicates_removed_arr = array.array("i", [])
# Iterate through int_arr and if the element isn't in duplicate_removed_arr, add it.
for num in int_arr:
if num not in duplicates_removed_arr:
duplicates_removed_arr.append(num)
return(f"The array with duplicates removed is: {duplicates_removed_arr}")
print(remove_duplicates([1,2,1,5,6,2]))
print(remove_duplicates([1,1,1,2,-1,5,1,-1]))
"""5. This function accepts an array of integers and sorts it in ascending order."""
def sort_acsending(int_arr):
return f"Sorted ascending: {sorted(int_arr)}"
print(sort_acsending(array1))
print(sort_acsending(array2))
print(sort_acsending(array3))
print(sort_acsending(array4))
"""6. This function accepts an array of integers and returns True if it is sorted in non-decreasing order."""
def is_non_decreasing(int_arr):
# Compare int_arr to the sorted int_arr.
return f"This array is sorted in non-decreasing order: {int_arr.tolist() == sorted(int_arr.tolist())}"
print(is_non_decreasing(array1))
print(is_non_decreasing(array2))
print(is_non_decreasing(array3))
print(is_non_decreasing(array4))
"""7. This function accepts an array of integers and returns the average of the elements."""
def average_of_arr(int_arr):
arr_sum = sum(int_arr)
average = arr_sum / len(int_arr)
return f"The average is {round(average, 2)}"
print(average_of_arr(array1))
print(average_of_arr(array2))
print(average_of_arr(array3))
print(average_of_arr(array4))
"""Module03_assignment01
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1AUOQ8_8noiWp_5SGbLB4no5Y1tKH52Rp
"""
# Helper method to take an input array from user
def take_array_input():
input_array = []
# take number of elements in array
n = int(input("Number of elements in array: "))
# iterating till the range( 0, n)
for i in range(0, n):
print("Enter element-{}: ".format(i+1))
element = int(input())
input_array.append(element) # adding the element
return input_array
"""**1. Write a Python program that takes an array of integers as input and calculates the sum of all the elements in the array.**
**Algorithm of calculating the sum of all the elements in the array:**
1. Initialize a variable, sum = 0
2. For each element in Array, do
sum= sum + element
3. Return sum as the total summation of given array.
"""
# find sumation of an integer array
def find_sum(arr):
sum = 0
for element in arr:
sum = sum + element
return sum
# Takes array input from user and calculate sum
print('Enter an array')
arr = take_array_input()
sum = find_sum(arr)
print('Given array:', arr)
print('Sum of the given array:', sum)
"""**2. Write a Python program that takes an array of integers as input and finds the maximum and minimum values in the array.**
**Algorithm of finding the maximum value in the array:**
1. Initialize a variable, max = arr[0]
2. For each element of array do
if current_element > max;
max = current_element,i
3. return max as the maximum number of the given array.
"""
#Find max value of the array
def find_max(arr):
max = arr[0]
for i in arr:
if (i > max):
max = i
return max
# Takes array input from user and finds maximum number
print('Enter an array')
arr = take_array_input()
max = find_max(arr)
print('Given array:', arr)
print('Maximum value of the given array', max)
"""**Algorithm of finding the minimum value in the array:**
1. Initialize a variable,
min = arr[0]
2. For each element of array do if current_element, i < min;
min = current element, i
3. return min
"""
#Find min value of the array
def find_min(arr):
min = arr[0]
for i in arr:
if(i < min):
min = i
return min
# Takes array input from user and finds minimum number
print('Enter an array')
arr = take_array_input()
min = find_min(arr)
print('Given array:', arr)
print('Minimum value of given array:', min)
"""**3. Write a Python program that takes two arrays of integers as input and calculates their element-wise sum. The two arrays should have the same length.**
**Algorithm of calculating the element-wise sum of the given two arrays.**
1. Creare a new empty array, new_array
2. for index from 0 to length of a given array
- new_array.append = element at index of given array_A + element at index of given array_B
3. Return new_array as the summation of the indexes of two arrays.
"""
678
# this methid calculates the element-wise sime of the two arrays of integers
def find_elementwiseSum(array_A, array_B):
if(len(array_A) != len(array_B)):
print('Give array should be in same size/length, try again')
return
new_array = []
for i in range (0, len(array_A)):
new_array.append(array_A[i] + array_B[i])
return new_array
# Takes array input from user and calculate element-wise sum
print('Enter first array')
arr_A = take_array_input()
print('Enter second array')
arr_B = take_array_input()
sum_of_array = find_elementwiseSum(arr_A, arr_B)
print('Given first array:',arr_A )
print('Given second array:', arr_B)
print('Element wise sum of given two arrays:',sum_of_array)
"""**4. Write a Python program that takes an array of integers as input and removes all duplicate elements, keeping only the unique elements in the array.**
**Algorithm of removing all duplicate elements in the array**
1. Create a new empty array, new_array
2. for each element in given_array
- if element not in new_array:
- - add element to the new_array
3. Return new_array as array with no duplicate element.
"""
# This method removes the duplication and makes the new array
def remove_duplicate(given_arr):
new_array = []
for element in given_arr:
if element not in new_array:
new_array.append(element)
return new_array
#Takes array input from user and remove duplicate elements
print('Enter an array')
arr = take_array_input()
array_without_duplicate = remove_duplicate(arr)
print('Given array:', arr)
print('Array after removing duplicate:', array_without_duplicate)
"""**5. Write a Python program that takes an array of integers as input and sorts the elements in ascending order.**
**Algorithm of sorting the elements in ascending order**
1. Take array of integer as given array
2. Call python builtin sort method
3. return the given array as sorted array
"""
# This method sorts the elements in ascending order
def sort_array(array):
array.sort()
return array
# Takes array input from user and sorts the given array
print('Enter an array')
arr = take_array_input()
sorted_array = sort_array(arr)
print('Given array:', arr)
print('List in Ascending Order: ', sorted_array)
"""**6. Write a Python program that takes an array of integers as input and checks if the array is sorted in non-decreasing order.**
**Algorithm of checking if the array is sorted in non-decreasing order.**
1. For index from 0 to the length of given_array-1
- if A[index] > A[index +1]
- return False
2. Then return True.
"""
# This method checks the sorted array in non-decreasing order
def is_non_decreasing(A):
for i in range(0, (len(A)-1)):
if (A[i]) > (A[i+1]):
return False
return True
# Takes array input from user and checkes wheather the given array is non decreasing or not
print('Enter an array')
arr = take_array_input()
is_non_decreasing_order = is_non_decreasing(arr)
print('Given array:', arr)
print('Check if it is in non decreasing order:', is_non_decreasing_order)
"""**7. Write a Python program that takes an array of integers as input and calculates the average (mean) of all the elements in the array.**
**Algorithm of calculating of the average(mean) of all the elements in the array.**
1. Take an array input from user.
2. Sum up all the elements of the array.
3. Divide the sum by the length of the array.
"""
# This method finds the average of the array
def find_average(A):
sum = find_sum(A)
return sum/len(A)
# Takes array input from user and finds the average
print('Enter an array')
arr = take_array_input()
average_array = find_average(arr)
print('Given array:', arr)
print('The average of the array is:', average_array )
#imports array module
import array
#definines values
arr_1 = array.array('i', [3, 9, 2, 6, 1, 8, 5])
sum_array = sum(arr_1)
#displays results
print('The sum of the array is:', sum_array)
#imports array module
import array
#defines values
arr_1 = array.array('i', [4, 2, 9, 5, 1, 6, 8])
max_number = arr_1[0]
#method to calculate greatest number in the given array
for num in arr_1:
if num > max_number:
max_number = num
#displays the result
print('The greatest number in the array is:', max_number)
#imports array module
import array
#defines values
arr_1 = array.array('i', [1, 2, 3, 4, 5])
arr_2 = array.array('i', [2, 4, 6, 8, 10])
#formats arrays for easy viewing
list_1 = arr_1.tolist()
list_2 = arr_2.tolist()
#displays starting arrays
print('Array 1:', list_1)
print('Array 2:', list_2)
#calculates element-wise sum of the arrays
ews = []
for x in range(0, len(arr_1)):
ews.append(arr_1[x] + arr_2[x])
#displays the element-wise sum of the two arrays
print('The element-wise sum of the two arrays is:', str(ews))
#imports array module
import array
#defines values
arr_1 = array.array('i', [5, 4, 3, 2, 1, 3, 5])
#formats array for easy viewing
list_1 = arr_1.tolist()
#Displays base array and total number of elements
print('Base array:', list_1)
print('Total elements in array:', len(arr_1))
#calculates unique elements
unique_array = list(set(list_1))
#displays unique elements
print('Unique elements in array:', unique_array)
#imports array module
import array
#defines value
arr_1 = array.array('i', [8, 5, 3, 9, 7, 15, 11])
#formats array for easy viewing
list_1 = arr_1.tolist()
#displays base array and total number of elements
print('Base array:', list_1)
print('Total elements in array:', len(arr_1))
#sorts the array in assending order
list_1.sort()
#displays the sorted array
print('Array in assending order:', list_1)
# -*- coding: utf-8 -*-
"""martin3.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/12aV8zpuQMs7x9tG2Z-eL4VawjnYL7Y-V
"""
#sum
import array as array
import numpy as np
def arraySum():
arr = array.array('i')
userInput = input("Do you wish to make an array? Please enter Yes to continue or No to exit")
while userInput == "Yes":
arr.append(int(input("Enter one integer: ")))
userInput = input("Do you wish to continue making an array? Please enter Yes to continue or No to exit: ")
if userInput == "Yes":
continue
else:
break
sum = 0
for i in range(len(arr)):
sum = sum + arr[i]
print(sum)
#using numpy library
a = int(input("Enter the size of the array: " ))
l = []
for i in range(a):
i = int(input("Enter the first element of the array: "))
l.append(i)
arr=np.array(l)
print(arr)
print(np.sum(arr))
arraySum()
#maximum
import array as array
import numpy as np
def maximumArray():
arr = array.array('i')
userInput = input("Do you wish to make an array? Please enter Yes to continue or No to exit")
while userInput == "Yes":
arr.append(int(input("Enter one integer: ")))
userInput = input("Do you wish to continue making an array? Please enter Yes to continue or No to exit: ")
if userInput == "Yes":
continue
else:
break
max = arr[0]
for i in range(1, len(arr)):
if arr[i]>max:
max = arr[i]
print(max)
#using numpy library
a = int(input("Enter the size of the array: " ))
l = []
for i in range(a):
i = int(input("Enter the first element of the array: "))
l.append(i)
arr=np.array(l)
print(arr)
print(np.max(arr))
maximumArray()
#minimum
import array as array
import numpy as np
def minimumArray():
arr = array.array('i')
userInput = input("Do you wish to make an array? Please enter Yes to continue or No to exit")
while userInput == "Yes":
arr.append(int(input("Enter one integer: ")))
userInput = input("Do you wish to continue making an array? Please enter Yes to continue or No to exit: ")
if userInput == "Yes":
continue
else:
break
min = arr[0]
for i in range(1, len(arr)):
if arr[i]<min:
min = arr[i]
print(min)
#using numpy library
a = int(input("Enter the size of the array: " ))
l = []
for i in range(a):
i = int(input("Enter the first element of the array: "))
l.append(i)
arr=np.array(l)
print(arr)
print(np.min(arr))
minimumArray()
#Sum of two arrays
import array as array
import numpy as np
def sumOfTwo():
arr1 = array.array('i')
userInput = input("Do you wish to make an array? Please enter Yes to continue or No to exit")
while userInput == "Yes":
arr1.append(int(input("Enter one integer: ")))
userInput1 = input("Do you wish to continue making an array? Please enter Yes to continue or No to exit: ")
if userInput1 == "Yes":
continue
else:
break
arr2 = array.array('i')
userInput2 = input("Do you wish to make a second array? Please enter Yes to continue or No to exit")
while userInput2 == "Yes":
arr2.append(int(input("Enter one integer: ")))
userInput2 = input("Do you wish to continue making an array? Please enter Yes to continue or No to exit: ")
if userInput2 == "Yes":
continue
else:
break
sum1 = 0
for i in range(len(arr1)):
sum1 = sum1 + arr1[i]
sum2 = 0
for i in range(len(arr2)):
sum2 = sum2 + arr2[i]
print("The sum of your arrays is: ", sum1+sum2)
#using numpy library
a = int(input("Enter the size of arrays 1 & 2: " ))
l = []
m = []
for i in range(a):
i = int(input("Enter the element you wish of array 1: "))
l.append(i)
for i in range(a):
j = int(input("Enter the element you wish of array 2: "))
m.append(j)
arr1=np.array(l)
arr2=np.array(m)
print(arr1)
print(arr2)
print(np.sum(arr1) + np.sum(arr2))
sumOfTwo()
#duplicate elements NB THIS CODE DOES NOT WORK I JUST TRIED WITHOUT NUMPY NB
import array as array
def duplicateArray():
arr = array.array('i')
userInput = input("Do you wish to make an array? Please enter Yes to continue or No to exit")
while userInput == "Yes":
arr.append(int(input("Enter one integer: ")))
userInput = input("Do you wish to continue making an array? Please enter Yes to continue or No to exit: ")
if userInput == "Yes":
continue
else:
break
final_arr = array.array('i', [])
for i in range(len(arr)):
for i in range(len(arr)):
if final_arr[i] != arr [i]:
final_arr.append(arr[i])
else:
continue
print(final_arr)
duplicateArray()
import array as array
#elements = int(input("Enter a list of integers seperated by spaces: "))
arr = array.array('i')
userInput = input("Do you wish to make an array? Please enter Yes to continue or No to exit")
while userInput == "Yes":
arr.append(int(input("Enter one integer: ")))
userInput = input("Do you wish to continue making an array? Please enter Yes to continue or No to exit: ")
if userInput == "Yes":
continue
else:
break
x = len(arr)
import numpy as np
a = int(input("Enter the size of the array: " ))
l = []
for i in range(a):
i = int(input("Enter the first element of the array: "))
l.append(i)
arr=np.array(l)
print(arr)
print(np.sum(arr))
print(np.max(arr))
print(np.min(arr))
#sum of two arrays
import numpy as np
a = int(input("Enter the size of arrays 1 & 2: " ))
l = []
m = []
for i in range(a):
i = int(input("Enter the element you wish of array 1: "))
l.append(i)
for i in range(a):
j = int(input("Enter the element you wish of array 2: "))
m.append(j)
arr1=np.array(l)
arr2=np.array(m)
print(arr1)
print(arr2)
print(np.sum(arr1) + np.sum(arr2))
#duplicates and sorting in an array
import numpy as np
def duplicateSorting():
a = int(input("Enter the size of the array: " ))
l = []
for i in range(a):
i = int(input("Enter the first element of the array: "))
l.append(i)
arr=np.array(l)
new_arr=np.unique(arr)
sorted_array = np.sort(arr)
print(new_arr)
print(sorted_array)
duplicateSorting()
#nondecreasing order NB THIS CODE COMPILES ONLY PARTLY NB
import numpy as np
def nonDecreasing():
a = int(input("Enter the size of the array: " ))
l = []
for i in range(a):
i = int(input("Enter the first element of the array: "))
l.append(i)
arr=np.array(l)
for i in range(a):
if arr[i+1] > arr[i]:
print(arr)
nonDecreasing()
#average
import numpy as np
def average():
a = int(input("Enter the size of the array: " ))
l = []
for i in range(a):
i = int(input("Enter the first element of the array: "))
l.append(i)
arr=np.array(l)
print(arr)
print(np.sum(arr)/a)
average()
import numpy as np
#Fifth Question
numbers = input("Enter a list of numbers separated by spaces and they'll be "
"sorted into ascending order: ").split(" ")
#Convert strings to integers
numbers = [int(num) for num in numbers]
#Sort the numbers into ascending order
numbers.sort()
#Convert the list into an array
array_of_numbers = np.array(numbers)
#Print the array
print(array_of_numbers)