content
stringlengths
7
1.05M
def setUpModule() -> None: print("[Module sserender Test Start]") def tearDownModule() -> None: print("[Module sserender Test End]")
print('begin program') # This program says hello and asks for my name. print('Hello, World!') print('What is your name?') myName = input() print('It is good to meet you, ' + myName) print('end program')
# -*- coding: utf-8 -*- def generate_translations(item): """Generate French and Spanish translations for the given `item`.""" fr_prefix = u'(français) ' es_prefix = u'(español) ' oldname = str(item.name) item.name = {'en': oldname, 'fr': fr_prefix + oldname, 'es': es_prefix + oldname} item.save()
""" Mehmet Said Turken 180401030""" dosya = open("veriler.txt.txt", "r") veri = [] for i in dosya.read().split(): veri.append(int(i)) n = len(veri) yitoplam = sum(veri) def x_degerleri(list, n): valuex = [] for i in range(13): x = 0 for k in range(n): x += (k+1)**i valuex.append(x) return valuex def toplam_xiyi(list, n): toplam_xiyi = [] for i in range(7): xiyi = 0 for k in range(n): xiyi += ((k+1)**i)*(list[k]) toplam_xiyi.append(xiyi) return toplam_xiyi def gaussyontemi(matris): #EBD (en buyuk deger)--- EBS(en buyuk satir) n = len(matris) for i in range(0, n): EBD = abs(matris[i][i]) EBS = i for k in range(i + 1, n): if abs(matris[k][i]) >EBD: EBD = abs(matris[k][i]) EBS = k for k in range(i, n + 1): temp = matris[EBS][k] matris[EBS][k] = matris[i][k] matris[i][k] = temp for k in range(i + 1, n): c = -matris[k][i] / matris[i][i] for j in range(i, n + 1): if i == j: matris[k][j] = 0 else: matris[k][j] += c * matris[i][j] son = [0 for i in range(n)] for i in range(n - 1, -1, -1): son[i] =matris[i][n] / matris[i][i] for k in range(i - 1, -1, -1): matris[k][n] -= matris[k][i] * son[i] return son #polinomlarin denklemlere yaklastirip katsayilarin return edildigi fonksiyon def liste_cozum(list, n): cozum = [] for i in range(2, 8): degerler = [] for j in range(i): degerler.append([]) for k in range(i): degerler[j].append(x_degerleri(list, n)[k + j]) degerler[j].append(toplam_xiyi(list, n)[j]) if j == i - 1: cozum.append(gaussyontemi(degerler)) degerler.clear() return cozum def deger_st(x, veri, n, yitoplam): #St nin degerini bulacagimiz fonksiyon y_ort = yitoplam / n st = 0 for i in range(n): st += (veri[i] - y_ort) ** 2 return st def sr_korelasyon(x, veri, n, yitoplam): #sr'yi buluyoruz,korelasyon katsayilarini donduruyoruz. sr = 0 for i in range(n): hesaplama = 0 hesaplama += x[0] for j in range(1, len(x)): hesaplama += x[j] * (i + 1) ** j sr += (veri[i] - hesaplama) ** 2 return ((deger_st(x, veri, n, yitoplam) - sr) / deger_st(x, veri, n, yitoplam)) ** (1/2) def korelasyon_list(korelasyon_degerleri, veri, n, yitoplam): deger = [] for i in korelasyon_degerleri: deger.append(sr_korelasyon(i, veri, n, yitoplam)) return deger def optimaldeger(korelasyon_degerleri, veri, n, yitoplam): a = korelasyon_list(korelasyon_degerleri, veri, n, yitoplam) ilk = 150 list = [] for i in range(len(a)): degerr = abs(1-a[i]) if int(degerr) < 0: degerr *= -1 if degerr < ilk: ilk = degerr list.clear() list.append((i+1, a[i])) return list def yaz(): filenew = open("sonuc.txt", "w+") filenew.write("*tum degerler icin**" + "\n") a = 0 for i in liste_cozum(veri, n): filenew.write("\t"+ str(a+1) + ". derece"+ "\n") b = 0 for k in i: filenew.write(str(b+1) + ". deger = " + str(k)+"\n") b += 1 filenew.write("Korelasyon = " + str(korelasyon_list(liste_cozum(veri, n), veri, n, yitoplam)[a])+"\n") a += 1 filenew.write("\n*En uygun polinom ve korelasyon degeri = " + str( optimaldeger(liste_cozum(veri, n), veri, n, yitoplam)[0]) + "*\n") for j in range(len(veri)): a = 0 newlist = [] if(j + 10 > len(veri)): break for l in range(j, j+10): newlist.append(veri[l]) filenew.write("*" + str(j+1) + " ile " + str(j+10) + " arasindaki degerler icin*") filenew.write("\n*En uygun polinom ve korelasyon degeri = " + str( optimaldeger(liste_cozum(newlist, len(newlist)), newlist, len(newlist), sum(newlist))[0]) + "*\n") bas = 1 bit = 10 a = 0 for j in range(len(veri)): newlist = [] if ((bit*a)+10 > len(veri)): break for l in range((bas*a*10), bit*a + 9): newlist.append(veri[l]) filenew.write("**" + str(bas*a*10) + " ile " + str(bit*a + 9) + " arasindaki degerler icin**") filenew.write("\n*En uygun polinom ve korelasyon degeri = " + str(optimaldeger(liste_cozum(newlist, len(newlist)), newlist, len(newlist), sum(newlist))[0]) + "*\n") a += 1 filenew.close() yaz()
#!/usr/bin/env python ''' primes.py @author: Lorenzo Cipriani <[email protected]> @contact: https://www.linkedin.com/in/lorenzocipriani @since: 2017-10-23 @see: ''' primesToFind = 1000000 num = 0 found = 0 def isPrime(num): if num > 1: for i in range(2, num): if (num % i) == 0: return False else: return True else: return False if __name__ == '__main__': print("Search for the first {} prime numbers:".format(primesToFind)) primesList = [] while primesToFind > 0: num += 1 if isPrime(num): primesList.append(num) found += 1 print(found, num) primesToFind -= 1
# # @lc app=leetcode id=705 lang=python3 # # [705] Design HashSet # # https://leetcode.com/problems/design-hashset/description/ # # algorithms # Easy (53.97%) # Likes: 145 # Dislikes: 39 # Total Accepted: 23.6K # Total Submissions: 43.5K # Testcase Example: '["MyHashSet","add","add","contains","contains","add","contains","remove","contains"]\n[[],[1],[2],[1],[3],[2],[2],[2],[2]]' # # Design a HashSet without using any built-in hash table libraries. # # To be specific, your design should include these functions: # # # add(value): Insert a value into the HashSet.  # contains(value) : Return whether the value exists in the HashSet or not. # remove(value): Remove a value in the HashSet. If the value does not exist in # the HashSet, do nothing. # # # # Example: # # # MyHashSet hashSet = new MyHashSet(); # hashSet.add(1); # hashSet.add(2); # hashSet.contains(1);    // returns true # hashSet.contains(3);    // returns false (not found) # hashSet.add(2);           # hashSet.contains(2);    // returns true # hashSet.remove(2);           # hashSet.contains(2);    // returns false (already removed) # # # # Note: # # # All values will be in the range of [0, 1000000]. # The number of operations will be in the range of [1, 10000]. # Please do not use the built-in HashSet library. # # # class MyHashSet: def __init__(self): """ Initialize your data structure here. """ self.__data = [False]*1000001 def add(self, key: int) -> None: self.__data[key] = True def remove(self, key: int) -> None: self.__data[key] = False def contains(self, key: int) -> bool: """ Returns true if this set contains the specified element """ return self.__data[key] # Your MyHashSet object will be instantiated and called as such: # obj = MyHashSet() # obj.add(key) # obj.remove(key) # param_3 = obj.contains(key)
class ExportingTemplate(): def __init__(self, exporting_template_name=None, channel=None, target_sample_rate=None, duration=None, created_date=None, modified_date=None, id=None): self.exporting_template_name = exporting_template_name self.channel = channel self.target_sample_rate = target_sample_rate self.duration = duration self.created_date = created_date self.modified_date = modified_date self.id = id # getting the values @property def value(self): # print('Getting value') return self.exp_tem_name, self.channel, self.target_sample_rate, self.duration, self.created_date, self.modified_date, self.id # setting the values @value.setter def value(self, exporting_template_name, channel, target_sample_rate, duration, created_date, modified_date, id): self.exporting_template_name = exporting_template_name self.target_sample_rate = target_sample_rate self.duration = duration self.created_date = created_date self.modified_date = modified_date self.id = id self.channel = channel # deleting the values @value.deleter def value(self): # print('Deleting value') del self.exporting_template_name, self.channel, self.target_sample_rate, self.duration, self.created_date, self.modified_date, self.id
# -*- coding: utf-8 -*- """ indico_payment_stripe ~~~~~~~~~~~~~~~~~~~~~ Indico plugin for Stripe payment support. :license: MIT """ RELEASE = False __version_info__ = ('0', '0', '1') __version__ = '.'.join(__version_info__) __version__ += '-dev' if not RELEASE else '' __author__ = 'NeIC' __homepage__ = 'https://github.com/neicnordic/indico-plugin-stripe'
# Based on container/push.bzl from rules_docker # Also based on pkg/pkg.bzl from bazel_tools # Copyright 2015, 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. load("@io_bazel_rules_docker//container:layer_tools.bzl", _get_layers = "get_from_target") def _quote(filename, protect = "="): """Quote the filename, by escaping = by \\= and \\ by \\""" return filename.replace("\\", "\\\\").replace(protect, "\\" + protect) def _impl(ctx): image = _get_layers(ctx, ctx.label.name, ctx.attr.image) blobsums = image.get("blobsum", []) blobs = image.get("zipped_layer", []) config = image["config"] manifest = image["manifest"] tarball = image.get("legacy") base = ctx.attr.folder mapping = {} if tarball: print("Pushing an image based on a tarball can be very " + "expensive. If the image is the output of a " + "docker_build, consider dropping the '.tar' extension. " + "If the image is checked in, consider using " + "docker_import instead.") mapping[base + "/tarball"] = tarball if config: mapping[base + "/config"] = config if manifest: mapping[base + "/manifest"] = manifest for i, f in enumerate(blobsums): mapping[base + "/digest." + str(i)] = f for i, f in enumerate(blobs): mapping[base + "/layer." + str(i)] = f # Start building the arguments. args = [ "--output=" + ctx.outputs.out.path, "--directory=/", "--mode=0644", "--owner=0.0", "--owner_name=.", ] file_inputs = [] for f_dest_path, target in mapping.items(): target_files = [target] # .files.to_list() if len(target_files) != 1: fail("Each input must describe exactly one file.", attr = "files") file_inputs += target_files args.append("--file=%s=%s" % (_quote(target_files[0].path), f_dest_path)) arg_file = ctx.actions.declare_file(ctx.label.name + ".args") ctx.actions.write(arg_file, "\n".join(args)) ctx.actions.run( inputs = file_inputs + [arg_file], executable = ctx.executable.build_tar, arguments = ["--flagfile", arg_file.path], outputs = [ctx.outputs.out], mnemonic = "TarOCI", use_default_shell_env = True, ) oci_to_tar = rule( attrs = { "folder": attr.string( mandatory = True, ), "image": attr.label( allow_single_file = [".tar"], mandatory = True, doc = "The label of the image to push.", ), # Implicit dependencies. "build_tar": attr.label( default = Label("@bazel_tools//tools/build_defs/pkg:build_tar"), cfg = "host", executable = True, allow_files = True, ), }, implementation = _impl, outputs = { "out": "%{name}.tar", }, )
"""文字列基礎 フォーマット済み文字列リテラル(f-string)の使い方 「=」で変数や式を含めて表示する方法 ※ python 3.8 で追加 [説明ページ] https://tech.nkhn37.net/python-str-format-f-string/#_Python_38 """ # フォーマット文字列で変数や式を表示する方法 name = '太郎' sex = '男性' age = 20 # f-stringで変数や式を含めて表示する方法 print(f'{name=}は{age=}歳の{sex=}です。') print(f'{name=}は{age*2=}歳の{sex=}です。')
# Given an array of strings strs, group the anagrams together. You can return the answer in any order. # An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. # Example 1: # Input: strs = ["eat","tea","tan","ate","nat","bat"] # Output: [["bat"],["nat","tan"],["ate","eat","tea"]] # Example 2: # Input: strs = [""] # Output: [[""]] # Example 3: # Input: strs = ["a"] # Output: [["a"]] # Constraints: # 1 <= strs.length <= 104 # 0 <= strs[i].length <= 100 # strs[i] consists of lower-case English letters. class Solution: def groupAnagrams(self, strs): result = [] lst = [] for i in strs: a = sorted(i) if a in lst: x = lst.index(a) result[x].append(i) else: lst.append(a) result.append([i]) return result
instructions = [] for line in open('input.txt', 'r').readlines(): readline = line.strip() instructions.append((readline[0], int(readline[1:]))) directions = { 'E': [1, 0], 'S': [0, -1], 'W': [-1, 0], 'N': [0, 1], } direction = 'E' x, y = 0, 0 for action, value in instructions: if action in [*directions]: x += directions[action][0] * value y += directions[action][1] * value elif action in ['L', 'R']: idx = [*directions].index(direction) idx += (-1 if action == 'L' else 1) * (value // 90) direction = [*directions][idx % 4] elif action == 'F': x += directions[direction][0] * value y += directions[direction][1] * value print(abs(x) + abs(y))
a = [ 1, 2, 3, 4, 5 ] print(a) print(a[0]) for i in range(len(a)): print(a[i]) a.append(10) a.append(20) print(a)
# -*- coding: utf-8 -*- # 从头到尾打印单链表 class Node(object): def __init__(self, val): self.val = val self.next = None class ChainTable(object): def __init__(self, data): self.head = Node(data[0]) p = self.head for val in data[1:]: p.next = Node(val) p = p.next # 方法 1: 递归 def print_chain_table(pointer): if pointer: print(pointer.val) print_chain_table(pointer.next) # 方法 2: 常规 def print_link_list(pointer): while pointer: print(pointer.val) pointer = pointer.next if __name__ == "__main__": ct = ChainTable([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) print_chain_table(ct.head) print_link_list(ct.head)
def buble_sort(nums): for i in range(1, len(nums)): if nums[i] < nums[i - 1]: nums[i], nums[i - 1] = nums[i - 1], nums[i] def check_sort(nums): for i in range(1, len(nums)): if nums[i] < nums[i - 1]: return False return True def main(): count_nums = int(input()) nums = list(map(int, input().split())) if check_sort(nums): print(*nums) else: while not check_sort(nums): buble_sort(nums) print(*nums) if __name__ == '__main__': main()
def temperature_statistics(t): mean = sum(t)/len(t) return mean, (sum((val-mean)**2 for val in t)/len(t))**0.5 print(temperature_statistics([4.4, 4.2, 7.0, 12.9, 18.5, 23.5, 26.4, 26.3, 22.5, 16.6, 11.2, 7.3]))
"""Top-level package for diffcalc-core.""" __author__ = """Diamond Light Source Ltd. - Scientific Software""" __email__ = "[email protected]" __version__ = "0.3.0"
# Helper function to print out relation between losses and network parameters # loss_list given as: [(name, loss_variable), ...] # named_parameters_list using pytorch function named_parameters(): [(name, network.named_parameters()), ...] def print_loss_params_relation(loss_list, named_parameters_list): loss_variables = {} for name, loss in loss_list: if loss.grad_fn is None: variables_ = [] else: def recursive_sub(loss): r = [] if hasattr(loss, 'next_functions'): for el, _ in loss.next_functions: if el is None: continue if hasattr(el, 'variable'): r.append(el.variable) else: r += recursive_sub(el) return r variables_ = recursive_sub(loss=loss.grad_fn) loss_variables[name] = variables_ # Assign params to networks and check for affection max_char_length = 0 affected_network_params = {} for network_name, named_parameters in named_parameters_list: affected_params = {} for n, p in named_parameters: # Ignore bias since this will just duplicate the outcome if (p.requires_grad) and ('bias' not in n): for loss_name in loss_variables.keys(): # Skip if loss_name is already existing in affected params if n in affected_params.keys() and loss_name in affected_params[n]: continue # Iterate through all variables for v in loss_variables[loss_name]: if v.shape == p.shape and (v.data == p.data).all(): if n in affected_params.keys(): affected_params[n].append(loss_name) else: affected_params[n] = [loss_name] max_char_length = len(n) if len(n) > max_char_length else max_char_length # Exit for after assigning loss name to param break affected_network_params[network_name] = affected_params # Print out for network_name in affected_network_params.keys(): print(f'Affected Params for {network_name}:') if len(affected_network_params[network_name].keys()) == 0: print('\t-') else: for p_name in affected_network_params[network_name].keys(): print(f'\t{p_name}:{" " * (max_char_length - len(p_name))}\t{affected_network_params[network_name][p_name]}') print('')
""" 【Python魔术方法】增量赋值魔术方法 2019/10/30 22:36 """ # TODO: 增量赋值魔术方法 """ 1.__iadd__(self,other)魔术方法:在给对象做+=运算的时候会执行的方法 2.__isub__(self,other)魔术方法:在给对象做-=运算的时候会执行的方法。 3.__imul__(self,other)魔术方法:在给对象做*=运算的时候会执行的方法。 4.__idiv__(self,other)魔术方法:在给对象做/=运算的时候会执行的方法。 -- Python2 5.__itruediv__(self,other)魔术方法:在给对象做真/=运算的时候会执行的方法。 --Python3 """ class Coornidate(object): def __init__(self, x, y): self.x = x self.y = y # TODO: += 运算 def __iadd__(self, other): self.x += other self.y += other return self # TODO: -= 运算 def __isub__(self, other): self.x -= other self.y -= other return self # TODO: *= 运算 def __imul__(self, other): self.x *= other self.y *= other return self # TODO: /= 运算 def __itruediv__(self, other): self.x /= other self.y /= other return self def __str__(self): return "(%s, %s)" % (self.x, self.y) c1 = Coornidate(1, 2) # c1 += 1 # c1 -= 1 # c1 *= 2 c1 /= 2 print(c1)
# %% [287. Find the Duplicate Number](https://leetcode.com/problems/find-the-duplicate-number/) class Solution: def findDuplicate(self, nums: List[int]) -> int: for i, v in enumerate(nums, 1): if v in nums[i:]: return v
def staircase(n): asteriscos = 1 # Write your code here for espacios in range(n, 0, -1): for i in range (espacios): print(' ', end='') for j in range(asteriscos): print('*', end='') print() asteriscos+=2 staircase(7)
#!/usr/bin/env python class Host(object): def __init__(self, name, groups,region, image, tags, size, meta=None): self.name = name self.groups = groups self.meta = meta or {} self.region = region self.image = image self.tags = tags self.size = size swifty_hosts = [ Host( name='swifty-gw-iac', region = 'ams3', image = 'ubuntu-18-04-x64', size = "s-2vcpu-4gb", tags = 'iac', groups=['gw'], meta={ 'vpn_ip': '192.168.0.1', 'public_dns': 'api.infra-ci.swifty.cloud', 'tinc_hostname': 'swygw' } ), Host( name='swifty-mw-iac', region = 'ams3', image = 'ubuntu-18-04-x64', size = "s-2vcpu-4gb", tags = 'iac', groups=['mw'], meta={ 'vpn_ip': '192.168.0.2', 'public_dns': 's3.infra-ci.swifty.cloud', 'tinc_hostname': 'swymw' } ), Host( name='swifty-dashboard-iac', region = 'ams3', image = 'ubuntu-18-04-x64', size = "s-1vcpu-2gb", tags = 'iac', groups=['ui'], meta={ 'vpn_ip': '192.168.0.3', 'public_dns': 'dashboard.infra-ci.swifty.cloud', 'tinc_hostname': 'swyui' } ), Host( name='swifty-connector-iac', region = 'ams3', image = 'ubuntu-18-04-x64', size = "s-1vcpu-2gb", tags = 'iac', groups=['connector'], meta={ 'vpn_ip': '192.168.0.4', 'public_dns': 'connector.infra-ci.swifty.cloud', 'tinc_hostname': 'swyconnector' } ), Host( name='swifty-worker0-iac', region = 'ams3', image = 'ubuntu-18-04-x64', size = "s-2vcpu-4gb", tags = 'iac', groups=['worker'], meta={ 'vpn_ip': '192.168.0.5', 'public_dns': 'worker0.infra-ci.swifty.cloud', 'tinc_hostname': 'swyworker0' } ), Host( name='swifty-worker1-iac', region = 'ams3', image = 'ubuntu-18-04-x64', size = "s-2vcpu-4gb", tags = 'iac', groups=['worker'], meta={ 'vpn_ip': '192.168.0.6', 'public_dns': 'worker1.infra-ci.swifty.cloud', 'tinc_hostname': 'swyworker1' } ), ]
''' Given an array of meeting time intervals intervals where intervals[i] = [starti, endi], return the minimum number of conference rooms required. Example 1: Input: intervals = [[0,30],[5,10],[15,20]] Output: 2 Example 2: Input: intervals = [[7,10],[2,4]] Output: 1 ''' #Approach 1: Priority Queues ''' Algorithm A) Sort the given meetings by their start time. B) Initialize a new min-heap and add the first meeting's ending time to the heap. We simply need to keep track of the ending times as that tells us when a meeting room will get free. C) For every meeting room check if the minimum element of the heap i.e. the room at the top of the heap is free or not. D) If the room is free, then we extract the topmost element and add it back with the ending time of the current meeting we are processing. E) If not, then we allocate a new room and add it to the heap. F) After processing all the meetings, the size of the heap will tell us the number of rooms allocated. This will be the minimum number of rooms needed to accommodate all the meetings. ''' class Solution(object): def minMeetingRooms(self, intervals): # MIN Heap (Priority QUEUE) TC (NLOGN), SPACE (N) if not intervals: return 0 intervals, res = sorted(intervals, key=lambda elem:elem[0]), [] # Add and create room for first meeting heapq.heappush(res, intervals[0][1]) # for rest of meeting rooms for elem in intervals[1:]: # if room due to free up the earliest is free, assign room to this meeting if res[0] <= elem[0]: heapq.heappop(res) #if new room assign then add to heap. If old room allocated, then add to heap with updated end time heapq.heappush(res, elem[1]) # size of heap minimum rooms required return len(res) #Approach 2: Chronological Ordering ''' Algorithm A) Separate out the start times and the end times in their separate arrays. B) Sort the start times and the end times separately. Note that this will mess up the original correspondence of start times and end times. They will be treated individually now. C) We consider two pointers: s_ptr and e_ptr which refer to start pointer and end pointer. The start pointer simply iterates over all the meetings and the end pointer helps us track if a meeting has ended and if we can reuse a room. D) When considering a specific meeting pointed to by s_ptr, we check if this start timing is greater than the meeting pointed to by e_ptr. E) If this is the case then that would mean some meeting has ended by the time the meeting at s_ptr had to start. So we can reuse one of the rooms. Otherwise, we have to allocate a new room. If a meeting has indeed ended i.e. if start[s_ptr] >= end[e_ptr], then we increment e_ptr. F) Repeat this process until s_ptr processes all of the meetings. ''' class Solution(object): def minMeetingRooms(self, intervals): # Chronocial Ordering TC (NLOGN) and Space (N) if not intervals: return 0 res = 0 #sort start and end time start_time = sorted([elem[0] for elem in intervals]) end_time = sorted([elem[1] for elem in intervals]) # define two pointer start_ptr, end_ptr = 0, 0 # untill all meeting room assigned while start_ptr < len(intervals): #if there is meeting ended by time the meeting at start_ptr starts if start_time[start_ptr] >= end_time[end_ptr]: # FreeUp rooma nd increment end_ptr res -= 1 end_ptr += 1 #if room got free then res += 1 wouldn't effective. res would remains same in that case. If room will not free then increase room res += 1 start_ptr += 1 return res
#!/usr/bin/env python3.5 #-*- coding: utf-8 -*- def foo(s): n = int(s) assert n != 0, 'n is zero!' return 10 / n def main(): foo('0') main()
# -*- coding: UTF-8 -*- # # You are given an n x n 2D matrix representing an image. # # Rotate the image by 90 degrees (clockwise). # # Note: # You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation. # # Example 1: # # Given input matrix = # [ # [1,2,3], # [4,5,6], # [7,8,9] # ], # # rotate the input matrix in-place such that it becomes: # [ # [7,4,1], # [8,5,2], # [9,6,3] # ] # Example 2: # # Given input matrix = # [ # [ 5, 1, 9,11], # [ 2, 4, 8,10], # [13, 3, 6, 7], # [15,14,12,16] # ], # # rotate the input matrix in-place such that it becomes: # [ # [15,13, 2, 5], # [14, 3, 4, 1], # [12, 6, 8, 9], # [16, 7,10,11] # ] # # Python, Python3 all accepted. class RotateImage: def rotate(self, matrix): """ :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. """ length = len(matrix) for i in range(length // 2): j = length - 1 - i cache = matrix[i] matrix[i] = matrix[j] matrix[j] = cache for i in range(length): for j in range(i + 1, length): cache = matrix[i][j] matrix[i][j] = matrix[j][i] matrix[j][i] = cache
class Libro: def __init__(self, paginas, tapa,nombre, autor, genero, isbn): self.paginas = paginas self.tapa = tapa self.nombre= nombre self.autor = autor self.genero = genero self.isbn = isbn def set_nombre(self,nombre): self.nombre = nombre def set_paginas(self,paginas): self.paginas = paginas def set_tapa(self,tapa): self.tapa = tapa def set_autor(self,autor): self.autor = autor def set_genero(self,genero): self.genero = genero def set_isbn(self,isbn): self.isbn = isbn
# # @lc app=leetcode id=68 lang=python3 # # [68] Text Justification # class Solution: def split(self, words: List[str], maxWidth: int) -> List[List[str]]: if not words: return [] lines, cur_len = [[words[0]]], len(words[0]) for w in words[1:]: if cur_len + 1 + len(w) <= maxWidth: lines[-1].append(w) cur_len += 1 + len(w) else: lines.append([w]) cur_len = len(w) return lines def justify(self, words: List[str], width: int, full: bool = False) -> str: word_len = sum(map(len, words)) space_len = width - word_len space_cnt = len(words) - 1 if space_cnt == 0: return words[0] + ' ' * space_len if full: return ' '.join(words) + ' ' * (space_len - space_cnt) space_sizes = [0] * (space_cnt + 1) while space_cnt > 0: sz = space_len // space_cnt space_sizes[space_cnt - 1] = sz space_len -= sz space_cnt -= 1 return ''.join(w + ' ' * sz for w, sz in zip(words, space_sizes)) def fullJustify(self, words: List[str], maxWidth: int) -> List[str]: lines = self.split(words, maxWidth) lines[-1] = self.justify(lines[-1], maxWidth, full=True) for i in range(len(lines) - 1): lines[i] = self.justify(lines[i], maxWidth) return lines
""" Build microservices with Python """ __author__ = "Vlad Calin" __email__ = "[email protected]" __version__ = "0.12.0"
""" Author: André Bento Date last modified: 01-02-2019 """
# # Copyright 2020- IBM Inc. All rights reserved # SPDX-License-Identifier: Apache2.0 # class K8sNamespace: """ Represents a K8s Namespace, storing its name and labels """ def __init__(self, name): self.name = name self.labels = {} # Storing the namespace labels in a dict as key-value pairs def __eq__(self, other): if isinstance(other, K8sNamespace): return self.name == other.name return NotImplemented def __hash__(self): return hash(self.name) def __str__(self): return self.name def set_label(self, key, value): """ Add/update a namespace label :param str key: The label key :param str value: The label value :return: None """ self.labels[key] = value
class Solution(object): def numEquivDominoPairs(self, dominoes): """ :type dominoes: List[List[int]] :rtype: int """ hashmap = dict() for a, b in dominoes: key = tuple([min(a, b), max(a, b)]) hashmap[key] = hashmap.setdefault(key, 0) + 1 count = 0 for v in hashmap.values(): count += v * (v - 1) return count // 2
def update_data(hyper_params): return dict( train=dict( samples_per_gpu=hyper_params['batch_size'], workers_per_gpu=hyper_params['workers_per_gpu'], dataset=dict( root_dir=hyper_params['dataset_root'], cifar_type=hyper_params['dataset_name'], noise_mode=hyper_params['noise_mode'], noise_ratio=hyper_params['noise_ratio'] ) ), test=dict( samples_per_gpu=hyper_params['batch_size'] * 4, workers_per_gpu=hyper_params['workers_per_gpu'], dataset=dict( root_dir=hyper_params['dataset_root'], cifar_type=hyper_params['dataset_name'] ) ), eval=dict( samples_per_gpu=hyper_params['batch_size'] * 4, workers_per_gpu=hyper_params['workers_per_gpu'], ) ) def update_openset_data(hyper_params): return dict( train=dict( samples_per_gpu=hyper_params['batch_size'], workers_per_gpu=hyper_params['workers_per_gpu'], dataset=dict( root_dir=hyper_params['dataset_root'], cifar_type=hyper_params['dataset_name'], noise_mode=hyper_params['noise_mode'], noise_ratio=hyper_params['noise_ratio'], ood_noise_name=hyper_params['ood_noise_name'], ood_noise_root_dir=hyper_params['ood_noise_root_dir'], ood_noise_num=hyper_params['ood_noise_num_train'] ) ), test=dict( samples_per_gpu=hyper_params['batch_size'] * 4, workers_per_gpu=hyper_params['workers_per_gpu'], dataset=dict( root_dir=hyper_params['dataset_root'], cifar_type=hyper_params['dataset_name'], ood_noise_name=hyper_params['ood_noise_name'], ood_noise_root_dir=hyper_params['ood_noise_root_dir'], ood_noise_num=hyper_params['ood_noise_num_test'] ) ), eval=dict( samples_per_gpu=hyper_params['batch_size'] * 4, workers_per_gpu=hyper_params['workers_per_gpu'], ) ) def update_webvision_data(hyper_params): return dict( train=dict( samples_per_gpu=hyper_params['batch_size'], workers_per_gpu=hyper_params['workers_per_gpu'], ), test=dict( samples_per_gpu=hyper_params['batch_size'] * 4, workers_per_gpu=hyper_params['workers_per_gpu'], ), eval=dict( samples_per_gpu=hyper_params['batch_size'] * 4, workers_per_gpu=hyper_params['workers_per_gpu'], ), imagenet=dict( samples_per_gpu=hyper_params['batch_size'] * 4, workers_per_gpu=8, ) ) def update_model(hyper_params): return dict( head=dict(num_classes=hyper_params['num_classes'], out_feat_dim=hyper_params['feature_dim']), num_classes=hyper_params['num_classes'], alpha=hyper_params['alpha'], data_parallel=hyper_params['data_parallel'] ) def update_solver(hyper_params): return dict( hyper_params=hyper_params, optimizer=dict(lr=hyper_params['lr'], weight_decay=hyper_params.get('weight_decay') or 5e-4), lr_scheduler=dict(T_max=hyper_params['max_epochs']), max_epochs=hyper_params['max_epochs'], )
class Person: def __init__(self, name, age=21, gender='unspecified', occupation='unspecified'): self.name = name self.gender = gender self.occupation = occupation if age >= 0 and age <= 120: self.age = age else: self.age = 21 def greets(self, greeter): return f'Hello, {greeter}! My name is {self.name}, nice to meet you!' def had_birthday(self): self.age += 1 def set_gender(self, gender): self.gender = gender def get_gender(self): return self.gender
""" Test group missing the last item .. pii: Group 2 - Annotation 1 .. pii_types: id, name """
def obj_sort_by_lambda(obj_list, lmbd): new_obj_list = obj_list.copy() new_obj_list.sort(key=lmbd) return new_obj_list def obj_sort_by_property_name(obj_list, prop_name): return obj_sort_by_lambda(obj_list, lambda x:getattr(x, prop_name)) def obj_list_decrypt(obj_list, enc): new_obj_list = [] for obj in obj_list: new_obj_list.append(obj.decrypt(enc)) return new_obj_list
# -*- coding: utf-8 -*- """Top-level package for appliapps.""" __author__ = """Lars Malmstroem""" __email__ = '[email protected]' __version__ = '0.1.0'
class InvalidUrl(Exception): pass class UnableToGetPage(Exception): pass class UnableToGetUploadTime(Exception): pass class UnableToGetApproximateNum(Exception): pass
''' LISTA 02 - EXERCICIO 11 Nome: Guilherme Augusto Sbizero Correa Data: Setembro /2020 Enunciado: Faça um programa solicite o preço de uma mercadoria e o percentual de desconto. Exiba o valor de desconto e o preço a pagar. ''' valorProduto = float(input("Digite o valor da mercadoria: ")) desconto = float(input("Digite o % de desconto: ")) descontoValor = (valorProduto * desconto)/100 novoValorProduto = valorProduto - descontoValor print("O valor do desconto foi de: ", descontoValor, " e o novo valor do produto ficou: ",novoValorProduto)
# ******************************************************************************************* # ******************************************************************************************* # # Name : error.py # Purpose : Error class # Date : 13th November 2021 # Author : Paul Robson ([email protected]) # # ******************************************************************************************* # ******************************************************************************************* # ******************************************************************************************* # # HPL Exception # # ******************************************************************************************* class HPLException(Exception): def __str__(self): msg = Exception.__str__(self) return msg if HPLException.LINE <= 0 else "{0} ({1}:{2})".format(msg,HPLException.FILE,HPLException.LINE) HPLException.FILE = None HPLException.LINE = 0 if __name__ == '__main__': x = HPLException("Error !!") print(">>",str(x)) raise x
# coding=utf-8 worker_thread_pool = None key_loading_thread_pool = None key_holder = None is_debug = False is_debug_requests = False is_no_validate = False is_only_validate_key = False is_override = False is_preview_filename = False is_resize = False thread_num = 1 src_dir = None dest_dir = None filename_pattern = None filename_replace = None resize_method = None width = None height = None
from_ = 1 to_ = 999901 # to_ = 1 output_file = open("result.txt", "w", encoding="utf-8") for i in range(from_, to_ + 1, 100): input_file = open("allTags/" + str(i) + ".txt", "r", encoding="utf-8") data = input_file.read() ind = 0 for j in range(100): ind = data.find("class=\"i-tag\"", ind) data = data[ind+1:] x = data.find("#") y = data.find("<", x) tag = data[x + 1:y] data = data[y:] output_file.write(tag + "," + str(i + j) + '\n') input_file.close() output_file.close()
#!/usr/bin/env python3 ''' In this question , we are going to find the longest common substring, among two given substrings. in order to solve this question we will be making use of dynamic programming. so we will create a matrix with all 0s in the initial row and column Step 1: we need to initialise a matrix with size len(String)+1, len(string)+1. Step 2: once you initialise matrix you can start comparing the letter of each string''' def LongestCommonSubstring(X,Y,m,n): LCSmatrix=[[0 for k in range(n+1)] for l in range(m+1)] result=0 for i in range(m+1): for j in range(n+1): if(i==0 or j==0): LCSmatrix[i][j]=0 elif (X[i-1]==Y[j-1]) : LCSmatrix[i][j]=LCSmatrix[i-1][j-1]+1 result= max(result, LCSmatrix[i][j]) else: LCSmatrix[i][j]=0 return result X = 'HELLO' Y = 'HELLOS' m = len(X) n = len(Y) print('Length of Longest Common Substring is', LongestCommonSubstring(X, Y, m, n))
''' Author : Govind Patidar DateTime : 10/07/2020 11:30AM File : AllPageLocators ''' class AllPageLocators(): def __init__(self, driver): ''' :param driver: ''' self.driver = driver '''Home page locator''' # get XPATH current temperature text text_curr_temp = '/html/body/div/div[1]/h2' # get ID current temperature value curr_temp = "temperature" # get XPATH moisturizes text moisturizes = '/html/body/div/div[3]/div[1]/p' # get XPATH buy moisturizes buy_moisturizes = '/html/body/div/div[3]/div[1]/a/button' # get XPATH sunscreens text sunscreens = '/html/body/div/div[3]/div[2]/p' # get XPATH buy sunscreens buy_sunscreens = '/html/body/div/div[3]/div[2]/a/button' '''Checkout page locator''' # get ID in add to cart items add_cart = 'cart' # get ID total amount total_amount = 'total' # get XPATH pay with cart button pay = '/html/body/div[1]/div[3]/form/button/span' '''Payment page''' # get XPATH payment page email = '//input[@type="email"]' cardNo = '//input[@type="tel"]' date = '//input[@placeholder="MM / YY"]' cvc = '//input[@placeholder="CVC"]' zip = '//input[@placeholder="ZIP Code"]' paynow = '//*[@id="container"]/section/span[2]/div/div/main/form/nav/div/div/div/button' '''Payment done''' pay_success = '/html/body/div/div[1]/h2' pay_text = '/html/body/div/div[2]/p'
word = input() out = '' prev = '' # remove same letters which are the same as the previous for x in word: if x != prev: out+=x prev = x print(out)
# # PySNMP MIB module TPLINK-IPADDR-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TPLINK-IPADDR-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 21:17:29 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueRangeConstraint, ConstraintsIntersection, SingleValueConstraint, ConstraintsUnion, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ConstraintsIntersection", "SingleValueConstraint", "ConstraintsUnion", "ValueSizeConstraint") ifIndex, = mibBuilder.importSymbols("IF-MIB", "ifIndex") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") MibScalar, MibTable, MibTableRow, MibTableColumn, Bits, MibIdentifier, iso, Counter32, Unsigned32, TimeTicks, Gauge32, ObjectIdentity, Integer32, IpAddress, NotificationType, ModuleIdentity, Counter64 = mibBuilder.importSymbols("SNMPv2-SMI", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Bits", "MibIdentifier", "iso", "Counter32", "Unsigned32", "TimeTicks", "Gauge32", "ObjectIdentity", "Integer32", "IpAddress", "NotificationType", "ModuleIdentity", "Counter64") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") tplinkMgmt, = mibBuilder.importSymbols("TPLINK-MIB", "tplinkMgmt") TPRowStatus, = mibBuilder.importSymbols("TPLINK-TC-MIB", "TPRowStatus") class TpInterfaceMode(TextualConvention, Integer32): status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3)) namedValues = NamedValues(("none", 0), ("manual", 1), ("dhcp", 2), ("bootp", 3)) class TpInterfaceMode2(TextualConvention, Integer32): status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(0, 1)) namedValues = NamedValues(("none", 0), ("manual", 1)) class TpPortLinkMode(TextualConvention, Integer32): status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(0, 1)) namedValues = NamedValues(("bridge", 0), ("route", 1)) tplinkIpAddrMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 11863, 6, 6)) tplinkIpAddrMIB.setRevisions(('2012-12-13 09:30',)) if mibBuilder.loadTexts: tplinkIpAddrMIB.setLastUpdated('201212130930Z') if mibBuilder.loadTexts: tplinkIpAddrMIB.setOrganization('TPLINK') tplinkIpAddrMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1)) tplinkIpAddrNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 11863, 6, 6, 2)) tpInterfaceConfig = MibIdentifier((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1)) tpVlanInterfaceTable = MibTable((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 1), ) if mibBuilder.loadTexts: tpVlanInterfaceTable.setStatus('current') tpVlanInterfaceConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 1, 1), ).setIndexNames((0, "TPLINK-IPADDR-MIB", "tpVlanInterfaceVlanId"), (0, "TPLINK-IPADDR-MIB", "tpVlanInterfaceIp"), (0, "TPLINK-IPADDR-MIB", "tpVlanInterfaceSecondary")) if mibBuilder.loadTexts: tpVlanInterfaceConfigEntry.setStatus('current') tpVlanInterfaceVlanId = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 1, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: tpVlanInterfaceVlanId.setStatus('current') tpVlanInterfaceSecondary = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 1, 1, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: tpVlanInterfaceSecondary.setStatus('current') tpVlanInterfaceMode = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 1, 1, 3), TpInterfaceMode()).setMaxAccess("readcreate") if mibBuilder.loadTexts: tpVlanInterfaceMode.setStatus('current') tpVlanInterfaceIp = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 1, 1, 4), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: tpVlanInterfaceIp.setStatus('current') tpVlanInterfaceMsk = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 1, 1, 5), IpAddress()).setMaxAccess("readcreate") if mibBuilder.loadTexts: tpVlanInterfaceMsk.setStatus('current') tpVlanInterfaceName = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 1, 1, 6), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 20))).setMaxAccess("readcreate") if mibBuilder.loadTexts: tpVlanInterfaceName.setStatus('current') tpVlanInterfaceStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 1, 1, 7), TPRowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: tpVlanInterfaceStatus.setStatus('current') tpLoopbackInterfaceTable = MibTable((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 2), ) if mibBuilder.loadTexts: tpLoopbackInterfaceTable.setStatus('current') tpLoopbackInterfaceConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 2, 1), ).setIndexNames((0, "TPLINK-IPADDR-MIB", "tpLoopbackInterfaceId"), (0, "TPLINK-IPADDR-MIB", "tpLoopbackInterfaceIp"), (0, "TPLINK-IPADDR-MIB", "tpLoopbackInterfaceSecondary")) if mibBuilder.loadTexts: tpLoopbackInterfaceConfigEntry.setStatus('current') tpLoopbackInterfaceId = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 2, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: tpLoopbackInterfaceId.setStatus('current') tpLoopbackInterfaceSecondary = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 2, 1, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: tpLoopbackInterfaceSecondary.setStatus('current') tpLoopbackInterfaceMode = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 2, 1, 3), TpInterfaceMode2()).setMaxAccess("readcreate") if mibBuilder.loadTexts: tpLoopbackInterfaceMode.setStatus('current') tpLoopbackInterfaceIp = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 2, 1, 4), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: tpLoopbackInterfaceIp.setStatus('current') tpLoopbackInterfaceMsk = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 2, 1, 5), IpAddress()).setMaxAccess("readcreate") if mibBuilder.loadTexts: tpLoopbackInterfaceMsk.setStatus('current') tpLoopbackInterfaceName = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 2, 1, 6), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 20))).setMaxAccess("readcreate") if mibBuilder.loadTexts: tpLoopbackInterfaceName.setStatus('current') tpLoopbackInterfaceStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 2, 1, 7), TPRowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: tpLoopbackInterfaceStatus.setStatus('current') tpRoutedPortTable = MibTable((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 3), ) if mibBuilder.loadTexts: tpRoutedPortTable.setStatus('current') tpRoutedPortConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 3, 1), ).setIndexNames((0, "IF-MIB", "ifIndex"), (0, "TPLINK-IPADDR-MIB", "tpRoutedPortIp"), (0, "TPLINK-IPADDR-MIB", "tpRoutedPortSecondary")) if mibBuilder.loadTexts: tpRoutedPortConfigEntry.setStatus('current') tpRoutedPortId = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 3, 1, 1), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 16))).setMaxAccess("readonly") if mibBuilder.loadTexts: tpRoutedPortId.setStatus('current') tpRoutedPortSecondary = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 3, 1, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: tpRoutedPortSecondary.setStatus('current') tpRoutedPortMode = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 3, 1, 3), TpInterfaceMode()).setMaxAccess("readcreate") if mibBuilder.loadTexts: tpRoutedPortMode.setStatus('current') tpRoutedPortIp = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 3, 1, 4), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: tpRoutedPortIp.setStatus('current') tpRoutedPortMsk = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 3, 1, 5), IpAddress()).setMaxAccess("readcreate") if mibBuilder.loadTexts: tpRoutedPortMsk.setStatus('current') tpRoutedPortName = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 3, 1, 6), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 20))).setMaxAccess("readcreate") if mibBuilder.loadTexts: tpRoutedPortName.setStatus('current') tpRoutedPortStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 3, 1, 7), TPRowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: tpRoutedPortStatus.setStatus('current') tpPortChannelTable = MibTable((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 4), ) if mibBuilder.loadTexts: tpPortChannelTable.setStatus('current') tpPortChannelConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 4, 1), ).setIndexNames((0, "TPLINK-IPADDR-MIB", "tpPortChannelId"), (0, "TPLINK-IPADDR-MIB", "tpPortChannelIp"), (0, "TPLINK-IPADDR-MIB", "tpPortChannelSecondary")) if mibBuilder.loadTexts: tpPortChannelConfigEntry.setStatus('current') tpPortChannelId = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 4, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: tpPortChannelId.setStatus('current') tpPortChannelSecondary = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 4, 1, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: tpPortChannelSecondary.setStatus('current') tpPortChannelMode = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 4, 1, 3), TpInterfaceMode()).setMaxAccess("readcreate") if mibBuilder.loadTexts: tpPortChannelMode.setStatus('current') tpPortChannelIp = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 4, 1, 4), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: tpPortChannelIp.setStatus('current') tpPortChannelMsk = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 4, 1, 5), IpAddress()).setMaxAccess("readcreate") if mibBuilder.loadTexts: tpPortChannelMsk.setStatus('current') tpPortChannelName = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 4, 1, 6), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 20))).setMaxAccess("readcreate") if mibBuilder.loadTexts: tpPortChannelName.setStatus('current') tpPortChannelStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 4, 1, 7), TPRowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: tpPortChannelStatus.setStatus('current') mibBuilder.exportSymbols("TPLINK-IPADDR-MIB", tpVlanInterfaceMode=tpVlanInterfaceMode, tpPortChannelIp=tpPortChannelIp, tpRoutedPortIp=tpRoutedPortIp, tpPortChannelSecondary=tpPortChannelSecondary, tpVlanInterfaceVlanId=tpVlanInterfaceVlanId, tpLoopbackInterfaceId=tpLoopbackInterfaceId, tplinkIpAddrMIB=tplinkIpAddrMIB, tpVlanInterfaceMsk=tpVlanInterfaceMsk, tpInterfaceConfig=tpInterfaceConfig, TpInterfaceMode=TpInterfaceMode, tpLoopbackInterfaceName=tpLoopbackInterfaceName, tpRoutedPortSecondary=tpRoutedPortSecondary, tpPortChannelMsk=tpPortChannelMsk, tpRoutedPortStatus=tpRoutedPortStatus, tpRoutedPortId=tpRoutedPortId, tpPortChannelMode=tpPortChannelMode, tpVlanInterfaceConfigEntry=tpVlanInterfaceConfigEntry, tpRoutedPortConfigEntry=tpRoutedPortConfigEntry, tpRoutedPortMode=tpRoutedPortMode, TpInterfaceMode2=TpInterfaceMode2, tpRoutedPortMsk=tpRoutedPortMsk, tpLoopbackInterfaceConfigEntry=tpLoopbackInterfaceConfigEntry, tpPortChannelName=tpPortChannelName, tplinkIpAddrNotifications=tplinkIpAddrNotifications, tpLoopbackInterfaceMsk=tpLoopbackInterfaceMsk, tpVlanInterfaceTable=tpVlanInterfaceTable, tpVlanInterfaceName=tpVlanInterfaceName, tpVlanInterfaceStatus=tpVlanInterfaceStatus, PYSNMP_MODULE_ID=tplinkIpAddrMIB, tpPortChannelTable=tpPortChannelTable, tpLoopbackInterfaceStatus=tpLoopbackInterfaceStatus, tpPortChannelStatus=tpPortChannelStatus, tpRoutedPortTable=tpRoutedPortTable, tpPortChannelConfigEntry=tpPortChannelConfigEntry, tpLoopbackInterfaceIp=tpLoopbackInterfaceIp, tpRoutedPortName=tpRoutedPortName, tpPortChannelId=tpPortChannelId, TpPortLinkMode=TpPortLinkMode, tplinkIpAddrMIBObjects=tplinkIpAddrMIBObjects, tpVlanInterfaceIp=tpVlanInterfaceIp, tpLoopbackInterfaceSecondary=tpLoopbackInterfaceSecondary, tpVlanInterfaceSecondary=tpVlanInterfaceSecondary, tpLoopbackInterfaceTable=tpLoopbackInterfaceTable, tpLoopbackInterfaceMode=tpLoopbackInterfaceMode)
# Exercício 064: '''Crie um programa que leia vários números inteiros pelo teclado. O programa só vai parar quando o usuário digitar 999, que é a condição de parada. No final mostre quantos números foram digitados e qual foi a soma entre eles, desconsiderando o "flag".''' numero = soma = contador = 0 while numero != 999: numero = int(input('''Digite um número inteiro para saber a soma e a quantidade de números digitados ao final. Se for digitado "999" o programa vai encerrar e apresentar o resultado: ''')) if numero == 999: print('Você digitou o comando de parada e o programa vai encerrar.') else: soma += numero contador += 1 print(f'Você digitou {contador} números e a soma entre eles foi {soma}.')
""" Write a method/function DISPLAYWORDS() in python to read lines from a text file STORY.TXT, using read function and display those words, which are less than 4 characters. """ F = open("story.txt", "r") value = F.read() lines = value.split() count = 0 for i in lines: if len(i) < 4: print(i) count += 1 else: pass print("The total number of words with length less than 4 are", count)
#Programa que leia um nome completo e diga o primeiro e ultimo nome nome = input('Digite seu nome completo: ').title() splt = nome.split() print(splt[0],splt[-1])
name = "chris alan" name = name.title() name = "1 w 2 r 3g" # Complete the solve function below. def solve(string): """ Capitalizing function """ list_strings = string.rstrip().split(" ") result = "" for item in list_strings: if item[0].isalpha(): item = item.title() result += item + " " return result.strip()
#!/usr/bin/python3 # -*- coding: utf-8 -*- # Esta class, contiene procedimientos de uso común. class Utils: # Devuelve S con Ancho caracteres (padding derecho con espacios). (Padding singnifica "relleno"). def FieldLeft(self, S, Ancho): return S + Utils.Espacios(self, Ancho - len(S)) # Devuelve S con Ancho caracteres (padding izquierdo con espacios). def FieldRight(self, S, Ancho): return Utils.Espacios(self, Ancho - len(S)) + S def FieldCenter(self, S, Ancho): if len(S) > Ancho: return S[:Ancho - 1] Padding = (Ancho - len(S)) // 2 S = Utils.Espacios(self, Padding) + S return S + Utils.Espacios(self, Ancho - len(S)) def Espacios(self, n): BLANK = " " return Utils.RunLength(self, BLANK, n) def RunLength(self, c, n): S = "" for i in range(0, n): S += c return S
def binary_search(ary, tar): head = 0 tail = len(ary) - 1 found = False while head <= tail and not found: mid = (head + tail) / 2 if ary[mid] == tar: found = True elif ary[mid] < tar: head = mid + 1 elif ary[mid] > tar: tail = mid - 1 return found def binary_search_recursive(ary, tar): if len(ary) == 0: return False mid = len(ary) / 2 if ary[mid] == tar: return True elif ary[mid] < tar: return binary_search_recursive(ary[mid+1:], tar) elif ary[mid] > tar: return binary_search_recursive(ary[:mid], tar) a = [1, 2, 3, 4, 5, 6, 7, 8, 9] print(binary_search(a, 0)) print(binary_search(a, 1)) print(binary_search(a, 3)) print(binary_search(a, 4)) print(binary_search(a, 11)) print(binary_search_recursive(a, 0)) print(binary_search_recursive(a, 1)) print(binary_search_recursive(a, 3)) print(binary_search_recursive(a, 4)) print(binary_search_recursive(a, 11))
# example solution. # You are not expected to make a nice plotting function, # you can simply call plt.imshow a number of times and observe print(faces.DESCR) # this shows there are 40 classes, 10 samples per class print(faces.target) #the targets i.e. classes print(np.unique(faces.target).shape) # another way to see n_classes X = faces.images y = faces.target fig = plt.figure(figsize=(16,5)) idxs = [0,1,2, 11,12,13, 40,41] for i,k in enumerate(idxs): ax=fig.add_subplot(2,4,i+1) ax.imshow(X[k]) ax.set_title(f"target={y[k]}") # looking at a few plots shows that each target is a single person.
#python 3.5.2 def areAnagram(firstWord, secondWord): firstList = list(firstWord) secondList = list(secondWord) result = True if len(firstList) == len(secondList) and result: #Sort both list alphabetically firstList.sort() secondList.sort() i = 0 length = len(firstList) while i < length : if firstList[i] != secondList[i]: result = False i = i + 1 else: result = False return result # Checking same word (Result should be True) print ( 'Is "earth" and "earth" an anagram ?' , areAnagram('earth','earth') ) # Checking two anagrams (Result should be True) print ( 'Is "heart" and "earth" an anagram ?' , areAnagram('heart','earth') ) # Checking two words that are not anagrams (Result should be False) print ( 'Is "eartj" and "earth" an anagram ?' , areAnagram('eartj','earth') ) # Checking not the same number of characters (Result should be False) print ( 'Is "eart" and "earth" an anagram ?' , areAnagram('eart','earth') ) # Checking more than one of the same characters (Result should be False) print ( 'Is "eearth" and "earth" an anagram ?' , areAnagram('eearth','earth') ) ''' OUTPUT: Is "earth" and "earth" an anagram ? True Is "heart" and "earth" an anagram ? True Is "eartj" and "earth" an anagram ? False Is "eart" and "earth" an anagram ? False Is "eearth" and "earth" an anagram ? False '''
#!/bin/zsh ''' Regex Search Write a program that opens all .txt files in a folder and searches for any line that matches a user-supplied regular expression. The results should be printed to the screen. '''
# -*- coding: utf-8 -*- """ Created on Sat Jun 15 16:11:48 2019 @author: Administrator """ #class Solution: # def canJump(self, nums: list) -> bool: # if 0 not in nums: # return True ## if nums == [0]: ## return True # a = [] # for k in range(len(nums)-1): # if nums[k] == 0: # a.append(k) # Mark = [] # for p in range(len(a)): # if p==0: # mark = 0 # for q in range(0, a[p]): ## print(nums[q], a[p]-q) # mark = mark or (nums[q] > a[p]-q) # Mark.append(mark) # else: # if nums[a[p]-1] != 0: # mark = 0 # for q in range(a[p-1], a[p]): # print(nums[q], a[p]-q) # print('mark', mark) # mark = mark or (nums[q] > a[p]-q) # Mark.append(mark) # print(Mark) # return False not in Mark# and 0 not in Mark class Solution: def canJump(self, nums: list) -> bool: start = 0 end = 0 n = len(nums) while start <= end and end < len(nums) - 1: #从每个位置出发(假设的),所能到达的最远处 end = max(end, nums[start] + start) #每轮得到最远能跳到哪里的索引 start += 1 return end >= n - 1 #class Solution: # def canJump(self, nums: list) -> bool: # #start = 0 # n = len(nums) # start = n - 2 # end = n - 1 # while start >= 0: # if start + nums[start] >= end: end = start # start -= 1 # return end <= 0 #作者:powcai #链接:https://leetcode-cn.com/problems/two-sum/solution/tan-xin-cong-qian-wang-hou-tiao-cong-hou-wang-qian/ #来源:力扣(LeetCode) #著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 class Solution: def canJump(self, nums: list) -> bool: start = 0 end = 0 n = len(nums) while start<=end and end<=n-1: #这个等号可以不写 end = max(end, start+nums[start]) start += 1 return end >= n-1 solu = Solution() nums = [2,3,1,1,4] #nums = [3,2,1,0,4] nums = [0] #nums = [2,0,0] nums = [3,0,0,0] #nums = [2,0,1,0,1] print(solu.canJump(nums))
''' Q1. Write a python code for creating a password for E-Aadhar card. The details used are the first 4 letters of your name, date and month of your birth. The task is to generate a password with the lambda function and display it.''' name = input("Input your name (as on your Aadhar)\n") dob = input("Please enter your dob in this order : 'ddmmyyyy'\n") first = lambda name: name[:4] last = lambda dob: dob[4:] pw = first(name) + last(dob) print("Your password is ",pw)
''' 给定一个二叉树,它的每个结点都存放一个 0-9 的数字,每条从根到叶子节点的路径都代表一个数字。 例如,从根到叶子节点路径 1->2->3 代表数字 123。 计算从根到叶子节点生成的所有数字之和。 说明: 叶子节点是指没有子节点的节点。 示例 1: 输入: [1,2,3] 1 / \ 2 3 输出: 25 解释: 从根到叶子节点路径 1->2 代表数字 12. 从根到叶子节点路径 1->3 代表数字 13. 因此,数字总和 = 12 + 13 = 25. 示例 2: 输入: [4,9,0,5,1] 4 / \ 9 0  / \ 5 1 输出: 1026 解释: 从根到叶子节点路径 4->9->5 代表数字 495. 从根到叶子节点路径 4->9->1 代表数字 491. 从根到叶子节点路径 4->0 代表数字 40. 因此,数字总和 = 495 + 491 + 40 = 1026. 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/sum-root-to-leaf-numbers ''' # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def sumNumbers(self, root: TreeNode) -> int: return self.helper(root,0) def helper(self,root,i): if not root : return 0 tmp = i * 10 + root.val if not root.left and not root.right: return tmp return self.helper(root.left,tmp) + self.helper(root.right,tmp)
# число N записали 100 раз поспіль і потім піднесли в квадрат. Що вийшло? ## Формат введення # Вводиться ціле невід'ємне число N не перевищує 1000. ## Формат виведення # Виведіть відповідь до задачі. n = int(100*input()) print(n ** 2)
# Follow up for N-Queens problem. # Now, instead outputting board configurations, return the total number of distinct solutions. class Solution(object): result = 0 def totalNQueens(self, n): """ :type n: int :rtype: int """ cols = [] self.search(n, cols) return self.result def search(self, n, cols): if len(cols) == n: self.result += 1 return for col in range(n): if not self.isValid(cols, col): continue self.search(n, cols + [col]) def isValid(self, cols, col): currentRowNumber = len(cols) for i in range(currentRowNumber): # same column if cols[i] == col: return False # left-top to right-bottom if i - cols[i] == currentRowNumber - col: return False # right-top to left-bottom if i + cols[i] == currentRowNumber + col: return False return True
# !/usr/bin/env python # coding: utf-8 ''' Description: '''
# -*- coding: utf-8 -*- """ PRTG Exceptions """ class PrtgException(Exception): """ Base PRTG Exception """ pass class PrtgBadRequest(PrtgException): """ Bad request """ pass class PrtgBadTarget(PrtgException): """ Invalid target """ pass class PrtgUnknownResponse(PrtgException): """ Unknown response """ pass class PrtgTooManyChannelsInSensorData(PrtgException): """ Too many channels in sensor data """ pass class PrtgUnsupportedHTTPMethod(PrtgException): """ UnsupportedHTTPMethod """ pass
# Faça um algoritimo que leia o preço de um produto e mostre seu novo preco com 5% de desconto # Fazendo a leitura do preço antigo do produto p = float(input('Informe qual preço do produto: ')) # Informar na tela o valor do novo preço com desconto calculado dentro do método .format. print('O valor pago com desconto será {} reais'.format(p-(p*0.05))) # Desafio concluído
def getSampleMetadata(catalogName, tagName, digest): return { 'schemaVersion': 2, 'mediaType': 'application/vnd.docker.distribution.manifest.v2+json', 'config': { 'mediaType': 'application/vnd.docker.container.image.v1+json', 'size': 1111, 'digest': digest }, 'layers': [ { 'mediaType': 'application/vnd.docker.image.rootfs.diff.tar.gzip', 'size': 123, 'digest': 'sha256:e6c96db7181be991f19a9fb6975cdbbd73c65f4a2681348e63a141a2192a5f10' }, { 'mediaType': 'application/vnd.docker.image.rootfs.diff.tar.gzip', 'size': 123, 'digest': 'sha256:8985e402e050840450bd9d60b20a9bec70d57a507b33a85e5c3b3caf2e0ada6e' }, { 'mediaType': 'application/vnd.docker.image.rootfs.diff.tar.gzip', 'size': 23, 'digest': 'sha256:78986f489cfa0d72ea6e357ab3e81a9d5ebdb9cf4797a41eb49bdefe579f1b01' } ] }
class Solution: def count(self, s, target): ans = 0 for i in s: if i == target: ans += 1 return ans def findMaxForm(self, strs: List[str], m: int, n: int) -> int: dp = [[0 for i in range(n+1)] for j in range(m+1)] for s in strs: zero = self.count(s, '0') one = self.count(s, '1') for i in range(m, zero-1, -1): for j in range(n, one-1, -1): dp[i][j] = max(dp[i][j], dp[i-zero][j-one]+1) return dp[m][n]
# remove nth node from end # https://leetcode.com/problems/remove-nth-node-from-end-of-list/ # brute # create a new linked list without that element # Time O(n) # Space O(n) # optimal # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: if(head.next == None): return None start = ListNode() start.next = head slow = fast = start for i in range(1, n+1): fast = fast.next while(fast.next != None): fast = fast.next slow = slow.next slow.next = slow.next.next return start.next
def readFile(fileName): try: with open(fileName,'r') as f: print (f.read()) except FileNotFoundError: print (f'File {fileName} is not found') readFile('1.txt') readFile('2.txt') readFile('3.txt')
''' In this simple assignment you are given a number and have to make it negative. But maybe the number is already negative? Examples: make_negative(1); # return -1 make_negative(-5); # return -5 make_negative(0); # return 0 Notes: * The number can be negative already, in which case no change is required. * Zero (0) is not checked for any specific sign. Negative zeros make no mathematical sense. ''' def make_negative(number): return number * -1 if number > 0 else number
cards = {'SPADE' : ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13'], 'HEART' : ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13'], 'CLUB' : ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13'], 'DIAMOND' : ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13'] }
CR_ATTACHMENT_AVAILABLE = 'cr_available' CR_ATTACHMENT_REQUEST = 'cr_request' TRR_ATTACHMENT_AVAILABLE = 'trr_available' TRR_ATTACHMENT_REQUEST = 'trr_request' ATTACHMENT_TYPE_CHOICES = [ [CR_ATTACHMENT_AVAILABLE, 'CR attachment available'], [CR_ATTACHMENT_REQUEST, 'CR attachment request'], [TRR_ATTACHMENT_AVAILABLE, 'TRR attachment available'], [TRR_ATTACHMENT_REQUEST, 'TRR attachment request'], ]
# Description: Sample Code to Run mypy # Variables without types i:int = 200 f:float = 2.34 str = "Hello" # A function without type annotations def greet(name:str)-> str: return str + " " + name if __name__ == '__main__': greet("Dilbert")
class GameObject: def __init__(self, *, x=0, y=0, size=None): self.x = x self.y = y self.size = size self.half_width = self.size[0] / 2. def to_rect(self): """Return the gameobject to be display by qs.anim""" return [[self.x, self.y], self.size] def update(self): """Update the game object every frame""" pass def reset_values(self, *, x=0, y=0, size=None): self.x = x self.y = y self.size = size self.half_width = self.size[0] / 2. class Crab(GameObject): def __init__(self, x, y, size, min_x=0, max_x=800): GameObject.__init__(self, x=x, y=y, size=size) # super() is not supported by pyckitup 0.1 self.speed = 15 self.min_x = min_x - self.size[0] # take into account sprite size self.max_x = max_x self.move_smoother = 0.9 def go_left(self, coefficient=1): self.x -= (self.speed * coefficient) ** self.move_smoother self.x = max(self.min_x, self.x) def go_right(self, coefficient=1): self.x += (self.speed * coefficient) ** self.move_smoother self.x = min(self.max_x, self.x) def refresh_position_on_platform(self, platform): self.y = platform.y - self.size[1] def can_catch_water_bubble(self, water_bubble): y_diff = water_bubble.y - self.y - 15 if y_diff < 0: # Handmade abs for performances y_diff = -y_diff if y_diff > 40: return False # Hack for performances x_diff = water_bubble.x - (self.x + self.half_width) if x_diff < 0: x_diff = -x_diff return x_diff + y_diff < 40 class Platform(GameObject): """Platform on which the crab is standing""" max_height = 580 min_up = 10 max_up = 30 min_down = 10 max_down = 100 def __init__(self, x, y, size, screen_height): GameObject.__init__(self, x=x, y=y, size=size) self.y_target = y self.screen_height = screen_height def refresh_height(self): if self.y < self.y_target: self.y += 1 elif self.y > self.y_target: self.y -= 1 def go_up(self): up_by = self.min_up + (self.y_target / self.screen_height * (self.max_up - self.min_up)) self.y_target -= up_by def go_down(self): down_by = self.min_down + (1. - self.y_target / self.screen_height) * (self.max_down - self.min_down) self.y_target += down_by self.y_target = min(self.y_target, self.max_height) class WaterBubble(GameObject): def __init__(self, x, y, size, radius): GameObject.__init__(self, x=x, y=y, size=size) self.speed = 5 self.radius = radius def update(self): self.y += self.speed def is_below(self, gameobject): return self.y >= gameobject.y + self.radius def reset_values(self, *, x=0, y=0, size=None, radius=0): GameObject.reset_values(self, x=x, y=y, size=size) self.radius = radius class WaterBubblePool: """Pool of water bubble used to avoid creating/destroying object in repetition""" def __init__(self): self.unused_water_bubble = [] def add(self, water_bubble): self.unused_water_bubble.append(water_bubble) def get(self, **kwargs): if len(self.unused_water_bubble) > 1: water_bubble = self.unused_water_bubble.pop() water_bubble.reset_values(**kwargs) return water_bubble else: return WaterBubble(**kwargs)
"""Top-level package for ZotUtil.""" __author__ = """Cheng Cui""" __email__ = "[email protected]" __version__ = "0.1.1"
numbers = [1,45,31,12,60] for number in numbers: if number % 8 == 0: # Reject the list print("The numbers are unacceptable") break else: print("List okay!")
velocidade = int(input('Qual a velocidade do carro(Km/h)? ')) if velocidade > 80: print('VOCÊ ESTÁ A {} Km/h,ACIMA DA VELOCIDADE PERMITIDA!'.format(velocidade)) print('VOCÊ FOI MULTADO!') print('VALOR DA MULTA R${:.2f}'.format((velocidade - 80)* 7)) '''else: print('PARABÉNS! VOCÊ ESTÁ NO LIMITE DE VELOCIDADE PERMITIDA de 80Km/h!')''' print('TENHA UM BOM DIA! DIRIJA COM SEGURANÇA!')
class WeatherResponse(object): """ Specifies the response to be sent for one weather object. """ def __init__(self, *args, **kwargs): """ Set values for object. :param args: :param kwargs: """ self.temp = kwargs.get("temp", None) self.temp_units = kwargs.get("temp_units", "C") self.max_temp = kwargs.get("max_temp", None) self.min_temp = kwargs.get("min_temp", None) self.code = kwargs.get("code", None) self.condensed = kwargs.get("condensed", None) self.description = kwargs.get("description", None) self.icon = kwargs.get("icon", None) self.humidity = kwargs.get("humidity", None) self.humidity_units = kwargs.get("humidity_units", "%") self.pressure = kwargs.get("pressure", None) self.pressure_units = kwargs.get("pressure_units", "hPa") def to_json(self): """ Return WeatherResponse object as python dictionary. :return: """ return self.__dict__
file = "01.data.txt" f = open(file) data = f.read() f.close() lines = data.split("\n") readings = [] for line in lines: readings.append(int(line)) print(readings) # count all the increases # have a counter counter = 0 # each time number icreases increment the counter for i in range(1, len(readings)): previous = readings[i - 1] current = readings[i] # compare previous to current is_greater = current > previous if is_greater: counter += 1 #print("{} {} {} {}".format(i, previous, current, is_greater)) print("Part 1") print(counter) # have a counter counter = 0 for i in range(3, len(readings)): a = readings[i - 3] b = readings[i - 2] c = readings[i - 1] d = readings[i] previous = a + b + c current = b + c + d # compare previous to current is_greater = current > previous if is_greater: counter += 1 #print("{} {} {} {}".format(i, previous, current, is_greater)) print("Part 2") print(counter)
"""Holds documentation for the bot in dict form.""" def help_book(p): return [ # Table of Contents { "title": "Table of Contents", "description": f"Navigate between pages with the reaction buttons", "1. Vibrant Tutorial": ["Learn how to use the bot and its commands"], "2. Theme Tutorial": ["Learn how to use themes"], "3. General Commands": ["Shows a list of general commands"], "4. Color Commands": ["Shows a list of color related commands"], "5. Theme Commands": ["Shows a list of theme related commands"], "6. Macros": ["Shows a list of macros the bot has"], "7. Alias Dictionary": ["All of the aliases that commands have to make input easier"], "-----------------------------": ["[Vote for Vibrant](https://top.gg/bot/821278454711320576/vote) | [Support Server](https://discord.gg/rhvyup5) | [Github](https://github.com/Gumbachi/Vibrant)"] }, # Tutorial { "title": "Vibrant Tutorial", "description": " ", "Manage Colors": [ f"1. Type `{p}add #ff0000 My Color` to add a color", f"2. Type `{p}colors` to view your colors", f"3. Type `{p}rename 1 | Blue` to rename the color", f"4. Type `{p}recolor 1 | #0000ff` to change the look of a color" ], "Assign Colors": [ f"1. Type `{p}colorme 1` to color yourself", f"2. Type `{p}color @user 1` to color someone else", f"3. Type `{p}splash` to color everyone without a color" ], "Remove Colors": [ f"1. Type `{p}remove 1` to remove the first color", f"2. Type `{p}clear_colors` to remove all colors" ], "Color New People": [ f"Welcome people by typing `{p}welcome` in the desired channel. Typing the command again will turn welcoming off", "The \"welcome channel\" is where the bot will send Hello/Goodbye messages", "With a welcome channel set the bot will randomly color any new member" ], "Themes": [f"Click the ➡️ to learn about themes"] }, # Theme Tutorial { "title": "Theme Tutorial", "description": "Themes work like save states. They record your colors and the members they are applied to so you can save your setup and use different ones without having to rebuild them", "Using Presets": [ f"1. Type `{p}imports` to see available presets", f"2. Type `{p}import vibrant` to import a theme", f"3. Type `{p}load vibrant` to set your colors", f"4. Type `{p}splash` to apply your colors to the server" ], "Custom Themes": [ f"1. Type `{p}save My Theme` to save your current color setup", f"2. Type `{p}themes` to view all of your themes", f"3. Type `{p}theme.rename My Theme | Custom Theme` to rename a theme" ], "Manage Themes": [ f"1. Type `{p}overwrite 1` to replace a theme with your current setup", f"2. Type `{p}erase 1` to remove one of your themes" ] }, # Commands { "title": "Commands", "description": f"`{p}command <argument>`.\n`*` indicates an optional argument\n`<color>` can be a name or index", "General Commands": [ f"`{p}prefix <new prefix*>` -- Changes the prefix the bot uses", f"`{p}welcome` -- Toggles a channel for greeting users" ], "Color Management Commands": [ f"`{p}colors` -- Shows available colors", f"`{p}add <hexcode> <name*>` -- Adds a color", f"`{p}remove <color>` -- Removes a color", f"`{p}rename <color>|<name>` -- Changes a color's name", f"`{p}recolor <color>|<hexcode>` -- Changes a color's looks", f"`{p}clear_colors` -- Clears all of the colors" ], "Color Assignment Commands": [ f"`{p}colorme <color*>` -- Assigns you your desired color or random", f"`{p}color <user> <color*>` -- Gives a specific user a color", f"`{p}uncolorme` -- Removes your color if you have one", f"`{p}splash <color*>` -- Gives a color to everyone in the server without one", f"`{p}unsplash` -- Uncolors everyone" ] }, # Theme Commands { "title": "Theme Commands", "description": f"{p}command <argument>.\n`*` indicates an optional argument\n`<theme>` can be a name or index", "Theme Commands": [ f"`{p}themes` -- Draws a pretty list of themes", f"`{p}imports` - - Shows available presets" ], "Theme Management Commands": [ f"`{p}save <name*>` -- Saves your theme", f"`{p}theme.remove <theme>` -- Deletes a theme", f"`{p}overwrite <theme>` -- Replaces a theme", f"`{p}load <theme>` -- Applies a saved theme to your server", f"`{p}theme.rename <theme>|<name>` -- Changes a theme's name", f"`{p}import <name>` -- Adds a preset as a theme" ] }, # Macros { "title": "Macros", "description": f"Macros are a way to execute multiple commands with one single command.\nThey make things clean and convenient", "Import, Load, Splash, Overwrite": [ f"`{p}ilso <name>` -- Imports a preset, Loads that preset, Splashes everyone with a random color, Overwrites the imported theme with member colors" ], "Load, Splash, Overwrite": [f"`{p}lso <name>` -- Same as ILSO but with an already saved theme"], "Add, Colorme": [f"`{p}acm <hexcode> <name*>` -- Adds a color and then applies it to you"], "Resplash": [f"`{p}resplash` -- Uncolors everyone and then splashes the server"], "Suggestions": ["If you have suggestions for macros you would like then please let me know in the support server"] }, # Alias Dictionary { "title": "Command Aliases", "description": "Most commands have shorthand aliases\nAny commands with `color` in the name have an alias with `colour`", "Color Commands": [ f"`{p}colors` -- `{p}c`", f"`{p}color` -- `{p}cu`", f"`{p}colorme` -- `{p}me`, `{p}cm`", f"`{p}uncolorme` -- `{p}ucm`", f"`{p}add` -- `{p}new`", f"`{p}remove` -- `{p}delete`", f"`{p}rename` -- `{p}rn`", f"`{p}recolor` -- `{p}rc`" ], "Theme Commands": [ f"`{p}themes` -- `{p}t`, `{p}temes`", f"`{p}imports` -- `{p}presets`", f"`{p}load` -- `{p}theme.load`", f"`{p}save` -- `{p}saveas`, `{p}theme.save`", f"`{p}erase` -- `{p}t.r`, `{p}theme.remove`", f"`{p}overwrite` -- `{p}theme.overwrite`", f"`{p}trn` - - `{p}t.rn`, `{p}theme.rename`" ], "Other Commands": [ f"`{p}prefix` -- `{p}vibrantprefix`" ] } ] change_log = { "0.1": { "title": "Vibrant 0.1", "description": " ", "@Vibrant for help": "Users can mention the bot to give info about help", "Changeable Prefixes": "Users can change prefix with prefix command to avoid prefix conflict with other bots", "Added patch notes": "you can see what I'm doing and I can see what I've done", "Color adding prompts removed": "They no longer show up", "Changed some help command things": "Made it so they show default prefixes" }, "0.2": { "title": "Vibrant 0.2", "description": " ", "Optimization": "Made many functions like prefix run faster", "Optimized Data storage": "improved function input to be more specific to make it faster", "Optimized splash command": "Splash runs faster due to better math", }, "0.3": { "title": "Vibrant 0.3", "description": " ", "Overhauled help command": "Gave help a bunch of useful stuff like setup and individual command help", "`clear_all_colors` and `set` changed": "Commands now send a backup just incase", "Changed data command name": "Changed it to channels since it only shows channel data", "Added a force prefix change": "can use vibrantprefix command to avoid overlap" }, "0.4": { "title": "Vibrant 0.4", "description": " ", "Aliased Commands": "Gave a bunch of commands alternate names like add/remove can be create/delete if you want", "Removed redundant commands": "removed redundant commands because I figured out how to alias commands", "Better Error Handling": "ignores things like command not found and has specific error handling for add command", }, "0.5": { "title": "Vibrant 0.5", "description": " ", "Black color now works": "black no longer shows up as transparent because hex value is auto converted to #000001", "Added more presets": "presets work differently and thus there are many more like Bootstrap, Metro, and Icecream", "Better Drawing": "Made drawing images for commands like colors look better and more open", "Preview command": "new command to show preset colors" }, "0.6": { "title": "Vibrant 0.6", "description": " ", "Changed the look of channels and expose": "Commands are simpler and easier to read", "DM Commands": "Some commands like help and howdy work in a DM channel now", "Less verbose": "Some commands are less verbose to clear up clutter", "More error handling": "Some more errors are handled", "Destroyed some bugs": "General stuff like me being stupid" }, "0.7": { "title": "Vibrant 0.7", "description": " ", "The return of reaction based UX": "Reaction based UX is back and works this time", "updated pfp algorithm": "Algorithm is more accurate now", "DBL integration": "better integration with the API", "Hyperlinks": "inline links for help to clean things up" }, "0.8": { "title": "Vibrant 0.8", "description": " ", "Themes(alpha)": "Themes not ready yet but kind of work", "Housekeeping": "Cleaned up a bunch of things that weren't necessary", "Added some functions to classes": "less imports, better looking", "Code documentation": "I can see what everything does easier. so can you if you care", "Splash changed": "Splash command now colors in an even distribution of colors", "Patchnotes": "Patchnotes doesnt bypass disabled channels now", "Help works": "help wont give setup every time", }, "0.9": { "title": "Vibrant 0.9", "description": " ", "Themes": "Themes allow you to save presets which allows switching the feel of the server", "Serialization": "Custom serialization per object to allow for the use of sets", "The use of python sets": "No more duplicate role members", "Clearing colors faster": "Fixed a bug that massively slowed down clearing colors", "Smarter updates": "The database is updated less but at better times to save your time", "Changed some functions": "Some functions within the code are now faster and smarter", }, "1.0": { "title": "Vibrant 1.0", "description": " ", "Themes Documentation": "Get help with using themes", "Segmented help": "More help categories", "Importing presets": "Can import named presets as themes", }, "1.1": { "title": "Vibrant 1.1", "description": " ", "Housekeeping": "New techniques for cleaner/faster code", "Exceptions": "New way to handle errors should be more descriptive", "Less prone to breaking": "Stricter error handling so less confusing errors", "Fixed major bug with missing guild problems": "Should handle data better" }, "1.2": { "title": "Vibrant 1.2", "description": " ", "Overlapping data": "Member data should be handled properly due to a fixed constructor error", "Unsplash is faster": "unsplash just deletes roles which should make it faster", "Help update": "Help command is simplified and now works like a book with buttons", "Overwrite simpler": "Overwrite just overwrite a theme now without changing name", "imports command": "You can now view all presets", "Pages for everything": "Everything that can be paginated is", "Better UX": "Asks for hexcode and then colors the user you wanted" }, "1.3": { "title": "Vibrant 1.3", "description": " ", "Smarter data handling": "Tries to fill in gaps with the data before reporting error", "Paginated Images changed": "No more double images its just one now for simplicity", "Back to PNG": "Apparently WebP doesn't work on iOS :(", "Visual Changes": "Switched a lot of responses to embeds" }, "1.4": { "title": "Vibrant 1.4", "description": " ", "Role positioning": "Creates roles under the bot role instead of at the bottom", "Theme limit": "Changed default limit to 5" }, "2.0": { "title": "Vibrant 2.0(rewrite)", "description": "Same bot but written better", "No more channel disabling": "got rid of a useless feature", "Better databasing": "better database interaction", "less code": "less code = better", "less data": "bot stores less data", }, "2.1": { "title": "Vibrant 2.1", "description": "Added Macros", "Macros": "Run multiple commands in common patterns with one command", "Caught some errors": "Caught 50001 and 50013 API Errors" } }
class EmptyDiscretizeFunctionError(ValueError): """Raise in place of empty discretize function when loading dataset.""" def __init__(self): message = self.message() super(EmptyDiscretizeFunctionError, self).__init__(message) @staticmethod def message(): return "Please pass discretization method in DataModel contructor when using discretize = True." class NotFittedError(ValueError): """Raise if predict is called before fit.""" def __init__(self, class_name): message = self.message(class_name) super(NotFittedError, self).__init__(message) @staticmethod def message(class_name): return ("This instance of " + class_name + " has not been fitted yet. Please call " "'fit' before you call 'predict'.") class NotEvaluatedError(ValueError): """Raise if get_f_score is called before evaluate.""" def __init__(self, class_name): message = self.message(class_name) super(NotEvaluatedError, self).__init__(message) @staticmethod def message(class_name): return ("This instance of " + class_name + " has not been evaluate yet. Please call " "'evaluate' before you call 'get_f_score'.")
""" spam ~~~~ Toy functions for testing. """ def spam_eggs(): pass def spam_bacon(): pass def spam_baked_beans(): pass
'''Refaça o desafio 035 dos triângulos, acrescentando o recurso de mostrar que tipo de triângulo será formado: -Equilátero: Todos os lados iguais -Isósceles: Dois lados iguais -Escaleno: Todos os lados diferentes''' l1 = float(input('Digite o valor do primeiro lado: ')) l2 = float(input('Digite o valor do segundo lado: ')) l3 = float(input('Digite o valor do terceiro lado: ')) if (l1 > l2 + l3) or (l2 > l1 + l3) or l3 > l2 + l1: print(f'O triângulo de lados {l1}, {l2} e {l3} não pode ser formado.') else: print(f'O triângulo de lados {l1}, {l2} e {l3} pode ser formado.') if l1 == l2 == l3: print('O triângulo é EQUILÁTERO') elif l1 == l2 or l1 == l3 or l2 == l3: print('O triângulo é ISÓSCELES') else: print('O triângulo é ESCALENO')
''' Machine Learning * Machine Learning is making the computer learn from studying data and statistics. * Machine Learning is a step into the direction of artificial intelligence (AI). * Machine Learning is a program that analyses data and learns to predict the outcome. Where To Start? * In this tutorial we will go back to mathematics and study statistics, and how to calculate important numbers based on data sets. * We will also learn how to use various Python modules to get the answers we need. * And we will learn how to make functions that are able to predict the outcome based on what we have learned. '''
class Subscriber: """ Class that defines a subscriber to a specific event """ def __init__(self, callback_method, program, event_type, object_id): self._callback_method = callback_method self._program = program self._event_type = event_type self._object_id = object_id def match(self, program, event_type, object_id): """ Looks for a subscriber to a specific event :param program: The program as defined in Program class :param event_type: The event type (NOTE_ON, NOTE_OFF, CTRL or PGM_CHG) :param object_id: The knob, pad or program change ID """ match = False if self._program == program and self._event_type == event_type and self._object_id == object_id: match = True return match def notify(self, program, object_id, data): """ Call the subscriber (subscribed method of an object) and send available data if any :param program: The program as defined in Program class :param object_id: The knob, pad or program change ID :param data: The data to send to the subscriber for processing if any """ if data == None: self._callback_method([program, object_id]) else: self._callback_method([program, object_id, data])
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"expand_dim_to_3": "00_core.ipynb", "parametric_ellipse": "00_core.ipynb", "elliplise": "00_core.ipynb", "EllipticalSeparabilityFilter": "00_core.ipynb"} modules = ["core.py"] doc_url = "https://AtomScott.github.io/circle_finder/" git_url = "https://github.com/AtomScott/circle_finder/tree/master/" def custom_doc_links(name): return None
LOG = [] def flush_log(filename): with open(filename, 'w') as logfile: for l in LOG: logfile.write("%s\n" % l) def log_message(msg): LOG.append(msg)
# print('hello world') # name = input('please input your name:') # print(name) a1 = 0.1 a2 = 0.2 print(a1 + a2) a3 = 1.23e10 print(a3) a4 = "I'm xiaogang" print(a4) a5 = 'I\' xiaogang' print(a5) print('\\\\t\\') print(r'\\\t\\') # 换行 print('line1\nlin22') print(''' line1 line2 ''' ) # 布尔值 # print(True,False) a1 = True a2 =isinstance(a1, bool) # print(a2) print(a1, 'a2') # 逻辑运算 a1 = True a2 = False a3 = a1 and a2 a4 = a1 or a2 a5 = not a1 print('逻辑运算',a1, a2, a3, a4, a5) # 逻辑运算 True False False True False # None 特殊的值,特殊的空值 a1 = None print(a1) #None # 变量 a = 'abc' b = a a = '123' print(a, b) # 常量 print(10 / 3) print(10 // 3) #3.3333333333333335 #3 # 编码 ''' ASCII 1 个字节 =编码不够=> Unicode 通常两个字节 =不浪费=>utf-8 1-6个字节 (常用英文字母1个字节、汉字3个字节、生僻字4-6个字节) 计算机内存统一用Unicode 码 需要保存或传输的时候转成utf-8 python 字符串是Unicode ''' a = '中' print(ord(a)) b = ord(a) c = chr(b) print(a,b,c) #中 20013 中 a = b'ABC' b = 'ABC' print(a, b) # 编码 print('ASC'.encode('ascii')) print('中文'.encode('utf-8')) # 解码 print(b'ABC'.decode('ascii')) print(b'\xe4\xb8\xad\xe6\x96\x87'.decode('utf-8')) # with error print(b'\xe4\xb8\xad\xe46\x96\x87'.decode('utf-8',errors='ignore')) print(len('ABC'),len(b'ABC')) # 3 3 print(len('中国'),len('中国'.encode('utf-8'))) # 2 6 #!/usr/bin/python # coding: utf-8 print('Hi %s ,I\'m %s,I\'m %d year old'%('xiaogang','xiaotang',19)) # 保留一位数字 print('Hello,{0},成绩提成了{1:.1f}%'.format('xiaotang',19.555))
is_correct = executor_result["is_correct"] test_feedback = executor_result["test_feedback"] test_comments = executor_result["test_comments"] congrats = executor_result["congrats"] feedback = "" output = (test_comments + "\n" + test_feedback).strip() if output == "": output = "No issues!" if is_correct: feedback = congrats else: feedback = "Not quite. Take a look at the feedback area for some pointers." grade_result["correct"] = is_correct grade_result["feedback"] = feedback grade_result["comment"] = output
""" Given an array of integers nums and an integer threshold, we will choose a positive integer divisor and divide all the array by it and sum the result of the division. Find the smallest divisor such that the result mentioned above is less than or equal to threshold. Each result of division is rounded to the nearest integer greater than or equal to that element. (For example: 7/3 = 3 and 10/2 = 5). It is guaranteed that there will be an answer. Example: Input: nums = [1,2,5,9], threshold = 6 Output: 5 Explanation: We can get a sum to 17 (1+2+5+9) if the divisor is 1. If the divisor is 4 we can get a sum to 7 (1+1+2+3) and if the divisor is 5 the sum will be 5 (1+1+1+2). Example: Input: nums = [2,3,5,7,11], threshold = 11 Output: 3 Example: Input: nums = [19], threshold = 5 Output: 4 Constraints: - 1 <= nums.length <= 5 * 10^4 - 1 <= nums[i] <= 10^6 - nums.length <= threshold <= 10^6 """ #Difficulty: Medium #61 / 61 test cases passed. #Runtime: 364 ms #Memory Usage: 20 MB #Runtime: 364 ms, faster than 88.71% of Python3 online submissions for Find the Smallest Divisor Given a Threshold. #Memory Usage: 20 MB, less than 79.06% of Python3 online submissions for Find the Smallest Divisor Given a Threshold. class Solution: def smallestDivisor(self, nums: List[int], threshold: int) -> int: l = 1 r = max(nums) while l < r: m = (l+r) // 2 result = sum([1 + n//m if n%m else n//m for n in nums]) if result > threshold: l = m + 1 else: r = m return l
""" Manages the character's self regeneration. -- Author : DrLarck Last update : 18/07/19 """ # charcter regen class Character_regen: """ Manages the character's self regeneration. - Attribute : `health` : Represents the health regen per turn. `ki` : Represents the ki regen per turn. """ # attribute def __init__(self): self.health = 0 self.ki = 0
## \file OutputFormat.py # \author Dong Chen # \brief Provides the function for writing outputs ## \brief Writes the output values to output.txt # \param theta dependent variables (rad) def write_output(theta): outputfile = open("output.txt", "w") print("theta = ", end="", file=outputfile) print(theta, file=outputfile) outputfile.close()
# LevPy: A Python JSON level-loader # for easier level abstraction # in text-based py games # Copyright (c) Finn Lancaster 2021 # Please Keep in mind that the JSONvar name must # also be the same as the function that # contains more data on it in LevPy.py # Valid JSON, names can be anything, with data after the # colon. The name must match your calls for mainLoop # in LevPy.py. See example for more detail JSONvar = '{"":""}'
class Solution: def isHappy(self, n): """ :type n: int :rtype: bool """ func = lambda x : sum(int(ch) ** 2 for ch in str(x)) seen = set() while True: if n == 1: return True if n in seen: return False seen.add(n) n = func(n)
# STACKS, QUEUES & HEAPS # Stacks ''' A stack is a last in first out (LIFO) data structure. - Push an item onto the stack - Pop an item out of the stack All push and pop operations are to/from the top of the stack. The only way to access the bottom items in the stack is to first remove all items above it Peek - getting an item on top of the stack without removing it Clear - clear all items from the stack Use Cases Undo - tracks which commands have been executed. Pop the last command off the command stack to undo it e.g pop the last command to undo bold. The program has to keep track of which command you have executed in which order. Each time you execute a common, it pushes that command onto the stack so that it has a record of it. If you hit the undo button, it will pop the last command off the stack and reverse that command '''
SETTINGS = { 'app': { 'schema': 'http://', 'host': 'localhost', 'port': 9000 } }
__name__ = "python-crud" __version__ = "0.1.3" __author__ = "Derek Merck" __author_email__ = "[email protected]" __desc__ = "CRUD endpoint API with Python", __url__ = "https://github.com/derekmerck/pycrud",
# -*- coding: utf-8 -*- """ SQLpie License (MIT License) Copyright (c) 2011-2016 André Lessa, http://sqlpie.com See LICENSE file. """ class CustomException(Exception): RECORD_NOT_FOUND = "Record Not Found." INVALID_ARGUMENTS = "Bad Request. Invalid Arguments." CACHE_IS_EMPTY = "Cache Is Empty." CACHE_KEY_NOT_FOUND = "Cache Key Not Found." INVALID_STOPWORD_FILE = "Invalid Stopword File." INVALID_PARSER = "Invalid Indexing Parser." INVALID_CONFIG_FILE_FORMAT = "Invalid Config File Format."
""" .. module:: build_features.py :synopsis: """
#!/usr/bin/env python __author__ = "Kishori M Konwar" __copyright__ = "Copyright 2013, MetaPathways" __credits__ = ["r"] __version__ = "1.0" __maintainer__ = "Kishori M Konwar" __status__ = "Release" exit_code=0
edges = { (1,'q'):1 } accepting = [1] def fsmsim(string, current, edges, accepting): if string == "": return current in accepting else: letter = string[0] if (current, letter) in edges: destination = edges[(current, letter)] remaining_string = string[1:] return fsmsim(remaining_string, destination, edges, accepting) else: return False print(fsmsim("",1,edges,accepting))
class Solution(object): def flipAndInvertImage(self, A): for row in A: for i in xrange((len(row) + 1) / 2): # ~ operator (not operator) x*-1-1 <- gets the element on the oposite side row[i], row[~i] = ~row[~i] ^ 1, row[i] ^ 1 return A
class Employee: num_of_emps = 0 raise_amt = 1.04 def __init__(self, first, last, pay): self.first = first self.last = last self.pay = pay self.email = str(first + '.' + last + '@company.com').lower() # see that we don't need to input all the # attributes. Some of them could be created using algorithms like we did here. Employee.num_of_emps += 1 def fullname(self): return '{} {}'.format(self.first, self.last) def apply_raise(self): self.pay = int(self.pay * self.raise_amt) @classmethod # this class method will change the value of the raise_amt. def set_raise_amt(cls, amount): cls.raise_amt = amount @classmethod # this class method will took a string and transform into a new instance of the class. In this case # it will create a new employee. def from_string(cls, emp_str): first, last, pay = emp_str.split('-') return cls(first, last, pay) emp_1 = Employee('Corey', 'Schafer', 50000) emp_2 = Employee('Test', 'User', 60000) Employee.set_raise_amt(1.05) print(Employee.raise_amt) print(emp_1.raise_amt) print(emp_2.raise_amt) emp_str_1 = 'John-Doe-70000' emp_str_2 = 'Steve-Smith-30000' emp_str_3 = 'Jane-Doe-90000' new_emp_1 = Employee.from_string(emp_str_1) print(new_emp_1) print(new_emp_1.email) print(new_emp_1.pay)