10
\$\begingroup\$

This a block of code taken from a program I am working on that creates multiple files. This part of the code is to create files and sort them by date by appending the date to the file name. User chooses the first and last date and which day(s) he needs the files named in. So if someone wanted to create a Microsoft Word document for every Mon, Wed, and Fri in the year they can do it in one shot.

I am trying to see if there is any way to optimize this. I started with bash scripting few months ago and recently started learning Python this is my first project. I am trying to figure out how to maybe condense all the different blocks for each day of the week to one if that's possible so that way I can have just 1 progress bar. There are some variables in the block that are assigned earlier in the program by user input. I did not include it due to length.

start = np.datetime64(input("Start with: "))
end = np.datetime64(input("End with  : "))
 
print()
print("                *************************** ")
print("Choose Day(s)  |          All Days         |")
print("               | ------------------------- |")
print("E.g.           | S | M | T | W | T | F | S |")
print("               | ------------------------- |")
print("(1=On, 0=Off)  | 1 | 1 | 1 | 1 | 1 | 1 | 1 |")
print("               |                           |")
print("                *************************** ")
print("S M T W T F S")

sun, mon, tue, wed, thu, fri, sat = map(int, input().split())
            
print()    

if sun == 1:
    first_sunday = np.busday_offset(start, 0, roll='forward', weekmask='Sun')
    last_sunday = np.busday_offset(end, 0, roll='preceding', weekmask='Sun')
    sun_count = np.busday_count(first_sunday, last_sunday, weekmask='Sun') + 1
                
    for i in trange(sun_count, desc="Sunday"):
        touch.touch(file_name + " " + datetime.strptime(str(first_sunday), '%Y-%m-%d').strftime('%m-%d-%Y') + "." + file_type)
        first_sunday += np.timedelta64(7, 'D')
 
if mon == 1:
    first_monday = np.busday_offset(start, 0, roll='forward', weekmask='Mon')
    last_monday = np.busday_offset(end, 0, roll='preceding', weekmask='Mon')
    mon_count = np.busday_count(first_monday, last_monday, weekmask='Mon') + 1
                
    for i in trange(mon_count, desc="Monday"):
        touch.touch(file_name + " " + datetime.strptime(str(first_monday), '%Y-%m-%d').strftime('%m-%d-%Y') + "." + file_type)
        first_monday += np.timedelta64(7, 'D')
 
if tue == 1:
    first_tuesday = np.busday_offset(start, 0, roll='forward', weekmask='Tue')
    last_tuesday = np.busday_offset(end, 0, roll='preceding', weekmask='Tue')
    tue_count = np.busday_count(first_tuesday, last_tuesday, weekmask='Tue') + 1
                
    for i in trange(tue_count, desc="Tuesday"):
        touch.touch(file_name + " " + datetime.strptime(str(first_tuesday), '%Y-%m-%d').strftime('%m-%d-%Y') + "." + file_type)
        first_tuesday += np.timedelta64(7, 'D')
 
if wed == 1:
    first_wednesday = np.busday_offset(start, 0, roll='forward', weekmask='Wed')
    last_wednesday = np.busday_offset(end, 0, roll='preceding', weekmask='Wed')
    wed_count = np.busday_count(first_wednesday, last_wednesday, weekmask='Wed') + 1
                
    for i in trange(wed_count, desc="Wednesday"):
        touch.touch(file_name + " " + datetime.strptime(str(first_wednesday), '%Y-%m-%d').strftime('%m-%d-%Y') + "." + file_type)
        first_wednesday += np.timedelta64(7, 'D')
 
if thu == 1:
    first_thursday = np.busday_offset(start, 0, roll='forward', weekmask='Thu')
    last_thursday = np.busday_offset(end, 0, roll='preceding', weekmask='Thu')
    thu_count = np.busday_count(first_thursday, last_thursday, weekmask='Thu') + 1
                
    for i in trange(thu_count, desc="Thursday"):
        touch.touch(file_name + " " + datetime.strptime(str(first_thursday), '%Y-%m-%d').strftime('%m-%d-%Y') + "." + file_type)
        first_thursday += np.timedelta64(7, 'D')
 
if fri == 1:
    first_friday = np.busday_offset(start, 0, roll='forward', weekmask='Fri')
    last_friday = np.busday_offset(end, 0, roll='preceding', weekmask='Fri')
    fri_count = np.busday_count(first_friday, last_friday, weekmask='Fri') + 1
                
    for i in trange(fri_count, desc="Friday"):
        touch.touch(file_name + " " + datetime.strptime(str(first_friday), '%Y-%m-%d').strftime('%m-%d-%Y') + "." + file_type)
        first_friday += np.timedelta64(7, 'D')
 
if sat == 1:
    first_saturday = np.busday_offset(start, 0, roll='forward', weekmask='Sat')
    last_saturday = np.busday_offset(end, 0, roll='preceding', weekmask='Sat')
    sat_count = np.busday_count(first_saturday, last_saturday, weekmask='Sat') + 1
                
    for i in trange(sat_count, desc="Saturday"):
        touch.touch(file_name + " " + datetime.strptime(str(first_saturday), '%Y-%m-%d').strftime('%m-%d-%Y') + "." + file_type)
        first_saturday += np.timedelta64(7, 'D')
\$\endgroup\$
14
\$\begingroup\$

Each of your if blocks does the same thing, but with different inputs.

if sun == 1:
    first_sunday = np.busday_offset(start, 0, roll='forward', weekmask='Sun')
    last_sunday = np.busday_offset(end, 0, roll='preceding', weekmask='Sun')
    sun_count = np.busday_count(first_sunday, last_sunday, weekmask='Sun') + 1
                
    for i in trange(sun_count, desc="Sunday"):
        touch.touch(file_name + " " + datetime.strptime(str(first_sunday), '%Y-%m-%d').strftime('%m-%d-%Y') + "." + file_type)
        first_sunday += np.timedelta64(7, 'D')

can be replaced with

abbrev= 'Sun'
name = 'Sunday'
if sun == 1:
    first = np.busday_offset(start, 0, roll='forward', weekmask=abbrev)
    last = np.busday_offset(end, 0, roll='preceding', weekmask=abbrev)
    count = np.busday_count(first, last, weekmask=abbrev) + 1
                
    for i in trange(count, desc=name):
        touch.touch(file_name + " " + datetime.strptime(str(first), '%Y-%m-%d').strftime('%m-%d-%Y') + "." + file_type)
        first += np.timedelta64(7, 'D')

This allows you to fold the days into a for loop, like so:

# Input the value for each day into a single list rather than individual variables
day_input = (int(val) for val in input().split())
NAMES = ('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday')

for val, name in zip(day_input, NAMES):
    # Skip any day that was inputted as 0
    if not val: # integer 0 is equivalent to boolean False
        continue
    abbrev = name[:3]
    first = np.busday_offset(start, 0, roll='forward', weekmask=abbrev)
    last = np.busday_offset(end, 0, roll='preceding', weekmask=abbrev)
    count = np.busday_count(first, last, weekmask=abbrev) + 1
                    
    for i in trange(count, desc=name):
        touch.touch(file_name + " " + datetime.strptime(str(first), '%Y-%m-%d').strftime('%m-%d-%Y') + "." + file_type)
        first += np.timedelta64(7, 'D')

I replaced your call to map with a generator comprehension, which are generally considered the more aesthetic method of getting the same result. If you plan on using the values more than the once seen here you should use a list comprehension instead.

Also, you can simplify your initial set of print statements by using a multiline string:

print(
"""
                *************************** 
Choose Day(s)  |          All Days         |
               | ------------------------- |
E.g.           | S | M | T | W | T | F | S |
               | ------------------------- |
(1=On, 0=Off)  | 1 | 1 | 1 | 1 | 1 | 1 | 1 |
               |                           |
                *************************** 
S M T W T F S""")
\$\endgroup\$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.