content
stringlengths
7
1.05M
def staircase(size: int = 0) -> str: """Generates a staircase of '#', ascending to the right Args: size: Width and height of staircase. Returns: A string composed of '#' and ' ', separated by '\n'. When printed to console, renders the following (given 'size' of 5). # ## ### #### ##### """ result = [] for num in range(1, size + 1): result.append(' ' * (size - num) + '#' * num) return '\n'.join(result)
class ObjDiff(object): """Represents a difference between two `CopyDiff` objects. Contains a list of `DiffField` objects that represent the changes to each field in the object. Also contains the `children` field which may be be a `ChildListField`. """ def __init__(self, old, new, changes, children=None): self.old = old self.new = new self.changes = changes self.children = children def get(self, name): """Gets a scalar field with the given name.""" for field in self.changes: if field.name == name: return field return None class DiffField(object): """Represents a generic field in a diff.""" def __init__(self, name): self.name = name class ScalarField(DiffField): """Represents a change to a scalar field (i.e., not a list or dict)""" def __init__(self, name, old, new): super().__init__(name) self.new = new self.old = old class ChildListField(DiffField): """Represents a change to a list of child objects whose changes are also tracked.""" def __init__(self, name, added, removed, changed): super().__init__(name) self.added = added self.removed = removed self.changed = changed class CopyDiff(object): """Base class providing copy and diff functions""" def copy(self, **kwargs): copy = self.blank(**kwargs) copy.copy_from(self) return copy def copy_from(self, other): """Copies changes from `other` to this object.""" # Copy changes to this object for f in self.copydiff_fields(): setattr(self, f, getattr(other, f)) # Remove children deleted in other for schild in self.get_children(): if not any(map(lambda o: o.same_as(schild), other.get_children())): self.rm_child(schild) # Copy children and add new children to self for ochild in other.get_children(): # Find a matching child in this object schild = next(filter(lambda s: ochild.same_as(s), self.get_children()), None) if schild: schild.copy_from(ochild) else: newchild = self.blank_child() newchild.copy_from(ochild) self.add_child(newchild) def diff(self, new, prefix=[]): """ Returns a dict representing the differences between this mod and `new`. Return value is an `ObjDiff` representing the differences between the objects. Note: At the moment tracked children are always represented by a field called `children` and there can only be one. This can be fixed later, but it's not really needed. """ changes = [] for f in self.copydiff_fields(): o = getattr(self, f) n = getattr(new, f) if o != n: changes.append(ScalarField(f, old=o, new=n)) # List removed children added = [] removed = [] changed = [] # List removed children. for schild in self.get_children(): if not any(map(lambda n: n.same_as(schild), new.get_children())): removed.append(schild) # List added and changed children for nchild in new.get_children(): # Find a matching child in the old object ochild = next(filter(lambda s: nchild.same_as(s), self.get_children()), None) if ochild: chdiff = ochild.diff(nchild) if len(chdiff.changes) > 0: changed.append(chdiff) else: added.append(nchild) # If children changed, add a `ChildListField` to the diff. if len(added) > 0 or len(removed) > 0 or len(changed) > 0: children = ChildListField('children', added, removed, changed) else: children = None print(changes) return ObjDiff(self, new, changes, children) def blank(self, **kwargs): """Creates an "empty" instance of this object""" raise NotImplementedError def blank_child(self, **kwargs): """Creates an "empty" instance of a child of this object. None if this object can't have children""" return None def copydiff_fields(self): """Returns a list of fields to be copied or diffed""" return [] def same_as(self, other): scur = hasattr(self, 'cur_id') ocur = hasattr(other, 'cur_id') if self.id == other.id: return True if scur and ocur: return self.cur_id == other.cur_id elif scur: return self.cur_id == other.id elif ocur: return other.cur_id == self.id else: return False def get_children(self): raise NotImplementedError def add_child(self, ch): raise NotImplementedError def rm_child(self, ch): raise NotImplementedError
{ "targets": [ { "target_name": "memcpy", "sources": [ "src/memcpy.cc" ], "include_dirs" : [ "<!(node -e \"require('nan')\")", "<!(node -e \"require('node-arraybuffer')\")" ] } ] }
# extracting filter information c_ang = 2.99792458e18 # speed of light in Angstroms/s # galex filters ffuv = open('splash/filters/galex1500.res','r') fuv_band = array([]) fuv_band_sens = array([]) for line in ffuv: columns = line.strip().split() columns = array(columns).astype(float) fuv_band = append(fuv_band,columns[0]) fuv_band_sens = append(fuv_band_sens,columns[1]) ffuv.close() #ln_band_nu = numpy.log(c_ang/fuv_band) #ln_band = numpy.log(fuv_band) #upper = trapz(ln_band*fuv_band_sens,ln_band_nu) #lower = trapz(fuv_band_sens,ln_band_nu) #lambda_eff = exp(upper/lower) fnuv = open('splash/filters/galex2500.res','r') nuv_band = array([]) nuv_band_sens = array([]) for line in fnuv: columns = line.strip().split() columns = array(columns).astype(float) nuv_band = append(nuv_band,columns[0]) nuv_band_sens = append(nuv_band_sens,columns[1]) fnuv.close() # hubble filter f = open('splash/filters/ACS_F814W.res','r') f814w_band = array([]) f814w_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) f814w_band = append(f814w_band,columns[0]) f814w_band_sens = append(f814w_band_sens,columns[1]) f.close() # CFHT fu = open('splash/filters/u_megaprime_sagem.res','r') u_band = array([]) u_band_sens = array([]) for line in fu: columns = line.strip().split() columns = array(columns).astype(float) u_band = append(u_band,columns[0]) u_band_sens = append(u_band_sens,columns[1]) fu.close() # subaru fb = open('splash/filters/B_subaru.res','r') bp_band = array([]) bp_band_sens = array([]) for line in fb: columns = line.strip().split() columns = array(columns).astype(float) bp_band = append(bp_band,columns[0]) bp_band_sens = append(bp_band_sens,columns[1]) fb.close() fv = open('splash/filters/V_subaru.res','r') vp_band = array([]) vp_band_sens = array([]) for line in fv: columns = line.strip().split() columns = array(columns).astype(float) vp_band = append(vp_band,columns[0]) vp_band_sens = append(vp_band_sens,columns[1]) fv.close() fg = open('splash/filters/g_subaru.res','r') gp_band = array([]) gp_band_sens = array([]) for line in fg: columns = line.strip().split() columns = array(columns).astype(float) gp_band = append(gp_band,columns[0]) gp_band_sens = append(gp_band_sens,columns[1]) fg.close() fr = open('splash/filters/r_subaru.res','r') rp_band = array([]) rp_band_sens = array([]) for line in fr: columns = line.strip().split() columns = array(columns).astype(float) rp_band = append(rp_band,columns[0]) rp_band_sens = append(rp_band_sens,columns[1]) fr.close() fi = open('splash/filters/i_subaru.res','r') ip_band = array([]) ip_band_sens = array([]) for line in fi: columns = line.strip().split() columns = array(columns).astype(float) ip_band = append(ip_band,columns[0]) ip_band_sens = append(ip_band_sens,columns[1]) fi.close() fi = open('splash/filters/i_subaru.res','r') ic_band = array([]) ic_band_sens = array([]) for line in fi: columns = line.strip().split() columns = array(columns).astype(float) ic_band = append(ic_band,columns[0]) ic_band_sens = append(ic_band_sens,columns[1]) fi.close() f = open('splash/filters/z_subaru.res','r') zp_band = array([]) zp_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) zp_band = append(zp_band,columns[0]) zp_band_sens = append(zp_band_sens,columns[1]) f.close() fz = open('splash/filters/suprime_FDCCD_z.res','r') zpp_band = array([]) zpp_band_sens = array([]) for line in fz: columns = line.strip().split() columns = array(columns).astype(float) zpp_band = append(zpp_band,columns[0]) zpp_band_sens = append(zpp_band_sens,columns[1]) fz.close() # CFHT/UKIRT WFcam/wircam or whatever fj = open('splash/filters/J_wfcam.res','r') j_band = array([]) j_band_sens = array([]) for line in fj: columns = line.strip().split() columns = array(columns).astype(float) j_band = append(j_band,columns[0]) j_band_sens = append(j_band_sens,columns[1]) fj.close() fh = open('splash/filters/wircam_H.res','r') h_band = array([]) h_band_sens = array([]) for line in fh: columns = line.strip().split() columns = array(columns).astype(float) h_band = append(h_band,columns[0]) h_band_sens = append(h_band_sens,columns[1]) fh.close() fk = open('splash/filters/flamingos_Ks.res','r') ks_band = array([]) ks_band_sens = array([]) for line in fk: columns = line.strip().split() columns = array(columns).astype(float) ks_band = append(ks_band,columns[0]) ks_band_sens = append(ks_band_sens,columns[1]) fk.close() fk = open('splash/filters/wircam_Ks.res','r') kc_band = array([]) kc_band_sens = array([]) for line in fk: columns = line.strip().split() columns = array(columns).astype(float) kc_band = append(kc_band,columns[0]) kc_band_sens = append(kc_band_sens,columns[1]) fk.close() # ultravista f = open('splash/filters/Y_uv.res','r') y_uv_band = array([]) y_uv_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) y_uv_band = append(y_uv_band,columns[0]) y_uv_band_sens = append(y_uv_band_sens,columns[1]) f.close() f = open('splash/filters/J_uv.res','r') j_uv_band = array([]) j_uv_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) j_uv_band = append(j_uv_band,columns[0]) j_uv_band_sens = append(j_uv_band_sens,columns[1]) f.close() f = open('splash/filters/H_uv.res','r') h_uv_band = array([]) h_uv_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) h_uv_band = append(h_uv_band,columns[0]) h_uv_band_sens = append(h_uv_band_sens,columns[1]) f.close() f = open('splash/filters/K_uv.res','r') k_uv_band = array([]) k_uv_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) k_uv_band = append(k_uv_band,columns[0]) k_uv_band_sens = append(k_uv_band_sens,columns[1]) f.close() # sloan data f = open('splash/filters/u_SDSS.res','r') u_s_band = array([]) u_s_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) u_s_band = append(u_s_band,columns[0]) u_s_band_sens = append(u_s_band_sens,columns[1]) f.close() f = open('splash/filters/g_SDSS.res','r') g_s_band = array([]) g_s_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) g_s_band = append(g_s_band,columns[0]) g_s_band_sens = append(g_s_band_sens,columns[1]) f.close() f = open('splash/filters/r_SDSS.res','r') r_s_band = array([]) r_s_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) r_s_band = append(r_s_band,columns[0]) r_s_band_sens = append(r_s_band_sens,columns[1]) f.close() f = open('splash/filters/i_SDSS.res','r') i_s_band = array([]) i_s_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) i_s_band = append(i_s_band,columns[0]) i_s_band_sens = append(i_s_band_sens,columns[1]) f.close() f = open('splash/filters/z_SDSS.res','r') z_s_band = array([]) z_s_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) z_s_band = append(z_s_band,columns[0]) z_s_band_sens = append(z_s_band_sens,columns[1]) f.close() # subaru intermediate bands f = open('splash/filters/IB427.SuprimeCam.pb','r') IB427_band = array([]) IB427_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) IB427_band = append(IB427_band,columns[0]) IB427_band_sens = append(IB427_band_sens,columns[1]) f.close() f = open('splash/filters/IB464.SuprimeCam.pb','r') IB464_band = array([]) IB464_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) IB464_band = append(IB464_band,columns[0]) IB464_band_sens = append(IB464_band_sens,columns[1]) f.close() f = open('splash/filters/IB484.SuprimeCam.pb','r') IB484_band = array([]) IB484_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) IB484_band = append(IB484_band,columns[0]) IB484_band_sens = append(IB484_band_sens,columns[1]) f.close() f = open('splash/filters/IB505.SuprimeCam.pb','r') IB505_band = array([]) IB505_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) IB505_band = append(IB505_band,columns[0]) IB505_band_sens = append(IB505_band_sens,columns[1]) f.close() f = open('splash/filters/IB527.SuprimeCam.pb','r') IB527_band = array([]) IB527_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) IB527_band = append(IB527_band,columns[0]) IB527_band_sens = append(IB527_band_sens,columns[1]) f.close() f = open('splash/filters/IB574.SuprimeCam.pb','r') IB574_band = array([]) IB574_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) IB574_band = append(IB574_band,columns[0]) IB574_band_sens = append(IB574_band_sens,columns[1]) f.close() f = open('splash/filters/IB624.SuprimeCam.pb','r') IB624_band = array([]) IB624_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) IB624_band = append(IB624_band,columns[0]) IB624_band_sens = append(IB624_band_sens,columns[1]) f.close() f = open('splash/filters/IB679.SuprimeCam.pb','r') IB679_band = array([]) IB679_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) IB679_band = append(IB679_band,columns[0]) IB679_band_sens = append(IB679_band_sens,columns[1]) f.close() f = open('splash/filters/IB709.SuprimeCam.pb','r') IB709_band = array([]) IB709_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) IB709_band = append(IB709_band,columns[0]) IB709_band_sens = append(IB709_band_sens,columns[1]) f.close() f = open('splash/filters/IB738.SuprimeCam.pb','r') IB738_band = array([]) IB738_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) IB738_band = append(IB738_band,columns[0]) IB738_band_sens = append(IB738_band_sens,columns[1]) f.close() f = open('splash/filters/IB767.SuprimeCam.pb','r') IB767_band = array([]) IB767_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) IB767_band = append(IB767_band,columns[0]) IB767_band_sens = append(IB767_band_sens,columns[1]) f.close() f = open('splash/filters/IB827.SuprimeCam.pb','r') IB827_band = array([]) IB827_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) IB827_band = append(IB827_band,columns[0]) IB827_band_sens = append(IB827_band_sens,columns[1]) f.close() # newfirm bands f = open('splash/filters/J1.res','r') j1_band = array([]) j1_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) j1_band = append(j1_band,columns[0]) j1_band_sens = append(j1_band_sens,columns[1]) f.close() f = open('splash/filters/J2.res','r') j2_band = array([]) j2_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) j2_band = append(j2_band,columns[0]) j2_band_sens = append(j2_band_sens,columns[1]) f.close() f = open('splash/filters/J3.res','r') j3_band = array([]) j3_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) j3_band = append(j3_band,columns[0]) j3_band_sens = append(j3_band_sens,columns[1]) f.close() f = open('splash/filters/H1.res','r') h1_band = array([]) h1_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) h1_band = append(h1_band,columns[0]) h1_band_sens = append(h1_band_sens,columns[1]) f.close() f = open('splash/filters/H2.res','r') h2_band = array([]) h2_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) h2_band = append(h2_band,columns[0]) h2_band_sens = append(h2_band_sens,columns[1]) f.close() f = open('splash/filters/Ks_newfirm.res','r') knf_band = array([]) knf_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) knf_band = append(knf_band,columns[0]) knf_band_sens = append(knf_band_sens,columns[1]) f.close() # subaru narrow bands f = open('splash/filters/NB711.SuprimeCam.pb','r') NB711_band = array([]) NB711_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) NB711_band = append(NB711_band,columns[0]) NB711_band_sens = append(NB711_band_sens,columns[1]) f.close() f = open('splash/filters/NB816.SuprimeCam.pb','r') NB816_band = array([]) NB816_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) NB816_band = append(NB816_band,columns[0]) NB816_band_sens = append(NB816_band_sens,columns[1]) f.close() # spitzer bands fch1 = open('splash/filters/irac_ch1.res','r') ch1_band = array([]) ch1_band_sens = array([]) for line in fch1: columns = line.strip().split() columns = array(columns).astype(float) ch1_band = append(ch1_band,columns[0]) ch1_band_sens = append(ch1_band_sens,columns[1]) fch1.close() fch2 = open('splash/filters/irac_ch2.res','r') ch2_band = array([]) ch2_band_sens = array([]) for line in fch2: columns = line.strip().split() columns = array(columns).astype(float) ch2_band = append(ch2_band,columns[0]) ch2_band_sens = append(ch2_band_sens,columns[1]) fch2.close() fch3 = open('splash/filters/irac_ch3.res','r') ch3_band = array([]) ch3_band_sens = array([]) for line in fch3: columns = line.strip().split() columns = array(columns).astype(float) ch3_band = append(ch3_band,columns[0]) ch3_band_sens = append(ch3_band_sens,columns[1]) fch3.close() fch4 = open('splash/filters/irac_ch4.res','r') ch4_band = array([]) ch4_band_sens = array([]) for line in fch4: columns = line.strip().split() columns = array(columns).astype(float) ch4_band = append(ch4_band,columns[0]) ch4_band_sens = append(ch4_band_sens,columns[1]) fch4.close() ##### Extracting filter effective band centers # centers of the relevant bands (taken from Olivier+09, VISTA filter page, # Fukugita+96, newfirm filter doc, and stsci WFC3 handbook c06_uvis06 table 6.2) # Includes: # Galex # u (CFHT), b-z (subaru), zpp (subaru - calculated, but might be a bit off) # IB,NB subaru # i (CFHT) # wfcam (J), wircam (H,Kc), flamingos (Ks) # spitzer # ultravista # sloan # newfirm # hubble f814w ## ALL OF THESE HAVE BEEN PAINSTAKINGLY ORDERED - KEEP THEM THIS WAY fuv_cent = 1551.3 nuv_cent = 2306.5 u_s_cent = 3540.0 u_cent = 3911.0 ib427_cent = 4256.3 b_cent = 4439.6 ib464_cent = 4633.3 gp_cent = 4728.3 g_s_cent = 4770.0 ib484_cent = 4845.9 ib505_cent = 5060.7 ib527_cent = 5258.9 vp_cent = 5448.9 ib574_cent = 5762.1 r_s_cent = 6222.0 ib624_cent = 6230.0 rp_cent = 6231.8 ib679_cent = 6778.8 ib709_cent = 7070.7 nb711_cent = 7119.6 ib738_cent = 7358.7 ic_cent = 7628.9 ip_cent = 7629.1 i_s_cent = 7632.0 ib767_cent = 7681.2 f814w_cent = 8024 nb816_cent = 8149.0 ib827_cent = 8240.9 zp_cent = 9021.6 z_s_cent = 9049.0 zpp_cent = 9077.4 y_uv_cent = 10210.0 j1_cent = 10484.0 j2_cent = 11903.0 j_cent = 12444.1 j_uv_cent = 12540.0 j3_cent = 12837.0 h1_cent = 15557.0 h_uv_cent = 16460.0 h2_cent = 17059.0 ks_cent = 21434.8 kc_cent = 21480.2 k_uv_cent = 21490.0 knf_cent = 21500.0 ch1_cent = 35262.5 ch2_cent = 44606.7 ch3_cent = 56762.4 ch4_cent = 77030.1
class Move: """ A Player where the user chooses its moves. === Public Attributes === row: The row that move takes place. col: The column that move takes place. """ row: int col: int def __init__(self, row: int, col: int) -> None: """ Creates Move with <row> row and <col> column. """ self.row = row self.col = col def get_row(self) -> int: """ Returns the row. """ return self.row def get_col(self) -> int: """ Returns the column. """ return self.col def to_string(self) -> str: """ Returns the string representation of Move in (row, column). """ return "(" + str(self.row) + "," + str(self.col) + ")"
def calculate_subsidy(income, children_count): if 30_000 <= income < 40_000 and children_count >= 3: return 1000 * children_count elif 20_000 <= income < 30_000 and children_count >= 2: return 1500 * children_count elif income < 20_000: return 2000 * children_count return 0 income = float(input("Inserire il reddito annuo (-1 per uscire): ")) while income >= 0: children = int(input("Inserire il numero di figli: ")) subsidy = round(calculate_subsidy(income, children), 2) if subsidy == 0: print("La famiglia non ha diritto ad un sussidio annuo.") else: print(f"La famiglia ha diritto a {subsidy}$ di sussidio annuo.") income = float(input("Inserire il reddito annuo (-1 per uscire): "))
#Let's teach the Robots to distinguish words and numbers. #You are given a string with words and numbers separated by whitespaces (one space). #The words contains only letters. You should check if the string contains three words in succession. #For example, the string "start 5 one two three 7 end" contains three words in succession. def checkio(string): string = string.split() lista = [] for c in string: if c.isalpha(): lista.append(c) if len(lista)==3: break else: lista.clear() if len(lista)==3: return True else: return False if __name__ == '__main__': print('Example:') print(checkio("Hello World hello")) print(checkio("haaas h366lo hello")) print(checkio('o 111 rato roeu a 111roupa do rei de roma')) print(checkio('he is 123 man')) print(checkio('one two 3 four five six 7 eight 9 ten eleven 12'))
# The MIT License (MIT) # Copyright (c) 2020, Tangliufeng for labplus Industries # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. class Service(object): """ 服务 """ def __init__(self, uuid): self.uuid = uuid self.characteristics = [] self.value_handle = None def __repr__(self): return "<{} {}{}>" .format(self.__class__.__name__, self.uuid, (': ' + str(self.characteristics).strip('[').strip(']')) if self.characteristics else '') def __setitem__(self, index, val): self.characteristics[index] = val def __getitem__(self, index): return self.characteristics[index] def __len__(self): return len(self.characteristics) def add_characteristics(self, *characteristics): """ 添加特征 """ for characteristic in tuple(characteristics): self.characteristics.append(characteristic) return self @property def definition(self): if self.characteristics: return (self.uuid, tuple([char.definition for char in self.characteristics])) else: raise ValueError("A service must contain at least one characteristics") @property def handles(self): service_handles = () for char in self.characteristics: service_handles += char.handles return service_handles @handles.setter def handles(self, value_handles): slice_start, slice_end = 0, 0 for n, char in enumerate(self.characteristics): slice_end += len(char.handles) char.handles = value_handles[slice_start:slice_end] slice_start = slice_end # def clear(self): # self.characteristics = []
# Time: O(logn) # Space: O(1) class Solution(object): def singleNonDuplicate(self, nums): """ :type nums: List[int] :rtype: int """ left, right = 0, len(nums)-1 while left <= right: mid = left + (right - left) / 2 if not (mid%2 == 0 and mid+1 < len(nums) and \ nums[mid] == nums[mid+1]) and \ not (mid%2 == 1 and nums[mid] == nums[mid-1]): right = mid-1 else: left = mid+1 return nums[left]
# -*- coding: utf-8 -*- ''' 模拟一个快餐店门店 ''' __author__ = 'lai yao (lake.lai)' __date__ ="$2019-06-25 10:02:39$"
class resolutions(object): res_1080p = '1080p' res_720p = '720p' res_1080i = '1080i' res_1024x768 = '1024x768' res_1360x768 = '1360x768' class modes(object): single = 'single' pip = 'pip' side_full = 'side_full' side_scale = 'side_scale' class ports(object): port_1 = '1' port_2 = '2' class pip_positions(object): top_left = 'top_left' top_right = 'top_right' bottom_left = 'bottom_left' bottom_right = 'bottom_right' class pip_sizes(object): small = 'small' medium = 'medium' large = 'large' class pip_borders(object): show = 'show' hide = 'hide'
#!/usr/bin/env python # -*- coding: utf-8 -*- """ :Purpose: This module contains various low-level conversion functions. :Platform: Linux/Windows | Python 3.8 :Developer: J Berendt :Email: development@s3dev.uk :Comments: These functions are designed to be as close to core Python, or a C-esque implementation, as possible. """ # TODO: Move repeated messages into a central messaging class. def ascii2bin(asciistring: str) -> str: """Convert an ASCII string into a binary string representation. Args: asciistring (str): ASCII string to be converted. Returns: str: A binary string representation for the passed ASCII text. """ return ''.join(map(int2bin, ascii2int(asciistring))) def ascii2hex(asciistring: str) -> str: """Convert an ASCII string into a hexidecimal string. Args: asciistring (str): ASCII string to be converted. Returns: str: A hexidecimal string representation of the passed ASCII text. """ return ''.join(map(int2hex, ascii2int(asciistring))) def ascii2int(asciistring: str) -> list: """Convert an ASCII string to a list of integers. Args: asciistring (str): ASCII string to be converted. Returns: list: A list of integers, as converted from he ASCII string. """ return [ord(i) for i in asciistring] def bin2ascii(binstring: str, bits: int=8) -> str: """Convert a binary string representation into ASCII text. Args: binstring (str): Binary string to be converted. bits (int, optional): Bit chunks into which the binary string is broken for conversion. Defaults to 8. Returns: str: An ASCII string representation of the passed binary string. """ if len(binstring) % bits: raise ValueError('The string length cannot be broken into ' f'{bits}-bit chunks.') ints = [] for chunk in range(0, len(binstring), bits): byte_ = binstring[chunk:chunk+bits] ints.append(bin2int(byte_, bits=bits)[0]) text = ''.join(map(int2ascii, ints)) return text def bin2int(binstring: str, bits: int=8) -> int: """Convert a binary string representation into an integer. Args: binstring (str): Binary string to be converted. bits (int, optional): Bit chunks into which the binary string is broken for conversion. Defaults to 8. Returns: int: Integer value from the binary string. """ if len(binstring) % bits: raise ValueError('The string length cannot be broken into ' f'{bits}-bit chunks.') ints = [] for chunk in range(0, len(binstring), bits): int_ = 0 s = 0 byte = binstring[chunk:chunk+bits] for b in range(len(byte)-1, -1, -1): int_ += int(byte[b]) << s s += 1 ints.append(int_) return ints def bin2hex(binstring: str, bits: int=8) -> str: """Convert a binary string representation into a hex string. Args: binstring (str): Binary string to be converted. bits (int, optional): Bit chunks into which the binary string is broken for conversion. Defaults to 8. Returns: A hexidecimal string representation of the passed binary string. """ if len(binstring) % bits: raise ValueError('The string length cannot be broken into ' f'{bits}-bit chunks.') return ''.join(int2hex(i) for i in bin2int(binstring, bits=bits)) def hex2ascii(hexstring: str) -> str: """Convert a hexidecimal string to ASCII text. Args: hexstring (str): Hex string to be converted. Returns: str: An ASCII string representation for the passed hex string. """ return ''.join(map(int2ascii, hex2int(hexstring))) def hex2bin(hexstring: str) -> str: """Convert a hexidecimal string into a binary string representation. Args: hexstring (str): Hex string to be converted. Returns: str: A binary string representation of the passed hex string. """ return ''.join(map(int2bin, hex2int(hexstring))) def hex2int(hexstring: str, nbytes: int=1) -> int: """Convert a hexidecimal string to an integer. Args: hexstring (str): Hex string to be converted. nbytes (int, optional): Number of bytes to consider for each decimal value. Defaults to 1. :Examples: Example usage:: hex2int(hexstring='c0ffee', nbytes=1) >>> [192, 255, 238] hex2int(hexstring='c0ffee', nbytes=2) >>> [49407, 238] hex2int(hexstring='c0ffee', nbytes=3) >>> [12648430] Returns: list: A list of decimal values, as converted from the hex string. """ nbytes *= 2 out = [] # Split hex string into (n)-byte size chunks. for chunk in range(0, len(hexstring), nbytes): i = 0 for char in hexstring[chunk:nbytes+chunk]: if (char >= '0') & (char <= '9'): nib = ord(char) if (char >= 'a') & (char <= 'f'): nib = ord(char) + 9 if (char >= 'A') & (char <= 'F'): nib = ord(char) + 9 i = (i << 4) | (nib & 0xf) out.append(i) return out def int2ascii(i: int) -> str: """Convert an integer to an ASCII character. Args: i (int): Integer value to be converted to ASCII text. Note: The passed integer value must be <= 127. Raises: ValueError: If the passed integer is > 127. Returns: str: The ASCII character associated to the passed integer. """ if i > 127: raise ValueError('The passed integer value must be <= 127.') return chr(i) def int2bin(i: int) -> str: """Convert an 8-bit integer to a binary string. Args: i (int): Integer value to be converted. Note: The passed integer value must be <= 255. Raises: ValueError: If the passed integer is > 255. Returns: str: A binary string representation of the passed integer. """ if i > 255: # Limited to 1 byte. raise ValueError(f'Passed value exceeds 1 byte: {i=}') return ''.join(str((i >> shift) & 1) for shift in range(7, -1, -1)) def int2hex(i: int) -> str: """Convert an integer into a hexidecimal string. Args: i (int): Integer value to be converted. Returns: str: A two character hexidecimal string for the passed integer value. """ chars = '0123456789abcdef' out = '' out_ = '' while i > 0: out_ += chars[i % 16] i //= 16 # Output string must be reversed. for x in range(len(out_)-1, -1, -1): out += out_[x] # Pad so all hex values are two characters. if len(out) < 2: out = '0' + out return out
my_foods = ['pizza', 'tartalete', 'pastel', 'hamburguer'] miguel_foods = my_foods[:] print(my_foods, miguel_foods) # copia a lista do primeiro ao último item my_foods.append('strawberry') miguel_foods.append('lollipop') print(my_foods, miguel_foods) other_person_foods = miguel_foods.copy() # também serve para copiar uma lista # miguel_foods = my_foods está errado, pois assim é feito uma linkagem com a lista e nao uma copia
# Please complete the following exercise this week. Write a Python script containing a function called factorial() # that takes a single input/argument (x) which is a positive integer and returns its factorial. # The factorial of a number is that number multiplied by all of the positive numbers less than it. # For example, the factorial of 5 is 5x4x3x2x1 which equals 120. # You should, in your script, test the function by calling it with the values 5, 7, and 10. # First define function factorial(x) returning factorial of input x def factorial(x): result = x for a in range(x-1,1,-1): result = result * a return result # Test for numbers 5,7,10 for x in (5,7,10): print(f"{x}! = ",factorial(x)) # Results checked using scientifict calculator factorial function
class Generic: def __init__(self, **kwargs): self.__dict__.update(kwargs)
while True: if hero.canCast("regen"): bernardDistance = hero.distanceTo("Bernard") if bernardDistance < 10: hero.cast("regen", "Bernard") chandraDistance = hero.distanceTo("Chandra") if chandraDistance < 10: hero.cast("regen", "Chandra") else: enemy = hero.findNearestEnemy() if enemy and hero.distanceTo(enemy) <= hero.attackRange: hero.attack(enemy);
m=0 n=120120 while 1: c=0 for i in range(1,n+1): if (n*n)%i==0: #print("--------",i,(n*n)%i,(n*(n+i))%i) c+=1 if c>m: m=c print(n,m) if(m>=1000): break else: n+=20
"""Configuration File for pyCon server and client""" HOST = '127.0.0.1' PORT = 8000 SERVER_ADDRESS = 'http://127.0.0.1:8000'
# 3Sum fixes one number and uses either the two pointers pattern or a hash set to find complementary pairs. Thus, the time complexity is O(N^2) # Two Pointers class Solution: def threeSumClosest(self, nums: List[int], target: int) -> int: diff = float('inf') nums.sort() for i in range(len(nums)): # set up two pointers lo, hi = i+1,len(nums)-1 while (lo<hi): sum = nums[i]+nums[lo]+nums[hi] if abs(target - sum) < abs(diff): diff = target - sum if sum < target: lo+=1 else: hi-=1 if diff == 0: break return target - diff # Time: O(N^2): O(NlogN + N^2) # Space:O(logN) to O(N)
# mypy: allow-untyped-defs class EventListener: def __init__(self, dispatcher_token): super().__init__() self.dispatcher_token = dispatcher_token self.token = None def send_message(self, message): raise Exception("Client.send_message(message) not implemented!")
class SkuItem(): def __init__(self, id, lookup, other_offers=None) -> None: self._id = id self._lookup = lookup self._unrelated_offers = other_offers if other_offers is not None else {} def _calc_free_unrealted_items(self, count): res = {} for other_id, other_count in self._unrelated_offers.items(): if other_id == self._id: continue # count how many free there should be res[other_id] = count//other_count return res def calculate_cost(self, items_count: int) -> int: items_cost = 0 if self._id in self._unrelated_offers: # check how many free Fs by checking groups of (2+1) offer_counts = items_count // (self._unrelated_offers[self._id] + 1) # apply cost with reduced effective count items_cost += self._lookup[1]*(items_count - offer_counts) else: remaining_count = items_count offer_amounts = list(self._lookup.keys()) offer_amounts.sort(reverse=True) for offer_units in offer_amounts: offer_collection_price = self._lookup[offer_units] speacials_count = remaining_count // offer_units remaining_count = remaining_count % offer_units items_cost += speacials_count*offer_collection_price assert remaining_count == 0 return items_cost, self._calc_free_unrealted_items(items_count)
n = int(input()) values = [int(input()) for _ in range(n)] values_10_20 = [value for value in values if value >= 10 and value <= 20] print('{} in'.format(len(values_10_20))) print('{} out'.format(len(values) - len(values_10_20)))
class SessionHelper: def __init__(self, app): self.app = app def login(self, username, password): driver = self.app.driver self.app.open_page() driver.find_element_by_name("username").click() driver.find_element_by_name("username").clear() driver.find_element_by_name("username").send_keys(username) driver.find_element_by_xpath("//div/div").click() driver.find_element_by_name("password").click() driver.find_element_by_name("password").clear() driver.find_element_by_name("password").send_keys(password) driver.find_element_by_xpath("//button[@type='submit']").click() def logout(self): driver = self.app.driver driver.find_element_by_xpath("//div[@id='app']/aside/div[2]/div/div[2]/div/div/div/div").click() driver.find_element_by_xpath("//button[@type='submit']").click() def is_logged_in(self): driver = self.app.driver return len(driver.find_elements_by_xpath("//button[@type='submit']")) > 0 def is_logged_in_as(self, username): driver = self.app.driver return driver.find_element_by_xpath("//div[@id='app']/aside/div[2]/div/div[2]/div/div/div/div").text == username def ensure_logout(self): driver = self.app.driver if self.is_logged_in(): self.logout() def ensure_login(self, username, password): driver = self.app.driver if self.is_logged_in(): if self.is_logged_in_as(username): return else: self.logout() self.login(username, password)
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None """ timecomplexity= O(n) spacecomplexity = O(n) serialize construct recusive function to covert tree into string replace None by '# ' and use ' ' to separate each node deserialize At first, define a list which element is from the string split ' ', then check special tase if len is 0 or only '#' in the List construct recusive function to get tree node from the List by pop the [0] from it. """ class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str """ def rserialize(root,string): if root == None: string += '# ' else: string += str(root.val) + ' ' string = rserialize(root.left,string) string = rserialize(root.right, string) return string string = rserialize(root, '') return string def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode """ def rdeserialize(l): if len(l) == 0: return if l[0] == '#': l.pop(0) return None root = TreeNode(l[0]) l.pop(0) root.left = rdeserialize(l) root.right = rdeserialize(l) return root data_list = data.split(' ') return rdeserialize(data_list) # Your Codec object will be instantiated and called as such: # codec = Codec() # codec.deserialize(codec.serialize(root))
# -*- coding: utf-8 -*- __version__ = '0.0.2' __author__ = 'matteo vezzola <matteo@studioripiu.it>' default_app_config = 'ripiu.cmsplugin_vivus.apps.VivusConfig'
''' Given an array of integers heights representing the histogram's bar height where the width of each bar is 1, return the area of the largest rectangle in the histogram. Time Complexity : O(N^2) ''' def Largest_Rectangle_In_Histogram(height): height.append(0) res = 0 st = [-1] for i in range(len(height)): # store the heights in increasing order in the stack while height[i]<height[st[-1]]: h = height[st.pop()] w = i - st[-1] - 1 res = max(res,h*w) st.append(i) height.pop() return res height = [2,1,5,6,2,3] print(Largest_Rectangle_In_Histogram(height))
"""Gazebo colors. https://bitbucket.org/osrf/gazebo/src/default/media/materials/scripts/gazebo.material?fileviewer=file-view-default#gazebo.material-129 """ materials = { 'Gazebo/Grey': { 'ambient': [0.3, 0.3, 0.3, 1.0], 'diffuse': [0.7, 0.7, 0.7, 1.0], 'specular': [0.01, 0.01, 0.01, 1.0] }, 'Gazebo/Gray': { 'ambient': [0.3, 0.3, 0.3, 1.0], 'diffuse': [0.7, 0.7, 0.7, 1.0], 'specular': [0.01, 0.01, 0.01, 1.0] }, 'Gazebo/DarkGrey': { 'ambient': [0.175, 0.175, 0.175, 1.0], 'diffuse': [0.175, 0.175, 0.175, 1.0], 'specular': [0.175, 0.175, 0.175, 1.0] }, 'Gazebo/DarkGray': { 'ambient': [0.175, 0.175, 0.175, 1.0], 'diffuse': [0.175, 0.175, 0.175, 1.0], 'specular': [0.175, 0.175, 0.175, 1.0] }, 'Gazebo/White': { 'ambient': [1, 1, 1, 1], 'diffuse': [1, 1, 1, 1], 'specular': [0.1, 0.1, 0.1, 1] }, 'Gazebo/FlatBlack': { 'ambient': [0.1, 0.1, 0.1, 1], 'diffuse': [0.1, 0.1, 0.1, 1], 'specular': [0.01, 0.01, 0.01, 1.0] }, 'Gazebo/Black': { 'ambient': [0, 0, 0, 1], 'diffuse': [0, 0, 0, 1], 'specular': [0.1, 0.1, 0.1, 1] }, 'Gazebo/Red': { 'ambient': [1, 0, 0, 1], 'diffuse': [1, 0, 0, 1], 'specular': [0.1, 0.1, 0.1, 1] }, 'Gazebo/RedBright': { 'ambient': [0.87, 0.26, 0.07, 1], 'diffuse': [0.87, 0.26, 0.07, 1], 'specular': [0.87, 0.26, 0.07, 1] }, 'Gazebo/Green': { 'ambient': [0, 1, 0, 1], 'diffuse': [0, 1, 0, 1], 'specular': [0.1, 0.1, 0.1, 1] }, 'Gazebo/Blue': { 'ambient': [0, 0, 1, 1], 'diffuse': [0, 0, 1, 1], 'specular': [0.1, 0.1, 0.1, 1] }, 'Gazebo/SkyBlue': { 'ambient': [0.13, 0.44, 0.70, 1], 'diffuse': [0, 0, 1, 1], 'specular': [0.1, 0.1, 0.1, 1] }, 'Gazebo/Yellow': { 'ambient': [1, 1, 0, 1], 'diffuse': [1, 1, 0, 1], 'specular': [0, 0, 0, 1] }, 'Gazebo/ZincYellow': { 'ambient': [0.9725, 0.9529, 0.2078, 1], 'diffuse': [0.9725, 0.9529, 0.2078, 1], 'specular': [0.9725, 0.9529, 0.2078, 1] }, 'Gazebo/DarkYellow': { 'ambient': [0.7, 0.7, 0, 1], 'diffuse': [0.7, 0.7, 0, 1], 'specular': [0, 0, 0, 1] }, 'Gazebo/Purple': { 'ambient': [1, 0, 1, 1], 'diffuse': [1, 0, 1, 1], 'emissive': [1, 0, 1, 1] }, 'Gazebo/Turquoise': { 'ambient': [0, 1, 1, 1], 'diffuse': [0, 1, 1, 1], 'specular': [0.1, 0.1, 0.1, 1] }, 'Gazebo/Orange': { 'ambient': [1, 0.5088, 0.0468, 1], 'diffuse': [1, 0.5088, 0.0468, 1], 'specular': [0.5, 0.5, 0.5, 1] }, 'Gazebo/Indigo': { 'ambient': [0.33, 0.0, 0.5, 1], 'diffuse': [0.33, 0.0, 0.5, 1], 'specular': [0.1, 0.1, 0.1, 1] } }
# Crie um programa que leia o nome de uma cidade e diga se ela começa ou não com o nome "SANTO" nome = str(input('Qual o nome da cidade que você nasceu? ')).strip() print(nome[:5].upper() == 'SANTO') # Exercício Python 025: Crie um programa que leia o nome de uma pessoa e diga se ela tem "SILVA" no nome. nome = str(input('Qual é o seu nome completo? ')).strip() print('Seu nome começa com Silva? {}'.format(nome[:5].upper() == 'SILVA')) print('Seu nome tem Silva? {}'.format('SILVA'in nome.upper())) print('Seu nome tem Silva? {}'.format('silva'in nome.lower()))
class SetSettings: def __init__(self, token: str, version: int = 1): self.token: str = token self.version: int = version self.headers: dict = dict(Authorization=self.token) self.url: str = 'http://devapi.set.uz' self.main_api: str = f'{self.url}/api/v{self.version}/integration'
#!/usr/bin/env python # -*- coding:utf-8 -*- # file:__init__.py.py # author:PigKinght # datetime:2021/8/26 15:26 # software: PyCharm """ this is function description """
# -*- coding: utf-8 -*- ''' File name: code\perfection_quotients\sol_241.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #241 :: Perfection Quotients # # For more information see: # https://projecteuler.net/problem=241 # Problem Statement ''' For a positive integer n, let σ(n) be the sum of all divisors of n, so e.g. σ(6) = 1 + 2 + 3 + 6 = 12. A perfect number, as you probably know, is a number with σ(n) = 2n. Let us define the perfection quotient of a positive integer asp(n)=  σ(n)n . Find the sum of all positive integers n ≤ 1018 for which p(n) has the form k + 1⁄2, where k is an integer. ''' # Solution # Solution Approach ''' '''
def trailingZeroes(n): res = 0 i = 5 while i <= n: res+= n//i i*=5 return res n = 30 print("Number of Zeros in factorial of {0} is ".format(n),trailingZeroes(n))
# Given the names and grades for each student in a Physics class of N students, # store them in a nested list and print the name(s) of any student(s) having the second lowest grade. # Note: If there are multiple students with the same grade, order their names alphabetically # and print each name on a new line. # # Input Format # The first line contains an integer, N, the number of students. # The 2N subsequent lines describe each student over 2 lines; # the first line contains a student's name, and the second line contains their grade. # # Constraints # 2 <= N <= 5 # There will always be one or more students having the second lowest grade. # Output Format # Print the name(s) of any student(s) having the second lowest grade in Physics; # if there are multiple students, order their names alphabetically and print each one on a new line. # # Sample Input # 5 # Harry # 37.21 # Berry # 37.21 # Tina # 37.2 # Akriti # 41 # Harsh # 39 # # Sample Output # Berry # Harry # inputs students_quantity = int(input()) students = [[str(input()), float(input())] for i in range(students_quantity)] # get the lowest grade and remove all occurences of it from the list of grades lowest_grade = min([grade for name, grade in students]) grades = [grade for name, grade in students] lowest_grade_count = grades.count(lowest_grade) for i in range(lowest_grade_count): grades.remove(lowest_grade) # get the second lowest grade and # check which students have this grade second_lowest_grade = min(grades) second_lowest_grade_students = [name for name, grade in students if grade == second_lowest_grade] second_lowest_grade_students.sort() # print in alphabetical order the students names for student_name in second_lowest_grade_students: print(student_name)
class Joueur(): def __init__(self, tour): self._score = 0 self._tour = tour self.listeCouleurs = [] def getScore(self): return self._score def ajouterScore(self, valeur): self._score += valeur def getTour(self): return self._tour def setTour(self, tour): self._tour = tour def getCouleurs(self): return self.listeCouleurs def ajouterCouleur(self, couleur): self.listeCouleurs.append(couleur) def getNombreCouleurs(self): return len(self.listeCouleurs)
''' merge 2 orderd linked list into one linked list ''' class LinkedList: class Node: def __init__(self, data, next ): self.data = data self.next = next def __del__(self): print('结点被删除... 数据域值为 %s'%self.data) def __init__(self, lt_data): self.head = LinkedList.Node(len(lt_data), None) self.lt_data = lt_data def init(self): ''' 构造链表 :return: ''' cur = self.head for item in self.lt_data: tmp = LinkedList.Node(item, None) cur.next = tmp cur = tmp def print_whole(self): ''' 从头打印整个链表 :param head: :return: ''' cur = self.head while cur != None: print(cur.data) cur = cur.next def merge2orderedlinkedlist(linkedlist_1, linkedlist_2): ''' 将两个有序的链表合并为一个有序的链表 :param linkedlist_1: :param linkedlist_2: :return: merged linkedlist ''' if linkedlist_1.head.data == 0 and linkedlist_2.head.data > 0: return linkedlist_2 elif linkedlist_2.head.data == 0 and linkedlist_1.head.data > 0: return linkedlist_1 elif linkedlist_1.head.data == 0 and linkedlist_2.head.data == 0: return None else: cur_1 = linkedlist_1.head.next cur_2 = linkedlist_2.head.next if cur_1.data < cur_2.data: reslinkedlist = linkedlist_1 cur_main = reslinkedlist.head else: reslinkedlist = linkedlist_2 cur_main = reslinkedlist.head while cur_1 != None and cur_2!= None: if cur_1.data < cur_2.data: cur_main.next = cur_1 cur_main = cur_1 cur_1 = cur_1.next else: cur_main.next = cur_2 cur_main = cur_2 cur_2 = cur_2.next # 如果有一个链表提前遍历结束 if cur_1 == None: # 链表1提前结束 cur_main.next = cur_2 else: # 链表2提前结束 cur_main.next = cur_1 return reslinkedlist if __name__ == '__main__': print('构造链表...') linkedlist_1 = LinkedList([1,4,5]) linkedlist_1.init() linkedlist_2 = LinkedList([2,3,8,11,14]) linkedlist_2.init() reslinkedlist = merge2orderedlinkedlist(linkedlist_1, linkedlist_2) print('打印链表...') reslinkedlist.print_whole() print('END')
__all__ = [ 'base_controller', 'mail_send_controller', 'events_controller', 'stats_controller', 'subaccounts_controller', 'subaccounts_delete_controller', 'subaccounts_get_sub_accounts_controller', 'setrecurringcreditddetails_controller', 'subaccounts_setsubaccountcredit_controller', 'subaccounts_update_subaccount_controller', 'subaccounts_create_subaccount_controller', 'suppression_controller', 'domain_delete_controller', 'domain_controller', ]
def upper_case_name(name): return name.upper() if __name__ == "__main__": name = "Nina" name_upper = upper_case_name(name) print(f"Upper case name is {name_upper}") print("dunder name", __name__)
# Source : https://leetcode.com/problems/find-all-the-lonely-nodes/ # Author : foxfromworld # Date : 13/11/2021 # First attempt # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def getLonelyNodes(self, root: Optional[TreeNode]) -> List[int]: def help(node, ret): if not node: return if not node.left and node.right: ret.append(node.right.val) if not node.right and node.left: ret.append(node.left.val) help(node.left, ret) help(node.right, ret) ret = [] help(root, ret) return ret
class Solution: def numSquareSum(self, n): squareSum = 0 while(n): squareSum += (n % 10) * (n % 10) n = int(n / 10) return squareSum def isHappy(self, n: int) -> bool: # initialize slow # and fast by n slow, fast = n while(True): # move slow number # by one iteration slow = self.numSquareSum(slow) # move fast number # by two iteration fast = self.numSquareSum(self.numSquareSum(fast)) if(slow != fast): continue else: break # if both number meet at 1, # then return true return (slow == 1)
block_size = {"width": 0.3, "height": 0.2, "length": 0.6} wall_height = 3 wall_length = 10 print( "Общая длина 1 стены:", wall_length, "\nКоличество блоков на 1 ряд:", wall_length / block_size["length"], "\nРядов нужно:", wall_height / block_size["height"], "\nБлоков на 1 стену:", ((wall_length / block_size["length"]) * (wall_height / block_size["height"])) * 2, "\nСредняя цена блока:", 80, "\nЦена за стену:", 80 * ((wall_length / block_size["length"]) * (wall_height / block_size["height"])) * 2, )
# Patick Corcoran # Chekc if a number is prime. # The primes are 2, 3, 5, 7, 11, 13, ... p = 347 isprime = True for m in range(2, p-1): if p % m == 0: isprime = False break if isprime: print(p, "is a prime number.") else: print(p, "is not prime,")
# Leo colorizer control file for yaml mode. # This file is in the public domain. # Properties for yaml mode. properties = { "indentNextLines": "\\s*([^\\s]+\\s*:|-)\\s*$", "indentSize": "2", "noTabs": "true", "tabSize": "2", "lineComment": "#", } # Attributes dict for yaml_main ruleset. yaml_main_attributes_dict = { "default": "null", "digit_re": "", "escape": "", "highlight_digits": "true", "ignore_case": "true", "no_word_sep": "", } # Dictionary of attributes dictionaries for yaml mode. attributesDictDict = { "yaml_main": yaml_main_attributes_dict, } # Keywords dict for yaml_main ruleset. yaml_main_keywords_dict = {} # Dictionary of keywords dictionaries for yaml mode. keywordsDictDict = { "yaml_main": yaml_main_keywords_dict, } # Rules for yaml_main ruleset. def yaml_rule0(colorer, s, i): return colorer.match_seq_regexp(s, i, kind="comment1", regexp="\\s*#.*$", at_line_start=True, at_whitespace_end=False, at_word_start=False, delegate="") def yaml_rule1(colorer, s, i): return colorer.match_seq(s, i, kind="label", seq="---", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def yaml_rule2(colorer, s, i): return colorer.match_seq(s, i, kind="label", seq="...", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def yaml_rule3(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq="]", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def yaml_rule4(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq="[", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def yaml_rule5(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq="{", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def yaml_rule6(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq="}", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def yaml_rule7(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq="-", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def yaml_rule8(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq="+", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def yaml_rule9(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq="|", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def yaml_rule10(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq=">", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def yaml_rule11(colorer, s, i): return colorer.match_mark_following(s, i, kind="keyword2", pattern="&", at_line_start=False, at_whitespace_end=False, at_word_start=False, exclude_match=False) def yaml_rule12(colorer, s, i): return colorer.match_mark_following(s, i, kind="keyword2", pattern="*", at_line_start=False, at_whitespace_end=False, at_word_start=False, exclude_match=False) def yaml_rule13(colorer, s, i): # Fix #1082: # Old: regexp="\\s*(-|)?\\s*[^\\s]+\\s*:(\\s|$)" # Old: at_line_start=True. return colorer.match_seq_regexp(s, i, kind="keyword1", regexp=r"\s*-?\s*\w+:", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def yaml_rule14(colorer, s, i): return colorer.match_seq_regexp(s, i, kind="literal2", regexp="\\s+~\\s*$", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def yaml_rule15(colorer, s, i): return colorer.match_seq_regexp(s, i, kind="literal2", regexp="\\s+null\\s*$", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def yaml_rule16(colorer, s, i): return colorer.match_seq_regexp(s, i, kind="literal2", regexp="\\s+true\\s*$", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def yaml_rule17(colorer, s, i): return colorer.match_seq_regexp(s, i, kind="literal2", regexp="\\s+false\\s*$", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def yaml_rule18(colorer, s, i): return colorer.match_seq_regexp(s, i, kind="literal2", regexp="\\s+yes\\s*$", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def yaml_rule19(colorer, s, i): return colorer.match_seq_regexp(s, i, kind="literal2", regexp="\\s+no\\s*$", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def yaml_rule20(colorer, s, i): return colorer.match_seq_regexp(s, i, kind="literal2", regexp="\\s+on\\s*$", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def yaml_rule21(colorer, s, i): return colorer.match_seq_regexp(s, i, kind="literal2", regexp="\\s+off\\s*$", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def yaml_rule22(colorer, s, i): return colorer.match_seq_regexp(s, i, kind="keyword2", regexp="!!(map|seq|str|set|omap|binary)", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def yaml_rule23(colorer, s, i): return colorer.match_seq_regexp(s, i, kind="keyword3", regexp="!![^\\s]+", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def yaml_rule24(colorer, s, i): return colorer.match_seq_regexp(s, i, kind="keyword4", regexp="![^\\s]+", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") # Rules dict for yaml_main ruleset. rulesDict1 = { # EKR: \\s represents [\t\n\r\f\v], so the whitespace characters themselves, rather than a backspace, must be the leadin characters! # This is a bug in jEdit2py. "\t":[yaml_rule13,yaml_rule14,yaml_rule15,yaml_rule16,yaml_rule17,yaml_rule18,yaml_rule19,yaml_rule20,yaml_rule21,], "\n":[yaml_rule13,yaml_rule14,yaml_rule15,yaml_rule16,yaml_rule17,yaml_rule18,yaml_rule19,yaml_rule20,yaml_rule21,], " ": [yaml_rule13,yaml_rule14,yaml_rule15,yaml_rule16,yaml_rule17,yaml_rule18,yaml_rule19,yaml_rule20,yaml_rule21,], "#":[yaml_rule0,], "!": [yaml_rule22,yaml_rule23,yaml_rule24,], "&": [yaml_rule11,], "*": [yaml_rule12,], "+": [yaml_rule8,], "-": [yaml_rule1,yaml_rule7,yaml_rule13], # Fix #1082. ".": [yaml_rule2,], ">": [yaml_rule10,], "[": [yaml_rule4,], ## "\\": [yaml_rule13,yaml_rule14,yaml_rule15,yaml_rule16,yaml_rule17,yaml_rule18,yaml_rule19,yaml_rule20,yaml_rule21,], "]": [yaml_rule3,], "{": [yaml_rule5,], "|": [yaml_rule9,], "}": [yaml_rule6,], # Fix #1082. "A": [yaml_rule13,], "B": [yaml_rule13,], "C": [yaml_rule13,], "D": [yaml_rule13,], "E": [yaml_rule13,], "F": [yaml_rule13,], "G": [yaml_rule13,], "H": [yaml_rule13,], "I": [yaml_rule13,], "J": [yaml_rule13,], "K": [yaml_rule13,], "L": [yaml_rule13,], "M": [yaml_rule13,], "N": [yaml_rule13,], "O": [yaml_rule13,], "P": [yaml_rule13,], "Q": [yaml_rule13,], "R": [yaml_rule13,], "S": [yaml_rule13,], "T": [yaml_rule13,], "U": [yaml_rule13,], "V": [yaml_rule13,], "W": [yaml_rule13,], "X": [yaml_rule13,], "Y": [yaml_rule13,], "Z": [yaml_rule13,], "_": [yaml_rule13,], "a": [yaml_rule13,], "b": [yaml_rule13,], "c": [yaml_rule13,], "d": [yaml_rule13,], "e": [yaml_rule13,], "f": [yaml_rule13,], "g": [yaml_rule13,], "h": [yaml_rule13,], "i": [yaml_rule13,], "j": [yaml_rule13,], "k": [yaml_rule13,], "l": [yaml_rule13,], "m": [yaml_rule13,], "n": [yaml_rule13,], "o": [yaml_rule13,], "p": [yaml_rule13,], "q": [yaml_rule13,], "r": [yaml_rule13,], "s": [yaml_rule13,], "t": [yaml_rule13,], "u": [yaml_rule13,], "v": [yaml_rule13,], "w": [yaml_rule13,], "x": [yaml_rule13,], "y": [yaml_rule13,], "z": [yaml_rule13,], } # x.rulesDictDict for yaml mode. rulesDictDict = { "yaml_main": rulesDict1, } # Import dict for yaml mode. importDict = {}
# https://adventofcode.com/2020/day/8 def execute_code(code_lines: list[str]): """ Execute program code :param code_lines: code to execute given as lines of strings :return: (True, accumulator) if execution terminates; (False, accumulator) if it goes into an infinite loop """ accumulator = 0 code_pointer = 0 lines_executed = [] while True: if code_pointer in lines_executed: return False, accumulator if code_pointer == len(code_lines): return True, accumulator code_line = code_lines[code_pointer] instruction = code_line[:3] operand = int(code_line[4:]) lines_executed.append(code_pointer) if instruction == 'nop': code_pointer += 1 continue if instruction == 'acc': accumulator += operand code_pointer += 1 continue if instruction == 'jmp': code_pointer += operand continue exit(-1) infile = open('input.txt', 'r') lines = infile.readlines() infile.close() for i in range(len(lines)): line = lines[i] line_instruction = line[:3] if line_instruction == 'jmp': lines[i] = 'nop' + line[4:] execution_result, accumulator_result = execute_code(lines) if execution_result: print(accumulator_result) exit(0) lines[i] = line continue if line_instruction == 'nop': lines[i] = 'jmp' + line[4:] execution_result, accumulator_result = execute_code(lines) if execution_result: print(accumulator_result) exit(0) lines[i] = line continue exit(-1)
def maybeBuildTrap(x, y): hero.moveXY(x, y) item = hero.findNearestItem() if item and item.type == "coin": hero.buildXY("fire-trap", x, y) while True: maybeBuildTrap(12, 56) maybeBuildTrap(68, 56) maybeBuildTrap(68, 12) maybeBuildTrap(12, 12)
""" * * Author: Juarez Paulino(coderemite) * Email: juarez.paulino@gmail.com * """ n,m=map(int,input().split()) print(*[n//m]*(m-n%m)+[n//m+1]*(n%m))
# The minimal set of static libraries for basic Skia functionality. { 'variables': { 'component_libs': [ 'core.gyp:core', 'effects.gyp:effects', 'images.gyp:images', 'opts.gyp:opts', 'ports.gyp:ports', 'sfnt.gyp:sfnt', 'utils.gyp:utils', ], 'conditions': [ [ 'skia_arch_type == "x86" and skia_os != "android"', { 'component_libs': [ 'opts.gyp:opts_ssse3', ], }], [ 'arm_neon == 1', { 'component_libs': [ 'opts.gyp:opts_neon', ], }], [ 'skia_gpu', { 'component_libs': [ 'gpu.gyp:skgpu', ], }], ], }, 'targets': [ { 'target_name': 'skia_lib', 'conditions': [ [ 'skia_shared_lib', { 'conditions': [ [ 'skia_os == "android"', { # The name skia will confuse the linker on android into using the system's libskia.so # instead of the one packaged with the apk. We simply choose a different name to fix # this. 'product_name': 'skia_android', }, { 'product_name': 'skia', }], ], 'type': 'shared_library', }, { 'type': 'none', }], ], 'dependencies': [ '<@(component_libs)', ], 'export_dependent_settings': [ '<@(component_libs)', ], }, ], } # Local Variables: # tab-width:2 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=2 shiftwidth=2:
precos = ('Lápis', 1.75, 'Borracha', 2, 'Caderno', 15.9, 'Estojo', 25, 'Transferidor', 4.2, 'Compasso', 9.99, 'Mochila', 120.32, 'Canetas', 22.3, 'Livro', 34.9) print('') print('-' * 40) print(f'{"LISTAGEM DE PREÇOS":^40}') print('-' * 40) for i in range(0, len(precos), 2): print(f'{precos[i]:.<30}R${precos[i+1]:8.2f}') print('-' * 40, end='\n\n')
# Memory reference instructions MRI = {"AND": ["0", "8"], "ADD": ["1", "9"], "LDA": ["2", "A"], "STA": ["3", "B"], "BUN": ["4", "C"], "BSA": ["5", "D"], "ISZ": ["6", "E"]} # Register reference instructions NON_MRI = {"CLA": 0x7800, "CLE": 0x7400, "CMA": 0x7200, "CME": 0x7100, "CIR": 0x7080, "CIL": 0x7040, "INC": 0x7020, "SPA": 0x7010, "SNA": 0x7008, "SZA": 0x7004, "SZE": 0x7002, "HLT": 0x7001, "INP": 0xF800, "OUT": 0xF400, "SKI": 0xF200, "SKO": 0xF100, "ION": 0xF080, "IOF": 0xF040} PSEUDO = ["ORG", "HEX", "DEC", "END"] ALONE_IN_LINE = ["CLA", "CLE", "CMA", "CME", "CIR", "CIL", "INC", "SPA", "SNA", "SZA", "SZE", "HLT", "INP", "OUT", "SKI", "SKO", "ION", "IOF", "END"]
nome = "Cristiano" for letra in nome: print(letra)
def square(aList): return map(lambda x: x**2, aList) def merge(listOne, listTwo): result = [] while listOne and listTwo: #while both the lists still have elements if listOne[0] < listTwo[0]: result.append(listOne.pop(0)) #pops the first element from listOne from listOne and adds it to result else: #listOne[0] == listTwo[0] or listTwo[0] < listOne[0] result.append(listTwo.pop(0)) #now one of the lists is empty and we can just add all the remaining contents of the nonempty list into result if listOne: result += listOne #concatenating lists is done with plus operator if listTwo: result += listTwo return result def get_break_index(aList): index = 0 #this will be the index at which we break the list in two for i in range(len(aList)): if aList[i] > 0: #it's a positive number! index = i #this is where the first positive number in the list is break #we break here so that index remains the first positive number in the list return index def challenge9(aList): break_index = get_break_index(aList) listOne = aList[0:break_index] #we know this will be the negative half listTwo = aList[break_index:] a = square(listOne)[::-1] #we need to reverse this since [-3,-2,-1] --> square --> [9,4,1] b = square(listTwo) return merge(a,b) # a = [-3,-2,0,3,4,6] # print challenge9(a)
# Operators print('Module', 10%3) print('Exponential', 5**3) print('Floor division', 9//2) # Data types print(type(5)) print(type("Luis")) print(type(5.2)) # Condition num1 = 5 num2 = 7 if num1 > num2: print(num1, 'is bigger') else: print(num2, 'is bigger')
class BaseCommand(): def __init__(self): self.pre_command() self.exec_command() self.post_command() def pre_command(self): return 0 def exec_command(self): return 0 def post_command(self): return 0 if __name__ == '__main__': cmd = BaseCommand()
class MergeSort: def __init__(self): pass def sort(self, arr): self.mergesort(arr, 0, len(arr)-1) def mergesort(self, arr, left, right): if(left >= right): return mid = int((left+right)/2) self.mergesort(arr, left, mid) self.mergesort(arr, mid+1, right) self.merge(arr,left, right, mid) def merge(self, arr, left, right, mid): i = left j = mid+1 k = left temp = [0 for i in range(right+1)] while(i <= mid and j <= right): if(arr[i] < arr[j]): temp[k] = arr[i] k += 1 i += 1 else: temp[k] = arr[j] k += 1 j += 1 while(i <= mid): temp[k] = arr[i] k += 1 i += 1 while(j <= right): temp[k] = arr[j] k += 1 j += 1 for i in range(left, right+1): arr[i] = temp[i]
# -*- coding: utf-8 -*- __version__ = '1.2.5' __author__ = 'G Adventures'
salario = float(input('Qual é o salário do funcionário? R$')) if salario <= 1250: aumento1 = salario * 15 / 100 + salario print(f'Quem ganhava R${salario:.2f} passa a ganhar R${aumento1:.2f}') else: aumento2 = salario *10 / 100 + salario print(f'Quem ganhava R${salario:.2f} passa a ganhar R${aumento2:.2f}')
class Solution: def minDistance(self, word1, word2): """ :type word1: str :type word2: str :rtype: int """ m, n = len(word1)+1, len(word2)+1 dp = [[0 for _ in range(n)] for _ in range(m)] for i in range(m): dp[i][0] = i for i in range(n): dp[0][i] = i for i in range(1, m): for j in range(1, n): dp[i][j] = min(dp[i-1][j]+1, dp[i][j-1]+1) dp[i][j] = min(dp[i][j], dp[i-1][j-1] + (0 if word1[i-1] == word2[j-1] else 1)) return dp[m-1][n-1] if __name__ == "__main__": print(Solution().minDistance("horse", "aaahorse"))
''' Created on 2012. 8. 10. @author: root ''' class StaticTestingForm: header='' deviceConnection='' def __init__(self): self.header = '''import sys # Imports the monkeyrunner modules used by this program from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice, MonkeyImage''' self.deviceConnection = ''' # Connects to the current device, returning a MonkeyDevice object device = MonkeyRunner.waitForConnection() if not device: print >> sys.stderr, "Couldn't get connection" sys.exit(1) ''' def header(self): return self.header def deviceConnection(self): return self.deviceConnection
# 定义一个函数 def hcf(x, y): """该函数返回两个数的最大公约数""" # 获取最小值 if x > y: smaller = y else: smaller = x for i in range(1,smaller + 1): if((x % i == 0) and (y % i == 0)): hcf = i return hcf # 用户输入两个数字 num1 = int(input("输入第一个数字: ")) num2 = int(input("输入第二个数字: ")) print( num1,"和", num2,"的最大公约数为", hcf(num1, num2))
# -*- coding: utf-8 -*- k = int(input()) data = {} for i in range(k): data[i] = str(input()) for q in data.items(): q = q[1].split(" ") a = int(q[0]) # 總數 b = int(q[1]) # 箱子數 c = int(q[2]) # 小箱子可裝 d = int(q[3]) # 大箱子可裝 for m in range(0, b + 1): n = b-m result = m*c + n*d if result == a: print("%d %d" % (m, n))
{ 'name': 'prue01', 'description': 'Una aplicacion de facturacion.', 'author': 'Jose Antonio Duarte Perez', 'depends': ['mail'], 'application': True, 'data': ['views/contactos.xml'] }
stack = [3, 4, 5] stack.append(6) stack.append(7) print(stack) print(stack.pop()) print(stack) print(stack.pop()) print(stack.pop()) print(stack)
print('hi') s1 = input("input s1: ") s2 = input("input s2: ") print(s1) print(s2) shorter_length = 0 longer_s = '' if (len(s1) > len(s2)): shorter_length = len(s2) longer_s = s1 else: shorter_length = len(s1) longer_s = s2 result_s = '' for i in range(shorter_length): result_s += s1[i] + s2[i] for i in range(shorter_length, len(longer_s)): result_s += longer_s[i] print(result_s)
#create veriable. cr_pass=0 defer=0 fail=0 valid=[0,20,40,60,80,100,120]#finding range. values=[] #start the programme. print("--------------------------------------------------------") while True: try: #insert from user cr_pass=int(input("Please enter your credits at pass:")) values.append(cr_pass)#append values list if cr_pass in valid :##is in range. defer=int(input("Please enter your credit at defer:")) values.append(defer)#append values list if defer in valid :##is in range. fail=int(input("Please enter your credit at fail:")) values.append(fail)#append values list if fail in valid :##is in range. if sum(values)<=120:#calculation values list and find <=120. #programme. if cr_pass==120: print("Progress\n") elif cr_pass==100: print("Progress (module trailer)\n") elif fail>=80: print("Exclude\n") else: print("Do not progress – moduleretriever\n") pass else: print("Total incorrect.\n") else: print("Out of range.\n") else: print("Out of range.\n") else: print("Out of range.\n") values.clear()##clear the values list and start with empty list. except ValueError: print("Integer required\n") pass
def a_function(x, y): if isinstance(x, float): if isinstance(y, float): z = x + y return z
# mm => make mask dirty_imagename = "dirty/" + "RCrA_13CO_all_cube_dirty.image" beamsize_major = 7.889 beamsize_minor = 4.887 pa = -77.412 # find the RMS of a line free channel chanstat = imstat(imagename=dirty_imagename, chans="1") rms1 = chanstat["rms"][0] chanstat = imstat(imagename=dirty_imagename, chans="38") rms2 = chanstat["rms"][0] rms = 0.5 * (rms1 + rms2) print("rms = " + str(rms) + "Jy/beam") def make_mask(times_sigma): immath( imagename=dirty_imagename, expr="iif(IM0>" + str(times_sigma * rms) + ",1,0)", outfile="mask/" + str(times_sigma) + "sigma.im", ) imsmooth( imagename="mask/" + str(times_sigma) + "sigma.im", major=str(2 * beamsize_major) + "arcsec", minor=str(2 * beamsize_minor) + "arcsec", pa=str(pa) + "deg", outfile="mask/" + str(times_sigma) + "sigma.im.sm", ) immath( imagename="mask/" + str(times_sigma) + "sigma.im.sm", expr="iif(IM0>0.2,1,0)", outfile="mask/" + str(times_sigma) + "sigma_mask.im", ) make_mask(10)
# pseudo code taken from CLRS book # vertices is list of vertex in graph : [0, 1, 2, 3 ...] (must be continuous) # adjacencyList is the list whose 'i'th element is list of vertices adjacent to vertex i time = 0; class vertex: def __init__(self, adjVertices, color='White', parent='None', discovery_time=float('inf'), finishing_time=float('inf')): self.adjVertices = adjVertices; self.color = color; self.parent = parent; self.discovery_time = discovery_time; self.finishing_time = finishing_time; def topological_sort(vertices, adjacencyList): global time topological_order=[] vertices_objects = [ vertex(adjacencyList[v]) for v in vertices ] time = 0 for vert in vertices: if vertices_objects[vert].color == 'White': DFS_Visit(vert, vertices_objects, adjacencyList, topological_order) topological_order.reverse() for i in range(9): print (vertices_objects[i].discovery_time,vertices_objects[i].finishing_time) return topological_order def DFS_Visit(vertex, vertices, adjacencyList, topo_order): vertex_object = vertices[vertex] vertex_object.color = 'Gray' # Vertex just been discovered global time time = time + 1 vertex_object.discovery_time = time; for vert in adjacencyList[vertex]: if vertices[vert].color == 'White': vertices[vert].parent = vertex DFS_Visit(vert, vertices, adjacencyList, topo_order) vertex_object.color = 'Black' # Discovery of this vertex has been finished time = time + 1 vertex_object.finishing_time = time topo_order.append(vertex)
# Time: O(min(n, h)), per operation # Space: O(min(n, h)) class TrieNode(object): # Initialize your data structure here. def __init__(self): self.is_string = False self.leaves = {} class WordDictionary(object): def __init__(self): self.root = TrieNode() # @param {string} word # @return {void} # Adds a word into the data structure. def addWord(self, word): curr = self.root for c in word: if c not in curr.leaves: curr.leaves[c] = TrieNode() curr = curr.leaves[c] curr.is_string = True # @param {string} word # @return {boolean} # Returns if the word is in the data structure. A word could # contain the dot character '.' to represent any one letter. def search(self, word): return self.searchHelper(word, 0, self.root) def searchHelper(self, word, start, curr): if start == len(word): return curr.is_string if word[start] in curr.leaves: return self.searchHelper(word, start+1, curr.leaves[word[start]]) elif word[start] == '.': for c in curr.leaves: if self.searchHelper(word, start+1, curr.leaves[c]): return True return False
""" TESTS is a dict with all you tests. Keys for this will be categories' names. Each test is dict with "input" -- input data for user function "answer" -- your right answer "explanation" -- not necessary key, it's using for additional info in animation. """ TESTS = { "Basics": [ { "input": ('d3', ('d6', 'b6', 'c8', 'g4', 'b8', 'g6')), "answer": 5, "explanation": ('d6', 'g6', 'b6', 'b8', 'c8') }, { "input": ('a2', ('f6', 'f2', 'a6', 'f8', 'h8', 'h6')), "answer": 6, "explanation": ('a6', 'f6', 'h6', 'h8', 'f8', 'f2') }, { "input": ('a2', ('f6', 'f8', 'f2', 'a6', 'h6')), "answer": 4, "explanation": ('a6', 'f6', 'f2', 'f8') }, ], "Extra": [ { "input": ('c5', ('h5',)), "answer": 1, "explanation": ('h5',) }, { "input": ('c5', ('e3', 'b6', 'e7', 'f2', 'd6', 'b4', 'g8', 'd4')), "answer": 0, "explanation": [] }, { "input": ('e5', ('e8', 'e2', 'h8', 'h5', 'b5', 'h2', 'b2', 'b8')), "answer": 8, "explanation": ('b5', 'b8', 'b2', 'e2', 'h2', 'h5', 'h8', 'e8') }, { "input": ('c5', ('a5', 'd5', 'g5', 'h5', 'b5', 'e5', 'f5')), "answer": 7, "explanation": ('b5', 'd5', 'e5', 'f5', 'g5', 'h5', 'a5') }, { "input": ('e1', ('e8', 'h1', 'c2', 'h5', 'e4', 'a1', 'e6', 'a3')), "answer": 3, "explanation": ('a1', 'h1', 'h5') }, { "input": ('h1', ('a5', 'b6', 'e2', 'a2', 'h5', 'e4', 'e6', 'h7')), "answer": 7, "explanation": ('h5', 'a5', 'a2', 'e2', 'e4', 'e6', 'b6') }, { "input": ('c7', ('d5', 'f7', 'e6', 'e7', 'c5', 'd6', 'e5', 'c6')), "answer": 8, "explanation": ('c6', 'd6', 'd5', 'c5', 'e5', 'e6', 'e7', 'f7') }, { "input": ('c7', ('d5', 'f7', 'e7', 'c5', 'd6', 'd4', 'c6', 'c4')), "answer": 6, "explanation": ('c6', 'd6', 'd5', 'd4', 'c4', 'c5') }, ] }
class Damage(): def __init__(self, skill:float=1, added:float=1, dealing:float=1): self.__skill = skill self.__added = added self.__dealing = dealing def get_dmg(self): return (self.__skill, self.__added-1, self.__dealing) if __name__ == '__main__': dmg = Damage(1.15, 1.14, 1.18) print(dmg.get_dmg())
class Animal: def __init__(self, name): self.name = name self.fed_times = 0 self.groomed_times = 0 def feed(self, times): print("Fed {}".format(times)) self.fed_times += times return self.fed_times def groom(self, times): print("Groomed {} times".format(times)) self.groomed_times += times return self.groomed_times
def main (): entry = int(input("Enter the number you want here : ")) prime = False #prime is defined as false and will change if entry number is a prime number. if entry > 1 : for numbers in range(2, entry): if (entry % numbers) == 0: # Check if entry number has a factor prime = True break if prime : print(entry, 'is not prime number!') else : print(entry, 'is a prime number') start = 0 finish = entry print("All prime numbers between the 0 and the enterded value are : ") for entry in range(start, finish + 1): # all prime numbers are greater than 1 if entry > 1: for numbers in range(2, entry): if (entry % numbers) == 0: break else: print(entry) main()
#MaBe nomes = [] massas = [] while True: nome = input('Digite um nome: ').upper() massa = int(input('Digite a massa: ')) nomes.append(nome) massas.append(massa) r = input('Quer continuar? [s/n] ').lower() if r == 'n': break totcad = len(nomes) pesomai = max(massas) pesomin = min(massas) print(nomes) print(massas) print(f'{totcad} pessoas cadastradas.') print(f'O meior peso foi de {pesomai}kg. {nomes[massas.index(pesomai)]}.') print(f'O menor peso foi de {pesomin}kg. {nomes[massas.index(pesomin)]}.')
""" [2017-02-10] Challenge #302 [Hard] ASCII Histogram Maker: Part 2 - The Proper Histogram https://www.reddit.com/r/dailyprogrammer/comments/5t7l07/20170210_challenge_302_hard_ascii_histogram_maker/ # Description Most of us are familiar with the histogram chart - a representation of a frequency distribution by means of rectangles whose widths represent class intervals and whose areas are proportional to the corresponding frequencies. It is similar to a bar chart, but a histogram groups numbers into ranges. The area of the bar is the total frequency of all of the covered values in the range. # Input Description You'll be given four numbers on the first line telling you the start and end of the horizontal (X) axis and the vertical (Y) axis, respectively. The next line tells you the interval for the X-axis to use (the width of the bar). Then you'll have a number on a single line telling you how many records to read. Then you'll be given the data as 2 numbers: the first is the variable, the second number is the frequency of that variable. Example: 1 4 1 10 2 4 1 3 2 3 3 2 4 6 # Challenge Output Your program should emit an ASCII histogram plotting the data according to the specification - the size of the chart and the frequency of the X-axis variables. Example: 10 9 8 7 6 5 4 *** 3*** *** 2*** *** 1*** *** 1 2 3 4 # Challenge Input 0 40 0 100 8 40 1 56 2 40 3 4 4 67 5 34 6 48 7 7 8 45 9 50 10 54 11 20 12 24 13 44 14 44 15 49 16 28 17 94 18 37 19 46 20 64 21 100 22 43 23 23 24 100 25 15 26 81 27 19 28 92 29 9 30 21 31 88 32 31 33 55 34 87 35 63 36 88 37 76 38 41 39 100 40 6 """ def main(): pass if __name__ == "__main__": main()
n = int(input()) for row in range(0, n): if row == 0 or row == n - 1: print('*' * 2 * n + ' ' * n + '*' * 2 * n) else: if row == ((n - 1) // 2): print('*' + '/' * 2 * (n - 1) + '*' + '|' * n + '*' + '/' * 2 * (n - 1) + '*') else: print('*' + '/' * 2 * (n - 1) + '*' + ' ' * n + '*' + '/' * 2 * (n - 1) + '*')
''' Implementação da priority queue com lista ordenada. ''' class Person(object): ''' nome -> nome da pessoa. prior -> prioridade da pessoa. ''' def __init__(self, name, prior): self.name = name self.prior = prior def getName(self): return self.name def getPrior(self): return self.prior class PriorityQueue(object): def __init__(self): self.pq = []# priority queue self.len = 0 # insere decrescentemente pela prioridade def push(self, person): if self.empty(): self.pq.append(person) else: flag_push = False # procura onde inserir para manter a fila ordenada. for i in range(self.len): if self.pq[i].getPrior() < person.getPrior(): self.pq.insert(i, person) flag_push = True break if not flag_push: # se entrou aqui e porque tem que inserir ao final da fila self.pq.insert(self.len, person) self.len += 1 def pop(self): if not self.empty(): self.pq.pop(0) self.len -= 1 def empty(self): if self.len == 0: return True return False def show(self): for p in self.pq: print('Nome: %s' % p.getName()) print('Prioridade: %d\n' % p.getPrior()) # criando os objetos person p1 = Person('Marcos', 28) p2 = Person('Catarina', 3) p3 = Person('Pedro', 20) p4 = Person('João', 35) # criando a fila de prioridades e inserindo os elementos. pq = PriorityQueue() pq.push(p1) pq.push(p2) pq.push(p3) pq.push(p4) print('Exibindo apos as inserções: \n') pq.show()# João, Marcos, Pedro, Catarina. # removendo elementos pq.pop() pq.pop() print('Exibindo após as remoções: \n') pq.show()# Pedro, Catarina pq.push(Person('Goku', 30)) print('Exibindo apos as inserções: \n') pq.show()# Goku, Pedro, Catarina.
# Configuration file for ipython-kernel. # See <https://ipython.readthedocs.io/en/stable/config/options/kernel.html> # With IPython >= 6.0.0, all outputs to stdout/stderr are captured. # It is the case for subprocesses and output of compiled libraries like Spark. # Those logs now both head to notebook logs and in notebooks outputs. # Logs are particularly verbose with Spark, that is why we turn them off through this flag. # <https://github.com/jupyter/docker-stacks/issues/1423> # Attempt to capture and forward low-level output, e.g. produced by Extension # libraries. # Default: True # type:ignore c.IPKernelApp.capture_fd_output = False # noqa: F821
# Copyright (C) 2001 Python Software Foundation __version__ = '0.4' __all__ = ['Errors', 'Generator', 'Image', 'MIMEBase', 'Message', 'MsgReader', 'Parser', 'StringableMixin', 'Text', 'address', 'date', ]
""" Search In Sorted Matrix: You're given a two-dimensional array (a matrix) of distinct integers and a target integer. Each row in the matrix is sorted, and each column is also sorted; the matrix doesn't necessarily have the same height and width. Write a function that returns an array of the row and column indices of the target integer if it's contained in the matrix, otherwise [-1, -1]. Sample Input: matrix = [ [1, 4, 7, 12, 15, 1000], [2, 5, 19, 31, 32, 1001], [3, 8, 24, 33, 35, 1002], [40, 41, 42, 44, 45, 1003], [99, 100, 103, 106, 128, 1004], ] target = 44 Sample Output: [3, 3] https://www.algoexpert.io/questions/Search%20In%20Sorted%20Matrix """ def searchInSortedMatrix(matrix, target): # start at top right row = 0 col = len(matrix[0]) - 1 while row < len(matrix) and col >= 0: if matrix[row][col] > target: col -= 1 # move left elif matrix[row][col] < target: row += 1 # move down else: return[row, col] return[-1, -1]
# entrada v1 v1 = float(input()) # entrada v2 v2 = float(input()) # entrada v3 v3 = float(input()) # entrada v4 v4 = float(input()) # entrada v5 v5 = float(input()) # entrada v6 v6 = float(input()) # variaveis count = 0 countJ = 0 media = 0 listV = [] listP = [] # adicionar a lista listV.append(v1) listV.append(v2) listV.append(v3) listV.append(v4) listV.append(v5) listV.append(v6) # percorrer a lista e encontrar numeros positivos for i in listV: if i >= 0: count = count + 1 listP.append(i) # percorrer a lista de positivos e calcular a media for j in listP: media = media + j countJ = countJ + 1 # media total mediaT = media / countJ print('{} valores positivos\n{:.1f}'.format(count, mediaT))
# Pretty good, but I golfed the top one even more n=input s="".join(n()for _ in"_"*int(n())) print(s.count("00")+s.count("11")+1)
"""Provides the repo macro to import google libprotobuf_mutator""" load("//third_party:repo.bzl", "tf_http_archive") def repo(): """Imports libprotobuf_mutator.""" tf_http_archive( name = "com_google_libprotobuf_mutator", sha256 = "792f250fb546bde8590e72d64311ea00a70c175fd77df6bb5e02328fa15fe28e", strip_prefix = "libprotobuf-mutator-1.0", build_file = "//third_party/libprotobuf_mutator:BUILD.bazel", urls = [ "https://storage.googleapis.com/mirror.tensorflow.org/github.com/google/libprotobuf-mutator/archive/v1.0.tar.gz", "https://github.com/google/libprotobuf-mutator/archive/v1.0.tar.gz", ], )
def do_twice(f, v): f(v) f(v) def print_twice(s): print(s) print(s) # do_twice(print_twice, 'spam') def do_four(f, v): do_twice(f, v) do_twice(f, v) do_four(print, 'spam')
phi_list = {} def naples(num): b_count = 0 rel_list = [] for i in range(1, num+1): count = 0 for j in range(2, i): if num%j==0 and i%j==0: count += 1 break if count==0: b_count += 1 rel_list.append(i) phi_list[num] = b_count for val in rel_list: if val!=1: phi_list[val*num] = phi_list[val] * phi_list[num] return b_count inc = 0 while True: inc += 1 naples(inc) if max(phi_list) > 1000000: break max1 = 0 max2 = 0 for i in phi_list: if i/phi_list[i] > max1: max1 = i/phi_list[i] max2 = i print(max2) # 510510 """ Using the fact that the totient function is multiplicative here. Our answer was not going to be a prime, since n/phi(n) is small for primes. So once we get over 1,000,000 in our list, we know the only values left to be filled in are prime. We don't have to check those. """
# -*- coding: utf-8 -*- """ Created on Mon Dec 4 12:31:27 2017 @author: James Jiang """ with open('Data.txt') as f: for line in f: number = line digits = [i for i in str(number)] step = int(len(digits)/2) for i in range(int(len(digits)/2)): digits.append(digits[i]) sum = 0 for i in range(int(len(digits)*2/3)): if digits[i] == digits[i + step]: sum += int(digits[i]) print(sum)
# https://www.youtube.com/watch?v=OSGv2VnC0go names = ["rouge", "geralt", "blizzard", "yennefer"] colors = ["red", "green", "blue", "yellow"] for color in reversed(colors): print(color) for i, color in enumerate(colors): print(i, "-->", color) for name, color in zip(names, colors): print("{:<12}{:<12}".format(name, color)) for color in sorted(zip(names, colors), key=lambda x: x[0]): print(color)
# -------------------------------------------------------------- # DO NOT EDIT BELOW OF THIS UNLESS REALLY SURE NFDUMP_FIELDS = [] NFDUMP_FIELDS.append( { "ID": "pr", "AggrType_A": "proto", "AggrType_s": "proto", "Name": "Protocol" } ) NFDUMP_FIELDS.append( { "ID": "exp", "AggrType_A": None, "AggrType_s": "sysid", "Name": "Exporter ID" } ) NFDUMP_FIELDS.append( { "ID": "sa", "AggrType_A": "srcip", "AggrType_s": "srcip", "Name": "Source Address", "Details": "IP" } ) NFDUMP_FIELDS.append( { "ID": "da", "AggrType_A": "dstip", "AggrType_s": "dstip", "Name": "Destination Address", "Details": "IP" } ) NFDUMP_FIELDS.append( { "ID": "sp", "AggrType_A": "srcport", "AggrType_s": "srcport", "Name": "Source Port" } ) NFDUMP_FIELDS.append( { "ID": "dp", "AggrType_A": "dstport", "AggrType_s": "dstport", "Name": "Destination Port" } ) NFDUMP_FIELDS.append( { "ID": "nh", "AggrType_A": "next", "AggrType_s": "nhip", "Name": "Next-hop IP Address", "Details": "IP" } ) NFDUMP_FIELDS.append( { "ID": "nhb", "AggrType_A": "bgpnext", "AggrType_s": "nhbip", "Name": "BGP Next-hop IP Address", "Details": "IP" } ) NFDUMP_FIELDS.append( { "ID": "ra", "AggrType_A": "router", "AggrType_s": "router", "Name": "Router IP Address", "Details": "IP" } ) NFDUMP_FIELDS.append( { "ID": "sas", "AggrType_A": "srcas", "AggrType_s": "srcas", "Name": "Source AS", "Details": "AS" } ) NFDUMP_FIELDS.append( { "ID": "das", "AggrType_A": "dstas", "AggrType_s": "dstas", "Name": "Destination AS", "Details": "AS" } ) NFDUMP_FIELDS.append( { "ID": "nas", "AggrType_A": "nextas", "AggrType_s": None, "Name": "Next AS", "Details": "AS" } ) NFDUMP_FIELDS.append( { "ID": "pas", "AggrType_A": "prevas", "AggrType_s": None, "Name": "Previous AS", "Details": "AS" } ) NFDUMP_FIELDS.append( { "ID": "in", "AggrType_A": "inif", "AggrType_s": "inif", "Name": "Input Interface num" } ) NFDUMP_FIELDS.append( { "ID": "out", "AggrType_A": "outif", "AggrType_s": "outif", "Name": "Output Interface num" } ) NFDUMP_FIELDS.append( { "ID": "sn4", "AggrType_A": "srcip4/%s", "AggrType_s": None, "Name": "IPv4 source network", "Details": "IP", "OutputField": "sa", "ArgRequired": True } ) NFDUMP_FIELDS.append( { "ID": "sn6", "AggrType_A": "srcip6/%s", "AggrType_s": None, "Name": "IPv6 source network", "Details": "IP", "OutputField": "sa", "ArgRequired": True } ) NFDUMP_FIELDS.append( { "ID": "dn4", "AggrType_A": "dstip4/%s", "AggrType_s": None, "Name": "IPv4 destination network", "Details": "IP", "OutputField": "da", "ArgRequired": True } ) NFDUMP_FIELDS.append( { "ID": "dn6", "AggrType_A": "dstip6/%s", "AggrType_s": None, "Name": "IPv6 destination network", "Details": "IP", "OutputField": "da", "ArgRequired": True } )
# # Vivante Cross Toolchain configuration # load("@bazel_tools//tools/build_defs/cc:action_names.bzl", "ACTION_NAMES") load("@bazel_tools//tools/cpp:cc_toolchain_config_lib.bzl", "tool_path", "feature", "with_feature_set", "flag_group", "flag_set") load("//:cc_toolchain_base.bzl", "build_cc_toolchain_config", "all_compile_actions", "all_cpp_compile_actions", "all_link_actions") tool_paths = [ tool_path(name = "ar", path = "bin/wrapper-ar",), tool_path(name = "compat-ld", path = "bin/wrapper-ld",), tool_path(name = "cpp", path = "bin/wrapper-cpp",), tool_path(name = "dwp", path = "bin/wrapper-dwp",), tool_path(name = "gcc", path = "bin/wrapper-gcc",), tool_path(name = "gcov", path = "bin/wrapper-gcov",), tool_path(name = "ld", path = "bin/wrapper-ld",), tool_path(name = "nm", path = "bin/wrapper-nm",), tool_path(name = "objcopy", path = "bin/wrapper-objcopy",), tool_path(name = "objdump", path = "bin/wrapper-objdump",), tool_path(name = "strip", path = "bin/wrapper-strip",), ] def _impl(ctx): builtin_sysroot = "external/gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu/aarch64-linux-gnu/libc" compile_flags_feature = feature( name = "compile_flags", enabled = True, flag_sets = [ flag_set( actions = all_compile_actions, flag_groups = [ flag_group( flags = [ "-idirafter", "external/gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu/aarch64-linux-gnu/libc/usr/include", "-idirafter", "external/gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu/lib/gcc/aarch64-linux-gnu/7.3.1/include", "-idirafter", "external/gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu/lib/gcc/aarch64-linux-gnu/7.3.1/include-fixed", "-idirafter", "external/gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu/lib/gcc/aarch64-linux-gnu/7.3.1/install-tools/include", "-idirafter", "external/gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu/lib/gcc/aarch64-linux-gnu/7.3.1/plugin/include", ], ), flag_group( flags = [ "-D__arm64", "-Wall", # All warnings are enabled. "-Wunused-but-set-parameter", # Enable a few more warnings that aren't part of -Wall. "-Wno-free-nonheap-object", # Disable some that are problematic, has false positives "-fno-omit-frame-pointer", # Keep stack frames for debugging, even in opt mode. "-no-canonical-prefixes", "-fstack-protector", "-fPIE", "-fPIC", ], ), ], ), flag_set( actions = all_cpp_compile_actions + [ACTION_NAMES.lto_backend], flag_groups = [ flag_group( flags = [ "-isystem" , "external/gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu/aarch64-linux-gnu/include/c++/7.3.1", "-isystem" , "external/gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu/aarch64-linux-gnu/include/c++/7.3.1/aarch64-linux-gnu", ] ), ], ), flag_set( actions = all_compile_actions, flag_groups = [ flag_group( flags = [ "-g", ], ), ], with_features = [with_feature_set(features = ["dbg"])], ), flag_set( actions = all_compile_actions, flag_groups = [ flag_group( flags = [ "-g0", "-O2", "-DNDEBUG", "-ffunction-sections", "-fdata-sections", ], ), ], with_features = [with_feature_set(features = ["opt"])], ), flag_set( actions = all_link_actions, flag_groups = [ flag_group( flags = [ "-lstdc++", ], ), ], ), flag_set( actions = all_link_actions, flag_groups = [ flag_group( flags = [ "-Wl,--gc-sections", ], ), ], with_features = [with_feature_set(features = ["opt"])], ), flag_set( actions = [ ACTION_NAMES.cpp_link_executable, ], flag_groups = [ flag_group( flags = [ "-pie", ], ), ], ), ], ) cxx_builtin_include_directories = [ "%package(@gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu//aarch64-linux-gnu/libc/usr/include)%", "%package(@gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu//lib/gcc/aarch64-linux-gnu/7.3.1/include)%", "%package(@gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu//lib/gcc/aarch64-linux-gnu/7.3.1/include-fixed)%", "%package(@gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu//lib/gcc/aarch64-linux-gnu/7.3.1/install-tools/include)%", "%package(@gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu//lib/gcc/aarch64-linux-gnu/7.3.1/plugin/include)%", "%package(@gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu//aarch64-linux-gnu/include/c++/7.3.1)%", "%package(@gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu//aarch64-linux-gnu/include/c++/7.3.1/aarch64-linux-gnu)%", ] objcopy_embed_flags_feature = feature( name = "objcopy_embed_flags", enabled = True, flag_sets = [ flag_set( actions = ["objcopy_embed_data"], flag_groups = [ flag_group( flags = [ "-I", "binary", ], ), ], ), ] ) dbg_feature = feature(name = "dbg") opt_feature = feature(name = "opt") return cc_common.create_cc_toolchain_config_info( ctx = ctx, toolchain_identifier = ctx.attr.toolchain_name, host_system_name = "", target_system_name = "linux", target_cpu = ctx.attr.target_cpu, target_libc = ctx.attr.target_cpu, compiler = ctx.attr.compiler, abi_version = ctx.attr.compiler, abi_libc_version = ctx.attr.compiler, tool_paths = tool_paths, features = [compile_flags_feature, objcopy_embed_flags_feature, dbg_feature, opt_feature], cxx_builtin_include_directories = cxx_builtin_include_directories, builtin_sysroot = builtin_sysroot, ) # DON'T MODIFY cc_toolchain_config = build_cc_toolchain_config(_impl) # EOF
dia = input('what day were you born?') mes = input('what month were you born?') ano = input('what year were you born?') saudacaoDia = ('voce nasceu no dia') saudacaoDe = ('de') print(saudacaoDia, dia,saudacaoDe,mes,saudacaoDe,ano)
#!/usr/bin/env python if __name__ == "__main__": N = int(raw_input()) for i in range(N): print(pow(i,2))
''' 1. Write a Python program to create a tuple. 2. Write a Python program to create a tuple with different data types. 3. Write a Python program to create a tuple with numbers and print one item. 4. Write a Python program to unpack a tuple in several variables. 5. Write a Python program to add an item in a tuple. 6. Write a Python program to convert a tuple to a string. 7. Write a Python program to get the 4th element and 4th element from last of a tuple. 8. Write a Python program to create the colon of a tuple. 9. Write a Python program to find the repeated items of a tuple. 10. Write a Python program to check whether an element exists within a tuple. '''
# Write a program that does the following: ## Prompt the user for their age. Convert it to a number, add one to it, and tell them how old they will be on their next birthday. ## Prompt the user for the number of egg cartons they have. Assume each carton holds 12 eggs, multiply their number by 12, and display the total number of eggs. ## Prompt the user for a number of cookies and a number of people. Then, divide the number of cookies by the number of people to determine how many cookies each person gets. age_now = int(input("How old are you? ")) age_one_year_after = age_now+1 print("Next year you will be " +str(age_one_year_after)) print("\n----------------") egg_cartoons = int(input("How much egg cartoons do you have? ")) total_eggs = egg_cartoons*12 print("Nice! So you have "+ str(total_eggs)+" eggs in total!") print("\n----------------") cookies = int(input("Give me a number of cookies: ")) people = int(input("Now, give a number of people: ")) num_parts_of_cookies = cookies/people print(f"If we divide these {cookies} cookies to these {people} people, each person with have {num_parts_of_cookies} parts of cookies")
# coding=utf-8 """ @author: xing @contact: 1059252359@qq.com @file: testbed_parser.py @date: 2021/3/5 16:12 @desc: """ def get_version(testbed: str): path = [e for e in testbed.split(" ") if e.find("/") > -1][0] full_name = path.split("/")[-1] return full_name.replace(".jar", "") def parse_engine_name(testbed: str): return get_version(testbed).split("-")[0]
listageral = [] listapar = [] listaimpar = [] while True: usuario = int(input('Digite um numero: ')) if usuario % 2 == 0: listageral.append(usuario) listapar.append(usuario) else: listageral.append(usuario) listaimpar.append(usuario) usuarioResp = str(input('Deseja continuar ? ')).upper().strip()[0] if usuarioResp == 'N': break listageral.sort() listapar.sort() listaimpar.sort() print('A lista com todos os elementos gerados é {}'.format(listageral)) print(f'A lista apenas com os PARES é {listapar}') print('A lista com os impares é: ',listaimpar)
def find_string_len(): str_dict = {x: len(x) for x in input().split(', ')} return str_dict def print_dict(dictionary): print(', '.join([f'{k} -> {v}' for k, v in dictionary.items()])) print_dict(find_string_len())
numbers = { items for items in range(2,471) if (items % 7 == 0) if (items % 5 != 0) } print (sorted(numbers))
class Node: def __init__(self, value): self.value = value self.next = None class Queue: def __init__(self): self.first = None self.last = None self.length = 0 def peek(self): if self.length > 0: return f"First: {self.first.value}\nLast: {self.last.value}\n" else: return def enqueue(self, value): new_node = Node(value) if self.length == 0: self.first = new_node self.last = new_node self.length += 1 else: new_node.next = self.last self.last = new_node self.length += 1 def dequeue(self): if self.length > 0: tmp = self.last for i in range(self.length - 2): # self.last = self.first.next tmp = tmp.next tmp.next = None self.first = tmp self.length -= 1 else: return # Instantiate Queue class q = Queue() q.enqueue('google') # 1 - First q.enqueue('twitter') # 2 q.enqueue('steam') # 3 q.enqueue('tesla') # 4 - Last print(q.peek()) q.dequeue() print(q.peek()) q.dequeue() print(q.peek())
def mdc(number_one, number_two): max_mdc = 1 if number_one < number_two: for max in range(1, abs(number_one) + 1): if number_one % max == 0 and number_two % max == 0: max_mdc = max elif number_one >= number_two: for max in range(1, abs(number_two) + 1): if number_one % max == 0 and number_two % max == 0: max_mdc = max return max_mdc class Rational: def __init__(self, numerator, denominator): self.numerator = int(numerator) self.denominator = int(denominator) def get_numerator(self): return self.numerator def get_denominator(self): return self.denominator def to_float(self): return self.numerator/self.denominator def reciprocal(self): return Rational(self.get_denominator(), self.get_numerator()) def reduce(self): mdc_value = mdc(self.get_numerator(), self.get_denominator()) return Rational(self.get_numerator() / mdc_value, self.get_denominator() / mdc_value) # Dunder methods def __add__(self, other): if isinstance(other, Rational): new_denominator = self.get_denominator() * other.get_denominator() return Rational(((new_denominator / self.get_denominator()) * self.get_numerator()) + ((new_denominator / other.get_denominator()) * other.get_numerator()), new_denominator).reduce() elif isinstance(other, int): return Rational(self.get_numerator() + self.get_denominator() * other, self.get_denominator()).reduce() elif isinstance(other, float): return self.to_float() + other else: return None def __mul__(self, other): if isinstance(other, Rational): return Rational(self.get_numerator() * other.get_numerator(), self.get_denominator() * other.get_denominator()).reduce() elif isinstance(other, int): return Rational(self.get_numerator() * other, self.get_denominator()).reduce() elif isinstance(other, float): return self.to_float() * other else: return None def __truediv__(self, other): if isinstance(other, Rational): return Rational(self.get_numerator() * other.get_denominator(), self.get_denominator() * other.get_numerator()).reduce() elif isinstance(other, int): return Rational(self.get_numerator(), self.get_denominator() * other).reduce() elif isinstance(other, float): return self.to_float() / other else: return None def __sub__(self, other): if isinstance(other, Rational): return Rational((self.get_numerator() * other.get_denominator() - self.get_denominator() * other.get_numerator()), (self.get_denominator() * other.get_denominator())).reduce() elif isinstance(other, int): return Rational(self.get_numerator() - self.get_denominator() * other, self.get_denominator()).reduce() elif isinstance(other, float): return self.to_float() - other else: return None
#!/usr/bin/env python command('start-configuration-editing') command('cd /') command('delete-element /sessionClusterConfig') command('activate-configuration')
class Field: __slots__ = ('name', 'typ') def __init__(self, typ, name=None): self.typ = typ self.name = name def __get__(self, instance, owner): if instance is None: return self typ = instance.__dict__.get(self.name) return typ.value if typ else typ def __set__(self, instance, value): instance._changed(self.name) instance.__dict__[self.name] = self.typ(value) def marshal(self, instance): return instance.__dict__[self.name].marshal()
# -*- coding: utf-8 -*- """ ------------------------------------------------- File Name: sample_16_3_coroaverager0 Description : 定义一个计算移动平均值得协程 date: 2022/3/8 ------------------------------------------------- """ def averager(): totoal = 0.0 count = 0 average = None while True: term = yield average totoal += term count += 1 average = totoal / count if __name__ == '__main__': coro_avg = averager() next(coro_avg) print(coro_avg.send(10)) print(coro_avg.send(30)) print(coro_avg.send(5))