doing index number search using Try and Except. I have example on how to do with if and else, but don't how to do it with try and except - try-catch

How to use try and except for an index number
numbersList = [1, 2, 3, 14, 15, 16, 19]
number = int(input("Enter an index number: "))
if number in range(len(numbersList)):
print ("Index number", number)
else:
print ("Index is out of range")

Related

Trying to write a solution to re-order an array without using sort()

I feel like I'm close but not quite sure why my while loop stops executing, I want it to run/ increase the counter then the conditions are true, then when it runs into numbers out of order, swap them, then decrease the counter, then run the while loop again until all the numbers are in order. So like it slides the number that's out of order backwards until it's higher than the number before it but lower than then number after it. If that makes sense.Probably an easy one for most of you but I'm just new to python. Here is my code so far;
arr = [7, 14, 21, 32, 17, 48, 69, 78, 72]
count = 0
while (count < len(arr) - 1) and (arr[count] < arr[count+1]):
count += 1
if (arr[count] > arr[count+1]):
arr[count], arr[count+1] = arr[count+1], arr[count]
count -= 1
continue
print(count)
print(arr)
below my code with some pseudocode to make it clearer.
# list of numbers out of order
arr = [7, 14, 21, 32, 17, 48, 69, 78, 72]
# first position in index
count = 0
# loop to check first if value of index position is less than length of array -1 (9-1 = 8)
# or if value of index position is less than index position + 1 (next index position)
while (count < len(arr) - 1) and (arr[count] < arr[count+1]):
# if true loop should continue + 1 on the next index
count += 1
# if the value of number in the current index position is greater than the next number it swaps them.
if (arr[count] > arr[count+1]):
arr[count], arr[count+1] = arr[count+1], arr[count]
count -= 1
continue
print(count)
print(arr)
I've tried various different things, I think I'm just stuck on how while loops actually work and I need to get the loop to run again after it hits it's first false statement.
This would work in the way that is required in the question:
finds the first two numbers that are out of order.
switched those numbers only and exit.
arr = [7, 14, 21, 32, 17, 48, 69, 78, 72]
for i, v in enumerate(arr):
if i == len(arr) -1:
print('reached the end')
break
if v > arr[i+1]:
print('out of order index', i, 'value:',v)
# do the switch
arr[i], arr[i+1] = arr[i+1], v
break
print(arr)
the result is this:
out of order index 3 value: 32
[7, 14, 21, 17, 32, 48, 69, 78, 72]
You could also achieve the same with a while loop so long as a break condition existed.

Regarding positions of elements within a row's 'islands of positive values'

Consider a specified row in a numpy integer array. My task has 3 parts:
Identify the locations of any positive islands (ie: consec positive values) in the specified row.
Identify the lengths of each of these positive islands.
Determine (True or False) if the island element that is closest in value to the row index is in the FIRST or LAST island position.
The following code, I believe, answers parts a) and b).
import numpy as np
arr = np.array([[-1, -4, -2, -8, 8, -3, -5, -6, 7],
[-4, -9, -1, 3, 8, -7, -6, 2, -5],
[ 4, 6, 9, 3, -1, -2, 5, 4, 8],
[ 5, -1, 2, 5, 6, 7, -3, -4, 1]])
row_idx = 2
arr_row = arr[row_idx]
mask = arr_row > 0
changes = np.concatenate(([mask[0]], mask[:-1] != mask[1:], [mask[-1]]))
isl_idx = np.where(changes)[0] # 1st index of islands
pos_idx = isl_idx[::2] # 1st index of POSITIVE islands
print('pos_idx = ', pos_idx)
pos_len = np.diff(isl_idx)[::2] # length of POSITIVE islands
print('pos_len = ', pos_len)
print()
When row_idx = 2, for example, we have output:
pos_idx = [0, 6] # first indices of the two positive islands
pos_len = [4,3]) # lengths of the two positive islands
My problem is that I can't find a good way to tackle part c). The desired output, for the example above, would look like:
firstLast = [True, False]
Explanation: We are in row_idx = 2, so:
The value in the 1st positive island closest to 2 is 3, and this 3 is indeed in the FIRST or LAST position of its island. (True)
The value in the 2nd positive island closest to 2 is 4, which is not in the FIRST or LAST position of its island. (False)

Binary Search a non-existing number in a sorted array, return a larger negative number than -1

When the search number is 12, why does it return -6 instead of -1?
int[] list = {2, 4, 7, 10, 11, 45, 50, 59, 60, 66, 69, 70, 79};
System.out.println("1. Index is " + Arrays.binarySearch(list, 11));
System.out.println("2. Index is " + Arrays.binarySearch(list, 12));
Result:
1. Index is 4
2. Index is -6
Update
Now I understand because
Arrays.binarySearch will return
(-(insertion point) - 1)
if the number is not in the array.
i.e
12 is at insertion of 5, so return (-(5) - 1) = -6.
Thanks for the help.
You may refer to the Javadoc : Arrays.binarySearch(int[] a,int key)
It returns :
index of the search key, if it is contained in the array;
otherwise : (-(insertion point) - 1).
Here the insertion point would be :
int[] list = {2, 4, 7, 10, 11, 45, 50, 59, 60, 66, 69, 70, 79};
// 1^ 2^ 3^ 4^ 5^
The position 5 so (-5-1) = -6
Extracted from BinarySearch
Return value:
This method returns index of the search key, if it is contained in the array, else it returns (-(insertion point) - 1). The insertion point is the point at which the key would be inserted into the array: the index of the first element greater than the key, or a.length if all elements in the array are less than the specified key.
From the return value explanation, it returns the negation of the position the element will be in the array (that is -5) minus 1, which would be -6.
This is a common return type for BinarySearch() methods.
If you would like to print the index of an integer a :
int[] list = {2, 4, 7, 10, 11, 45, 50, 59, 60, 66, 69, 70, 79};
int a =12; //Value can be updated or read through Scanner
int temp = Arrays.binarySearch(list,a);
if(temp>=0){
System.out.println("Index of a is : " + temp)
}else{
System.out.println("Insertion point for a is : " + (-1)*(temp+1);
}

Sort the array with reference to another array

I have two different arrays. Let's say:
a = [1, 2, 13, 4, 10, 11, 43]
b = [44, 23, 1, 4, 10, 2, 55, 13]
Now I have to sort the array b by referring to the array a. I tried the following solution:
lookup = {}
a.each_with_index do |item, index|
lookup[item] = index
end
b.sort_by do |item|
lookup.fetch(item)
end
But I'm getting the KeyError: key not found: 44 error. Can anyone help me find a solution?
Expected output is [1, 2, 13, 4, 10, 23, 44, 55].
Comparing arrays checks the first value, if it's equal goes to the second value and so on. Hence this will compare by the order of occurrence in a and then by the actual value for the ones not in a:
b.sort_by { |e| [a.index(e) || a.size, e] }
To keep O(nlogn), you could:
ai = a.each_with_index.to_h
b.sort_by { |e| [ai[e] || a.size, e] }

Best way to solve sum of an array with .each

Below is some code I submitted for a array sum algorithm. In this case I had to use .each but I feel like there is a better way to do this...
numbers = [5, 17, 2, 899, 101, 4, 66, 123, 98]
sum = 0
index = 0
numbers.each do |number|
sum = sum + numbers[index]
index += 1
end
puts sum
There is. You don't need to track index manually when using each; you can simply do
numbers.each do |number|
sum = sum + number
end

Resources