content
stringlengths
7
1.05M
class Helper: @staticmethod def is_Empty(obj): flag = False if obj is None: flag = True elif not obj.strip(): flag = True else: flag = False return flag if __name__ == '__main__': print(Helper.is_Empty(None))
''' Lambda expressions are quick way of creating the anonymous functions: ''' #function without lamda expression: def square(num): return num ** 2 print(square(5)) #converting it into lambda expression: lambda num : num ** 2 #if we want we can assign this to variable like square2 = lambda num : num ** 2. # we are...
# -*- coding: utf-8 -*- """ \file identity/views.py \brief Implements the core views for django-identity. \author Erich Healy (cactuscommander) ErichRHealy@gmail.com \author Ryan Leckey (mehcode) leckey.ryan@gmail.com \copyright Copyright 2012 © Concordus Applications, Inc. All Rights Reserved. """
# Builds the Netty fork of Tomcat Native. See http://netty.io/wiki/forked-tomcat-native.html { 'targets': [ { 'target_name': 'netty-tcnative-so', 'product_name': 'netty-tcnative', 'type': 'shared_library', 'sources': [ 'src/c/address.c', 'src/c/bb.c', 'src/c/dir.c',...
#!/usr/bin/python3 def set_dependencies(source_nodes): """Sets contract node dependencies. Arguments: source_nodes: list of SourceUnit objects. Returns: SourceUnit objects where all ContractDefinition nodes contain 'dependencies' and 'libraries' attributes.""" symbol_map = get_s...
# https://www.acmicpc.net/problem/9020 if __name__ == '__main__': input = __import__('sys').stdin.readline N = 10_001 T = int(input()) is_prime = [True for _ in range(N)] sqrt = int(N ** (1 / 2)) is_prime[0] = is_prime[1] = False for idx in range(2, sqrt + 1): if not is_prime[idx]...
def bin_value(num): return bin(num) [2:] def remove0b(num): return num [2:] numberA = int(input("")) numberB = int(input("")) binaryA = bin_value(numberA) binaryB = bin_value(numberB) sum = bin(int(binaryA,2) + int(binaryB,2)) cleaned = remove0b(sum) binaryA = str(binaryA) binaryB = str(binaryB) sum = str(cle...
# HEAD # Classes - Setters are shallow # DESCRIPTION # Describes how setting of inherited attributes and values function # RESOURCES # # Creating Parent class class Parent(): par_cent = "parent" # Parent Init method def __init__(self, val): self.par_cent = val print("Parent Instantiated ...
#!/usr/bin/env python # encoding: utf-8 ''' @author: Jason Lee @license: (C) Copyright @ Jason Lee @contact: jiansenll@163.com @file: jianzhi_offer_31.py @time: 2019/4/23 16:09 @desc: ''' class Solution: def FindGreatestSumOfSubArray(self, array): if not array: return 0 f = arr...
def get_eig_Jacobian(pars, fp): """ Simulate the Wilson-Cowan equations Args: pars : Parameter dictionary fp : fixed point (E, I), array Returns: evals : 2x1 vector of eigenvalues of the Jacobian matrix """ #get the parameters tau_E, a_E, theta_E = pars['tau_E'], pars['a_E'], pars[...
k, n, w = map(int, input().split()) x = 1 money = 0 while x <= w and money != -1: money += k * x x += 1 money_toborrow = money - n if money_toborrow >= 0: print(money_toborrow) else: print(0)
def fatorial (n): r = 1 for num in range (n, 1, -1): r *= num return r def dobro (n): num = n * 2 return num def triplo (n): num = n * 3 return num
#####################################Data class class RealNews(object): def __init__(self, date, headline, description,distype, url="", imageurl="",location=""): self.date = date self.headline = headline self.description = description self.url = url self.distype = distype ...
bicicleta=["bike","cannon","cargo", "CALOI"] #Armazenamento de farias mensagens/lista em uma string print(bicicleta[0].title()) print(bicicleta[1]) print(bicicleta[2]) print(bicicleta[3]) print(bicicleta[-1]) print(bicicleta[-2]) print(bicicleta[-3]) print(bicicleta[-4].title()) #como...
""" Utilitary methods to display ouputs """ # Add color to a string def str_color(message, rgbcol): r, g, b = rgbcol return "\033[38;2;{};{};{}m{}\033[0m".format(r, g, b, message) # print(squares from a palette) def print_palette(rgbcols, size=2): str_palette = "" for col in rgbcols: str_pal...
class Subtract: def __init__(self,fnum,snum): self.fnum=fnum self.snum=snum def allSub(self): self.sub=self.fnum-self.snum return self.sub
model = Sequential() model.add(LSTM(50, return_sequences = True, input_shape = (x_train.shape[1], 1))) model.add(LSTM(50, return_sequences = False)) model.add(Dense(25)) model.add(Dense(1)) #Compiling the model model.compile(optimizer = 'adam', loss = 'mean_squared_error') #using rmse
DEFAULT_REDIS_PORT = 6379 # Number of seconds to sleep upon successful end to allow graceful termination of subprocesses. TERMINATION_TIME = 3 # Max caps on parameters MAX_NUM_STEPS = 10000 MAX_OBSERVATION_DELTA = 5000 MAX_VIDEO_FPS = 60
# -*- coding: utf-8 -*- """Utils for celery.""" def init_celery(celery, app): celery.conf.update(app.config) celery.conf.update( task_serializer='json', accept_content=['json'], # Ignore other content result_serializer='json', timezone='Europe/Berlin', enable_utc=True...
key = input().strip() value = input().strip() count = int(input()) result = '' for entry in range(count): keys, values = input().split(' => ') if key in keys: result += f'{keys}:\n' if value in values: all_values = '\n'.join([f'-{v}' for v in values.split(';') if value in v]) ...
""" Written by Jesse Evers Finds the factorial of a number. """ def factorial(num): # While num > 1, multiply num by num - 1 if num > 1: return num * factorial(num - 1) return num print(factorial(10))
n1 = float(input('Primeiro número: ')) n2 = float(input('Segundo número: ')) n3 = float(input('Terceiro número: ')) menor = n1 if n2<n1 and n2<n3: menor = n2 if n3<n1 and n3<n2: menor = n3 maior = n1 if n2>n1 and n2>n3: maior = n2 if n3>n1 and n3>n2: maior = n3 print('{} é o maior'.format(maior)) pri...
''' Author : MiKueen Level : Medium Problem Statement : Product of Array Except Self Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i]. Example: Input: [1,2,3,4] Output: [24,12,8,6] Constraint: It's guaranteed...
name = str(input()) salary = float(input()) sales = float(input()) total = salary + (sales * 0.15) print(f'TOTAL = R$ {total:.2f}')
class Parameters: WINDOW_WIDTH = 500 WINDOW_HEIGHT = 600 BASE_HEIGHT = 100 BASE_IMAGE = "base.png" BACKGROUND_IMAGE = "bg.png" BIRD_IMAGES = ["bird1.png", "bird2.png", "bird3.png"] PIPE_IMAGES = ["pipe.png"]
# It make a node class node: def __init__(self, symbol): self.symbol = symbol self.edges = [] self.shortest_distance = float('inf') self.shortest_path_via = None # Adds another node as a weighted edge def add_edge(self, node, distance): self.edges.append([node, dista...
d=dict() for _ in range(int(input())): s=input().split(' ',1) d[s[0]]=list(map(int,s[1].split())) d=dict(sorted(d.items(), key=lambda x: x[0])) d=dict(sorted(d.items(), key=lambda x: x[1][2],reverse=True)) d=dict(sorted(d.items(), key=lambda x: x[1][1],reverse=True)) d=dict(sorted(d.items(), key=lambda x: x[1][...
def my_func(count=4): for i in range (1, 5): print("count", count) if count == 2: print("count", count) count = count - 1 my_func()
""" 217. Contains Duplicate https://leetcode.com/problems/contains-duplicate/ Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct. Example: Input: [1,2,3,1] Ou...
class Aumento: codigo = 0 nome = '' preco = 0.0 aumento = 0.0 def main(): p = Aumento() p.codigo = int(input('Informe o código do produto: ')) p.nome = str(input('Informe o nome do produto: ')) p.preco = float(input('Informe o preço do produto: R$ ')) p.aumento = (p.preco*0.1) + p.p...
s = str(input()) ss = ''.join(list(reversed(s))) sss = ss[:2] ssss = ''.join(list(reversed(sss))) print(ssss)
num=5 for i in range(1,num+1): toPrint="" end=int(i*(i+1)/2) a=list(j for j in range(end+1-i,end+1)) for x in a: toPrint+=" "+str(x) print(toPrint) toPrint="" #output ''' 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 '''
if __name__ == '__main__': x = int(input()) y = int(input()) z = int(input()) n = int(input()) ar = [] #p=0 for i in range(x+1): for j in range(y+1): for k in range(z+1): if (i+j+k) != n: ar.append([i,j,k]) print(ar) """for i in r...
expected_output = { 'mstp': { 'mst_instances': { 0: { 'mst_id': 0, 'bridge_priority': 32768, 'bridge_sysid': 0, 'bridge_address': '00e3.04ff.ad03', 'topology_change_flag': False, 'topology_detected_...
#THIS IS HANGMAN print('"Hangman"\nA game where you will try to guess which the hidden word is!') print('\n') word = input('Input the word to guess:\n') while True: if word.isalpha(): break else: word = input('Wrong input, type a valid word:\n') number_of_letters = len(word) word_listed_lett...
dataset_type = "SuperviselyDataset" data_root = '/data/slyproject' class_names = ['Car', 'Pedestrian', 'Cyclist', 'DontCare'] point_cloud_range = [0, -40, -3, 70.4, 40, 1] input_modality = dict(use_lidar=True, use_camera=False) file_client_args = dict(backend='disk') # db_sampler = dict( # data_root=data_root, # ...
LIST_ASSIGNED_USER_ROLE_RESPONSE = """ [ { "id": "IFIFAX2BIRGUSTQ", "label": "Application Administrator", "type": "APP_ADMIN", "status": "ACTIVE", "created": "2019-02-06T16:17:40.000Z", "lastUpdated": "2019-02-06T16:17:40.000Z", "assignmentType": "USER", ...
while True: num = int(input("Enter a number: ")) if num % 2 == 0: print(num, "is an even number") else: print(f"{num} is a odd number")
# Initialisierung mit () tupel_eins = (1, True, 4.5, "hallo") # Elemente abfragen wie bei Listen viereinhalb = tuple_eins[2] #4.5 hallo = tuple_eins[-1] #'hello' vordere = tuple_eins[:2] #(1, True) # Elemente verändern, unmöglich ! tupel_eins[0] = "neuer Wert" #TypeError # Ganzes Tuple austauschen, möglich ! tupel_ei...
__package_name__ = 'python-utils' __version__ = '2.5.0' __author__ = 'Rick van Hattem' __author_email__ = 'Wolph@wol.ph' __description__ = ( 'Python Utils is a module with some convenient utilities not included ' 'with the standard Python install') __url__ = 'https://github.com/WoLpH/python-utils'
class BBUtil(object): def __init__(self,width,height): super(BBUtil, self).__init__() self.width=width self.height=height def xywh_to_tlwh(self, bbox_xywh): x,y,w,h = bbox_xywh xmin = max(int(round(x - (w / 2))),0) ymin = max(int(round(y - (h / 2))),0) r...
class Storage: __storage = 0 def __init__(self, capacity): self.capacity = capacity self.storage = [] def add_product(self, product): if not Storage.__storage == self.capacity: self.storage.append(product) Storage.__storage += 1 def get_products(self): ...
# A CAN bus. class Bus(object): """A CAN bus. """ def __init__(self, name, comment=None, baudrate=None, fd_baudrate=None, autosar_specifics=None): self._name = name # If the 'comment' argument is a strin...
def signFinder (s): plus = s.count("-") minus = s.count("+") total = plus+minus if total == 1: return True else: return False
"""Postgres Connector error classes.""" class PostgresConnectorError(Exception): """Base class for all errors.""" class PostgresClientError(PostgresConnectorError): """An error specific to the PostgreSQL driver."""
def binary_search(arr, target): low, high = 0, len(arr)-1 while low < high: mid = (low + high)/2 if arr[mid] == target: return mid elif arr[mid] > target: high = mid - 1 else: low = mid + 1 return high if __name__ == "__main__": lst = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] ...
''' Write a function that takes a string of braces, and determines if the order of the braces is valid. It should return true if the string is valid, and false if it's invalid. This Kata is similar to the Valid Parentheses Kata, but introduces new characters: brackets [], and curly braces {}. Thanks to @arnedag for th...
#EP1 ''' def getPentagonalNumber(n): i = 1 for i in range(1,n+1): s = (i*(3*i-1)*1.0)/2 print (str(s)+' ',end='') if i%10==0: print() getPentagonalNumber(100) ''' #EP2 ''' def sum(n): s= 0 while(n%10!=0): a=n%10 b=n//10 s=s+a n=b p...
# -*- coding: utf-8 -*- """ Created on Fri Feb 19 13:45:46 2021 @author: Lakhan Kumawat """ mylist=input().split() k=int(input()) k1=k mylist1=mylist mylist1.sort() mylist.sort() max1=max(mylist1) #print(mylist,mylist1) #remove k-1th max from list1 and print max while(k1-1!=0): while(max(mylist1)...
# coding=utf-8 __author__ = 'co2y' __email__ = 'co2y@foxmail.com' __version__ = '0.0.1'
""" Errors relating to partitioning """ # Partitioning partitionWarning = ("Partitioning suggests no partitions.\n" "Recommend running with different partitioning method or disable partitioning")
def main(): full_name = get_full_name() print() password = get_password() print() first_name = get_first_name(full_name) print("Hi " + first_name + ", thanks for creating an account.") def get_full_name(): while True: name = input("Enter full name: ").s...
#EVALUATION OF THE MODEL def evaluate_model(model, X_test, y_test): _, score = model.evaluate(X_test, y_test, verbose = 0) print(score) def predict_model(model, X): y = model.predict(X) print(y) def predict_class_model(model, X): y = model.predict_classes(X) print(y)
class Solution: def removeKdigits(self, num: str, k: int) -> str: if len(num) == 0 and len(num) <= k : return "0" st = [num[0]] i = 1 while i < len(num): while len(st) > 0 and int(st[-1]) > int(num[i]) and k > 0: st.pop() ...
file_input = open("motivation.txt",'w') file_input.write("Never give up") file_input.write("\nRise above hate") file_input.write("\nNo body remember second place") file_input.close()
__title__ = "django-kindeditor" __description__ = "Django admin KindEditor integration." __url__ = "https://github.com/waketzheng/django-kindeditor" __version__ = "0.3.0" __author__ = "Waket Zheng" __author_email__ = "waketzheng@gmail.com" __license__ = "MIT" __copyright__ = "Copyright 2019 Waket Zheng"
class BoundingBox: x: int y: int x2: int y2: int cx: int cy: int width: int height: int def __init__(self, x: int, y: int, width: int, height: int): self.x = x self.y = y self.width = width self.height = height self.x2 = x + width - 1 ...
#!/usr/bin/env python3 def convert_to_celsius(fahrenheit: float) -> float: return (fahrenheit - 32.0) * 5.0 / 9.0 def above_freezing(celsius: float) -> bool: return celsius > 0 fahrenheit = float(input('Enter the temperature in degrees Fahrenheit: ')) celsius = convert_to_celsius(fahrenheit) print(celsius)...
numero = str(input('digite um numero')) print('unidade: {}'.format(numero[1])) print('dezena: {}'.format(numero[2])) print('centena: {} '.format(numero[3])) print('unidade de milhar: {}'.format(numero[4]))
def floydwarshall(G): """ Compute and return the all pairs shortest paths solution. Notice the returned path cost matrix P has modified entries. For example, P[i][j] contains a tuple (c, v1) where c is the cost of the shortest path from i to j, and v1 is the first vertex along said path after i....
def binary_search(array: list, valor_buscado, inicio=0, fin=None): if fin == None: fin = len(array)-1 if inicio > fin: return f"No se encontró el valor: {valor_buscado}" medio = (inicio + fin)//2 if valor_buscado == array[medio]: return f"El valor {valor_buscado} está ...
""" Tema: Arrays Curso: Estructura de Datos Lineales (Python). Plataforma: Platzi. Profesor: Hector Vega. Alumno: @edinsonrequena. """ class Array(object): """A simple array""" def __init__(self, capacity: int, fill_value=None) -> None: self.items = list() for i in range(capacity): ...
CODE = { 200: {'code': 200, 'msg': "ok"}, 201: {'code': 201, 'msg': "no data"}, 400: {'code': 400, 'msg': "Bad Request"}, # 请求错误 401: {'code': 401, 'msg': "Unauthorized"}, # 没有用户凭证 403: {'code': 403, 'msg': 'Forbidden'}, # 拒绝授权 418: {'code': 418, 'msg': 'happy new year'}, 429: {'code': 42...
# # @lc app=leetcode id=231 lang=python3 # # [231] Power of Two # # @lc code=start class Solution: def isPowerOfTwo(self, n: int) -> bool: # 每次向下除2, 看最后的结果 if n < 1: return False elif n == 1: return True return self.isPowerOfTwo(n/2) def test(self): assert(self....
def f(): '''f''' pass def f1(): pass f2 = f if True: def g(): pass else: def h(): pass class C: def i(self): pass def j(self): def j2(self): pass class C2: def k(self): pass
# 450. Delete_Node_in_a_BST # ttungl@gmail.com # 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 deleteNode(self, root, key): """ :type root: TreeNode ...
""" Day 8 - Part 1 https://adventofcode.com/2021/day/8 By NORXND @ 08.12.2021 (C) NORXND 2021 - Under The MIT License """ input_file = open('Day8/input.txt', 'r') entries = [] for entry in input_file.readlines(): entry = entry.strip().split(" | ") patterns = entry[0].split(" ") output = entry[1].split("...
IPlist = ['209.85.238.4','216.239.51.98','64.233.173.198','64.3.17.208','64.233.173.238'] # for address in range(len(IPlist)): # IPlist[address] = '%3s.%3s.%3s.%3s' % tuple(IPlist[address].split('.')) # IPlist.sort(reverse=False) # for address in range(len(IPlist)): # IPlist[address] = IPlist[address].re...
class Ponto(object): def __init__(self, x, y): #método construtor (cria ponto) self.x = x self.y = y def exibe_ponto(self): print('Coordenadas -> x: ', self.x, ', y: ', self.y) def set_x(self, x): self.x = x def set_y(self, y): self.y = y def dis...
class Base1: def FuncA(self): print("Base1::FuncA") class Base2: def FuncA(self): print("Base2::FuncA") class Child(Base1, Base2): pass def main(): obj=Child() obj.FuncA() if __name__ == "__main__": main()
#custo de uma viagem. ate 200km( R$0,50), mais q isso (R$0,45) distancia = float(input('Informe a distância: ')) print('Por essa distância {}km: '.format(distancia)) if distancia <= 200: preco = distancia * 0.50 print('O valor da passagem será de R${:.2f}.'.format(preco)) else: preco = distancia * 0...
KIND_RETRIEVE_DATA = { "_embedded": { "naam": { "_embedded": { "inOnderzoek": { "_embedded": { "datumIngangOnderzoek": { "dag": None, "datum": None, "ja...
# -*- coding: utf-8 -*- #from pkg_resources import resource_filename class dlib_model: def pose_predictor_model_location(): return "./models/dlib/shape_predictor_68_face_landmarks.dat" def pose_predictor_five_point_model_location(): return "./models/dlib/shape_predictor_5_face_landmarks.dat" def face_...
# %% [705. Design HashSet](https://leetcode.com/problems/design-hashset/) class MyHashSet(set): remove = set.discard contains = set.__contains__
# # # you have some similar items that you want to store # a1 = 3 # a2 = 5 # a3 = 8 # # ... # a100 = 151 # # # # # # # There has to be a better way # # # # # # # # # # # What is a list after all? # # # # # # # # # * ordered # # # # # # # # # * collection of arbitrary objects (anything goes in) # # # # # # # # # * neste...
words_count = int(input()) words_dict = {} def add_word(word,definition): words_dict[word] = definition def translate_sentence(words_list): sentence = "" for word in words_list: if word in words_dict: sentence += words_dict[word] + " " else: sentence += word + " "...
''' Control Structures A statement used to control the flow of execution in a program is called a control structure. Types of control structures 1. Sequence ****************************************************** In a sequential structure the statements are executed in the same order in which they a...
#33 # Time: O(logn) # Space: O(1) # Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. # (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). # # You are given a target value to search. If found in the array return its index, otherwise return -1. # # You may assume no dupli...
# Número de quantos alunos vão ser cadastrados numeroAlunos = int(input('Quantos alunos quer cadastrar? ')) notasAlunos = {} todosAlunos = [] # Usei um for que se repete na quantidade de vezes no número de alunos for i in range(numeroAlunos): notasAlunos['aluno'] = input('Qual o nome do aluno? ') # Pegando o nome...
"""Chapter 8 Practice Question 3 Draw the complete truth tables for the and, or, and not operators. """ def notTruthTable() -> None: """Not truth table. Prints a truth table for the not operator. Returns: None. Only prints out a table. """ print(" _________________________\n", ...
""" -*- coding: utf-8 -*- Time : 2019/7/19 8:25 Author : Hansybx """ class Res: code = 200 msg = '' info = {} def __init__(self, code, msg, info): self.code = code self.msg = msg self.info = info
''' 输入一棵二叉树的根节点,判断该树是不是平衡二叉树。如果某二叉树中任意节点的左右子树的深度相差不超过1,那么它就是一棵平衡二叉树。   示例 1: 给定二叉树 [3,9,20,null,null,15,7] 3 / \ 9 20 / \ 15 7 返回 true 。 示例 2: 给定二叉树 [1,2,2,3,3,null,null,4,4] 1 / \ 2 2 / \ 3 3 / \ 4 4 返回 false 。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/pro...
class Task: def __init__(self,name,due_date): self.name = name self.due_date = due_date self.comments=[] self.completed=False def change_name(self,new_name:str): if self.name==new_name: return f"Name cannot be the same." self.name=new_name ret...
class BITree: def __init__(self, nums): self.n = len(nums) self.arr = [0 for _ in range(self.n)] self.bitree = [0 for _ in range(self.n + 1)] for i in range(self.n): self.update(i, nums[i]) def update(self, i, val): diff = val - self.arr[i] ...
class Solution(object): def hammingWeight(self, n): """ :type n: int :rtype: int """ res = 0 while n: res += 1 n &= (n-1) return res def hammingWeight(self, n): for i in range(33): if not n: return i ...
""" 133 / 133 test cases passed. Runtime: 56 ms Memory Usage: 15.1 MB """ class Solution: def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: m, n = len(matrix), len(matrix[0]) l, r = 0, m * n - 1 while l < r: mid = (l + r + 1) >> 1 if matrix[mid // ...
class ManuscriptSubjectAreaService: def __init__(self, df): self._df = df self._subject_areas_by_id_map = df.groupby( 'version_id')['subject_area'].apply(sorted).to_dict() @staticmethod def from_database(db, valid_version_ids=None): df = db.manuscript_subject_area.read_f...
def _cc_stamp_header(ctx): out = ctx.outputs.out args = ctx.actions.args() args.add("--stable_status", ctx.info_file) args.add("--volatile_status", ctx.version_file) args.add("--output_header", out) ctx.actions.run( outputs = [out], inputs = [ctx.info_file, ctx.version_file], ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Oct 11 11:47:23 2021 @author: Claire He Selecting Topics : paper suggest topic selection policy-wise using Meade (2017) work on dissent in policies. We may want to use the same method to select Using Lasso regression shrinkage """
def permute(obj_list, l, r, level): """Helper function to implement the nAr permutation operation Arguments: obj_list -- the list of objects from which the permutation should be generated l -- left end point of current permutation r -- right end point (exclusive) of current p...
print('Challenge 14: WAF to check if a number is present in a list or not.') test_list = [ 1, 6, 3, 5, 3, 4 ] print("Checking if 6 exists in list: ") # Checking if 6 exists in list # using loop for i in test_list: if(i == 6) : print ("Element Exists")
# dictionaries friends = ["john", "andre", "mark", "robert"] ages = [23, 43, 54, 12] biodatas_dict = dict(zip(friends, ages)) print(biodatas_dict) # list biodatas_list = list(zip(friends, ages)) print(biodatas_list) # tuple biodatas_tuple = tuple(zip(friends, ages)) print(biodatas_tuple)
#!/usr/bin/env python def count_fish(lanternfish: list, repro_day: int) -> int: return len([x for x in lanternfish if x == repro_day]) def pass_one_day(fish_age_hash: dict, day: int, lanternfish: list=None): if day == 0: if not lanternfish: raise AttributeError("Error: lanternfish list mus...
class MyClass: def __call__(self): print('__call__') c = MyClass() c() c.__call__() print() c.__call__ = lambda: print('overriding call') c() c.__call__()
token = 'Ndhhfghfgh' firebase = { "apiKey": "AIzaSyBYHMxJYFVWP6xH55gAY1TJpVECq4KRjKM", "authDomain": "test24-13912.firebaseapp.com", "databaseURL": "https://test24-13912-default-rtdb.firebaseio.com", "projectId": "test24-13912", "storageBucket": "test24-13912.appspot.com", "messagingSenderId": "939334214645", "...
class InstagramQueryId: USER_MEDIAS = '17880160963012870' USER_STORIES = '17890626976041463' STORIES = '17873473675158481'
class person: def __init__(self, first_name, last_name, age): self.first_name = first_name self.last_name = last_name self.age = age def get_full_name(self): return f"{self.first_name} {self.last_name}" def introduce(self): return f"Hi. I'm {self.first_name}. {se...
# factoryboy_utils.py @classmethod def _get_manager(cls, model_class): return super(cls, cls)._get_manager(model_class).using(cls.database) class DBAwareFactory(object): """ Context manager to make model factories db aware Usage: with DBAwareFactory(PersonFactory, 'db_qa') as personfactory_o...
# # PySNMP MIB module HPN-ICF-FLASH-MAN-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HPN-ICF-FLASH-MAN-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:26:48 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (def...
# # PySNMP MIB module BENU-IP-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BENU-IP-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:37:23 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, 0...