0% found this document useful (0 votes)
47 views

Arrays Answers Python

Uploaded by

shreekeerthykk
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views

Arrays Answers Python

Uploaded by

shreekeerthykk
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

ARRAYS

Program to find all pairs in Python


def find_pairs(arr, target_sum):
pairs = []
for i in range(len(arr)):
for j in range(i+1, len(arr)):
if arr[i] + arr[j] == target_sum:
pairs.append((arr[i], arr[j]))
return pairs

arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


target_sum = 12
result = find_pairs(arr, target_sum)
print("All pairs Whose sum is equal to ",target_sum," is:
\n",result)

Python Program to check two


arrays are equal or not
arr1=[1,2,3,4,5]
arr2=[1,3,4,5,7]
if len(arr1) == len(arr2):
print("array is equal")
else:
print("array is not equal")

Python Program to find largest and smallest


number in an array
arr = []
n = int(input("enter size of array : "))
for x in range(n): # USER INPUT
x=int(input("enter element of array : "))
arr.append(x)
largest = arr[0]
smallest = arr[0]
for i in range(n):
if arr[i]>largest:
largest = arr[i]
if arr[i]<smallest:
smallest = arr[i]
print(f"largest element in array is {largest}")
print(f"smallest element in array is {smallest}")

Python Program to print second largest number in an array

import array
arr = []
n = int(input("enter size of array : "))
for x in range(n):
x=int(input("enter element of array : "))
arr.append(x)
sorted_array = sorted(array.array('i', arr))
for i in range(len(arr)-1, 0, -1):
if sorted_array[i]!=sorted_array[i-1]:
print(f"second largest element is {sorted_array[i-1]}")
break

Python Program to find two largest number in an


array
import array
arr = []
n = int(input("enter size of array : "))
for x in range(n):
x=int(input("enter element of array : "))
arr.append(x)
sorted_array = sorted(array.array('i', arr))
for i in range(len(arr)-1, 0, -1):
if sorted_array[i]!=sorted_array[i-1]:
print(f"First two largest element of array is {sorted_array[i-1]} and {sorted_array[i]}")
break

EXPLANATION:

1. for i in range(len(arr)-1, 0, -1):: This loop iterates backward through


the sorted array, starting from the second last element and ending at
index 1.
2. if sorted_array[i]!=sorted_array[i-1]:: This condition checks if the
current element is not equal to the previous element. This indicates that
the current element is the largest and the previous element is the second
largest.
3. print(f"First two largest element of array is {sorted_array[i-1]} and
{sorted_array[i]}"): This line prints the first two largest elements of the
array using formatted string literals ( f-strings).

Python Program to remove duplicate elements


from array
import array
arr, count = [],[]
n = int(input("enter size of array : "))
for x in range(n):
count.append(0)
x=int(input("enter element of array : "))
arr.append(x)
print("Array elements after removing duplicates")
for x in range(n):
count[arr[x]]=count[arr[x]]+1
if count[arr[x]]==1:
print(arr[x])
EXPLANATION:
1. count[arr[x]]=count[arr[x]]+1: This line increments the count of the
element arr[x] by 1.
2. if count[arr[x]]==1:: This condition checks if the count of the element
arr[x] is equal to 1, indicating that it's the first occurrence of that
element.
3. print(arr[x]): This line prints the element arr[x], which is the first
occurrence of the element in the array.

Python code to print an array(list) in reverse


order using while loop
arr = [1, 2, 3, 4, 5]
length = len(arr)
index = length - 1

while index >= 0:


print(arr[index])
index -= 1

Python code to add an element at the end of


array(list)
arr = [1,2,3,4,5]num=int(input("Enter a number to insert in array at
end :"))
# adding element at the end of the array(list)
arr.append(num)print("Array after inserting",num,"at end",arr)

Python code to insert an element at a given


location of an array(list)
arr = [1, 2, 3, 4, 5]
num=int(input("Enter a number to insert in array : "))
index=int(input("Enter a index to insert value : "))
if index >= len(arr):
print("please enter index smaller than",len(arr))
else:
# insering element ‘num’ at ‘index’ position
arr.insert(index, num)
print("Array after inserting",num,"=",arr)

PYTHON CODE TO DELETE AN ELEMENT


FROM END OF AN ARRAY
arr = [1, 2, 3, 4, 5]

if len(arr) > 0:

arr.pop() # Removes the last element from the array

print("Array after deleting the last element:", arr)

else:

print("Array is empty, cannot delete an element.")

Python code to delete a given element of an


array(list)
#taking input to fix the size of the array
size=int(input("Enter the number of elements you want in array: "))
arr=[]
# adding elements to the array
for i in range(0,size):
elem=int(input("Please give value for index "+str(i)+": "))
arr.append(elem)
num=int(input("Enter a number to remove from array : "))
# removing element ‘num’ from the array.
arr.remove(num)
print("Array after removing",num,"=",arr)
Python Program to Delete Element
at Given Index in Array
arr = [1, 2, 3, 4, 5]
arr.pop(2)

print("Array after removing from index : ", arr)

Python code to find the sum of array (list)


elements
size=int(input("Enter the number of elements you want in array: "))
arr=[]
sum=0
# adding elements to the array (list)
for i in range(0,size):
elem=int(input("Please give value for index "+str(i)+": "))
arr.append(elem)
sum+=elem
print("Sum of array elements = ",sum)

Python code to print even numbers from array


(list)
#taking the input from the user to fix the array size
size=int(input("Enter the number of elements you want in array: "))
arr=[]
sum=0
# adding elements to the array (list)
for i in range(0,size):
elem=int(input("Please give value for index "+str(i)+": "))
arr.append(elem)
print("All even number in array are ")
# check and print if any element of array (list) is even
for i in range(0,size):
if arr[i]%2==0:
print(arr[i],end=' ')

Perform left rotation by two


positions in Array Using Python
arr = [1, 2, 3, 4, 5]
arr = arr[2:] + arr[:2]
print("After two left rotaion :",arr)
Python code to perform right rotation on array
(list) elements by two positions
#taking the input from the user to fix the array size
size=int(input("Enter the number of elements you want in array: "))
arr=[]
# adding elements to the array (list)
for i in range(0,size):
elem=int(input("Please give value for index "+str(i)+": "))
arr.append(elem)
for i in range(0,2):
# storing last element of the array (list) in temp variable
temp=arr[size-1];
for j in range(size-1,-1,-1):
arr[j]=arr[j-1]
# making the last element of the array, the first element
arr[0]=temp;
print("Array after performing right rotation :")
print(arr)
Python Program to Merge two
Arrays
Using the + operator
arr1 = [1, 2, 3]

arr2 = [4, 5, 6]

merged_arr = arr1 + arr2

print("Array After Merging =",merged_arr)

Using the append() method and a for loop


arr1 = [1, 2, 3]
arr2 = [4, 5, 6]
for element in arr2:
arr1.append(element)
print("Array After Merging =",arr1)
Using the extend() method and a for loop
arr1 = [1, 2, 3]
arr2 = [4, 5, 6]
arr1.extend(arr2)
print("Array After Merging =",arr1)

Python Program to Find Highest


Frequency Element in Array
arr = [1, 2, 3, 4, 5, 6, 5, 4, 5, 1, 2, 3, 4, 5, 6, 5, 4,
5]
freq_dict = {}
for element in arr:
if element in freq_dict:
freq_dict[element] += 1
else:
freq_dict[element] = 1
highest_freq_element = max(freq_dict,
key=freq_dict.get)
print("Highest frequency element:",
highest_freq_element)
Add two numbers using Recursion
def add(num1, num2):

if num2 == 0:

return num1

else:

return add(num1 ^ num2, (num1 & num2) << 1)

num1 = 5

num2 = 7

result = add(num1, num2)

print("The sum of", num1, "and", num2, "is", result)

You might also like