Saturday, April 13, 2019

codingdirectional: How to use the reverse method of a list in python

Most of the time a python programmer will need to reverse the order of the entire python list’s elements so a program can loop through those elements in the list starting from the end instead of from the beginning. Below is an example which we will use the python list’s reverse method to reverse the order of the list before using it.

Wolves have been reintroduced to Great Britain. You are a sheep farmer and are now plagued by wolves which pretend to be sheep. Fortunately, you are good at spotting them.

Warn the sheep in front of the wolf that it is about to be eaten. Remember that you are standing at the front of the queue which is at the end of the array:

[sheep, sheep, sheep, sheep, sheep, wolf, sheep, sheep]      (YOU ARE HERE AT THE FRONT OF THE QUEUE)
   7      6      5      4      3            2      1

If the wolf is the closest animal to you, return "Pls go away and stop eating my sheep". Otherwise, return "Oi! Sheep number N! You are about to be eaten by a wolf!" where N is the sheep’s position in the queue.

Note: there will always be exactly one wolf in the array!

Examples:

warn_the_sheep(["sheep", "sheep", "sheep", "wolf", "sheep"]) == 'Oi! Sheep number 1! You are about to be eaten by a wolf!'

warn_the_sheep(['sheep', 'sheep', 'wolf']) == 'Pls go away and stop eating my sheep'

Before we solve the above problem, we need to reverse the order of the list using the below method.

queue.reverse()

Here is the entire solution.

def warn_the_sheep(queue):
    queue.reverse()
    the_wolf_position = queue.index("wolf")
    if(the_wolf_position == 0):
        return 'Pls go away and stop eating my sheep'
    else:
        return "Oi! Sheep number " + str(the_wolf_position) + "! You are about to be eaten by a wolf!"

A simple solution indeed, in the meantime I feel really shocked that the animals (both the wolf and the sheep) in Great Britain knows English so well! Like, share or follow me on Twitter.



from Planet Python
via read more

No comments:

Post a Comment

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...