Skip to content

Instantly share code, notes, and snippets.

@moonblade
Created October 20, 2019 17:06
Show Gist options
  • Save moonblade/7053cea95e64e0da9f6f6bc62e720150 to your computer and use it in GitHub Desktop.
Save moonblade/7053cea95e64e0da9f6f6bc62e720150 to your computer and use it in GitHub Desktop.
#!/usr/local/bin/python3
# generic test case maker for hacker rank questions
from __future__ import print_function
from enum import Enum
import random
from lorem.text import TextLorem
from datetime import datetime
from random import randrange
from datetime import timedelta
import string
# Input types, Attributes
# common: name(string), print(bool), probability(0 to 1)
# Int : minVal, maxVal
# Static: value
# Loop: length, elements (list of other inputs)
# Date: from, to, format
# String: minLength, maxLength
# Sentence: minLength, maxLength
defaults = {
"intMinVal": 1,
"intMaxVal": 10000,
"loopLength": 10,
"staticValue": " ",
"dateFrom": "1970-01-01",
"dateTo": "2100-12-31",
"dateFormat": "%Y-%m-%d",
"print": True,
"strMin": 3,
"strMax": 10,
"parMin": 3,
"parMax": 10,
"probability": 1
}
named = {}
letters = string.ascii_lowercase
def random_date(start, end):
"""
This function will return a random datetime between two datetime
objects.
"""
delta = end - start
int_delta = (delta.days * 24 * 60 * 60) + delta.seconds
random_second = randrange(int_delta)
return start + timedelta(seconds=random_second)
class Type(Enum):
Int="Int"
Static="Static"
Loop="Loop"
Date="Date"
String="String"
Sentence="Sentence"
class Input():
def __init__(self, dict):
self.dict = dict
self.name = self.getData("name")
self.type = Type[dict["type"]]
self.probability = self.getData("probability")
self.setPrint()
named[self.name] = self
def getData(self, key, defKey=None):
returnVal = None
if defKey is None and key in defaults:
returnVal = defaults[key]
if defKey is not None and defKey in defaults:
returnVal = defaults[defKey]
if key in self.dict:
if isinstance(self.dict[key], int):
returnVal = self.dict[key]
if self.dict[key] in named:
returnVal = named[self.dict[key]].value
else:
returnVal = self.dict[key]
# print(key, returnVal)
return returnVal
def setPrint(self):
self.print = self.getData("print")
if self.print and not self.probability == 1:
if (random.random() > self.probability):
self.print = False
def generate(self):
pass
@staticmethod
def getInput(dict):
return globals()[dict["type"]](dict)
class Int(Input):
def __init__(self, dict):
super(Int, self).__init__(dict)
self.minVal = self.getData("minVal", "intMinVal")
self.maxVal = self.getData("maxVal", "intMaxVal")
self.generate()
def generate(self):
self.value = random.randint(self.minVal, self.maxVal)
class Static(Input):
def __init__(self, dict):
super(Static, self).__init__(dict)
self.generate()
def generate(self):
self.value = self.getData("value", "staticValue")
class Loop(Input):
def __init__(self, dict):
super(Loop, self).__init__(dict)
self.elements = []
self.length = self.getData("length", "loopLength")
if "elements" in dict:
for y in range(self.length):
for x in dict["elements"]:
self.elements.append(Input.getInput(x))
self.generate()
def generate(self):
if self.type == Type.Loop:
self.value = [x.value for x in self.elements]
class Date(Input):
def __init__(self, dict):
super(Date, self).__init__(dict)
self.format = self.getData("format", "dateFormat")
self.dateFrom = datetime.strptime(self.getData("from", "dateFrom"), self.format)
self.to = datetime.strptime(self.getData("to", "dateTo"), self.format)
self.generate()
def generate(self):
self.value = random_date(self.dateFrom, self.to).strftime(self.format)
class String(Input):
def __init__(self, dict):
super(String, self).__init__(dict)
self.minLength = self.getData("minLength", "strMin")
self.maxLength = self.getData("maxLength", "strMax")
self.generate()
def generate(self):
self.length = random.randint(self.minLength, self.maxLength)
self.value = ''.join(random.choice(letters) for i in range(self.length))
class Sentence(Input):
def __init__(self, dict):
super(Sentence, self).__init__(dict)
self.minLength = self.getData("minLength", "parMin")
self.maxLength = self.getData("maxLength", "parMax")
self.generate()
def generate(self):
sen = TextLorem(srange=(self.minLength, self.maxLength))
self.value = sen.sentence()
class Generator():
def __init__(self, input):
self.input = []
self.testCases = input["testCases"]
for x in input["inputs"]:
self.input.append(Input.getInput(x))
def generate(self):
string = []
for _ in range(self.testCases):
testCase = []
for y in self.input:
if y.print:
testCase.append(y.value)
string.append(testCase)
return string
def pprint(self, string):
for x in string:
for y in x:
if isinstance(y, list):
for z in y:
print(z, end='')
else:
print(y, end='')
print()
if __name__ == "__main__":
# input = {"testCases":1,
# "inputs":[
# {
# "type": "Int",
# "minVal": 1,
# "maxVal": 10,
# "name": "firstNumber",
# "print": False
# },
# {
# "type": "Date"
# },{
# "type": "String"
# },{
# "type": "Static"
# }, {
# "type": "Sentence"
# },
# {
# "type": "Static",
# "value": "\n"
# },
# {
# "type": "Loop",
# "length": "firstNumber",
# "elements": [{
# "type": "Int"
# }, {
# "type": "Static",
# "value": " "
# }]
# },
# ]}
input = {
"testCases": 1,
"inputs": [{
"type": "Int",
"minVal": 1,
"maxVal": 10,
"name": "dateLen",
"print": False
},{
"type": "Loop",
"length": "dateLen",
"elements": [{
"type": "Sentence"
}, {
"type": "Date"
}]
}, {
"type": "Sentence",
"probability": 0.5
}]
}
g=Generator(input)
g.pprint(g.generate())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment