7r0jan005
7r0jan005

Reputation: 31

Applying time.sleep on each element of a python list

I want to independently iterate elements of a list in a marathon-like formation, such that each lane/element can move at a random/varied pace.

In order to still be able to access each element by index, I tried the following code:

cyclists = ['abcde', 'fghij', 'klmno', 'pqrst', 'uvwxy']            #each elements represent an athlete

choose_athlete = random.choices((range(len(cyclists))), k=len(cyclists))    # index select athlete from elements/lane
################################################################
def circular_shifts(runners, step=1):
    step %= min(len(e) for e in runners)
    return [e[step:] + e[:step] for e in runners]


for laps in range(10):
    for i in range(len(cyclists)):
        cycling = circular_shifts(cyclists, i)
        print(cycling)

#Problem::: #is there a way I can apply the concept of time.sleep to each element as they loop so I can determine their speed of running, i.e while lane1/element[0] is looping fast, lane2 is slower, and so on?

Another example:

cyclists = ['abcde', 'fghij', 'klmno', 'pqrst', 'uvwxy']            #each elements represent an athlete

for i in range(5):
    for aa in cyclists[0]: 
        time.sleep(0)
        print(aa)

    for bb in cyclists[1]: 
            time.sleep(0.1)
            print(bb)

    for cc in cyclists[1]: 
            time.sleep(0.2)
            print(cc)

    for dd in cyclists[1]: 
            time.sleep(0.3)
            print(dd)

    for ee in cyclists[0]: 
        time.sleep(0.4)
        print(ee)

But this approach print separately, instead, i want the output to still show up together as list so i can access them with index ([0:4])

Preferred output:

['abcde', 'fghij', 'klmno', 'pqrst', 'uvwxy']
['bcdea', 'ghijf', 'lmnok', 'qrstp', 'vwxyu']
['cdeab', 'hijfg', 'mnokl', 'rstpq', 'wxyuv']
['deabc', 'ijfgh', 'noklm', 'stpqr', 'xyuvw']
['eabcd', 'jfghi', 'oklmn', 'tpqrs', 'yuvwx']
['abcde', 'fghij', 'klmno', 'pqrst', 'uvwxy']
['bcdea', 'ghijf', 'lmnok', 'qrstp', 'vwxyu']
['cdeab', 'hijfg', 'mnokl', 'rstpq', 'wxyuv']
['deabc', 'ijfgh', 'noklm', 'stpqr', 'xyuvw']
['eabcd', 'jfghi', 'oklmn', 'tpqrs', 'yuvwx']

Upvotes: 0

Views: 235

Answers (1)

The way this was set up was a bit too confusing to me, so I coded up my own version of how a race could happen using time.sleep. I tried to add lots of comments to explain all the steps:

import time

runners = [
    {'name':'Samantha', 'speed':3.5, 'distance_traveled':0},
    {'name':'Ben',      'speed':2.9, 'distance_traveled':0}, 
    {'name':'Luis',     'speed':1.8, 'distance_traveled':0}, 
    {'name':'Jane',     'speed':2.2, 'distance_traveled':0}
    ] 
# each elements represent an athlete. Their name and their speed. Also 'distance traveled' tracker
# let's set the speed to be units (m/s). The distance traveled is measured in (m)

# initialize a "finish line" which registers when the distance traveled is enough to win
finish_line = 30    # Distance required to win.             Units of (m)
time_tracker = 0    # Total time elapsed.                   Units of (s)
time_delta = 1      # Change in time for each iteration.    Units of (s)

# fun printing stuff
print("And we're off! Here's the standings: ")

# "while some of the athletes have not finished yet"
while any(i['distance_traveled'] < finish_line for i in runners):
    # we can use time.sleep with a while loop to register the race for each second.

    # update the distance traveled for each runner
    for r in runners:
        r["distance_traveled"] += r["speed"]*time_delta
    
    # sort the runners dict depending on who's in first place, etc.
    runners = sorted(runners, key=lambda d: d['distance_traveled'], reverse=True) 

    print(f"\nAt time {time_tracker}s the current standings are:")
    for place, r in enumerate(runners):
        print(f'{place+1}.: {r["name"]} at {r["distance_traveled"]:.1f}m')
    
    time_tracker += time_delta
    time.sleep(time_delta)

There's a lot of stuff I haven't added such as:

  1. Changing speeds of runners as they run. Decide speeds randomly?
  2. Declaring winners when they cross the finish line.
  3. Other environmental factors such as wind or conditions?

Hopefully this helps! Have fun!

Upvotes: 1

Related Questions