Insert dot in currency amount

Set-up

I have several integers that represent monetary values.

Problem is that the integers are missing a dot, i.e. 12345 should be 123.45.

My Code

amount = str(12345)
first_amount = amount[:-2]
last_amount = amount[-2:]
order_amount = float(first_amount + '.' + last_amount)

this works fine, i.e. I obtain 123.45.

I was wondering if there’s a one-line solution.

Solution:

Yes there’s a solution, dividing by 100.00, note the .00 part:

a = 12345
print(a/100.00) # prints 123.45

Different implementations of compare method for Long, Integer and Short?

Why are the implementations of the static method compare for Long, Integer and Short in Java’s library different?

For Long:

public static int compare(long x, long y) {
    return (x < y) ? -1 : ((x == y) ? 0 : 1);
}

For Integer:

public static int compare(int x, int y) {
    return (x < y) ? -1 : ((x == y) ? 0 : 1);
}

For Short:

public static int compare(short x, short y) {
    return x - y;
}

Solution:

If you try:

System.out.println(Long.MIN_VALUE - Long.MAX_VALUE);

or

System.out.println(Integer.MIN_VALUE - Integer.MAX_VALUE);

You will get 1 because of overflow(update: should be underflow here, as mentioned in another answer), which is incorrect.

However, with

System.out.println(Short.MIN_VALUE - Short.MAX_VALUE);

you will get correct value -65535, because short will be converted to int before - operation, which prevents the overflow.

Maximum distance between two different element in an array

I have a problem where I need to find the maximum distance between two different elements in an array.

For example: given an array 4,6,2,2,6,6,4 , the method should return 5 as the max distance.

I am able to solve the problem using two for loops but it is not an optimized solution. Am trying to optimize it by doing it in a single for loop.

here is my current solution:

int [] A = {4,6,2,2,6,6,4};
int N = A.length;
int result = 0;

for (int i = 0; i < N; i++){
    for (int j = i; j < N; j++) {
        if(A[i] != A[j]){
            result = Math.max(result, j - i);
        }
    }
}

// tried below code but it is not efficient
//      for (int i = 0; i < N; i++){
//          
//          if(A[N-1] != A[i]){
//              result = Math.max(result, N-1-i);
//          }
//      }

System.out.println(result);

How to make this better in terms of time complexity?

Solution:

Simple (not nested) loop is enough, but two cases should be taken into
account: either the best result is

  4,6,2,2,6,6,4
    ^         ^ - moving first

or

  4,6,2,2,6,6,4
  ^         ^   - moving last

for instance: [4, 2, 4, 4, 4] moving first brings the answer, when in case of [4, 4, 4, 2, 4] moving last should be used.

  int first = 0;
  int last = A.length - 1;

  // 1st case: moving "first"
  while (first < last) {
    if (A[first] == A[last])
      first++;
    else
      break;
  }

  int diff1 = last - first;

  first = 0;
  last = A.length - 1;

  // 2nd case: moving "last"
  while (first < last) {
    if (A[first] == A[last])
      last--;
    else
      break;
  }

  int diff2 = last - first;

  // result is the max between two cases
  int result = diff1 > diff2
    ? diff1
    : diff2;

So we have O(N) time complexity.

Edit: Let’s proof that at least one of the indexes is either 0 or length - 1. Let’s do it by contradiction. Suppose we have a solution like

  a, b, c, .... d, e, f, g
        ^ ..... ^  <- solution indexes (no borders)

Items to the left of c must be d, otherwise we can take a or b indexes and have an improved solution. Items to right of d must be c or we can once again push last index to the right and have a better solution. So we have

  d, d, c .... d, c, c, c
        ^ .... ^  <- solution indexes 

Now, since d <> c (c..d is a solution) we can improve the solution into

  d, d, c .... d, c, c, c
        ^ .... ^           <- solution indexes 
  ^       ....          ^  <- better solution

We have a contradiction (the supposed solution is not one – we have a better choice) and that’s why at least one index must be 0 or length - 1.

Now we have 2 scenarions to test:

  a, b, ..... y, z
     ^  ......   ^ <- moving first
  ^  ......   ^    <- moving last

We can combine both conditions into if and have just one loop:

  int result = 0;

  for (int i = 0; i < A.length; ++i)
    if (A[i] != A[A.length - 1] || A[0] != A[A.length - 1 - i]) {
      result = A.length - i - 1;

      break;
    }

How to read an input file of integers separated by a space using readlines in Python 3?

I need to read an input file (input.txt) which contains one line of integers (13 34 14 53 56 76) and then compute the sum of the squares of each number.

This is my code:

# define main program function
def main():
    print("\nThis is the last function: sum_of_squares")
    print("Please include the path if the input file is not in the root directory")
    fname = input("Please enter a filename : ")
    sum_of_squares(fname)

def sum_of_squares(fname):
    infile = open(fname, 'r')
    sum2 = 0
    for items in infile.readlines():
        items = int(items)
        sum2 += items**2
    print("The sum of the squares is:", sum2)
    infile.close()

# execute main program function
main()

If each number is on its own line, it works fine.

But, I can’t figure out how to do it when all the numbers are on one line separated by a space. In that case, I receive the error: ValueError: invalid literal for int() with base 10: '13 34 14 53 56 76'

Solution:

You can use file.read() to get a string and then use str.split to split by whitespace.

You’ll need to convert each number from a string to an int first and then use the built in sum function to calculate the sum.

As an aside, you should use the with statement to open and close your file for you:

def sum_of_squares(fname):

    with open(fname, 'r') as myFile: # This closes the file for you when you are done
        contents = myFile.read()

    sumOfSquares = sum(int(i)**2 for i in contents.split())
    print("The sum of the squares is: ", sumOfSquares)

Output:

The sum of the squares is: 13242

bash: perform mathematical operations on strings

If VAR1 and VAR2 are strings having integer values like:
VAR1=”12″

VAR2=”2″

Then mathematical operations can be performed on it as below:
VAR3=$(echo “$VAR1 $VAR2” | awk ‘{print $1+$2}’)

OR you can also use:
VAR3=$(awk ‘{print $1+$2}’ <<<“$VAR1 $VAR2”)