content
stringlengths
7
1.05M
""" This module implements the helm toolchain rule. """ HelmInfo = provider( doc = "Information on Helm command line tool", fields = { "tool": "Target pointing to Helm executable", "cmd": "File pointing to Helm executable" } ) def _helm_toolchain_impl(ctx): toolchain_info = platform_common.ToolchainInfo( helminfo = HelmInfo( tool = ctx.attr.tool_path, cmd = ctx.executable.tool_path, ), ) return [toolchain_info] helm_toolchain = rule( implementation = _helm_toolchain_impl, attrs = { "tool_path": attr.label( allow_single_file = True, cfg = "host", executable = True, ), }, )
# On est sur la première case. # On a un grain de blé sur la première case. # On a un grain de blé sur l'échéquier. # Nombre de grain de blé par case. # case est un nombre entier. case = 1 # Nombre de grain blé au total sur l'échiquier. # blé est un nombre entier. ble = 1 # Coefficient d'augmentation du nombre de grain de blé par case. # coef est un nombre entier coef = 2 # Il y a 8*8=64 cases sur un échiquier. # Il nous reste 63 cases à remplir de grain de blé. # Si on veut connaitre pour toutes les cases. print("Sur la première case, il y a : ", case, "grains de blé, pour un total de : ", ble , "grains sur l'échiquier.") # On parcours les 63 cases restantes for i in range(2,65): # Les cases suivantes contienent deux fois plus de grain de blé. case = case * coef # À chaque fois on rajoute les grains de la case dans le sac de blé. ble = ble + case # Si on veut connaitre pour toutes les cases. print("Sur la case : ", i , " , il y a : ", case, "grains de blé, pour un total de : ", ble , "grains sur l'échiquier.") print("Nombre de grain de blé sur l'échéquier", ble) print("Écriture scientifique : ", ble*1.) # Poids en g. On multiplie le nombre de grain par 0.05g poids = ble * 0.05 # Poids en tonnes. On divise par 10^6 ou on multiplie par 10^-6 poids = ble * 0.05 * 10**(-6) print("Poids du blé total en tonnes : ", poids, " tonnes") # Le nombre d'année nécéssaire. # Par an, la production mondiale de blé est : 600 millions. prod_an = 600 * 10 **6 print("La production annuelle de blé est de ", prod_an, "tonnes de blé") # Le nombre d'année nécéssaire = # notre poids de blé sur l'échiquier diviser par la production annuelle. nombre_an = poids / prod_an print("Il faudra : ", nombre_an, "années à l'empereur afin de combler ça promesse.")
class ChocolateBoiler: unique_instance = None def __new__(cls, *args, **kwargs): if not cls.unique_instance: cls.unique_instance = super().__new__(cls, *args, **kwargs) return cls.unique_instance def __init__(self): self.empty = True self.boiled = False def is_empty(self): return self.empty def is_boiled(self): return self.boiled def fill(self): if self.is_empty(): self.empty = False self.boiled = False def drain(self): if not self.is_empty() and self.is_boiled(): self.empty = True def boil(self): if not self.is_empty() and not self.is_boiled(): self.boiled = True
class Solution: def numRescueBoats(self, people, limit): """ :type people: List[int] :type limit: int :rtype: int """ people.sort() l, r, cnt = 0, len(people) - 1, 0 saved = 0 while saved < len(people): if people[r] + people[l] <= limit: l += 1 saved += 1 r -= 1 saved += 1 cnt += 1 return cnt
inpu = """4 aba baba aba xzxb 3 aba xzxb ab """ inp = """100 lekgdisnsbfdzpqlkg eagemhdygyv jwvwwnrhuai urcadmrwlqe mpgqsvxrijpombyv mpgqsvxrijpombyv urcadmrwlqe mpgqsvxrijpombyv eagemhdygyv eagemhdygyv jwvwwnrhuai urcadmrwlqe jwvwwnrhuai kvugevicpsdf kvugevicpsdf mpgqsvxrijpombyv urcadmrwlqe mpgqsvxrijpombyv exdafbnobg qhootohpnfvbl suffrbmqgnln exdafbnobg exdafbnobg eagemhdygyv mpgqsvxrijpombyv urcadmrwlqe jwvwwnrhuai lekgdisnsbfdzpqlkg mpgqsvxrijpombyv lekgdisnsbfdzpqlkg jwvwwnrhuai exdafbnobg mpgqsvxrijpombyv kvugevicpsdf qhootohpnfvbl urcadmrwlqe kvugevicpsdf mpgqsvxrijpombyv lekgdisnsbfdzpqlkg mpgqsvxrijpombyv kvugevicpsdf qhootohpnfvbl lxyqetmgdbmh urcadmrwlqe urcadmrwlqe kvugevicpsdf lxyqetmgdbmh urcadmrwlqe lxyqetmgdbmh jwvwwnrhuai qhootohpnfvbl qhootohpnfvbl jwvwwnrhuai lekgdisnsbfdzpqlkg kvugevicpsdf mpgqsvxrijpombyv exdafbnobg kvugevicpsdf lekgdisnsbfdzpqlkg qhootohpnfvbl exdafbnobg qhootohpnfvbl exdafbnobg mpgqsvxrijpombyv suffrbmqgnln mpgqsvxrijpombyv qhootohpnfvbl jwvwwnrhuai mpgqsvxrijpombyv qhootohpnfvbl lekgdisnsbfdzpqlkg eagemhdygyv jwvwwnrhuai kvugevicpsdf eagemhdygyv eagemhdygyv lxyqetmgdbmh qhootohpnfvbl lxyqetmgdbmh exdafbnobg qhootohpnfvbl qhootohpnfvbl exdafbnobg suffrbmqgnln mpgqsvxrijpombyv urcadmrwlqe eagemhdygyv lxyqetmgdbmh urcadmrwlqe suffrbmqgnln qhootohpnfvbl kvugevicpsdf lekgdisnsbfdzpqlkg lxyqetmgdbmh mpgqsvxrijpombyv jwvwwnrhuai lxyqetmgdbmh lxyqetmgdbmh lekgdisnsbfdzpqlkg qhootohpnfvbl 100 exdafbnobg eagemhdygyv mpgqsvxrijpombyv kvugevicpsdf lekgdisnsbfdzpqlkg kvugevicpsdf exdafbnobg qhootohpnfvbl eagemhdygyv kvugevicpsdf suffrbmqgnln jwvwwnrhuai lekgdisnsbfdzpqlkg lekgdisnsbfdzpqlkg mpgqsvxrijpombyv jwvwwnrhuai kvugevicpsdf lekgdisnsbfdzpqlkg exdafbnobg suffrbmqgnln qhootohpnfvbl eagemhdygyv exdafbnobg suffrbmqgnln jwvwwnrhuai qhootohpnfvbl eagemhdygyv exdafbnobg exdafbnobg jwvwwnrhuai qhootohpnfvbl lxyqetmgdbmh qhootohpnfvbl suffrbmqgnln lxyqetmgdbmh qhootohpnfvbl eagemhdygyv jwvwwnrhuai eagemhdygyv qhootohpnfvbl mpgqsvxrijpombyv qhootohpnfvbl jwvwwnrhuai exdafbnobg eagemhdygyv eagemhdygyv kvugevicpsdf kvugevicpsdf jwvwwnrhuai urcadmrwlqe lxyqetmgdbmh qhootohpnfvbl exdafbnobg exdafbnobg eagemhdygyv qhootohpnfvbl exdafbnobg exdafbnobg lekgdisnsbfdzpqlkg jwvwwnrhuai eagemhdygyv urcadmrwlqe kvugevicpsdf lekgdisnsbfdzpqlkg jwvwwnrhuai eagemhdygyv lekgdisnsbfdzpqlkg exdafbnobg kvugevicpsdf jwvwwnrhuai exdafbnobg lxyqetmgdbmh exdafbnobg lxyqetmgdbmh jwvwwnrhuai mpgqsvxrijpombyv eagemhdygyv urcadmrwlqe kvugevicpsdf qhootohpnfvbl jwvwwnrhuai eagemhdygyv urcadmrwlqe urcadmrwlqe exdafbnobg qhootohpnfvbl exdafbnobg eagemhdygyv exdafbnobg jwvwwnrhuai eagemhdygyv jwvwwnrhuai mpgqsvxrijpombyv urcadmrwlqe urcadmrwlqe eagemhdygyv eagemhdygyv jwvwwnrhuai suffrbmqgnln eagemhdygyv""" inp = list(inp.strip().split("\n")) string_count = int(inp[0]) strings = [] for i in range(string_count): strings.append(inp[i+1]) query_count = int(inp[string_count + 1]) queries = [] for i in range(query_count): queries.append(inp[i + string_count + 2]) print(query_count, string_count) def queryProcessed(ele, arr): for var in arr: if (ele == var): return True return False def matchingStrings(strings, queries): query_count,string_count = len(queries),len(strings) result = [0 for x in range(query_count)] for i,query in enumerate(queries): for string in strings: if (query == string): if (not queryProcessed(query, queries[:i])): ind = i result[ind] += 1 else: ind = queries.index(query) result[i] = result[ind] return (result) print(matchingStrings(strings,queries))
class StartUploadEvent(object): """Event dispatched when an upload starts""" def __init__(self, filepath, upload_file_rank, files_to_upload): """ Constructor :param str filepath: file which starts to be uploaded :param int upload_file_rank: rank of the file in upload queue :param int files_to_upload: total files to upload count """ self._filepath = filepath self._upload_file_rank = upload_file_rank self._files_to_upload = files_to_upload @property def filepath(self): # pragma: no cover """ Getter for the file which starts to be uploaded :type: str """ return self._filepath @property def upload_file_rank(self): # pragma: no cover """ Getter for the rank of the file in upload queue :type: int """ return self._upload_file_rank @property def files_to_upload(self): # pragma: no cover """ Getter for the total files to upload count :rtype: int """ return self._files_to_upload
class Solution: def minAvailableDuration(self, slots1: List[List[int]], slots2: List[List[int]], duration: int) -> List[int]: timeslots = list(filter(lambda x: x[1] - x[0] >= duration, slots1 + slots2)) heapq.heapify(timeslots) while len(timeslots) > 1: start1, end1 = heapq.heappop(timeslots) start2, end2 = timeslots[0] if end1 >= start2 + duration: return [start2, start2 + duration] return []
someParameters = input("Please Enter some parameters: ") def createList(*someParameters): paramList = [] for add in someParameters: paramList.append(add) print(paramList) return paramList createList(someParameters)
""" Write a program that first takes the year, month (as integer), and day of the user's birth date from console. Then, calculate and print on which day of the year the user has been born. You can assume user will enter a valid value for all inputs. Example: Enter your birth year: 1998 Enter your birth month as integer (Jan=1, Feb=2, ...): 9 Enter your birth day of the month: 21 You are born at the 264th day of the year 1998. Hint: You may want to utilize your solution to leapyear problem. """ year = int(input('Enter your birth year: ')) month = int(input('Enter your birth month as integer (Jan=1, Feb=2, ...): ')) day = int(input('Enter your birth day of the month: ')) days = 0 # Part I: add days from the past months complete_months = month - 1 # We will assume february has 30 days for now and correct later # Number of days in each month: 31,30,31,30,31,30,31,31,30,31,30,31 # If we combine the pairs: 61,61,61,62,61,61 pairs = complete_months // 2 days += pairs * 61 # if number of pairs is bigger than 3, we need to add 1 since 4th pair has 62 days if pairs > 3: days += 1 # we need to add the latest month if it's not included in pairs, i.e, complete_monts % 2 != 0 if complete_months % 2 != 0: # months 1, 3, 5, 7 has 31 days if complete_months < 8: days += 31 # months 9, 11 has 30 days else: days += 30 # Part II: Correct for the February assumption (we assumed Feb has 30 days in Part I) # If the year is a leap year we need to substract 1 if year % 4 == 0 and year % 100 != 0 or year % 400 == 0: days -= 1 # If its a common we need to substract 2 else: days -= 2 # Part III: Add the days of the current month days += day print('You are born at the ' + str(days) + 'th day of the year ' + str(year) + '.')
def first_repeating(n,arr): #initialize with the minimum index possible Min = -1 #create a empty dictionary newSet = dict() # tranversing the array elments from end for x in range(n - 1, -1, -1): #check if the element is already present in the dictionary #then update min if arr[x] in newSet.keys(): Min = x #if element is not present #add element in the dictionary else: newSet[arr[x]] = 1 #print the minimum index of repeating element if (Min != -1): print("The first repeating element is",arr[Min]) else: print("There are no repeating elements") #Drivers code arr = [10, 5, 3, 4, 3, 5, 6] n = len(arr) print(first_repeating(n,arr))
SECRET_KEY = 'testing' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } } INSTALLED_APPS = [ 'django.contrib.contenttypes', 'django.contrib.auth', 'django.contrib.admin', 'django.contrib.staticfiles', 'django.contrib.sessions', 'cruditor', ] # We really don't rely on the urlconf but we need to set a path anyway. ROOT_URLCONF = 'django.contrib.staticfiles.urls' STATIC_URL = '/static/'
class Drawable(): def draw(self, screen): pass def blit(self, screen): pass
# Arke # User-configurable settings. # Dirty little seeekrits... SECRET_KEY='much_sekrit_such_secure_wow' # Database # See http://docs.sqlalchemy.org/en/rel_0_9/core/engines.html#database-urls # With DEBUG defined, this is ignored and a SQLite DB in the root folder is used instead. # SQLite is probably not the best for production, either... DB_URL='sqlite:///arke.db' # Development DEBUG=True
#crie um programa que leia o preço de um #produto e mostre seu novo preço com 5% #de desconto p=float(input('Digite o preço do produto:R$ ')) pn=p-(p*5/100) print ('O novo preço com desconto de 5% é:R$ {:.2f}'.format (pn))
class TrieNode: def __init__(self, c=None, end=False): self.c = c self.children = {} self.end = end class Trie: def __init__(self): """ Initialize your data structure here. """ self.root = TrieNode('') def insert(self, word: str) -> None: """ Inserts a word into the trie. """ root = self.root for ch in word: if ch not in root.children: node = TrieNode(ch) root.children[ch] = node root = root.children[ch] root.end = True def search(self, word: str) -> bool: """ Returns if the word is in the trie. """ root = self.root for ch in word: if ch not in root.children: return False root = root.children[ch] return root.end def startsWith(self, prefix: str) -> bool: """ Returns if there is any word in the trie that starts with the given prefix. """ root = self.root for ch in prefix: if ch not in root.children: return False root = root.children[ch] return True
def n_choose_m_iterator(N, M, startpoint=None): if startpoint is None: subscripts = list(range(M)) else: subscripts = copy.deepcopy(startpoint) while True: yield subscripts off = M - 1 while off > -1: rev_off = M - off if subscripts[off] < N - rev_off and off >= 0: break off -= 1 if off < 0: break subscripts[off] += 1 off += 1 while off < M: subscripts[off] = subscripts[off - 1] + 1 off += 1 def main(): n = 4 m = 2 for sub in n_choose_m_iterator(n, m): print(sub) if __name__ == '__main__': main()
#Author wangheng class Solution: def isNStraightHand(self, hand, W): c = collections.Counter(hand) for i in sorted(c): if c[i] > 0: for j in range(W)[::-1]: c[i + j] -= c[i] if c[i + j] < 0: return False return True
class EnumMeta(type): base = False def __new__(cls, name, bases, kw): klass = type.__new__(cls, name, bases, kw) if not EnumMeta.base: EnumMeta.base = True return klass return klass() class Enum(metaclass=EnumMeta): def __getitem__(self, key): if isinstance(key, int): for k in dir(self): if len(k)==2: if getattr(self, k)==key: return k return self.__missing__(key) return getattr(self, key, self.__missing__(key)) def __missing__(self, key): return None class chatCommu(Enum): en = 1 fr = 2 ru = 3 br = 4 es = 5 cn = 6 tr = 7 vk = 8 pl = 9 hu = 10 nl = 11 ro = 12 id = 13 de = 14 e2 = 15 ar = 16 ph = 17 lt = 18 jp = 19 fi = 21 cz = 22 hr = 23 bg = 25 lv = 26 he = 27 it = 28 pt = 31 def __missing__(self, key): if isinstance(key, int): return 'int' return 1 class commu(Enum): en = 0 fr = 1 br = 2 es = 3 cn = 4 tr = 5 vk = 6 pl = 7 hu = 8 nl = 9 ro = 10 id = 11 de = 12 e2 = 13 ar = 14 ph = 15 lt = 16 jp = 17 ch = 18 fi = 19 cz = 20 sk = 21 hr = 22 bu = 23 lv = 24 he = 25 it = 26 et = 27 az = 28 pt = 29 def __missing__(self, key): if isinstance(key, int): return 'int' return 0
# #.. create syth_test.geo file form this file # # python3 mkSyntheticGeoData2D.py test # #.. create 3D mesh syth_testmesh.msh # # gmsh -3 -format msh2 -o syth_testmesh.msh syth_test.geo # #.. run for synthetic data # # python3 mkSyntheticData2D.py -s synth -g -m test # # creating test_grav.nc and test_mag.nc # # next step is start the inversion process: # # python3 mkGeoFromNc.py -c 60 -p 60 -h 1. -P benchmark1 -g test_grav.nc -m test_mag.nc # project="test" km=1000. gravfile=project+"_grav1Noise.nc" magfile=project+"_mag1Noise.nc" # # It is assumed that the XY-data arrays are flat and parallel to the surface at a given height and # corresponding data are not changing vertically across a thin layer. # # .... these are the horizontal coordinates of the lower-left (south-west) end of the data array in the mesh [m]: DataRefX=0.0 DataRefY=0.0 # ... this is the height of the grav and magnetic data above ground [m] (can be zero) DataHeightAboveGround=0*km # .... this total extent of the data array [m]:(total length of the array) #DataSpacingX=1*km #DataSpacingY=1*km LDataY=40*km LDataX=70*km # ... number of data points in east-west (X) and north-south (Y) direction: DataNumX=141 DataNumY=81 # Note: the resolution specified here should roughly match the resolution of the actual data as input data are interpolated to the resolution in the mesh # ... this is the "thickness" of the data array = the thickness of the vertical layer. DataMeshSizeVertical=0.5*km # ... this is the thickness of region below the data area. In essence it defines the depth of the inversion CoreThickness=60*km # ... there is also an air layer and this is its thickness [m] (no updates for density and magnetization here) AirLayerThickness=30*km # ... there is padding around the core and air layer. For the subsurface there will be updates in padding region but not for the air layer PaddingAir=60000.0 PaddingX=60000.0 PaddingY=60000.0 PaddingZ=60000.0 # ... these are factors by which the DataMeshSizeVertical is raised in the air layer and in the core. MeshSizeAirFactor=10 MeshSizeCoreFactor=5 # ... these are factors by which the core and air layer mesh size are raised for the padding zone. MeshSizePaddingFactor=5 # name of the mesh file (gmsh 3 file format) meshfile=project+'mesh.msh' B_hx = 45000.0 # background magnetic field in nT x direction B_hz = 0.0 # background magnetic field in nT y direction B_hy = 0.0 # background magnetic field in nT z direction # # this defines the assumed true density and magnetization: # s1={ 'xc' : LDataX/3, 'yc' : LDataY/3, 'zc' : -CoreThickness*0.145, 'r' : 8*km } s2={ 'xc' : 2*LDataX/3, 'yc' : 2*LDataY/3, 'zc' : -CoreThickness*0.11, 'r' : 6*km } # ... 500 kg/m^3 over the union of sphere 1 and 2 true_density = [(-320, [s1]),(500, [s2]) ] # ... 0.1 on sphere 1 and 0.03 on sphere 2: true_magnetization= [ ( 0.16, [s1]), (-0.25, [s2])] noise=5
class Item: def __init__(self, id, quantity, price): self.__product_id = id self.__quantity = quantity self.__price = price def update_quantity(self, quantity): None class ShoppingCart: def __init__(self): self.__items = [] def add_item(self, item): None def remove_item(self, item): None def update_item_quantity(self, item, quantity): None def get_items(self): return self.__items def checkout(self): None class OrderLog: def __init__(self, order_number, status=OrderStatus.PENDING): self.__order_number = order_number self.__creation_date = datetime.date.today() self.__status = status class Order: def __init__(self, order_number, status=OrderStatus.PENDING): self.__order_number = 0 self.__status = status self.__order_date = datetime.date.today() self.__order_log = [] def send_for_shipment(self): None def make_payment(self, payment): None def add_order_log(self, order_log): None
class Solution(object): def search(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ if not nums: return -1 lo = 0 hi = len(nums)-1 old_size = len(nums) # if not rotated if nums[lo] <= nums[hi]: return self.binary_search(nums,lo,hi+1,target) else: # extent list so that new list[lo:] is sorted while(nums[lo] > nums[hi]): lo = hi hi -= 1 nums += nums[:hi+1] # get result re = self.binary_search(nums,lo,len(nums),target) # if index large origin list size, return index-length of origin list return re - old_size if re >= old_size else re def binary_search(self,array,low,high,target): ''' low: dtype int, index of lowest int high: dtype int, index of highest int target: dtype int, the int we search for this function is a normal binary search function O(log(n)) ''' mid = low +(high - low) // 2 mid_value = array[mid] if low+1 >= high: return -1 if mid_value != target else mid if mid_value == target : return mid elif target > mid_value: return self.binary_search(array,mid,high,target) else: return self.binary_search(array,low,mid,target) if __name__ == '__main__': re = Solution().search([4,5,6,1,2,3],4) print(re)
a = [1,2,3] print(a) a.append(5) print(a) list1=[1,2,3,4,5] list2=['rambutan','langsa','salak','durian','apel'] list1.extend(list2) c = [1,2,3] print(c) c.insert(0,12) print(c) ### Perbedaan antara fungsi Append,extend,dan insert # append berfungsi untuk menambahkan elemen ke daftar # extend berfungsi untuk memperpanjang daftar dengan menambahkan elemen dari iterable # insert berfungsi untuk menyisipkan data baru di tengah araay list ## fungsi reverse dan sort # fungsi reversed() berfungsi untuk menghasilkan iterator yang berisi kembalikan dari suatu sequence sedangkan sort berfungsi untuk mengurutkan suatu iterabel baik secara naik maupun turun ### contoh kodenya dari reverse def reverse(string): reverse_string = "" for i in string: reverse_string = i+reversed_string print("reversed string is:",reversed_string) string = input("enter a string:") print("enterd string",string) reverse(string) ### contoh kode dari sort pylist = ['e','a','u','i','o'] word = 'python' print(sorted(pylist)) print(sorted(word)) print(sorted(pylist, reverse=True)) def takesecond(elem): return elem[1] random = [(2,2), (3,4), (4,1), (1,3)] sortedlist = sorted(random, key =takesecond) print('sorted list:', sortedlist)
# coding=utf8 # Copyright 2018 JDCLOUD.COM # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # NOTE: This class is auto generated by the jdcloud code generator program. class EventOut(object): def __init__(self, createTime=None, physicalId=None, resourceAction=None, resourceName=None, resourceStatus=None, resourceStatusReason=None, resourceType=None, stackId=None, uuid=None): """ :param createTime: (Optional) 创建时间 :param physicalId: (Optional) 资源ID :param resourceAction: (Optional) 资源运行操作 :param resourceName: (Optional) 资源名称 :param resourceStatus: (Optional) 资源运行状态 :param resourceStatusReason: (Optional) 资源运行状态原因 :param resourceType: (Optional) 资源类型 :param stackId: (Optional) 资源栈ID :param uuid: (Optional) 唯一标识 """ self.createTime = createTime self.physicalId = physicalId self.resourceAction = resourceAction self.resourceName = resourceName self.resourceStatus = resourceStatus self.resourceStatusReason = resourceStatusReason self.resourceType = resourceType self.stackId = stackId self.uuid = uuid
# 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 averageOfLevels(self, root: TreeNode) -> List[float]: queue, levelsData, result = deque([(root, 0)]), defaultdict(lambda : (0, 0)), [] while queue: node, level = queue.popleft() if node: currentSum, currentCount = levelsData[level] currentSum += node.val currentCount += 1 levelsData[level] = (currentSum, currentCount) if node.left: queue.append((node.left, level + 1)) if node.right: queue.append((node.right, level + 1)) for key in sorted(levelsData.keys()): result.append(levelsData[key][0] / levelsData[key][1]) return result
af = list(b"\x13\x13\x11\x17\x12\x1d\x48\x45\x45\x41\x0b\x26\x2c\x42\x5f\x09\x0b\x5f\x6c\x3d\x56\x56\x1b\x54\x5f\x41\x45\x29\x3c\x0b\x5c\x58\x00\x5f\x5d\x09\x54\x6c\x2a\x40\x06\x06\x6a\x27\x48\x42\x5f\x4b\x56\x42\x2d\x2c\x43\x5d\x5e\x6c\x2d\x41\x07\x47\x43\x5e\x31\x6b\x5a\x0a\x3b\x6e\x1c\x49\x54\x5e\x1a\x2b\x34\x05\x5e\x47\x28\x28\x1f\x11\x26\x3b\x07\x50\x04\x06\x04\x0d\x0b\x05\x03\x48\x77\x0a") flag = "r" char = "r" for stuff in af: flag += chr(ord(char) ^ stuff) char = flag[-1] print(flag)
I = input("Enter the string: ") S = I.upper() freq = {} for i in I: if i != " ": if i in freq: freq[i] += 1 else: freq[i] = 1 print(freq)
# Desenvolva um algoritmo que receba um valor inteiro e que exiba os números de 0 até ele. # OBS: Obrigatório o uso do while valor_digitado = int(input("Digite um valor maior que 0: ")) numero = 0 while numero <= valor_digitado: print(numero) numero = numero + 1 print("Valor final do numero: " + str(numero))
class Solution(object): def threeSum(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ nums.sort() res = [] for i,a in enumerate(nums): # If same as the previous value just continue, already checked if i>0 and a == nums[i-1]: continue # Using left and right pointers l,r = i+1, len(nums)-1 while l < r: threeSum = a + nums[l] + nums[r] if threeSum > 0: r -= 1 elif threeSum < 0: l += 1 else: res.append([a,nums[l],nums[r]]) l += 1 # Making sure that left pointer is not same as its previous value while nums[l] == nums[l-1] and l<r: l += 1 return res # Time Limit Exceed # res = [] # if len(nums) < 3: # return res # nums.sort() # for i in range(0,len(nums)): # temp = 0 # for j in range(i+1,len(nums)): # temp = nums[i] + nums[j] # temp = temp * -1 # if temp in nums[j+1:]: # res1 = [nums[i],nums[j],temp] # if res1 not in res: # res.append(res1) # return res
# -*- coding: utf-8 -*- """ Created on Wed Mar 24 22:12:02 2021 @author: Abeg """ #all symmetric pair of an array def symmetricpair(pairs): s=set() for (x,y) in pairs: s.add((x,y)) if (y,x) in s: print((x,y),"|",((y,x))) pairs=[(11,20),(30,40),(5,10),(40,30),(10,5)] print(symmetricpair(pairs),end="") #repeating element n=int(input("enter the size")) arr=[] for i in range(0,n): e=int(input()) arr.append(e) x=list(dict.fromkeys(arr)) for i in x: if(arr.count(i)>1): print(i) #non-repeating element n=int(input("enter the size")) arr=[] for i in range(0,n): e=int(input()) arr.append(e) x=list(dict.fromkeys(arr)) for i in x: if(arr.count(i)==1): print(i) #no of even element and odd elemnet in an array arr=[] n=int(input()) count1=0 count2=0 for i in range(n): e=int(input()) arr.append(e) for i in range(n): if(arr[i]%2==0): count1+=1 else: count2+=1 print("no of even",count1) print("no of odd is",count2) #finding min scalarproduct of two vector arr1=[] arr2=[] n=int(input("size of the array")) for i in range(n): e=int(input()) arr1.append(e) for i in range(n): e=int(input()) arr2.append(e) list=() arr1.sort() arr2.sort(reverse=True) sum=0 for i in range(0,n): sum=sum+arr1[i]*arr2[i] print(sum) #minimum abs difference of given array arr=[5,10,1,4,8,7] n=len(arr) sum=0 arr.sort() sum=sum+abs(arr[0]-arr[1]) sum+=abs(arr[n-1]-arr[n-2]) for i in range(1,n-1): sum+=min(abs(arr[i]-arr[i-1]),abs(arr[i]-arr[i+1])) print(sum) #finding max scalarproduct of two vector arr1=[] arr2=[] n=int(input("size of the array")) for i in range(n): e=int(input()) arr1.append(e) for i in range(n): e=int(input()) arr2.append(e) list=() arr1.sort() arr2.sort() sum=0 for i in range(0,n): sum=sum+arr1[i]*arr2[i] print(sum) # Function to return maximum product of a sublist of given list def maxProduct(A): max_ending = min_ending = 0 max_so_far = 0 for i in A: temp = max_ending max_ending = max(i, max(i * max_ending, i * min_ending)) min_ending = min(i, min(i * temp, i * min_ending)) max_so_far = max(max_so_far, max_ending) return max_so_far if __name__ == '__main__': A = [6,-10,-3,0,5] print("The maximum product of a sublist is", maxProduct(A)) #check frequency of each char n=int(input("enter the size")) arr=[] for i in range(0,n): e=int(input()) arr.append(e) x=list(dict.fromkeys(arr)) for i in x: print("{}occours {} time".format(i,arr.count(i))) #removing duplicate element prom an array n=int(input("enter the size")) arr=[] for i in range(0,n): e=int(input()) arr.append(e) x=list(dict.fromkeys(arr)) print(x) #distinctelement n=int(input("enter the size")) arr=[] for i in range(0,n): e=int(input()) arr.append(e) x=list(dict.fromkeys(arr)) print(x) print(len(x)) #ARR is disjoint or not def disjoint(arr1,arr2): for i in range(0,len(arr1)): for j in range(0,len(arr2)): if(arr1[i]==arr2[j]): return -1 else: return 1 arr1=[1,2,3,4] arr2=[1,2,3,4] res=disjoint(arr1,arr2) print(res) if(res==-1): print("not disjoint") else: print("disjoint") #dtermine array is a subset of anthor array or not def subset(arr1,arr2,m,n): i=0 j=0 for i in range(n): for j in range(m): if(arr2[i]==arr1[j]): break if(j==m): return 0 return 1 arr1=[1,2,3,4] arr2=[2,3] m=len(arr1) n=len(arr2) if(subset(arr1,arr2,m,n)): print("arr2 is a subset of arr1") else: print("not") #rotation from left to right arr=[10,20,30,40,50] k=int(input("enter the no of rotation")) k=k%len(arr) for i in range(k): x=arr.pop(-1) arr.insert(0,x) print(arr) #all no array be made equal def make_equal(arr,n): for i in range(n): while(arr[i]%2==0): arr[i]=arr[i]/2 while(arr[i]%3==0): arr[i]=arr[i]/3 for i in range(n): if arr[i]!=arr[0]: return False else: return True arr=[3,50,75,100] n=len(arr) if(make_equal(arr,n)): print("yes") else: print("no") #sum of dight in the array def sumarr(arr,n): for i in range(n): temp=arr[i] sum=0 while(temp>0): d=temp%10 sum=sum+d temp=temp//10 print(sum,end=" ",sep=" ") arr=[] n=int(input("size")) for i in range(n): e=int(input()) arr.append(e) sumarr(arr,n) #placed all even no followed odd no # variables def rearrangeEvenAndOdd(arr, n) : j = -1 for i in range(0, n) : if (arr[i] % 2 == 0) : j = j + 1 temp = arr[i] arr[i] = arr[j] arr[j] = temp n=int(input("fj")) arr=[] for i in range(n): arr.append(int(input())) rearrangeEvenAndOdd(arr, n) for i in range(n): print(arr[i],end=" ",sep=" ") #array rotation def leftrotate(arr,d,n): for i in range(d): leftrotateone(arr,n) def leftrotateone(arr,n): temp=arr[0] for i in range(n-1): arr[i]=arr[i+1] arr[n-1]=temp arr=[1,2,3,4,5,6] print(arr) leftrotate(arr,2,len(arr)) print(arr) #max Element in an array def largeelearray(arr): max=arr[0] for i in range(0,len(arr)): if arr[i]>max: max=arr[i] else: max=max return max arr=[1,2,3,4] print(largeelearray(arr)) #recurrent element in an array def recurr(arr,n): for i in range(0,n): for j in range(0,n): if arr[i]==arr[j+1]: return arr[i] else: return False arr=[2,5,1,2,3,5,1,2,4] n=len(arr) print(recurr(arr,n)) #O(n^2) #o(1) #sum of array def sumarray(arr): sum=0 for i in range(0,len(arr)): sum=sum+arr[i] return sum arr=[1,2,3,4] print(sumarray(arr)) #Twosum array """ def twosum(arr,target): outputarr=[] for i in range(0,len(arr),1): for j in range(i+1,len(arr),1): if (arr[j] == target - arr[i]): outputarr.append(i) outputarr.append(j) return outputarr target=int(input("uju")) arr=[2,3,4,5] print(twosum(arr,target))""" """ def twosum(arr,target): outputarr=[] for i in range(0,len(arr)): for j in range(i+1,len(arr)): sum=arr[i]+arr[j] if sum==target: outputarr.append(i) outputarr.append(j) return outputarr print(twosum(arr=[2,7,11,15],target=9))"""
nome = str(input('Digite seu nome completo ')).strip() maisculas = nome.upper() minusculas = nome.lower() letras = len(nome) - nome.count(' ') primeiro = nome.find(' ') print(f'Seu nome em maiusculas é {maisculas}') print(f'Seu nome em minusculas é {minusculas}') print(f'Seu nome tem ao todo {letras} letras') print(f'Seu primeiro nome tem {primeiro} letras')
# exc. 7.2.4 def seven_boom(end_number): my_list = [] for i in range(0, end_number + 1): s = str(i) if '7' in s or i % 7 == 0: my_list += ['BOOM'] else: my_list += [i] print(my_list) def main(): end_number = 17 seven_boom(end_number) if __name__ == "__main__": main()
"""Format a number with grouped thousands. Number will be formatted with a comma separator between every group of thousands. Source: cup """ # Implementation author: cup # Created on 2018-09-17T20:09:08.888749Z # Last modified on 2018-09-17T20:09:08.888749Z # Version 1 print("f'{1000:,}'")
def main(): # input N, K = map(int, input().split()) # compute def twoN(a: int): if a%200 == 0: a = int(a/200) else: a = int(str(a) + "200") return a for i in range(K): N = twoN(N) # output print(N) if __name__ == '__main__': main()
def increment_by_one(x): return x + 1 def test_increment_by_one(): assert increment_by_one(3) == 4
class CTDConfig(object): def __init__(self, createStationPlot, createTSPlot, createContourPlot, createTimeseriesPlot, binDataWriteToNetCDF, describeStation, createHistoricalTimeseries, showStats, plotStationMap, tempName, saltName, oxName, ftuName, oxsatName, refdate, selected_depths, write_to_excel, survey=None, conductivity_to_salinity=False, calculate_depth_from_pressure=False, debug=False): self.createStationPlot = createStationPlot self.createTSPlot = createTSPlot self.createContourPlot = createContourPlot self.createTimeseriesPlot = createTimeseriesPlot self.binDataWriteToNetCDF = binDataWriteToNetCDF self.describeStation = describeStation self.showStats = showStats self.plotStationMap = plotStationMap self.useDowncast = None self.tempName = tempName self.saltName = saltName self.oxName = oxName self.ftuName = ftuName self.oxsatName = oxsatName self.refdate = refdate self.calculate_depth_from_pressure = calculate_depth_from_pressure self.conductivity_to_salinity = conductivity_to_salinity self.debug=debug self.survey=survey self.write_to_excel=write_to_excel self.projectname=None self.selected_depths=selected_depths self.mgperliter_to_mlperliter=0.7 self.createHistoricalTimeseries=createHistoricalTimeseries
class Solution: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ i, j = 0, 0 for i, n in enumerate(nums): a = target - n # print('i = ',i,'n = ',n) # print('a = ',a) for j, m in enumerate(nums[i+1:], start=i+1): # print('j = ',j,'m = ',m) if m == a: return [i, j] return [i, j] class Solution2: def twoSum(self, nums, target): if len(nums) < 2: return [] m = {} # val:idx for i in range(len(nums)): t = target - nums[i] if t in m: return [m[t], i] m[nums[i]] = i # print(m) return [] if __name__ == "__main__": # nums = [2, 7, 11, 15] # nums = [3, 2, 4] nums = [1, 3, 2, 3] target = 6 print(Solution2().twoSum(nums, target))
##Generalize orienteering contours=name ##maximumdistancebetweentheoriginalandthesimplifiedcurvedouglaspeuckeralgorithm=number4 ##contours=vector ##min=string37 ##generalizecontours=output vector outputs_QGISFIELDCALCULATOR_1=processing.runalg('qgis:fieldcalculator', contours,'length',0,10.0,2.0,True,'round($length,2)',None) outputs_QGISEXTRACTBYATTRIBUTE_1=processing.runalg('qgis:extractbyattribute', outputs_QGISFIELDCALCULATOR_1['OUTPUT_LAYER'],'length',3,min,None) outputs_GRASS7V.GENERALIZE.SIMPLIFY_1=processing.runalg('grass7:v.generalize.simplify', outputs_QGISEXTRACTBYATTRIBUTE_1['OUTPUT'],0,maximumdistancebetweentheoriginalandthesimplifiedcurvedouglaspeuckeralgorithm,7.0,50.0,False,True,None,-1.0,0.0001,0,None) outputs_QGISDELETECOLUMN_1=processing.runalg('qgis:deletecolumn', outputs_GRASS7V.GENERALIZE.SIMPLIFY_1['output'],'length',generalizecontours)
L=[1,2,3] it=iter(L) print("The Iteration:{}".format(it)) print("item is:{}".format(it.__next__())) print("item is:{}".format(next(it))) print("item is:{}".format(next(it))) print("item is:{}".format(next(it))) # 在代码段 for X in Y 中,Y必须是个迭代器或者可以通过使用 iter() 创建迭代器的一些对象 obj=(12,34) for i in iter(obj): print(i) for i in obj: print(i) # 可以使用list()或tuple()构造函数将迭代器实现为列表或元组: L=[1,2,3] iterator=iter(L) t=tuple(iterator) print(t) # 如果你知道迭代器将返回N个元素,你可以将它们解压缩成为一个N元组: L=[1,2,3] iterator=iter(L) a,b,c=iterator print(a,b,c) # 特别的,在迭代器中只能逐个元素从第一个到最后一个进行枚举, # 但不能访问前一个元素,也不能重置枚举器或者获取一份枚举器的拷贝 # Iterator对象可以选择提供这些附加功能,但是迭代器协议只指定了 __next__() 方法 # 因此,函数可能会消耗所有迭代器的输出,如果需要对相同的数据流做一些不一样的事情,需要创建一个新的迭代器 #Python 的 sequence 类型,例如 string 将支持自动创建迭代器 m = {'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6,\ 'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12} for key in m: print(key,m[key]) # 可以调用 字典的 values() 和 items() 方法获取适当的迭代器 # dict() 构造器可以接收一个返回(key,value)元组的有限流的迭代器 L = [('Italy', 'Rome'), ('France', 'Paris'), ('US', 'Washington DC')] values=dict(iter(L)) for value in values: print(value,values[value]) # 文件也可以通过调用readline()来获得枚举器 file=open('poem.txt') for line in file: # do something for each line print(line)
# model settings norm_cfg = dict(type='SyncBN', requires_grad=True) # norm_cfg = dict(type='BN', requires_grad=True) model = dict( type='EncoderDecoder', pretrained='open-mmlab://resnet18_v1c', backbone=dict( type='BiseNetV1', base_model='ResNetV1c', depth=18, out_indices=(0, 1, 2), with_sp=False, # using the Spatial Path or not # dilations=(1, 1, 1, 1), # no dilations in BiseNet, so this line can be annotated # strides=(1, 2, 1, 1), # need downsample for regular resnet, so this line can be annotated norm_cfg=norm_cfg, align_corners=False), decode_head=dict( type='FCNHead', in_index=-1, # Backbone stage index in_channels=256, channels=256, num_convs=1, concat_input=False, dropout_ratio=0.1, num_classes=19, norm_cfg=norm_cfg, align_corners=False, loss_decode=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)), auxiliary_head=[ dict( type='FCNHead', in_index=-2, in_channels=128, channels=64, num_convs=1, concat_input=False, dropout_ratio=0.1, num_classes=19, norm_cfg=norm_cfg, align_corners=False, loss_decode=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)), dict( type='FCNHead', in_index=-3, in_channels=128, channels=64, num_convs=1, concat_input=False, dropout_ratio=0.1, num_classes=19, norm_cfg=norm_cfg, align_corners=False, loss_decode=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)), ], # model training and testing settings train_cfg=dict(), test_cfg=dict(mode='whole'))
#For packaging ''' Users api handles JWT auth for users '''
def run(params={}): return { 'project_name': 'Core', 'bitcode': True, 'min_version': '9.0', 'enable_arc': True, 'enable_visibility': True, 'conan_profile': 'ezored_ios_framework_profile', 'archs': [ {'arch': 'armv7', 'conan_arch': 'armv7', 'platform': 'OS'}, {'arch': 'armv7s', 'conan_arch': 'armv7s', 'platform': 'OS'}, {'arch': 'arm64', 'conan_arch': 'armv8', 'platform': 'OS64'}, {'arch': 'arm64e', 'conan_arch': 'armv8.3', 'platform': 'OS64'}, {'arch': 'x86_64', 'conan_arch': 'x86_64', 'platform': 'SIMULATOR64'}, ], 'build_types': ['Debug', 'Release'], 'install_headers': [ { 'type': 'dir', 'path': 'files/djinni/001-app-domain/generated-src/objc', }, { 'type': 'dir', 'path': 'files/djinni/002-app-core/generated-src/objc', }, { 'type': 'dir', 'path': 'files/djinni/003-app-data-services/generated-src/objc', }, { 'type': 'dir', 'path': 'files/djinni/004-app-system-service/generated-src/objc', }, { 'type': 'dir', 'path': 'files/djinni/005-app-helpers/generated-src/objc', }, { 'type': 'dir', 'path': 'files/djinni/datetime/generated-src/objc', }, { 'type': 'dir', 'path': 'files/djinni/file-helper/generated-src/objc', }, { 'type': 'dir', 'path': 'files/djinni/httpclient/generated-src/objc', }, { 'type': 'dir', 'path': 'files/djinni/shared-data/generated-src/objc', }, { 'type': 'dir', 'path': 'files/djinni/logger/generated-src/objc', }, { 'type': 'dir', 'path': 'files/djinni/string-helper/generated-src/objc', }, { 'type': 'dir', 'path': 'files/src/file-helper/objc', }, { 'type': 'dir', 'path': 'files/src/httpclient/objc', }, { 'type': 'dir', 'path': 'files/src/logger/objc', }, { 'type': 'dir', 'path': 'files/src/shared-data/objc', }, ] }
#!/usr/bin/python # encoding: utf-8 """ custom_stopwords Purpose: Collect custom stopwords lists Author: datadonk23 (datadonk23@gmail.com) Date: 2018-05-01 """ arxiv_stopwords = ["arxiv", "astro-ph", "astro-ph.co", "astro-ph.ep", "astro-ph.ga", "astro-ph.he", "astro-ph.im", "astro-ph.sr", "cond-mat.dis-nn", "cond-mat.mes-hall", "cond-mat.mtrl-sci", "cond-mat.other", "cond-mat.quant-gas", "cond-mat.soft", "cond-mat.stat-mech", "cond-mat.str-el", "cond-mat.supr-con", "cs.ai", "cs.ar", "cs.CC", "cs.ce", "cs.cg", "cs.cl", "cs.cr", "cs.cv", "cs.cy", "cs.db", "cs.dc", "cs.dl", "cs.dm", "cs.ds", "cs.et", "cs.fl", "cs.gl", "cs.gr", "cs.gt", "cs.hc", "cs.ir", "cs.it", "cs.lg", "cs.lo", "cs.ma","cs.mm", "cs.ms", "cs.na", "cs.ne", "cs.ni", "cs.oh", "cs.os", "cs.pf", "cs.pl", "cs.ro", "cs.sc", "cs.sd", "cs.se", "cs.si", "cs.sy", "econ.em", "eess.as", "eess.iv", "eess.sp", "gr-qc", "hep-ex", "hep-lat", "hep-ph", "hep-th", "math.ac", "math.ag", "math.ap","math.at", "math.ca", "math.co", "math.ct", "math.cv", "math.dg", "math.ds", "math.fa", "math.gm", "math.gn", "math.gr", "math.gt", "math.ho", "math.it", "math.kt", "math.lo", "math.mg", "math.mp", "math.na", "math.nt", "math.oa", "math.oc", "math.pr", "math.qa", "math.ra", "math.rt", "math.sg", "math.sp", "math.st", "math-ph", "nlin.ao", "nlin.cd", "nlin.cg", "nlin.ps", "nlin.si", "nucl-ex", "nucl-th", "physics.acc-ph", "physics.ao-ph", "physics.app-ph", "physics.atm-clus", "physics.atom-ph", "physics.bio-ph", "physics.chem-ph", "physics.class-ph", "physics.comp-ph", "physics.data-an", "physics.ed-ph", "physics.flu-dyn", "physics.gen-ph", "physics.geo-ph", "physics.hist-ph", "physics.ins-det", "physics.med-ph", "physics.optics", "physics.plasm-ph", "physics.pop-ph", "physics.soc-ph", "physics.space-ph", "q-bio.bm", "q-bio.cb","q-bio.gn", "q-bio.mn", "q-bio.nc", "q-bio.ot", "q-bio.pe", "q-bio.qm", "q-bio.sc", "q-bio.to", "q-fin.cp", "q-fin.ec", "q-fin.gn", "q-fin.mf", "q-fin.PM", "q-fin.PR", "q-fin.RM", "q-fin.ST", "q-fin.tr", "quant-ph", "stat.ap", "stat.co", "stat.me", "stat.ml", "stat.ot", "stat.th"] def get_stopwords(): """ Make custom stopwords list accessible :return: [stopwords] - List of stopwords """ stopwords_list = arxiv_stopwords # add additional lists with + return stopwords_list
# Copyright 2020 Axis Communications AB. # # For a full list of individual contributors, please see the commit history. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Log area provider data module.""" class LogArea: """Log area data object.""" _log_area_dictionary = None def __init__(self, **log_area): """Take a dictionary as input and setattr on instance. :param log_area: Dictionary to set attributes from. :type log_area: dict """ self._log_area_dictionary = log_area for key, value in log_area.items(): setattr(self, key, value) def __setattr__(self, name, value): """Set log area parameters to dict and object. :param name: Name of parameter to set. :type name: str :param value: Value of parameter. :type value: any """ if self._log_area_dictionary is not None: self._log_area_dictionary[name] = value super().__setattr__(name, value) def update(self, **dictionary): """Update log area dictionary with new data. :param dictionary: Dictionary to update attributes from. :type dictionary: dict """ self._log_area_dictionary.update(**dictionary) for key, value in dictionary.items(): setattr(self, key, value) @property def as_dict(self): """Represent log area as dictionary. :return: Log area dictionary. :rtype: dict """ return self._log_area_dictionary def __repr__(self): """Represent log area as string. :return: Log area dictionary as string. :rtype: str """ return repr(self._log_area_dictionary)
''' Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. Example 1: Input: 121 Output: true Example 2: Input: -121 Output: false Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. Example 3: Input: 10 Output: false Explanation: Reads 01 from right to left. Therefore it is not a palindrome. Follow up: Coud you solve it without converting the integer to a string? ''' class Solution: def isPalindrome(self, x: int) -> bool: y = str(x) if y == y[::-1]: return True else: return False class Solution: def isPalindrome(self, x: int) -> bool: if x < 0: return False y = 0 count = 1 a = x while a != 0: temp = a%10 a = a // 10 y = 10 * y + temp if y == x: return True else: return False
class Tile(): """ The smallest building block in a map """ def __init__(self): self.tile = '.' def get(self): return self.tile def set(self, item): self.tile = item
def longestDigitsPrefix(inputString): # iterate through the string arr = '' for i in inputString: if i.isdigit(): arr += i else: break return arr
# Copyright 2017 The Bazel Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Provides the stamp info file containing the Bazel non-volatile keys """ def _impl(ctx): output = ctx.outputs.out ctx.actions.run_shell( outputs = [output], inputs = [ctx.info_file], command = "cp {src} {dst}".format( src = ctx.info_file.path, dst = output.path, ), ) stamp_info = rule( implementation = _impl, outputs = { # The stamp file. "out": "%{name}.txt", }, )
"""Debug functions for notebooks. """ def count(df, name=None): """Print the count of dataframe with title.""" if name: print("Dataset: %s" % (name)) print("Count: %d" % (df.count())) def show(df, name=None, num_rows=1): """Print title and show a dataframe""" if name: print("Dataset: %s" % (name)) df.show(num_rows) def profile(df, name): """Profile a dataframe, initially just count and show.""" count(df, name) show(df, name=name)
# --------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. # --------------------------------------------------------- class LCS: """ Compute the Longest Common Subsequence (LCS) of two given string.""" def __init__(self, str_m, str_n): self.str_m_len = len(str_m) self.str_n_len = len(str_n) dp_table = self._construct_dp_table(str_m, str_n) self._lcs_len = dp_table[self.str_m_len][self.str_n_len] self._lcs = self._find_lcs_str(str_m, str_n, dp_table) def _construct_dp_table(self, str_m, str_n): m = self.str_m_len n = self.str_n_len # Initialize DP table dp = [[0 for j in range(n + 1)] for i in range(m + 1)] for i in range(1, m + 1): for j in range(1, n + 1): # Case 1: if char1 == char2 if str_m[i - 1] == str_n[j - 1]: dp[i][j] = 1 + dp[i - 1][j - 1] # Case 2: take the max of the values in the top and left cell else: dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]) return dp def _find_lcs_str(self, str_m, str_n, dp_table): m = self.str_m_len n = self.str_n_len lcs = "" while m > 0 and n > 0: # same char if str_m[m - 1] == str_n[n - 1]: # prepend the character lcs = str_m[m - 1] + lcs m -= 1 n -= 1 # top cell > left cell elif dp_table[m - 1][n] > dp_table[m][n - 1]: m -= 1 else: n -= 1 return lcs def get_len(self): return self._lcs_len def get_str(self): return self._lcs
class Error: none_or_invalid_attribute = "main attributes should have value." unacceptable_json = "json input has unacceptable format." unacceptable_object_type = "object has unacceptable type"
def decimalni_zapis(deljenec, delitelj): memo = set() decimalni_zapis = '' while (deljenec, delitelj) not in memo: if deljenec % delitelj == 0: decimalni_zapis += str(deljenec // delitelj) return decimalni_zapis, deljenec, delitelj elif deljenec < delitelj: decimalni_zapis += '0' memo.add((deljenec, delitelj)) deljenec *= 10 else: decimalni_zapis += str(deljenec // delitelj) memo.add((deljenec, delitelj)) deljenec = deljenec % delitelj * 10 return decimalni_zapis # def je_prastevilo(n): # if n < 2 or n == 4 or n == 6 or n == 8: # return False # i = 3 # while i*i <= n: # if n % i == 0 or n % 2 == 0: # return False # i += 2 # return True slovar = dict() for i in range(2, 1000): slovar[i] = len(decimalni_zapis(1, i)) # for stevilo in range(1, 10 ** 6): # if len(decimalni_zapis(1, stevilo)) == stevilo: # print(stevilo) print(max(slovar, key=slovar.get))
class Solution: """ @param grids: a maxtrix with alphabet @return: return sorted lists """ def CounterDiagonalSort(self, grids): # write your code here m = len(grids) n = len(grids[0]) table = [] for i in range(m): temp = [] row = i col = 0 while row >= 0 and col < n: temp.append(grids[row][col]) row -= 1 col += 1 table.append(temp) for i in range(m, m + n - 1): temp = [] row = m - 1 col = i - m + 1 while row >= 0 and col < n: temp.append(grids[row][col]) row -= 1 col += 1 table.append(temp) l = min(m, n) result = [] for t in table: temp = [] i = 0 while len(temp) < l: temp.append(t[i % len(t)]) i += 1 result.append(temp) return sorted(result)
#!/usr/bin/python3 bridgera = ['Arijit','Soumya','Gunjan','Arptia','Bishwa','Rintu','Satya','Lelin'] # Generator Function iterarates through all items of array def gen_func(data): for i in range(len(data)): yield data[i] data_gen = list(gen_func(bridgera)) print (data_gen) # Normal Function iterates through only first item of array def norm_func(data): for i in range(len(data)): return data[i] norm_gen = list(norm_func(bridgera)) print (norm_gen)
class Node: def __init__(self, value): self.value = value self.next = None class LinkedList: """ Class to create a linked list and perform some basic operations such as: append, display, prepend, convert, insert, remove, search, pop """ def __init__(self, value=None): self.head = value def append(self, value): if self.head is None: self.head = Node(value) return node = self.head while node.next is not None: node = node.next node.next = Node(value) return def display(self): node = self.head while node: print(node.value) node = node.next def convert_list(self): Pylist = [] node = self.head while node: Pylist.append(node.value) node = node.next return Pylist def prepand(self, value): new_node = Node(value) new_node.next = self.head self.head = new_node def search(self, value): node = self.head while node: if node.value == value: return node node = node.next return None def remove(self, value): node = self.head #If head contains the value, change the head if node is not None: if node.value == value: self.head = node.next node = None return # Keep track of the previous node of the node that contains the value while node: if node.value == value: break prev_node = node node = node.next if node == None: return #Link the previous node to the next node prev_node.next = node.next node = None def pop(self): node = self.head value = node.value self.head = node.next # node = None return value def insert(self, value, pos): node = self.head new_node = Node(value) idx = 0 prev_node = None while node: if idx == pos: break prev_node = node node = node.next idx+=1 if prev_node == None: new_node.next = self.head self.head = new_node return new_node.next = prev_node.next prev_node.next = new_node return LinkedList.insert = insert LinkedList.prepand = prepand LinkedList.pop = pop LinkedList.remove = remove LinkedList.search = search def create_linked_list(_list_): """ The function converts a python list/array into a linked list; Time complexity: O(n) :param _list_: a Python list :return: A linked list """ head = None tail = None for val in _list_: if head is None: head = Node(val) tail = head else: tail.next = Node(val) tail = tail.next return head def reverse(linked_list): """ Reverse a linked list :param linked_list: linked_list :return: reversed linked list """ new_list = LinkedList prev_node = None for value in linked_list: new_node = Node(value) new_node.next = prev_node prev_node = new_node new_list.head = prev_node return new_list def isCircular(linked_list): """ Checks if a linked list is circular i.e., has loops :param linked_list: Linked list :return: True/False """ if linked_list.head is None: return False fast = linked_list.head slow = linked_list.head while fast and fast.next: fast = fast.next.next slow = slow.next if fast == slow: return True return False if __name__ == "__main__": llist = LinkedList() llist.append(2) llist.append(-1) llist.append(10) llist.append(1) _list_ = llist.convert_list() print("Linked List: ") llist.display() print("Python List: ", _list_) llist.prepand(8) print("Prepanded Linked List") llist.display() node = llist.search(-1) print("Value searched: ", node.value, " Next Node: ", node.next.value) rm = 10 llist.remove(rm) print("Linked List after removal {}: ".format(rm)) llist.display() Pop = llist.pop() print("Element Popped: {}, Value of the head now: {}, linked list after popping element: ".format(Pop, llist.head.value)) llist.display() print("Insertion: ") llist.insert(3, 2) llist.display() reverse_list = reverse(llist) reverse_list.display()
def data_for_fitting(*, building_id, date): """ Retrieves data for fitting from the previous business day taking into account holidays """ lease_start = None while lease_start is None: # Previous business day according to Pandas (might be a holiday) previous_bday = pd.to_datetime(date) - BDay(1) # If a holiday, this will return None lease_start = ( db() .execute( building_daily_stats.select() .where(building_daily_stats.c.building_id == building_id) .where(building_daily_stats.c.date == previous_bday) ) .fetchone() .lease_obligations_start_at ) date = previous_bday # Retrieve 8 hours of data from the lease start return load_sensor_values( building_id=building_id, start_time=lease_start, end_time=lease_start + timedelta(hours=8), )
"""Top-level package for leimpy.""" __author__ = """Marco Berzborn""" __email__ = 'marco.berzborn@akustik.rwth-aachen.de' __version__ = '0.0.0'
class Node: """ A node in a graph """ def __init__(self, identifier): """ :param identifier: Identifier is hash of given Shape Object """ self.identifier = identifier self.outgoing_pointers = [] self.incoming_pointers = [] def get_identifier(self): return self.identifier def point_to(self, identifier): """ Points to Node with the given identifier. :param identifier: :return: """ self.incoming_pointers.append(identifier) def pointed_at(self, identifier): self.outgoing_pointers.append(identifier) def has_edges(self): return len(self.incoming_pointers) > 0 or len(self.outgoing_pointers) > 0 def has_mutual_edge(self): for in_edge in self.incoming_pointers: if in_edge in self.outgoing_pointers: return True return False def search_for(self, identifier): return self.__search_for(identifier, []) def __search_for(self, identifier, exclude): if self.identifier == identifier: return self else: for node in self.incoming_pointers: if not hash(node) in exclude: exclude.append(hash(node)) ret = node.__search_for(identifier, exclude) if ret is not None: return ret def __hash__(self): return self.identifier
#implicit type conversion num1 = 12 num2= 13.5 num3 = num1 + num2 print(type(num1)) print(type(num2)) print(num3) print(type(num3))
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def findTarget(self, root, k): """ :type root: TreeNode :type k: int :rtype: bool """ t = [] def preorder(r): if r: t.append(r.val) preorder(r.left) preorder(r.right) preorder(root) # print t d = set() for n in t: if n in d: return True d.add(k-n) return False
load("@rules_cuda//cuda:defs.bzl", "cuda_library") NVCC_COPTS = ["--expt-relaxed-constexpr", "--expt-extended-lambda"] def cu_library(name, srcs, copts = [], **kwargs): cuda_library(name, srcs = srcs, copts = NVCC_COPTS + copts, **kwargs)
''' Author: jianzhnie Date: 2022-03-04 17:13:55 LastEditTime: 2022-03-04 17:13:55 LastEditors: jianzhnie Description: '''
#!/usr/bin/env python3 #: Program Purpose: #: Read an integer N. For all non-negative integers i < N #: print i * i. #: #: Program Author: Happi Yvan <ivensteinpoker@gmail.com #: Program Date : 11/04/2019 (mm/dd/yyyy) def process(int_val): for x in range(int_val): print(x * x) def main(): val = int(input()) process(val) if __name__ == '__main__': main()
def names(name_list): with open('textfile3.txt', 'w') as myfile: myfile.writelines(name_list) myfile.close() print(name_list) menu() def display_name(n): with open('textfile3.txt', 'r') as myfile: name_list = myfile.readlines() print(name_list[n-1]) return namelist[n-1] def display_s(): with open('textfile3.txt', 'r') as myfile: name_list = myfile.readlines() for i in name_list: if i[0] in ["s", "S"]: print('the name/names that starts with an s is ', i) def append_to_list(n): global namelist name_list = [] for i in range(n): name_to_append = str( input("enter the name you want to append(add) to the list ")) name_list.append(name_to_append) name_list.append('\n') namelist.append(name_to_append) namelist.append('\n') with open('textfile3.txt', 'a') as myfile: myfile.writelines(name_list) for i in range(0, len(namelist), 2): print(namelist[i]) print('are the names in order ') def menu(): print("----------------------- menu to choose function ------------------------") print("enter your choice") print("enter 1 to display the nth name ") print("enter 2 to display names starting with s ") print("enter 3 to add/append more names ") print("if you want to execute all be my guest enter 4 ") x = int(input("enter choice ")) try: if x == 1: index = int(input("enter the index to display name ")) try: display_name(index) except: print("enter an index in range") if x == 2: display_s() if x == 3: number_of_names_to_append = int( input("enter how many names you want to add ")) append_to_list(number_of_names_to_append) if x == 4: pass except: print("TRY AGAIN", "\n", "please enter a valid option") if x == 4: for i in range(1, 4): x = i if x == 1: index = int(input("enter the index to display name ")) try: display_name(index) except: print("enter an index in range") if x == 2: display_s() if x == 3: number_of_names_to_append = int( input("enter how many names you want to add ")) append_to_list(number_of_names_to_append) namelist = [] x = int(input("enter number of names to enter in list ")) for i in range(x): n = str(input("enter the list element ")) namelist.append(n) namelist.append('\n') names(namelist)
test = { 'name': 'Problem 7', 'points': 1, 'suites': [ { 'cases': [ { 'answer': '103495fc3358e1b6354d1d4a277039e6', 'choices': [ r""" Pair('quote', Pair(A, nil)), where: A is the quoted expression """, r""" [A], where: A is the quoted expression """, r""" Pair(A, nil), where: A is the quoted expression """, r""" A, where: A is the quoted expression """ ], 'hidden': False, 'locked': True, 'question': 'What is the structure of the expressions argument to do_quote_form?' } ], 'scored': False, 'type': 'concept' }, { 'cases': [ { 'code': r""" scm> (quote hello) 506108214132d6cb9c307edb2f9d0f8b # locked scm> 'hello 506108214132d6cb9c307edb2f9d0f8b # locked scm> ''hello 11e53d0ebd5fcb87953db84e824e20c7 # locked # choice: (quote hello) # choice: hello # choice: (hello) # choice: (quote (quote (hello))) scm> (quote (1 2)) e0115c13325291c6a30393eff9777ee4 # locked scm> '(1 2) e0115c13325291c6a30393eff9777ee4 # locked scm> (quote (1 . 2)) 9a8a33947ee1cd41aa91f5f15184c47b # locked scm> '(1 . (2)) e0115c13325291c6a30393eff9777ee4 # locked scm> (car '(1 2 3)) 1d6ef7880cd9b59b64a1f4e1a1e35a12 # locked scm> (cdr '(1 2)) 1c70ebb4f1aabfcbe22f96bda497dd0b # locked scm> (car (car '((1)))) 1d6ef7880cd9b59b64a1f4e1a1e35a12 # locked scm> (quote 3) ed2605996ac3b24d98b27c6d58145f06 # locked scm> (eval (cons 'car '('(4 2)))) 5dc34dbe25d53109ac62b4184b75a40f # locked """, 'hidden': False, 'locked': True } ], 'scored': True, 'setup': '', 'teardown': '', 'type': 'scheme' }, { 'cases': [ { 'code': r""" >>> read_line(" (quote x) ") 55894b325c4c2817733a8a1223c79f1e # locked >>> read_line(" 'x ") 55894b325c4c2817733a8a1223c79f1e # locked # choice: Pair('x', nil) # choice: 'x' # choice: Pair('quote', 'x') # choice: Pair('quote', Pair('x', nil)) >>> read_line(" (a b) ") 6e7962ce0515005f1aa1ece26c1f9f99 # locked # choice: Pair('a', Pair('b', nil)) # choice: Pair('quote', Pair(Pair('a', Pair('b', nil)), nil)) # choice: Pair('quote', Pair('a', 'b')) # choice: Pair('quote', Pair('a', Pair('b', nil))) >>> read_line(" '(a b) ") 1af43453acd78705e072b903fe9ce759 # locked # choice: Pair('a', Pair('b', nil)) # choice: Pair('quote', Pair(Pair('a', Pair('b', nil)), nil)) # choice: Pair('quote', Pair('a', 'b')) # choice: Pair('quote', Pair('a', Pair('b', nil))) >>> read_line(" '((a)) ") 6b34a9dd52ff83f52d5e6953f2d7375f # locked # choice: Pair('quote', Pair(Pair('a', nil), nil)) # choice: Pair('quote', Pair(Pair('a', nil), nil), nil) # choice: Pair('quote', Pair(Pair('a'), nil)) # choice: Pair('quote', Pair(Pair('a'), nil), nil) # choice: Pair('quote', Pair(Pair(Pair('a', nil), nil), nil)) """, 'hidden': False, 'locked': True } ], 'scored': True, 'setup': r""" >>> from scheme_reader import * """, 'teardown': '', 'type': 'doctest' } ] }
n = int(input()) even_numbers_set = set() odd_numbers_set = set() for current_iteration_count in range(1, n+1): name = input() current_sum = sum([ord(el) for el in name]) // current_iteration_count if current_sum % 2 == 0: even_numbers_set.add(current_sum) else: odd_numbers_set.add(current_sum) sum_evens = sum(even_numbers_set) sum_odds = sum(odd_numbers_set) if sum_evens == sum_odds: modified_set = [str(el) for el in odd_numbers_set.union(even_numbers_set)] print(f", ".join(modified_set)) if sum_odds > sum_evens: modified_set = [str(el) for el in odd_numbers_set.difference(even_numbers_set)] print(f", ".join(modified_set)) if sum_evens > sum_odds: modified_set = [str(el) for el in odd_numbers_set.symmetric_difference(even_numbers_set)] print(f", ".join(modified_set))
# -*- coding: utf-8 -*- r"""Testing code for the (Python) bandit library. Testing is done via the Testify package: https://github.com/Yelp/Testify This package includes: * Test cases/test setup files * Tests for bandit/epsilon: :mod:`moe.tests.bandit.epsilon` * Tests for bandit/ucb: :mod:`moe.tests.bandit.ucb` * Tests for bandit/bla: :mod:`moe.tests.bandit.bla` This package includes: * Test cases/test setup files * Tests for classes and utils in :mod:`moe.bandit` **Files in this package** * :mod:`moe.tests.bandit.bandit_interface_test`: tests for :mod:`moe.bandit.interfaces.bandit_interface.BanditInterface` * :mod:`moe.tests.bandit.bandit_test_case`: base test case for bandit tests with a simple integration test case * :mod:`moe.tests.bandit.linkers_test`: tests for :mod:`moe.bandit.linkers` * :mod:`moe.tests.bandit.utils_test`: tests for :mod:`moe.bandit.utils` """
num = int(input("Numero: ")) for i in range(1,13): m = num * i print(num,"X",i,"=",m)
class Solution: def setZeroes(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ if not matrix: return # use first row as "cols" array, use first column as "rows" array # to do that, first store what needs to be done of first row/col # i.e., do they contain zeroes firstRowZeros = False firstColZeros = False m = len(matrix) n = len(matrix[0]) for i in range(m): if matrix[i][0] == 0: firstColZeros = True break for j in range(n): if matrix[0][j] == 0: firstRowZeros = True break for i in range(1,m): for j in range(1,n): if matrix[i][j] == 0: matrix[0][j] = 0 matrix[i][0] = 0 for i in range(1,m): if matrix[i][0] == 0: for j in range(1,n): matrix[i][j] = 0 for j in range(1,n): if matrix[0][j] == 0: for i in range(1,m): matrix[i][j] = 0 if firstRowZeros: for j in range(n): matrix[0][j] = 0 if firstColZeros: for i in range(m): matrix[i][0] = 0 return ############ O(m+n) space ############ # if not matrix: # return # m = len(matrix) # n = len(matrix[0]) # # O(m+n) space # rows = [False] * m # cols = [False] * n # for i in range(m): # for j in range(n): # if matrix[i][j] == 0: # rows[i] = True # cols[j] = True # for i in range(m): # if rows[i]: # for j in range(n): # matrix[i][j] = 0 # for j in range(n): # if cols[j]: # for i in range(m): # matrix[i][j] = 0 # return
class Solution(object): def leastBricks(self, wall): """ :type wall: List[List[int]] :rtype: int """ hash_map = {} for row in wall: sum = 0 for brick in row[:-1]: sum += brick hash_map[str(sum)] = hash_map.setdefault(str(sum), 0) + 1 return len(wall) - max(hash_map.values()) if hash_map else len(wall)
# function type class function(object): def __get__(self, obj, objtype): # when used as attribute a function returns a bound method or the function itself object = ___id("%object") method = ___id("%method") NoneType = ___id("%NoneType") if obj is None and objtype is not NoneType: # no object to bind, result is the function itself return self else: # result is a method bound to obj with self as the underlying function new_method = object.__new__(method) method.__init__(new_method, self, obj) return new_method def __getattr__(self, key): # the __call__ attribute is the function itself if ___delta("str=", key, "__call__"): return self else: str = ___id("%str") msg = ___delta("str+", "function object has not attribute ", key, str) raise AttributeError(msg) ___assign("%function", function)
class GenerationTemplate: def __init__( self, source_path: str, template: str, group_template: str, unit_template: str ): self.source_path: str = source_path self.template: str = template self.group_template: str = group_template self.unit_template: str = unit_template
#Son directorios donde se almacenan módulos ''' 1) Crear una carpeta con un archivo __init__.py <- constructor '''
""" Exercícios 2 - FizzBuzz parcial, parte 1 Receba um número inteiro na entrada e imprima Fizz se o número for divisível por 3. Caso contrário, imprima o mesmo número que foi dado na entrada. """ numero = int(input("Digite um número inteiro: ")) if(numero % 3 == 0): print("Fizz") else: print(numero)
#!/usr/bin/env python3 # # eask: # The initialization program (your puzzle input) can either update the bitmask # or write a value to memory. Values and memory addresses are both 36-bit # unsigned integers. For example, ignoring bitmasks for a moment, a line # like mem[8] = 11 would write the value 11 to memory address 8. # The bitmask is always given as a string of 36 bits, written with the most # significant bit (representing 2^35) on the left and the least significant # bit (2^0, that is, the 1s bit) on the right. The current bitmask is applied # to values immediately before they are written to memory: a 0 or 1 overwrites # the corresponding bit in the value, while an X leaves the bit in the value # unchanged. For example: # - value: 000000000000000000000000000000001011 (decimal 11) # - mask: XXXXXXXXXXXXXXXXXXXXXXXXXXXXX1XXXX0X # - result: 000000000000000000000000000001001001 (decimal 73) # Execute the initialization program. What is the sum of all values left # in memory after it completes? (Do not truncate the sum to 36 bits.) # # Solution: # We read and process input file line by line, tearing each line as instruction # to be executed. If the instruction is mask, we just save the value as is # to a string variable. If the instruction is about writing a value to memory # we read the address as string, which will become identifier (key) in the # memory map (dictionary), and the value to write as integer. Then we process # every bit from the mask string, iterating from the right side with counting # the position (enumerate -> i). If the mask bit is X, we do not perform any # change. If it is 1, we do binary sum of the current value to write with # value 1 shifted left by i-bits. If the mask bit is 0, we produce a value # of all ones, except on a given i-bit (negation of 1 left shifted by i-bits), # and multiply it binary-wise (and) with the value to write to memory. # Then we just save the final value to a dictionary with address as a key. # Finally we sum all values registered in the dictionary. # INPUT_FILE = 'input.txt' def main(): instructions = [line.strip('\n') for line in open(INPUT_FILE, 'r')] mask = None memory = {} for instruction in instructions: if instruction.startswith('mask = '): mask = instruction.split(' = ')[1] elif instruction.startswith('mem['): address, value = instruction.split(' = ') address = address[4:-1] value = int(value) for i, bit in enumerate(mask[::-1]): if bit == 'X': continue elif bit == '0': value = value & ~(1 << i) elif bit == '1': value = value | (1 << i) else: print('BIT VALUE ERROR') return 1 memory[address] = int(value) else: print('VALUE ERROR') return 1 print(sum(memory.values())) if __name__ == '__main__': main()
class Email: client = None optional_arguments = [ "antispamlevel", "antivirus", "autorespond", "autorespondsaveemail", "autorespondmessage", "password", "quota" ] def __init__(self, client): self.client = client def overview(self): return self.client.get("/email/overview") def globalquota(self, quota = None): data = None if(quota == None): data = self.client.post_request("/email/globalquota") else: data = self.client.post_request("/email/globalquota", { "globalquota": quota }) return data["globalquota"] def list(self, domain): data = self.client.get_request("/email/list", { "domainname": domain }) return { "accounts": data["list"]["emailaccounts"], "aliases": data["list"]["emailaliases"] } def createaccount(self, email, password, extra = None): if(extra != None): for k in extra: if k not in self.optional_arguments: raise Exception( "Invalid parameter: %s " % k) params = extra else: params = {} if(email is None or email == ""): raise Exception("Please supply email address") if(password is None or password == ""): raise Exception("Please supply password") params["emailaccount"] = email params["password"] = password data = self.client.post_request("/email/createaccount", params) return data["emailaccount"] def editaccount(self, email, params): for k in params: if k not in self.optional_arguments: raise Exception("Invalid parameter: %s" % k) if(email is None or email == ""): raise Exception("Please supply email address") params["emailaccount"] = email data = self.client.post_request("/email/editaccount", params) return data["emailaccount"] def delete(self, email): if(email is None or email == ""): raise Exception("Please supply email address") self.client.post_request("/email/delete", { "email": email }) def quota(self, email): if(email is None or email == ""): raise Exception("please supply email address") data = self.client.post_request("/email/quota", { "emailaccount": email }) return data["emailaccount"]
class MyArray: def __init__(self, *args): self.elems = list(args) def __repr__(self): return str(self.elems) def __getitem__(self, index): return self.elems[index] def __setitem__(self, index, value): self.elems[index] = value def __delitem__(self, index): del self.elems[index] def __contains__(self, item): return item in self.elems delim = '*' * 20 m_a = MyArray(*(range(0, 20, 3))) print('MyArray m_a -->', m_a) print(delim) ind = 2 print('m_a[', ind, '] = ', m_a[ind]) print(delim) new_val = 42 print("setting value ", new_val, " to index ", ind) m_a[ind] = new_val print('MyArray m_a -->', m_a) print(delim) ind = 0 print("delete item from index", ind) del m_a[ind] print('MyArray m_a -->', m_a) print(delim) print("checking if ", new_val, " in m_a") print(new_val in m_a) print('MyArray m_a -->', m_a) print(delim)
# getTotalPage.py # 06-3 게시판 페이징하기 (나의 풀이_한 번에 성공!) # divmod를 사용해서 몫과 나머지를 한 번에 구했다는 점, # 그리고 그 결과는 튜플이라 리스트처럼 인덱싱했다는 점! result = 0 # 총 페이지 (output) m = 0 # 게시물의 총 건수 (input) n = 0 # 한 페이지에 보여줄 게시물 수 (input) def getTotalPage(m, n): page = divmod(m, n) if not page[1]==0: result = page[0]+1 else: result = page[0] return result print(getTotalPage(30, 10))
n = input() def odd_even(a): odd = 0 even = 0 for i in range(len(a)): if int(a[i]) % 2 == 0: even += int(a[i]) else: odd += int(a[i]) return (f'Odd sum = {odd}, Even sum = {even}') print(odd_even(n))
# Suponho que a população de um país A seja da ordem de 80000 habiteantes com uma taxa anual de crescimento de 3% e que # a população B seja 200000 habitantes com uma taxa de crescimento de 1.5%. Faça um programa que calcule e escreva o numero # de anos necessarios para que a população do Pais A ultrapasse ou iguale a população do Pais B, mantidas as taxas de crescimento pais_A, pais_B, cont_anos = 80000, 200000, 0 cresc_A, cresc_B = 3, 1.5 validar = True if (pais_A >= pais_B) else False while (validar != True): pais_A = pais_A + ((pais_A * cresc_A) / 100) pais_B = pais_B + ((pais_B * cresc_B) / 100) cont_anos += 1 validar = True if (pais_A >= pais_B) else False print(f'O pais A vai ultrapassar o Pais B em {cont_anos} anos.')
""" Entradas numero_hombres-->int-->p_h numero_mujeres-->int-->p_m salidas Porcentaje de hombres-->float-->p_h Porcentaje de mujeres-->float-->p_m """ numero_hombres=int(input("digite total de hombres: ")) numero_mujeres=int(input("digite total de mujeres: ")) #caja negra p_h=numero_hombres*100/(numero_hombres+numero_mujeres)#float p_m=numero_mujeres*100/(numero_hombres+numero_mujeres)#float #salida print("porcentaje de hombres:", p_h, "y el porcentaje de mujeres: ",p_m)
load("//internal/jsweet_transpile:jsweet_transpile.bzl", "jsweet_transpile","TRANSPILE_ATTRS") load("@npm_bazel_typescript//:index.bzl", "ts_library") JWSEET_TRANSPILE_KEYS = TRANSPILE_ATTRS.keys() def jsweet_ts_lib(name, **kwargs): transpile_args = dict() for transpile_key in JWSEET_TRANSPILE_KEYS: if transpile_key in kwargs: value = kwargs.pop(transpile_key) if value != None: transpile_args[transpile_key] = value jsweet_transpiled_name = name + "_jsweet_transpiled" jsweet_transpile( name = jsweet_transpiled_name, **transpile_args ) jsweet_ts_sources_name = name + "_jsweet_ts_sources" native.filegroup( name = jsweet_ts_sources_name, srcs = [":" + jsweet_transpiled_name], output_group = "ts_sources" ) ts_library( name = name, srcs = [":" + jsweet_ts_sources_name], **kwargs # The remaining arguments go to `ts_library` )
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: dummy = ListNode() output = dummy # l1_eol = False # l2_eol = False while 1: # if l1.next == None: # # output.next = l2 # # break # l1_eol = True # if l2.next == None: # # output.next = l1 # # break # l2_eol = True if l1 is None: output.next = l2 break if l2 is None: output.next = l1 break if l1.val < l2.val: output.next = l1 l1= l1.next # print("l1 val ",l1.val) # break else: output.next = l2 l2= l2.next # print("l2 val ",l2.val) # break output = output.next return dummy.next class Solution2: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: if l1 == None: return l2 elif l2 == None: return l1 elif l1.val < l2.val: l1.next = self.mergeTwoLists(l1.next, l2) return l1 else: l2.next = self.mergeTwoLists(l1, l2.next) return l2
text = """first row second row third row""" print(text)
# WSADMIN SCRIPT TO SHOW USEFUL ADMINTASK COMMANDS AND HELP TOWARDS THEM # Santiago Garcia Arango # Command: # wsadmin.sh -lang jython -f /tmp/test.py print("***** Showing AdminTask help *****") print(AdminTask.help()) print("***** Showing AdminTask commands *****") print(AdminTask.help("-commands")) print("***** Showing AdminTask commands with <*something*> pattern *****") print(AdminTask.help("-commands", "*server*")) print(AdminTask.help("-commands", "*jvm*")) print(AdminTask.help("-commands", "*user*")) print("***** Showing AdminTask command groups *****") print(AdminTask.help("-commandGroups")) print("***** Showing AdminTask specific command help (some examples) *****") print(AdminTask.help("listNodes")) print(AdminTask.help("listServers")) print(AdminTask.help("showServerInfo")) print(AdminTask.help("setJVMProperties")) print(AdminTask.help("showJVMProperties")) print(AdminTask.help("createAuthDataEntry")) print(AdminTask.help("modifyAuthDataEntry")) print(AdminTask.help("modifyWMQQueue")) print(AdminTask.help("createWMQQueue")) print(AdminTask.help("listUserIDsOfAuthorizationGroup")) print(AdminTask.help("listAuditUserIDsOfAuthorizationGroup")) print(AdminTask.help("createUser"))
def dummy_function(a): return a DUMMY_GLOBAL_CONSTANT_0 = 'FOO'; DUMMY_GLOBAL_CONSTANT_1 = 'BAR';
''' Given a non-negative integer num represented as a string, remove k digits from the number so that the new number is the smallest possible. Note: - The length of num is less than 10002 and will be ≥ k. - The given num does not contain any leading zero. Example: Input: num = "1432219", k = 3 Output: "1219" Explanation: Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest. Example: Input: num = "10200", k = 1 Output: "200" Explanation: Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes. Example: Input: num = "10", k = 2 Output: "0" Explanation: Remove all the digits from the number and it is left with nothing which is 0. ''' #Difficlty: Medium #33 / 33 test cases passed. #Runtime: 32 ms #Memory Usage: 14.1 MB #Runtime: 32 ms, faster than 92.66% of Python3 online submissions for Remove K Digits. #Memory Usage: 14.1 MB, less than 99.94% of Python3 online submissions for Remove K Digits. class Solution: def removeKdigits(self, num: str, k: int) -> str: length = len(num) - k stack = [] for n in num: while stack and k and stack[-1] > n: stack.pop() k -= 1 stack.append(n) while stack and stack[0] == '0': stack.pop(0) return ''.join(stack)[:length] if stack and length else '0'
# Matrix solver (TDMA) # parameters required: # n: number of unknowns (length of x) # a: coefficient matrix # b: RHS/constant array # return output: # b: solution array def solve_TDMA(n, a, b): # forward substitution a[0][2] = -a[0][2] / a[0][1] b[0] = b[0] / a[0][1] for i in range(1, n): a[i][2] = -a[i][2] / (a[i][1] + a[i][0] * a[i - 1][2]) b[i] = (b[i] - a[i][0] * b[i - 1]) / (a[i][1] + a[i][0] * a[i - 1][2]) # backward elimination for i in range(n - 2, -1, -1): b[i] = a[i][2] * b[i + 1] + b[i] return b
n = int(input('Quantos termos [FIBONACCI], você quer mostrar? ')) ant = 0 post = 1 cont = 0 print('{} -> {}'.format(ant, post),end='') while cont <= n: atual = ant + post print( '-> {}'.format(atual),end='') ant = post post = atual cont += 1 print('-> FIM!')
default_response = { "features":[ { "geometry":{ "coordinates":[ -43.21986610772104, -22.8049732 ], "type":"Point" }, "type":"Feature", "properties":{ "osm_id":5519132, "osm_type":"R", "extent":[ -43.265963, -22.7757114, -43.1557502, -22.8339199 ], "country":"Brazil", "osm_key":"place", "city":"Rio de Janeiro", "osm_value":"island", "name":"Governador Island", "state":"Rio de Janeiro" } }, { "geometry":{ "coordinates":[ -62.92761666754802, -0.9610612000000001 ], "type":"Point" }, "type":"Feature", "properties":{ "osm_id":209813884, "osm_type":"W", "extent":[ -62.9292942, -0.958921, -62.9257127, -0.9631287 ], "country":"Brazil", "osm_key":"place", "city":"Barcelos", "osm_value":"islet", "postcode":"69700000", "name":"Ilha do Governador", "state":"Amazonas" } }, { "geometry":{ "coordinates":[ -42.10028206205817, -19.0068657 ], "type":"Point" }, "type":"Feature", "properties":{ "osm_id":286169517, "osm_type":"W", "extent":[ -42.1071179, -19.001967, -42.096832, -19.0114867 ], "country":"Brazil", "osm_key":"place", "city":"Alpercata", "osm_value":"island", "name":"Ilha do Arroz", "state":"Minas Gerais" } }, { "geometry":{ "coordinates":[ -48.557870106181525, -27.406375599999997 ], "type":"Point" }, "type":"Feature", "properties":{ "osm_id":10773467, "osm_type":"W", "extent":[ -48.5588059, -27.4058472, -48.5570169, -27.406895 ], "country":"Brazil", "osm_key":"place", "city":"Governador Celso Ramos", "osm_value":"island", "postcode":"88190-000", "name":"Ilha do Maximiliano", "state":"Santa Catarina" } }, { "geometry":{ "coordinates":[ -41.94406791407067, -18.86703455 ], "type":"Point" }, "type":"Feature", "properties":{ "osm_id":250255623, "osm_type":"W", "extent":[ -41.9505911, -18.8595339, -41.9381017, -18.8759379 ], "country":"Brazil", "osm_key":"place", "city":"Governador Valadares", "osm_value":"island", "name":"Ilha dos Araújos", "state":"Minas Gerais" } }, { "geometry":{ "coordinates":[ -41.9427495, -18.865785 ], "type":"Point" }, "type":"Feature", "properties":{ "osm_id":5548936, "osm_type":"R", "extent":[ -41.9522571, -18.8591612, -41.936979, -18.8795156 ], "country":"Brazil", "osm_key":"place", "city":"Governador Valadares", "osm_value":"suburb", "name":"Ilha dos Araújos", "state":"Minas Gerais" } }, { "geometry":{ "coordinates":[ -42.089677830705526, -18.98877025 ], "type":"Point" }, "type":"Feature", "properties":{ "osm_id":286169516, "osm_type":"W", "extent":[ -42.0910104, -18.9866293, -42.088439, -18.9910726 ], "country":"Brazil", "osm_key":"place", "city":"Alpercata", "osm_value":"islet", "name":"Ilha Funda", "state":"Minas Gerais" } }, { "geometry":{ "coordinates":[ -51.0641413, -23.2929031 ], "type":"Point" }, "type":"Feature", "properties":{ "osm_id":106941503, "osm_type":"W", "extent":[ -51.0641413, -23.2924122, -51.0623139, -23.2929031 ], "country":"Brazil", "osm_key":"highway", "city":"Ibiporã", "osm_value":"residential", "postcode":"86200-981", "name":"Rua Ilha do Governador", "state":"Paraná" } }, { "geometry":{ "coordinates":[ -46.9692001, -22.8601013 ], "type":"Point" }, "type":"Feature", "properties":{ "osm_id":142677919, "osm_type":"W", "extent":[ -46.969598, -22.8600213, -46.9689513, -22.860149 ], "country":"Brazil", "osm_key":"highway", "city":"Campinas", "osm_value":"residential", "postcode":"13104-164", "name":"Rua Ilha do Governador", "state":"São Paulo" } }, { "geometry":{ "coordinates":[ -40.8756976, -14.8355181 ], "type":"Point" }, "type":"Feature", "properties":{ "osm_id":223347577, "osm_type":"W", "extent":[ -40.8757429, -14.8355181, -40.8756976, -14.8378329 ], "country":"Brazil", "osm_key":"highway", "city":"Vitória da Conquista", "osm_value":"residential", "postcode":"45085130", "name":"Rua Ilha do Governador", "state":"Bahia" } }, { "geometry":{ "coordinates":[ -44.0756304, -22.4904658 ], "type":"Point" }, "type":"Feature", "properties":{ "osm_id":95304428, "osm_type":"W", "extent":[ -44.0758156, -22.4902065, -44.0755289, -22.4909837 ], "country":"Brazil", "osm_key":"highway", "city":"Volta Redonda", "osm_value":"residential", "postcode":"27213-145", "name":"Rua Ilha do Governador", "state":"Rio de Janeiro" } }, { "geometry":{ "coordinates":[ -46.8977948, -23.5097169 ], "type":"Point" }, "type":"Feature", "properties":{ "osm_id":173208053, "osm_type":"W", "extent":[ -46.8983151, -23.5097058, -46.8973236, -23.5099122 ], "country":"Brazil", "osm_key":"highway", "city":"Barueri", "osm_value":"residential", "postcode":"06420-340", "name":"Rua Ilha do Governador", "state":"São Paulo" } }, { "geometry":{ "coordinates":[ -46.8040744, -23.6570636 ], "type":"Point" }, "type":"Feature", "properties":{ "osm_id":439820004, "osm_type":"W", "extent":[ -46.8043329, -23.6566816, -46.8038392, -23.6575009 ], "country":"Brazil", "osm_key":"highway", "city":"Embu das Artes", "osm_value":"residential", "postcode":"06814-160", "name":"Rua Ilha do Governador", "state":"São Paulo" } }, { "geometry":{ "coordinates":[ -44.69132688556381, -23.216495600000002 ], "type":"Point" }, "type":"Feature", "properties":{ "osm_id":10936780, "osm_type":"W", "extent":[ -44.6933283, -23.2148027, -44.6896087, -23.2180194 ], "country":"Brazil", "osm_key":"boundary", "city":"Paraty", "street":"Rodovia Governador Mário Covas", "osm_value":"protected_area", "postcode":"23970-000", "name":"Ilha da Bexiga", "state":"Rio de Janeiro" } }, { "geometry":{ "coordinates":[ -47.0308807, -23.6626934 ], "type":"Point" }, "type":"Feature", "properties":{ "osm_id":225637207, "osm_type":"W", "extent":[ -47.0313205, -23.6616765, -47.0305328, -23.6634982 ], "country":"Brazil", "osm_key":"highway", "city":"Cotia", "osm_value":"residential", "postcode":"06726-466", "name":"Rua União da Ilha do Governador", "state":"São Paulo" } } ], "type":"FeatureCollection" } twoinoneout = { "features":[ { "geometry":{ "coordinates":[ -43.21986610772104, -22.8049732 ], "type":"Point" }, }, { "geometry":{ "coordinates":[ -44.69132688556381, -23.216495600000002 ], "type":"Point" }, }, { "geometry":{ "coordinates":[ -47.0308807, -23.6626934 ], "type":"Point" }, } ] }
allowed_request_categories = [ 'stock', 'mutual_fund', 'intraday', 'history', 'history_multi_single_day', 'forex', 'forex_history', 'forex_single_day', 'stock_search' ]
""" Constant values used all over the place. Fare data is stored in fares/data.py. """ # Directories DIR_DOWNLOAD = "data_src" DIR_CONVERTED = "data_feeds" DIR_SINGLE_FEED = "data_gtfs" DIR_SHAPE_ERR = "err_shapes" DIR_SHAPE_CACHE = "data_shapes" # How long to keep Overpass data cached (in minutes) SHAPE_CACHE_TTL = 2 * 1440 # External data sources FTP_ADDR = "rozklady.ztm.waw.pl" _BASE_GIST = "https://gist.githubusercontent.com/MKuranowski/0ca97a012d541899cb1f859cd0bab2e7/" GIST_MISSING_STOPS = _BASE_GIST + "raw/missing_stops.json" GIST_RAIL_PLATFORMS = _BASE_GIST + "raw/rail_platforms.json" GIST_STOP_NAMES = _BASE_GIST + "raw/stop_names.json" URL_METRO_GTFS = "https://mkuran.pl/gtfs/warsaw/metro.zip" # Logging attrivutes LOGGING_STYLE = "{" LOGGING_FMT = "[{levelname}] {name}: {message}" # List of rail stops used by S× lines. Other rail stops are ignored. ACTIVE_RAIL_STATIONS = { "4900", "4901", "7900", "7901", "7902", "2901", "2900", "2918", "2917", "2916", "2915", "2909", "2908", "2907", "2906", "2905", "2904", "2903", "2902", "4902", "4903", "4923", "4904", "4905", "2914", "2913", "2912", "2911", "2910", "4919", "3901", "4918", "4917", "4913", "1910", "1909", "1908", "1907", "1906", "1905", "1904", "1903", "1902", "1901", "7903", "5908", "5907", "5904", "5903", "5902", "1913", "1914", "1915", } # Irregular stop names PROPER_STOP_NAMES = { "1226": "Mańki-Wojody", "1484": "Dom Samotnej Matki", "1541": "Marki Bandurskiego I", "2005": "Praga-Płd. - Ratusz", "2296": "Szosa Lubelska", "2324": "Wiązowna", "4040": "Lotnisko Chopina", "4305": "Posag 7 Panien", # theoretically "Zajezdnia Ursus Płn." "4400": "Mobilis Sp. z.o.o.", "5001": "Połczyńska - Parking P+R", "6201": "Lipków Paschalisa-Jakubowicza", } # GTFS headers HEADERS = { "agency.txt": [ "agency_id", "agency_name", "agency_url", "agency_timezone", "agency_lang", "agency_phone", "agency_fare_url", ], "attributions.txt": [ "attribution_id", "organization_name", "is_producer", "is_operator", "is_authority", "is_data_source", "attribution_url", ], "feed_info.txt": ["feed_publisher_name", "feed_publisher_url", "feed_lang", "feed_version"], "calendar_dates.txt": ["service_id", "date", "exception_type"], "fare_attributes.txt": [ "fare_id", "price", "currency_type", "payment_method", "transfers", "agency_id", "transfer_duration", ], "fare_rules.txt": ["fare_id", "route_id", "contains_id"], "shapes.txt": [ "shape_id", "shape_pt_sequence", "shape_dist_traveled", "shape_pt_lat", "shape_pt_lon" ], "stops.txt": [ "stop_id", "stop_name", "stop_lat", "stop_lon", "location_type", "parent_station", "zone_id", "stop_IBNR", "stop_PKPPLK", "platform_code", "wheelchair_boarding", ], "routes.txt": [ "agency_id", "route_id", "route_short_name", "route_long_name", "route_type", "route_color", "route_text_color", "route_sort_order", ], "trips.txt": [ "route_id", "service_id", "trip_id", "trip_headsign", "direction_id", "shape_id", "exceptional", "wheelchair_accessible", "bikes_allowed", ], "stop_times.txt": [ "trip_id", "arrival_time", "departure_time", "stop_id", "stop_sequence", "pickup_type", "drop_off_type", "shape_dist_traveled", ], }
#Encontrar el menor valor en un array #con busqueda binaria def menor (array): l=0 r=len(array)-1 while l<=r: mid = l+(r-l)//2 if array[mid] > array[r]: l=mid+1 if array[mid]< array[r]: r=mid if r==l or mid==0: return array[r] nums=[15,18,25,35,1,3,12] print(menor(nums))
def fun(s): ans = 0 o = 0 c = 0 for i in s: if(i=="("): o+=1 elif(i==")"): c+=1 if(c>o): c-=1 o+=1 ans+=1 return ans t = int(input()) for _ in range(t): n = int(input()) s = input() ans = 0 N = 10**9+7 value = ((n+1)*n)//2 value = pow(value,N-2,N) print(value) for i in range(n): ans+=fun(s[i:]) print((ans*value)%N)
for _ in range(int(input())): s = set() n = input().split() while True: m = input().split() if m[-1] == "say?": break s.add(m[-1]) for i in n: if i not in s: print(i, end=' ') print()
# -*- coding: utf-8 -*- BOT_TOKEN = "b73225fbdf517ed6cbc842b4c2c9b0d19422071825c18a4efc62c52a5b0bf89d270434602d03c729d7fa3" # Задержка перед ответом бота в секундах. RESPONSE_DELAY = 3 # Шанс ответа в процентах (от 1 до 100). RESPONSE_CHANCE = 25
# Copyright (c) 2018 Stephen Bunn <stephen@bunn.io> # MIT License <https://opensource.org/licenses/MIT> __name__ = "standardfile" __repo__ = "https://github.com/stephen-bunn/standardfile" __description__ = "A library for accessing and interacting with a Standard File server." __version__ = "0.0.0" __author__ = "Stephen Bunn" __contact__ = "stephen@bunn.io" __license__ = "MIT License"
""" 10. Faça um Programa que pergunte em que turno você estuda. Peça para digitar M-Matutino ou V-Vespertino ou N-Noturno. Imprima a mensagem "Bom Dia!", "Boa Tarde!" ou "Boa Noite!" ou "Valor Inválido!", conforme o caso. """ turno = input("Qual o turno que você estuda: ") if turno == 'M' or turno == "Matutino": print("Bom Dia!") elif turno == 'V' or turno == "Vespertino": print("Boa Tarde!") elif turno == 'N' or turno == "Noite": print("Boa Noite!") else: print("Valor Inválido!")
""" LIST: CHUNKING """ __author__ = 'Sol Amour - amoursol@gmail.com' __twitter__ = '@solamour' __version__ = '1.0.0' # Example of Chunking (Grouping an item with its next) def chunks(list, number): # Requires a list and a number for index in range(0, len(list), number): # For every # index inside of a number range starting at '0' # and running to the length of the list, with steps # of a chosen 'number' yield list[index : index + number] # Yield returns # a 'generator' object, so we cast the result to a # 'list' and will return 'list slices' ranging from # the chosen 'index' to the chosen 'index' + chosen # 'number' # Exemplar list itemList = [0, 1, 2, 3, 4, 5] # A simple list of numbers to # parse with our 'chunks' definition count = 2 # A number which we want to chunk to. We choose '2' # which will result in sublists of: [[0, 1], [2, 3], [4,5]] chunksList = chunks(itemList, count) # Here we call our new # 'chunks' definition on our 'itemList' and with our 'count' # then push those results to our variable called 'chunksList' OUT = chunksList # Returning our chunked data
class Dataset(object): def __init__(self, env_spec): self._env_spec = env_spec def get_batch(self, batch_size, horizon): raise NotImplementedError def get_batch_iterator(self, batch_size, horizon, randomize_order=False, is_tf=True): raise NotImplementedError
# -------------- ##File path for the file file_path def read_file(path): f=open(path,'r') sentence=f.readline() f.close() return sentence sample_message=read_file(file_path) #Code starts here # -------------- #Code starts here file_path_1 file_path_2 message_1=read_file(file_path_1) message_2=read_file(file_path_2) message_1,message_2 def fuse_msg(message_a,message_b): ima=int(message_a) imb=int(message_b) quotient=int(imb/ima) return str(quotient) #fuse_msg(message_1,message_2) secret_msg_1=fuse_msg(message_1,message_2) # -------------- #Code starts here message_3=read_file(file_path_3) message_3 def substitute_msg(message_c): sub="Data Scientist" if message_c is 'Red':sub='Army General' if message_c is 'Green':sub='Data Scientist' if message_c is 'Blue':sub='Marine Biologist' return sub secret_msg_2=substitute_msg(message_3) secret_msg_2 # -------------- # File path for message 4 and message 5 file_path_4 file_path_5 message_4=read_file(file_path_4) message_5=read_file(file_path_5) message_4,message_5 def compare_msg(message_d,message_e): alist=message_d.split() blist=message_e.split() c_list=(i for i in alist+blist if i not in blist) final_msg=" ".join(c_list) return final_msg secret_msg_3=compare_msg(message_4,message_5) secret_msg_3 # -------------- #Code starts here message_6=read_file(file_path_6) message_6 def extract_msg(message_f): a_list=message_f.split() even_word= lambda x:(len(x)%2==0) b_list=filter(even_word,a_list) print(b_list) final_msg = " ".join(b_list) return final_msg secret_msg_4=extract_msg(message_6) # -------------- #Secret message parts in the correct order message_parts=[secret_msg_3, secret_msg_1, secret_msg_4, secret_msg_2] secret_msg=" ".join(message_parts) final_path= user_data_dir + '/secret_message.txt' def write_file(secret_msg,path): file1=open(path,'a+') file1.write(secret_msg) file1.close() write_file(secret_msg,final_path) secret_msg