Are you looking for customized advices? Click here to contact the expert!
mprisznyak
mprisznyak
Reputation Top 1%
Miklós Prisznyák
24 Snippets  (19th place)
Published
1 Channel
Created
2 Channels
Following
Sep 9, 2016
Last Visit
Apr 1, 2013
Registered
795 points  (22nd place)
Reputation
Top 5% Publisher
Junior Code Generator
Serious Code Generator
Senior Code Generator
Junior Publisher
Serious Publisher
Senior Publisher
Junior Topic Creator
Junior Topic Hub
Serious Topic Hub
Junior Trend Maker
Serious Trend Maker
Junior Judge
Serious Judge
Junior Popular Coder
Serious Popular Coder
Senior Popular Coder
Master Popular Coder
Junior Autobiographer
Serious Autobiographer
Senior Autobiographer
Master Autobiographer
Junior Famous Coder

Recent Snippets See all snippets by mprisznyak

public by mprisznyak created Apr 27, 2016  293  2  4  3

Command pattern

Look ma, no objects!
# Command Pattern 
# using only functions which are "first-class citizen" in Python
# and therefore they can be passed around 

# do something actually
def say(msg):
	print(msg)

# action functions
def meauw():
	say("meauw")

def woof():
	say("woof")
	
def neigh():
	say("nyihaha!!!")

# command -> action mapping
actions =  {
	"cat": meauw,
	"dog": woof,
	"horse": neigh,
}


def handle(command):
  """
  the command executioner...
  whoohaahaa! :)
  """
	action = actions.get(command,None)
	if action: # existing command
		action() # execute command
	else: # no command found
		say("Sorry! No %s here." % command) # no such command!


for cmd in ["cat", "horse", "dog", "elephant"]:
  handle(cmd)
                                    
;

public by mprisznyak created Jan 9, 2016  306  0  5  2

Counting specific elements in a list

The Bad, Ugly One and the Good, Beautiful One
# data
test = [1,3, 'a', 'a', 1, 1, 'b', 'a']            

# the wrong way
count = 0
for item in test:
    if item == 'a': count += 1
print("The number of 'a's is {}".format(count)) 

# the right way
print("The number of 'a's is {}".format(test.count('a'))) 
;

public by mprisznyak created Aug 4, 2015  1437  5  6  2

Command design pattern

A generic implementation for the Command design pattern It's demonstrated by two toy examples: 1/ a lamp which can be turned on and off 2/ a car which can be started up, filled up with petrol and driven. Some commands have parameters in this example.
# -*- coding: utf-8 -*-
"""
Command design pattern
"""

class Command(object):
    """ generic command class
    """
    def __init__(self, action, target):
        if callable(action):
            self._action = action
        else:
            raise Exception("callable action required")
        self.target = target

    def execute(self, *args):
        self._action(*args)


class CommandClient(object):
    """Generic command client class"""

    def __init__(self, subject):
        self.subject = subject
        self._commands = {}

    def reset_subject(self):
        self.subject.__init__()

    def add_command(self, command_name, action):
        """
        :param command_name: the name of the command
        :type command_name: string
        :param action: a method of 'subject'
        :type action: string
        """
        command_name = command_name.strip().upper()
        action = getattr(self.subject, action, None)
        if action:
            self._commands[command_name] = Command(action, self.subject)
        else:
            raise Exception("invalid action %s" % action)

    def execute(self, cmd, *args):
        """
        :param cmd: command name
        :type cmd: string
        :param args: possible arguments for command
        :type args: optional input parameters for command
        """
        cmd = cmd.strip().upper()
        command = self._commands.get(cmd)
        if command is None:
            print 'Unknown command ', cmd
        else:
            command.execute(*args)

    def query(self, attr):
        """
        :param attr: name of attribute for 'subject'
        :type attr: string
        """
        return getattr(self.subject, attr, "Undefined")



class Light(object):
    """An example command receiver class"""

    ON = "ON"
    OFF = "OFF"

    def __init__(self):
        self.state = Light.OFF

    def turn_on(self):
        print "Switching the lights on"
        self.state = Light.ON

    def turn_off(self):
        print "Switching the lights off"
        self.state = Light.OFF

class Car(object):
    """Another example command receiver class"""

    PETROL_IN_100 = 6.5

    def __init__(self):
        self.engine_running = False
        self.speed = 0.0
        self.fuel = 0.0

    def start(self):
        if self.fuel > 0.0:
            print "The car engine is starting..."
            self.engine_running = True
        else:
            print "The car tank is empty"

    def drive(self, distance):
        " drive distance kilometres"
        if self.engine_running:
            fuel_required = distance*self.PETROL_IN_100/100.0
            if self.fuel < fuel_required:
                print "The car needs fuel"
            else:
                print "  travelled %s kms" % distance
                self.fuel -= fuel_required
                print "  %s litres of petrol left" % self.fuel
        else:
            print "Car engine hasn't been started..."

    def fill_up_with_petrol(self, amount):
        self.fuel += amount


if __name__ == "__main__":

    print "========= Lights ==========="
    light_switch = CommandClient(Light())
    light_switch.add_command("ON", "turn_on")
    light_switch.add_command("OFF", "turn_off")

    light_switch.execute("ON")
    print "The lamp is", light_switch.query("state")
    light_switch.execute("OFF")
    print "The lamp is", light_switch.query("state")
    print "Invalid Command for lights"
    light_switch.execute("****")
    print "Lamp is", light_switch.query("state")


    print
    print "====== Fine ride ========"
    car_ride = CommandClient(Car())
    car_ride.add_command("fill", "fill_up_with_petrol")
    car_ride.add_command("Start", "start")
    car_ride.add_command("DRIVE", "drive")

    car_ride.execute("FILL", 15)
    print "fuel: ", car_ride.query("fuel")
    car_ride.execute("START")
    car_ride.execute("DRIVE", 34)

    print
    print "==== Fool's ride  ======="
    car_ride.reset_subject()

    print "fuel: ", car_ride.query("fuel")
    car_ride.execute("DRIVE", 77)
    print "fuel: ", car_ride.query("fuel")
    car_ride.execute("START")
    car_ride.execute("FILL", 15)
    car_ride.execute("DRIVE", 18843)
    print "fuel: ", car_ride.query("fuel")            
;

public by mprisznyak created Jul 1, 2015  1391  0  6  2

Tell it in code

Descriptive code, please, instead of descriptions in comments
# Not so good
class BadWidget(object):
  """
  A Widget which draws itself
  """
  def __init__(self, **params):
    self.params = params
    self.flags = 0b0000

  def set_flags(self, new_value):
    self.flags |= new_value

  def draw(self):
    if self.flags & 0b1000:  # Am I visible?
      print ("You can see a real BadWidget!")


# Better
class GoodWidget(BadWidget):

  @property
  def is_visible(self):
    return self.flags & 0b1000

  def draw(self):
    if self.is_visible:
      print ("You can see a real GoodWidget!")

            
;

public by mprisznyak created Dec 10, 2014  415  2  5  2

Do something until you find a specific value in a sequence

The Bad, Ugly Villain and the Good, Handsome Hero
# test.txt contains this:
# 1
# 344
# END
# ff
# and you want to count how many lines there are before "END"

# the ugly way
with open("test.txt") as f:
    counter = 0
    while True:
        line = f.readline()
        if line == 'END':
            break
        counter += 1
print counter, "lines before END"

# the cool way                   
with open("test.txt") as f:
    counter = 0
    # https://docs.python.org/2/library/functions.html#iter
    for line in iter(f.readline, 'END'):
        counter += 1
print counter, "lines before END"
                                    
;