Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How i find out which person stayed maximum nights? Name and total how many days?

Tags:

python-3.x

How i find out which person stayed maximum nights? Name and total how many days? (date format MM/DD)

for example

text file contain's

Robin 01/11 01/15
Mike 02/10 02/12
John 01/15 02/15

output expected

('john', 30 )

my code

def longest_stay(fpath):
    with open(fpath,'r')as f_handle:
        stay=[]

        for line in f_handle:
            name, a_date, d_date = line.strip().split()
            diff = datetime.strptime(d_date, "%m/%d") -datetime.strptime(a_date, "%m/%d")
            stay.append(abs(diff.days+1))
    return name,max(stay)

It always return first name.

like image 314
john_cris Avatar asked Nov 09 '22 20:11

john_cris


1 Answers

This can also be implemented using pandas. I think it will much simpler using pandas.

One issue I find is that how you want to handle when you have many stayed for max nights. I have addressed that in the following code.

import pandas as pd
from datetime import datetime as dt

def longest_stay(fpath):
    # Reads the text file as Dataframe
    data = pd.read_csv(fpath + 'test.txt', sep=" ", header = None) 

    # adding column names to the Data frame
    data.columns = ['Name', 'a_date', 'd_date'] 

    # Calculating the nights for each customer
    data['nights'] = datetime.strptime(d_date, "%m/%d") - datetime.strptime(a_date, "%m/%d") 

    # Slicing the data frame by applying the condition and getting the Name of the customer and nights as a tuple (as expected)
    longest_stay = tuple( data.ix[data.nights == data.nights.max(), {'Name', 'nights'}])

    # In case if many stayed for the longest night. Returns a list of tuples.
    longest_stay = [tuple(x) for x in longest_stay]

    return longest_stay
like image 195
Venkat Avatar answered Jan 04 '23 02:01

Venkat