Ex1 Count elements in the array arr length len arr print Elements coun

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
# Ex1: Count elements in the array
arr = [1, 3, 5, 6]
length = len(arr)
print('Elements count:')
print(length)
# Ex2: Count elements equal to defined
def equal_num(arr, num):
count = 0
for i in arr:
if i == num:
count += 1
return count
print('Count elements equal to 2:')
equal_res = equal_num([1, 2, 1, 2, 1, 3], 2)
print(equal_res)
# Ex3: Sum all elements in the array
arr2 = [1, 3, 5, 6, 8]
sum_arr = sum(arr2)
print('Sum of array:')
print(sum_arr)
# Ex4: Find max of elements in the array
print('Max of array:')
print(max(arr2))
# Ex5: Find mean of elements in the array
print('Mean of array:')
print(sum(arr2) / len(arr2))
# Ex6: Write elements with space as delimiter
print('Splitted string:')
print(' '.join(str(i) for i in arr2))
# Ex7: Multiply numbers on even positions by 2
# and numbers on odd positions by 3
arr3 = []
for i in range(0, len(arr2)):
if i % 2 == 0:
arr3.append(arr2[i]*2)
else:
arr3.append(arr2[i]*3)
print('Multiplied values:')
print(arr3)
# Ex8: Check if all elements in the array are multiple of a number.
def multiple_num(arr, num):
for i in arr:
if i % 7 != 0:
return False
return True
arr4 = [7, 0, 14, 210]
print('Multiple of a 7:')
print(multiple_num(arr2, 7))
print(multiple_num(arr4, 7))
# Ex9: check if there is a negative number in the array
arr5 = [1, 3, -5, 6, 8]
def is_negative(arr):
for i in arr:
if i < 0:
return True
return False
print('Contains negative:')
print(is_negative(arr))
print(is_negative(arr5))
# Ex10: Leave only even numbers in the array
def only_even(arr):
evens = []
for i in arr:
if i % 2 == 0:
evens.append(i)
return evens
evens = only_even(arr2)
print("Only even numbers:")
print(evens)
# Ex11: Split string into words
str = "quick brown fox jumps over the lazy dog"
splits = str.split(" ")
print("Splitted string:")
print(splits)
# Ex12: Return list starting from 5th element.
arr6 = [1, 3, 5, 6, 8, 7, 12, 1111, 19]
print("Elements starting from 5th:")
print(arr6[5:])
# Ex13: Return list excluding first and last element.
print('Elements excluding first and last:')
print(arr6[1:-1])