Home > Net >  Recently interviewer asked a question even though my answer is right got rejected, Any reason?
Recently interviewer asked a question even though my answer is right got rejected, Any reason?

Time:01-30

Question

When opening his fruit shop for the day a shopkeeper found that his stock of apples could be perfectly arranged in a complete triangular array: that is, every row with one apple more than the row immediately above, going all the way up ending with a single apple at the top. During any sales transaction, apples are always picked from the uppermost row, and going below only when that row is exhausted. When one customer walked in the middle of the day she found an incomplete array in display having 126 apples totally. How many rows of apples (complete and incomplete) were seen by this customer? (Assume that the initial stock did not exceed 150 apples.)

My Answer

import math

cust_seen = 126
assume_apple = 150
row_left=0
final_row=0

def sumofAapple(n):
 return ((n*(n 1))//2)

def assumption(n):
 '''
 :param n: assumption for total number of apple
 :return: total number of rows based on assumption
 Apply AP Series Sum Formula and quadratic Equation
 Sum = n/2[2*1 (n-1)*d]
 Quadratic equation: ax^2  bx c=0
 x = (-b -sqrt((b^2)-4*a*c))//2a
 '''

 return int((math.sqrt(1 8*n)-1)//2)


assume_row = assumption(assume_apple)
assume_total = sumofAapple(assume_row)

for i in range(1,assume_row 1):
 total_left = assume_total-sumofAapple(i)
 if total_left == cust_seen:
 row_left = i
 break
#Since at row number row_answer apple is 126..total row left = assume_row-row_left
final_row = assume_row - row_left

print("Answer = ", final_row)

Please let me know the reason and how do i improved this?

I tried in different platform but none of the answer convinced me.

CodePudding user response:

Perhaps, a simpler solution without calculus was expected:

cust_seen = 126
assume_apple = 150

apples = 1
row = 1
while apples < assume_apple:
    row  = 1
    apples  = row

row -= 1
apples = row
seen_rows = 1
while apples < cust_seen:
    row -= 1
    seen_rows  = 1
    apples  = row

print(f"seen rows: {seen_rows}")

CodePudding user response:

def find_n(apple_not_exceed, apple_left, n=0, apple_total_n=0, apple_sold=0):
    print("row_num", "apple_count", "apple_accum")
    
    while apple_total_n <= apple_not_exceed:
        print(n, n, apple_total_n)
        apple_sold = apple_total_n - apple_left
        if (apple_total_n <= apple_left):
            complete_row = n
        n  = 1
        apple_total_n = n * (n   1) // 2
        
        
        
    print("total_row", "complete_row", "apple_sold", "incomplete_row")
    return n-1, complete_row, apple_sold, n-1 - complete_row

your case:

enter image description here

check:

enter image description here

  • Related