def is_balanced_b_tree(self, tree) -> bool:
        balanceStatuswithheight = collections.nametuple(
            'balancedStatusWithHeight', ('balanced', 'height'))

        def check_balance(tree):
            if not tree:
                return balanceStatuswithheight(True, -1)
            left_result = check_balance(tree.left)
            if not left_result.balanced:
                return balanceStatuswithheight(False, 0)
            right_result = check_balance(tree.right)
            if not right_result.balanced:
                return balanceStatuswithheight(False, 0)
            is_balanced = abs(left_result.height - right_result.height) <= 1
            height = max(left_result.height, right_result.height)
            return balanceStatuswithheight(is_balanced, height)

        return check_balance(tree).balanced
Ejemplo n.º 2
0
class ConfigParseOptions(
        collections.nametuple(
            'ConfigParseOptions',
            ('syntax', 'origin_description', 'allow_missing', 'includer'))):
    """
    A set of options related to parsing.

    <p>
    This object is immutable, so the "setters" return a new object.

    <p>
    Here is an example of creating a custom {@code ConfigParseOptions}:

    <pre>
        ConfigParseOptions options = ConfigParseOptions.defaults()
            .setSyntax(ConfigSyntax.JSON)
            .setAllowMissing(false)
    </pre>

    :param syntax: ConfigSyntax
        The file format. If set to null, try to guess from any available
        filename extension; if guessing fails, assume {@link ConfigSyntax#CONF}.

    :param origin_description: String
        A description for the thing being parsed. In most cases this will be
        set up for you to something like the filename, but if you provide just an
        input stream you might want to improve on it. Set to null to allow the
        library to come up with something automatically. This description is the
        basis for the {@link ConfigOrigin} of the parsed values.

    :param allow_missing: boolean
        Set to false to throw an exception if the item being parsed (for example
        a file) is missing. Set to true to just return an empty document in that
        case.

    :param includer: ConfigIncluder
        A ConfigIncluder which customizes how includes are handled.
    """
    @classmethod
    def defaults(cls):
        """
        :return: ConfigParseOptions
        """
        return ConfigParseOptions(
            syntax=None,
            origin_decription=None,
            allow_missing=True,
            includer=None,
        )

    def set_syntax(self, syntax):
        """
        Set the file format. If set to null, try to guess from any available
        filename extension; if guessing fails, assume {@link ConfigSyntax#CONF}.

        @param syntax
                   a syntax or {@code null} for best guess
        @return options with the syntax set

        :param syntax: ConfigSyntax
        :return: ConfigParseOptions
        """
        return self._replace(syntax=syntax)

    def set_origin_description(self, origin_description):
        """
        Set a description for the thing being parsed. In most cases this will be
        set up for you to something like the filename, but if you provide just an
        input stream you might want to improve on it. Set to null to allow the
        library to come up with something automatically. This description is the
        basis for the {@link ConfigOrigin} of the parsed values.

        @param originDescription
        @return options with the origin description set

        :param origin_description: String
        :return: ConfigParseOptions
        """
        return self._replace(origin_description=origin_description)

    def _with_fallback_origin_description(self, origin_description):
        if self.origin_description is None:
            return self.replace(origin_description=origin_description)
        else:
            return self

    def set_allow_missing(self, allow_missing):
        """
        Set to false to throw an exception if the item being parsed (for example
        a file) is missing. Set to true to just return an empty document in that
        case.

        @param allowMissing
        @return options with the "allow missing" flag set

        :param allow_missing: Boolean
        :return: ConfigParseOptions
        """
        return self._replace(allow_missing=allow_missing)

    def set_includer(self, includer):
        """
        Set a ConfigIncluder which customizes how includes are handled.

        @param includer
        @return new version of the parse options with different includer

        :param includer: ConfigIncluder
        :return: ConfigParseOptions
        """
        return self._replace(includer=includer)

    def prepend_includer(self, includer):
        """
        :param includer: ConfigIncluder
        :return: ConfigParseOptions
        """
        if self.includer is not None:
            return self.set_includer(includer.with_fallback(self.includer))
        else:
            return self.set_includer(includer)

    def append_includer(self, includer):
        """
        :param includer: ConfigIncluder
        :return: ConfigParseOptions
        """
        if self.includer is not None:
            return self.set_includer(self.includer.with_fallback(includer))
        else:
            return self.set_includer(includer)
Ejemplo n.º 3
0
-class
#===================================================================
#format
#https://www.python-course.eu/python3_formatted_output.php
#===================================================================
#arg parse
'''
-Multiple options in any order.
-Short and long options.
-Default values.
-Generation of a usage help message.
-requried args
'''
#https://www.pyimagesearch.com/2018/03/12/python-argparse-command-line-arguments/

from argparse

parser = argparse.ArgumentParser()
parser.add_argument("-f", "--file", dest="filename",required = True
                    help="write report to FILE", metavar="FILE")
parser.add_argument("-q", "--quiet",
                    action="store_false", dest="verbose", default=True,
                    help="don't print status messages to stdout")

#will turn argments name and arg values into dictionary
#args[file]
args = vars(parser.parse_args())

#command line arg
import sys
#command line argument can be access through sys.argv as list
print(sys.argv) #[arg1,arg2,arg3]
filename = sys.argv[1]

#===================================================================
#lambda
bigger = lambda  x , y : x if x > y else y
bigger(4,3)
fruits = ['apple', 'banana','pear']
sorted(fruits,key = lambda word: word[::-1])


#===================================================================
#list comphrehension
arr = [3,4,2,1]
val_pos={v:p for (p,v) in enumerate(arr)}

#* for unpacking
#https://www.python.org/dev/peps/pep-3132/
#===================================================================
#list comphrehension 
a = { good:1, #line break are ignored in [],{},(), no need \
     bad:2}

symbols = "absded"
ascii = [ord(s) for s in symbols if ord(s) > 127]
ascii = list(filter(lambda c: c> 127, map(ord,symbols))) #same as above

#cartesian product using list comphrehension
colors = ['black', 'white']
sizes = ['S','M','L']
#make two nested for loop in a listcomp
tshirts = [(color,size) for color in colors for size in sizes]

#-----------------------------------------------------------------
#using tuple unpacking to swap two variable without using a temp var
a, b = b, a
divmod(20,8)
t = (20,8)
divmod(*t) #*t unpack tuple as separate arg 

#using * for grab excess/rest items
a,b,*rest =range(5) 
'''
(0,1,[2,3,4])
'''
a,*body,b =range(5) 
'''
(0,1[1,2],3)
'''

*a, = range(5)

for a, *b in [(1, 2, 3), (4, 5, 6, 7)]:
    print(b)
'''
[2, 3]
[5, 6, 7]
'''

#unpacking nested tuple as long as expression match the nested struct
metro_area = [
    ('Tokyo','JP',36.933,(35.44,139.33)),
    #...
]
for name ,cc ,pop ,(lat, lon) in metro_area:
    #do something

#-----------------------------------------------------------------
#named tuple as record
from collections import nametuple
#class take two args:1.class name 2.field names delimited by space
City = nametuple('City','name country population coordinates')
Tokyo = City('Tokyo','JP',36.44,(35.32,193.11)) #construct an instance of this tuple class with filed init
Tokyo.name #can access filed by name or position
Tokyo[1] #JP

#inherited special method 
City._files #print out all the fileds
LatLong = nametuple('lat','lon')
shanghai_data = ('Shanghai','CN',21.2,Latlong(28.34,139.23)) #constructor could be inside another
Shanghai = City._make(shanghai_data) #init from a iterable , 
Shanghai = City(*shanghai_data) #will do the same
Shanghai._asdict() #return ordered dict with each file name as key

#-----------------------------------------------------------------
#slicing
s[begin:end:step] #step can be negative in opposite order
s.__getitem__(slice(start,stop,step))
#we cand name the slice object like name a group of cells in excel
#and then pass the slice object to the list the seq to retrive the relevant filed
UNIT_PRICE = slice(3,10)
items[UNIT_PRICE] #same as: items[3:10]

#multiple dim array with ellipsis
#for numpy.ndarray get access multiple dim array
a[i,j]
a[m:n,k:l]
x[i,...] #same as x[i,:,:,:,]

#assignment to slices
l[2:5] = [20,30]
del l[5:7]
l[3::2] = [11,22]
l[2:5] = [100] #when the target of assignment is a slice ,RHS must be an iterable

#-----------------------------------------------------------------
# using + and * with seq
# both + and * will create a new object but never chang the operands
l = [1,2,3]
l * 2#[1,2,3,1,2,3]
2 * 'abc' #'abcabc'
#when a * n a is a seq containing mutable items
#will return 3 reference to the inner mutable item
my_list =[[1]] * 3 #[[1],[1],[1]]
my_list[1][0] = 99 #[[99],[99],[99]]

#use listcomp to int list of list
board = [['_']*3] for i in range(3)] #seq of "_" not mutable
Ejemplo n.º 4
0
data.columns
data.shape
pd.to_datetime(data)
data.year
def analyze_df(df,colnames):
  for col in colnames:
    print(f'mean {df[col].mean()})
    print(f'max {df[col].max()}')
    print(f'minimo {df[col].min()}')
def increment_year(df):
  df['year']=df['year']+1    

#errores
#atributos 
from collections import nametuple
person= nametuple('person','name age year')
david= person(name='carlos',age=30,year=1987)
david.name
david.age
david.year
#key error
d.get('x','default')
d.['d']=8 #añadir al diccionario
d['d'] #llamar
#type error
#value error
#import error no tienes importador instalado
#io error archivo que no existe ruta mal
#manually raisen exceptions
def even_number_check(n):
  if n % 2 != 0:
Ejemplo n.º 5
0
#coding: utf-8
from abc import ABC, abstractmethod
from collections import nametuple

Customer = nametuple('Customer', 'name fidelity')


class LineItem(object):
    def __init__(self, product, quantity, price):
        self.product = product
        self.quantity = quantity
        self.price = price

    def total(self):
        return self.quantity * self.price


class Order(object):  #上下文
    def __init__(self, customer, cart, promotion=None):
        self.customer = customer
        self.cart = list(cart)
        self.promotion = promotion

    def total(self):
        if not hasattr(self, '__total'):
            self.__total = sum(item.total() for item in self.cart)
        return self.__total

    def due(self):
        if self.promotion is None:
            discount = 0
Ejemplo n.º 6
0
class Block(collections.nametuple('Block',['scope','unit_fn','args'])):
    '''A named tuple describing a ResNet block'''
Ejemplo n.º 7
0
# 爲元組命名, 使用元組節省內存空間
from collections import nametuple
Student = nametuple('Student', ['name', 'age', 'sex', 'email']) # 創建了一個命名元組類
s = Student('Jim', 16, 'male', '*****@*****.**') # s是一個元組
isinstance(s, tuple) # True
s.name
s.age



# 字典值排序
# 1.1. 轉換爲元組排序
from random import randint
d = {k: randint(60, 100) for k in 'abcdefgh'}
l = [(v, k) for k, v in d.items()]
sorted(l, reverse= True)

# 1.2. zip, 背後都是轉換成元組排序
list(zip(d.values, d.keys()))

# 2. 直接利用sorted的key參數
p =sorted(d.items(), key=lambda item: item[1], reverse=True)

# 將結果賦予次序
for i, (k, v) enumerate(p, 1): # 返回一個enumerate對象,第二個參數代表起始值
    d[k] = (i, v)
# {'h': (1, 99), 'g': (5, 98).....}
# 也可以生成一個新字典
{k: (i, v) for i, (k, v) in enumerate(p, 1)}

Ejemplo n.º 8
0
Archivo: 3_31.py Proyecto: wUWu11/ics31
Syntax - grammar , how you say something
Semantics - meaning, what it does

Syntactically incorrect: PI equals 3.14159
Semantically incorrect: PI = "apple"

Multi - value data
    - LISTS
        -[1,2,4,5,6]
    - Nametuples - package heterogeneous things into a item

'''

#using a nametuple

#First: import the appropriate components

from collections import nametuple

# Second: Define what your object looks like

Student = nametuple("Student", "name id major GPA")

#Third: Create distinct students

s1 = student("John Doe", 12345678, "ics", 3.5)
s2 = student("Jane Doe", 81442144, "ics", 3.9)

print(s1.name)
print(s2.name)
Ejemplo n.º 9
0
# %%

import collections

Card = collections.namedtuple('Card', ['rank', 'suit'])
"""
collections.nametuple()创建简单类 适用于有少数属性且没有函数的类
:param Card 纸牌类类名
:param rank 牌数
:param suit 花色['黑桃', '方块', '梅花', '桃心']
"""


class FrenchDeck:
    ranks = [str(n) for n in range(2, 11)] + list('JQKA')
    suits = '黑桃 方块 梅花 桃心'.split()

    def __init__(self) -> None:
        self._cards = [
            Card(rank, suit) for suit in self.suits for rank in self.ranks
        ]

    def __len__(self):
        return len(self._cards)

    def __getitem__(self, position):
        return self._cards[position]


if __name__ == "__main__":
    beer_card = Card('7', '黑桃')