Skip to content

Instantly share code, notes, and snippets.

@Pinacolada64
Created October 28, 2021 04:43
Show Gist options
  • Save Pinacolada64/a3952a9c6e6abbbfa21a889c0e10e5d9 to your computer and use it in GitHub Desktop.
Save Pinacolada64/a3952a9c6e6abbbfa21a889c0e10e5d9 to your computer and use it in GitHub Desktop.
List exits from a room.
direction_names = ['North', 'East', 'South', 'West', 'Up', 'Down']
def show_exits(exits):
"""list room exits"""
exit_list = []
if exits[0]:
exit_list.append("North")
if exits[1]:
exit_list.append("East")
if exits[2]:
exit_list.append("South")
if exits[3]:
exit_list.append("West")
if exits[4]:
exit_list.append("Up")
if exits[5]:
exit_list.append("Down")
if len(exit_list) > 1:
exit_list[-1] = f"and {exit_list[-1]}"
print(f'Ye may travel: {", ".join(exit_list)}')
if __name__ == '__main__':
exits = [0, 1, 0, 1, 0, 1]
show_exits(exits) # should print "East, West, and Down"
@tanabi
Copy link

tanabi commented Oct 28, 2021

How I would do it ....

def show_exits(exits):
    ret = []
    for x in range(0, len(direction_names)):
        if exits[x]:
            ret.append(direction_names[x])

     if len(ret) > 1:
         ret[-1] = f"and {ret[-1]}"

     print(f"Ye may travel: {", ".join(ret)}")

@tanabi
Copy link

tanabi commented Oct 28, 2021

Or:

def show_exits(exits):
    ret = [
        direction_names[x]
         for x in range(0, len(direction_names))
         if exits[x]
    ]

     if len(ret) > 1:
         ret[-1] = f"and {ret[-1]}"

     print(f"Ye may travel: {", ".join(ret)}")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment