def wrapper(*args, **kwargs):
     start_time = time.time()
     f = fn(*args, **kwargs)
     end_time = time.time()
     logger().info("%s() running costs time is : %s ms" %
                   (fn.__name__, 1000 * (end_time - start_time)))
     return f
def validate_age(name):
    age = 0
    try:
        age = input('Welcome {}. How old are you? '.format(name))
        age = int(age)
    except ValueError:
        logger().info("Age {} is invalid, please try again…".format(age))
        return False, age
    return True, age
Ejemplo n.º 3
0
def print_data_number(data_apply: str):
    """
    打印每种数据集对应的样本数量。
    :param data_apply:
    :return:
    """
    data_file = os.path.join(get_data_dir(), data_apply)
    with open(data_file, mode="r", encoding="UTF-8") as reader:
        logger().info(
            data_file.split("/")[-1] + " has " + str(len(reader.readlines())) +
            " examples !")
def connect_to(filepath):
    """
    对输入参数进行校验,只有.json和.xml文件的格式才处理,否则会抛出异常。
    :param filepath:
    :return:
    """
    factory = None
    try:
        factory = connection_factory(filepath)
    except ValueError as ve:
        logger().info(ve)
    return factory
def read_file(filename: str) -> tuple:
    """

    :param filename:
    :return:
    """
    contents, labels = [], []
    with open_file(filename) as reader:
        for line in reader:
            try:
                label, content = line.strip().strip("\t")
                if content:
                    contents.append(list(native_content(content)))
                    labels.append(native_content(label))
            except:
                logger().info("跳过...")
    return contents, labels
def main():
    sqlite_factory = connect_to('data/person.sq3')
    logger().info(sqlite_factory)

    xml_factory = connect_to('data/person.xml')
    xml_data = xml_factory.parsed_data
    liars = xml_data.findall(".//{}[{}='{}']".format('person', 'lastName', 'Liar'))
    print('found: {} persons'.format(len(liars)))
    for liar in liars:
        print('first name: {}'.format(liar.find('firstName').text))
        print('last name: {}'.format(liar.find('lastName').text))
        [print('phone number ({})'.format(p.attrib['type']), p.text) for p in liar.find('phoneNumbers')]

    json_factory = connect_to('data/donut.json')
    json_data = json_factory.parsed_data
    print('found: {} donuts'.format(len(json_data)))
    for donut in json_data:
        print('name: {}'.format(donut['name']))
        print('price: ${}'.format(donut['ppu']))
        [print('topping: {} {}'.format(t['id'], t['type'])) for t in donut['topping']]
Ejemplo n.º 7
0
        # 每趟比较的次数
        for j in range(len(array)-1-i):
            # 进行元素交换
            if array[j] > array[j+1]:
                array[j], array[j+1] = array[j+1], array[j]


@calculate_time
def bubble_optimizer(array):
    """
    冒泡排序的优化,通过判断某一趟中是否有元素交换,若没有,说明已经排好序,退出循环。
    :param array:
    :return:
    """
    for i in range(len(array)-1):
        exchange = False
        for j in range(len(array)-1-i):
            if array[i] > array[i+1]:
                array[i], array[i+1] = array[i+1], array[i]
                exchange = True
        if not exchange:
            return 


if __name__ == '__main__':
    test_parameter = list(range(9))
    random.shuffle(test_parameter)
    logger().info(test_parameter)
    bubble(test_parameter)
    logger().info(test_parameter)
from utils.my_logger import logger

MINI14 = '1.4GHz Mac mini'


class AppleFactory:
    class MacMini14:
        def __init__(self):
            self.memory = 4  # 单位为GB
            self.hdd = 500  # 单位为GB
            self.gpu = 'Intel HD Graphics 5000'

        def __str__(self):
            info = ('Model: {}'.format(MINI14), 'Memory: {}GB'.format(
                self.memory), 'Hard Disk: {}GB'.format(self.hdd),
                    'Graphics Card: {}'.format(self.gpu))
            return '\n'.join(info)

    def build_computer(self, model):
        if model == MINI14:
            return self.MacMini14()
        else:
            print("I don't know how to build {}".format(model))


if __name__ == '__main__':
    a_fac = AppleFactory()
    mac_mini = a_fac.build_computer(MINI14)
    logger().info(mac_mini)
Ejemplo n.º 9
0
@calculate_time
def merge2list(first, second):
    """
    归并排序
    :param first:
    :param second:
    :return:
    """
    li = []
    i, j = 0, 0
    while i < len(first) and j < len(second):
        if first[i] <= second[j]:
            li.append(first[i])
            i += 1
        else:
            li.append(second[j])
            j += 1
    while i < len(first):
        li.append(first[i])
        i += 1
    while j < len(second):
        li.append(second[j])
        j += 1
    return li


if __name__ == '__main__':
    parameter1 = [1, 2, 3, 4, 5, 6]
    parameter2 = [1, 4, 5, 6, 7, 8]
    logger().info(merge2list(parameter1, parameter2))
 def interact_with(self, obstacle):
     logger().info('{} the Wizard battles against {} and {}!'.format(self, obstacle, obstacle.action()))
 def interact_with(self, obstacle):
     logger().info('{} the Frog encounters {} and {}!'.format(self, obstacle, obstacle.action()))
Ejemplo n.º 12
0
    查找重复数中的最后一个数,数组是排好序的。
    :param in_list:
    :param target:
    :return:
    """
    left = 0
    right = len(in_list) - 1
    while left <= right:
        middle = (left + right) // 2
        if in_list[middle] <= target:
            left += 1
        else:
            right -= 1
    return right


if __name__ == '__main__':
    parameter = [i for i in range(9)]
    logger().info(parameter)
    need = 6
    answer = binary_search_recursive_todo(parameter, need, 0, len(parameter))
    logger().info(answer)

    test_second = [1, 2, 3, 3, 3, 3, 4, 5]
    num = 3
    answer_second = search_first_number(test_second, num)
    logger().info(answer_second)

    answer_third = search_last_number(test_second, num)
    logger().info(answer_third)