content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
# Link to problem : https://leetcode.com/problems/remove-element/ class Solution: def removeElement(self, nums ,val): count = 0 for i in range(len(nums)): if(nums[i] != val): nums[count] = nums[i] count += 1 return count
class Solution: def remove_element(self, nums, val): count = 0 for i in range(len(nums)): if nums[i] != val: nums[count] = nums[i] count += 1 return count
while True: n = int(input()) if not n: break s = 0 for i in range(n): s += [int(x) for x in input().split()][1] // 2 print(s//2)
while True: n = int(input()) if not n: break s = 0 for i in range(n): s += [int(x) for x in input().split()][1] // 2 print(s // 2)
new_minimum_detection = input("What is the minimum confidence?: ") with open('object_detection_webcam.py', 'r') as file: lines = file.readlines() for line in lines: if line[0:18] == ' min_detection_': line = ' min_detection_confidence = '+new_minimum_detection+' ###EDITE...
new_minimum_detection = input('What is the minimum confidence?: ') with open('object_detection_webcam.py', 'r') as file: lines = file.readlines() for line in lines: if line[0:18] == ' min_detection_': line = ' min_detection_confidence = ' + new_minimum_detection + ' ###EDITED B...
# class Student(object): # def __init__(self, name, score): # self.name = name # self.score = score # def print_score(self): # print('%s: %s' % (self.name, self.score)) class Student(object): def __init__(self, name, score): self.__name = name self.__score = score...
class Student(object): def __init__(self, name, score): self.__name = name self.__score = score def print_score(self): print('%s: %s' % (self.__name, self.__score)) fyp = student('fyp', 59) print('fyp===>', fyp) print('fyp===>', fyp.name) print('fyp===>', fyp.score)
# # 359. Logger Rate Limiter # # Q: https://leetcode.com/problems/logger-rate-limiter/ # A: https://leetcode.com/problems/logger-rate-limiter/discuss/473779/Javascript-Python3-C%2B%2B-hash-table # class Logger: def __init__(self): self.m = {} def shouldPrintMessage(self, t: int, s: str) -> bool: ...
class Logger: def __init__(self): self.m = {} def should_print_message(self, t: int, s: str) -> bool: m = self.m if not s in m or 10 <= t - m[s]: m[s] = t return True return False
for t in range(int(input())): a=int(input()) s=input() L=[] for i in range(0,a*8,8): b=s[i:i+8] k=0 for i in range(8): if b[i] == 'I': k += 2**(7-i) L.append(k) print("Case #"+str(t+1),end=": ") for i in L: print(chr(i),end="") ...
for t in range(int(input())): a = int(input()) s = input() l = [] for i in range(0, a * 8, 8): b = s[i:i + 8] k = 0 for i in range(8): if b[i] == 'I': k += 2 ** (7 - i) L.append(k) print('Case #' + str(t + 1), end=': ') for i in L: ...
# A program to display a number of seconds in other units data = 75475984 changedData = data years = 0 days = 0 hours = 0 minutes = 0 seconds = 0 now = 0 if data == 0: now = 1 for i in range(100): if changedData >= 31556952: years += 1 changedData -= 31556952 for i in range(365): if cha...
data = 75475984 changed_data = data years = 0 days = 0 hours = 0 minutes = 0 seconds = 0 now = 0 if data == 0: now = 1 for i in range(100): if changedData >= 31556952: years += 1 changed_data -= 31556952 for i in range(365): if changedData >= 86400: days += 1 changed_data -= ...
nombre=input("nombre del archivo? ") f=open(nombre,"r") palabras=[] for linea in f: palabras.extend(linea.split()) print(palabras)
nombre = input('nombre del archivo? ') f = open(nombre, 'r') palabras = [] for linea in f: palabras.extend(linea.split()) print(palabras)
# %% [278. First Bad Version](https://leetcode.com/problems/first-bad-version/) class Solution: def firstBadVersion(self, n): lo, up = 0, n while up - lo > 1: mid = (lo + up) // 2 if isBadVersion(mid): up = mid else: lo = mid ...
class Solution: def first_bad_version(self, n): (lo, up) = (0, n) while up - lo > 1: mid = (lo + up) // 2 if is_bad_version(mid): up = mid else: lo = mid return up
# dataset settings data_root = 'data/' img_norm_cfg = dict(mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) crop_size = (256, 512) train_pipeline = [ dict(type='LoadImageFromFile_Semi'), dict(type='LoadAnnotations_Semi'), dict(type='RandomCrop_Semi', crop_size=crop_size, cat_max_rat...
data_root = 'data/' img_norm_cfg = dict(mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) crop_size = (256, 512) train_pipeline = [dict(type='LoadImageFromFile_Semi'), dict(type='LoadAnnotations_Semi'), dict(type='RandomCrop_Semi', crop_size=crop_size, cat_max_ratio=0.75), dict(type='RandomFlip_...
P, T = map(int, input().split()) solved = 0 for _ in range(P): flag = True for _ in range(T): test1 = input().strip() test = test1[0].lower() + test1[1:] if test == test1.lower(): continue else: flag = False if flag: solved += 1 print(solved)
(p, t) = map(int, input().split()) solved = 0 for _ in range(P): flag = True for _ in range(T): test1 = input().strip() test = test1[0].lower() + test1[1:] if test == test1.lower(): continue else: flag = False if flag: solved += 1 print(solved)
def nb_year(p0, percent, aug, p): year = 0 while p0 < p: p0 = int(p0 + p0*(percent/100) + aug) year += 1 print(p0) return year print(nb_year(1000, 2, 50, 1200))
def nb_year(p0, percent, aug, p): year = 0 while p0 < p: p0 = int(p0 + p0 * (percent / 100) + aug) year += 1 print(p0) return year print(nb_year(1000, 2, 50, 1200))
# custom exceptions for ElasticSearch class SearchException(Exception): pass class IndexNotFoundError(SearchException): pass class MalformedQueryError(SearchException): pass class SearchUnavailableError(SearchException): pass
class Searchexception(Exception): pass class Indexnotfounderror(SearchException): pass class Malformedqueryerror(SearchException): pass class Searchunavailableerror(SearchException): pass
print("Digite um numero...") numero = int(input()); numero numeroSucessor = print(numero + 1); numeroAntecessor = print(numero - 1); print("o seu valor eh {}, seu sucessor eh {} e o seu antecessor eh {}".format(numero, numeroSucessor, numeroAntecessor));
print('Digite um numero...') numero = int(input()) numero numero_sucessor = print(numero + 1) numero_antecessor = print(numero - 1) print('o seu valor eh {}, seu sucessor eh {} e o seu antecessor eh {}'.format(numero, numeroSucessor, numeroAntecessor))
host_='127.0.0.1' port_=8086 user_='user name' pass_ ='user password' protocol='line' air_api_key="air api key" weather_api_key="weather_api_key"
host_ = '127.0.0.1' port_ = 8086 user_ = 'user name' pass_ = 'user password' protocol = 'line' air_api_key = 'air api key' weather_api_key = 'weather_api_key'
MASTER_KEY = "masterKey" BASE_URL = "http://127.0.0.1:7700" INDEX_UID = "indexUID" INDEX_UID2 = "indexUID2" INDEX_UID3 = "indexUID3" INDEX_UID4 = "indexUID4" INDEX_FIXTURE = [ {"uid": INDEX_UID}, {"uid": INDEX_UID2, "options": {"primaryKey": "book_id"}}, {"uid": INDEX_UID3, "options": {"uid": "wrong", "pr...
master_key = 'masterKey' base_url = 'http://127.0.0.1:7700' index_uid = 'indexUID' index_uid2 = 'indexUID2' index_uid3 = 'indexUID3' index_uid4 = 'indexUID4' index_fixture = [{'uid': INDEX_UID}, {'uid': INDEX_UID2, 'options': {'primaryKey': 'book_id'}}, {'uid': INDEX_UID3, 'options': {'uid': 'wrong', 'primaryKey': 'boo...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- class Inyourshoes(object): def __init__(self, nlp, object): self.object = object self.matcher = object.matcher.Matcher(nlp.vocab) self.matcher.add("Inyourshoes", None, #what i would do [{'LOWER': 'what'...
class Inyourshoes(object): def __init__(self, nlp, object): self.object = object self.matcher = object.matcher.Matcher(nlp.vocab) self.matcher.add('Inyourshoes', None, [{'LOWER': 'what'}, {'LOWER': 'i'}, {'LOWER': 'would'}, {'LOWER': 'do'}], [{'LOWER': 'if'}, {'LOWER': 'i'}, {'LOWER': 'were...
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: max_len = start = 0 m = {} for end, char in enumerate(s): if m.get(char, -1) >= start: # if in the current range start = m[char] + 1 max_len = max(max_len, end - start + 1) ...
class Solution: def length_of_longest_substring(self, s: str) -> int: max_len = start = 0 m = {} for (end, char) in enumerate(s): if m.get(char, -1) >= start: start = m[char] + 1 max_len = max(max_len, end - start + 1) m[char] = end ...
if __name__ == "__main__": null = "null" placeholder = null undefined = "undefined"
if __name__ == '__main__': null = 'null' placeholder = null undefined = 'undefined'
# optimized_primality_test : O(sqrt(n)) - if x divide n then n/x = y which divides n as well, so we need to check only # numbers from 1 to sqrt(n). sqrt(n) is border because sqrt(n) * sqrt(n) gives n, which then implies that values after # sqrt(n) need to be multiplied by values lesser then sqrt(n) which we already che...
def primality_test(num): i = 2 while i * i <= num: if num % i == 0: return False i += 1 return True print(primality_test(6793))
Elements_Symbols_Reverse = { "H":"Hydrogen", "He":"Helium", "Li":"Lithium", "Be":"Beryllium", "B":"Boron", "C":"Carbon", "N":"Nitrogen", "O":"Oxygen", "F":"Fluorine", "Ne":"Neon", "Na":"Sodium", "Mg":"Magnesium", "Al":"Aluminium", "Si":"Silicon", "P":"Phosphorus", "S":"Sulphur", "Cl":"Chlorine", "Ar":"Argon", "K":"Pota...
elements__symbols__reverse = {'H': 'Hydrogen', 'He': 'Helium', 'Li': 'Lithium', 'Be': 'Beryllium', 'B': 'Boron', 'C': 'Carbon', 'N': 'Nitrogen', 'O': 'Oxygen', 'F': 'Fluorine', 'Ne': 'Neon', 'Na': 'Sodium', 'Mg': 'Magnesium', 'Al': 'Aluminium', 'Si': 'Silicon', 'P': 'Phosphorus', 'S': 'Sulphur', 'Cl': 'Chlorine', 'Ar':...
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not ...
""" Created on Jan 8, 2020 @author: ballance """ class Testdata(object): def __init__(self, teststatus, toolcategory: str, date: str, simtime: float=0.0, timeunit: str='ns', runcwd: str='.', cputime: float=0.0, seed: str='0', cmd: str='', args: str='', compulsory: int=0, user: str='user', cost: float=0.0): ...
def even_numbers(numbers): even = [] for num in numbers: if num % 2 == 0: even.append(num) return even def odd_numbers(numbers): odd = [] for num in numbers: if num % 2 != 0: odd.append(num) return odd def sum_numbers(numbers): sum = 0 for num ...
def even_numbers(numbers): even = [] for num in numbers: if num % 2 == 0: even.append(num) return even def odd_numbers(numbers): odd = [] for num in numbers: if num % 2 != 0: odd.append(num) return odd def sum_numbers(numbers): sum = 0 for num in...
''' disjoint set forest implementation, uses union by rank and path compression worst case T.C for find_set is O(logn) in first find_set operation T.C for union and create_set is O(1) ''' class Node: # the identity of node(member of set) is given by data, parent_link, rank def __init__(self, data=None, rank=N...
""" disjoint set forest implementation, uses union by rank and path compression worst case T.C for find_set is O(logn) in first find_set operation T.C for union and create_set is O(1) """ class Node: def __init__(self, data=None, rank=None, parent_link=None): self.data = data self.rank = rank ...
'''# from app.game import determine_winner # FYI normally we'd have this application code (determine_winner()) in another file, # ... but for this exercise we'll keep it here def determine_winner(user_choice, computer_choice): return "rock" # todo: write logic here to make the tests pass! if user_choice == com...
"""# from app.game import determine_winner # FYI normally we'd have this application code (determine_winner()) in another file, # ... but for this exercise we'll keep it here def determine_winner(user_choice, computer_choice): return "rock" # todo: write logic here to make the tests pass! if user_choice == com...
N = int(input()) a = list(map(int, input().split())) for i, _ in sorted(enumerate(a), key=lambda x: x[1], reverse=True): print(i + 1)
n = int(input()) a = list(map(int, input().split())) for (i, _) in sorted(enumerate(a), key=lambda x: x[1], reverse=True): print(i + 1)
class Environment: def __init__(self, width=1000, height=1000): self.width = width self.height = height self.agent = None self.doors = [] def add_door(self, door): self.doors.append(door) def get_env_size(self): size = (self.height, self.width) return size
class Environment: def __init__(self, width=1000, height=1000): self.width = width self.height = height self.agent = None self.doors = [] def add_door(self, door): self.doors.append(door) def get_env_size(self): size = (self.height, self.width) retu...
# custom exceptions class PybamWarn(Exception): pass class PybamError(Exception): pass
class Pybamwarn(Exception): pass class Pybamerror(Exception): pass
################################################################################ # Copyright (c) 2015-2018 Skymind, Inc. # # This program and the accompanying materials are made available under the # terms of the Apache License, Version 2.0 which is available at # https://www.apache.org/licenses/LICENSE-2.0. # # Unless...
class Optype(object): transform = 0 accumulation = 1 index_accumulation = 2 scalar = 3 broadcast = 4 pairwise = 5 accumulation3 = 6 summarystats = 7 shape = 8 aggregation = 9 random = 10 custom = 11 graph = 12 variable = 30 boolean = 40 logic = 119
'''Given a binary string s, return true if the longest contiguous segment of 1s is strictly longer than the longest contiguous segment of 0s in s. Return false otherwise. For example, in s = "110100010" the longest contiguous segment of 1s has length 2, and the longest contiguous segment of 0s has length 3. Note that ...
"""Given a binary string s, return true if the longest contiguous segment of 1s is strictly longer than the longest contiguous segment of 0s in s. Return false otherwise. For example, in s = "110100010" the longest contiguous segment of 1s has length 2, and the longest contiguous segment of 0s has length 3. Note that ...
class UndergroundSystem(object): def __init__(self): # record the customer's starting trip # card ID: [station, t] self.customer_trip = {} # record the average travel time from start station to end station # (start, end): [t, times] self.trips = {} def checkIn(...
class Undergroundsystem(object): def __init__(self): self.customer_trip = {} self.trips = {} def check_in(self, id, stationName, t): self.customer_trip[id] = [stationName, t] def check_out(self, id, stationName, t): (start_station, start_t) = self.customer_trip[id] ...
# Black list for auto vote cast Blacklist_team = ["Royal Never Give Up", "NAVI"] Blacklist_game = ["CSGO"] Blacklist_event = [] # Program debug debugLevel = 0 # Switch of auto vote cast function autoVote = True # Cycle of tasks (seconds) cycleTime = 1800
blacklist_team = ['Royal Never Give Up', 'NAVI'] blacklist_game = ['CSGO'] blacklist_event = [] debug_level = 0 auto_vote = True cycle_time = 1800
print("Calorie Calulator") FAT = float(input("Enter grams of fat: ")) CARBOHYDRATES = float(input("Enter grams of Carbohydrates: ")) PROTEIN= float(input("Enter grams of Protein: ")) Fatg = 9 * FAT print("Number of calories from Fat is: " + str(Fatg)) Protieng = 4 * PROTEIN print("Number of calories from Prote...
print('Calorie Calulator') fat = float(input('Enter grams of fat: ')) carbohydrates = float(input('Enter grams of Carbohydrates: ')) protein = float(input('Enter grams of Protein: ')) fatg = 9 * FAT print('Number of calories from Fat is: ' + str(Fatg)) protieng = 4 * PROTEIN print('Number of calories from Protein is: '...
# sudoku solver with backtracking algorithm... board = [[4,0,0,0,1,0,3,0,0], [0,6,0,4,0,7,0,0,0], [0,5,0,0,3,2,1,4,0], [9,0,4,0,0,1,0,8,5], [0,0,6,0,0,0,9,0,0], [3,1,0,7,0,0,6,0,4], [0,4,9,5,7,0,0,3,0], [0,0,0,1,0,4,0,7,0], [0,0,1,0,9,0,0,0,2]] ...
board = [[4, 0, 0, 0, 1, 0, 3, 0, 0], [0, 6, 0, 4, 0, 7, 0, 0, 0], [0, 5, 0, 0, 3, 2, 1, 4, 0], [9, 0, 4, 0, 0, 1, 0, 8, 5], [0, 0, 6, 0, 0, 0, 9, 0, 0], [3, 1, 0, 7, 0, 0, 6, 0, 4], [0, 4, 9, 5, 7, 0, 0, 3, 0], [0, 0, 0, 1, 0, 4, 0, 7, 0], [0, 0, 1, 0, 9, 0, 0, 0, 2]] def find_empty(): for i in range(0, 9): ...
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- # ----------------------------------------------------------------------------- # # P A G E B O T E X A M P L E S # # Copyright (c) 2017 Thom Janssen <https://github.com/thomgb> # www.pagebot.io # Licensed under MIT conditions # # Supporting DrawBot, w...
empty_bytes = bytes(4) print(type(empty_bytes)) print(empty_bytes) mutable_bytes = bytearray(empty_bytes) print(mutable_bytes) mutable_bytes = bytearray(b'\x00\x0f') mutable_bytes[0] = 255 mutable_bytes.append(255) print(mutable_bytes) immutable_bytes = bytes(mutable_bytes) print(immutable_bytes) s = b'bla' print(s.dec...
# import math # import numpy as np def lagrange(f, xs, x): ys = [f(i) for i in xs] n = len(xs) y = 0 for k in range(0, n): t = 1 for j in range(0, n): if j != k: s = (x - xs[j]) / (xs[k] - xs[j]) t = t * s y = y + t * ys[k] retur...
def lagrange(f, xs, x): ys = [f(i) for i in xs] n = len(xs) y = 0 for k in range(0, n): t = 1 for j in range(0, n): if j != k: s = (x - xs[j]) / (xs[k] - xs[j]) t = t * s y = y + t * ys[k] return y def difference_quotient(f, xs): ...
#! /usr/bin/env python3 ''' Problem 52 - Project Euler http://projecteuler.net/index.php?section=problems&id=052 ''' def samedigits(x,y): return set(str(x)) == set(str(y)) if __name__ == '__main__': maxn = 6 x = 1 while True: for n in range(2, maxn+1): if not samedigits(x, x * n): ...
""" Problem 52 - Project Euler http://projecteuler.net/index.php?section=problems&id=052 """ def samedigits(x, y): return set(str(x)) == set(str(y)) if __name__ == '__main__': maxn = 6 x = 1 while True: for n in range(2, maxn + 1): if not samedigits(x, x * n): break ...
''' Given an array of integers what is the length of the longest subArray containing no more than two distinct values such that the distinct values differ by no more than 1 For Example: arr = [0, 1, 2, 1, 2, 3] -> length = 4; [1,2,1,2] arr = [1, 2, 3, 4, 5] -> length = 2; [1,2] arr = [1, 1, 1, 3, 3, 2, 2] -> length = ...
""" Given an array of integers what is the length of the longest subArray containing no more than two distinct values such that the distinct values differ by no more than 1 For Example: arr = [0, 1, 2, 1, 2, 3] -> length = 4; [1,2,1,2] arr = [1, 2, 3, 4, 5] -> length = 2; [1,2] arr = [1, 1, 1, 3, 3, 2, 2] -> length = ...
#!/usr/bin/env python3 # # --- Day 21: Dirac Dice / Part Two --- # # Now that you're warmed up, it's time to play the real game. # # A second compartment opens, this time labeled Dirac dice. Out of it falls # a single three-sided die. # # As you experiment with the die, you feel a little strange. An informational # bro...
input_file = 'input.txt' goal = 21 player_1 = 0 player_2 = 1 cache = {} def game(possibilities, positions, scores, turn=0): uuid = (tuple(positions), tuple(scores), turn) if uuid in CACHE: return CACHE[uuid] player = PLAYER_1 if turn % 2 == 0 else PLAYER_2 turn = (turn + 1) % 2 wins = [0, 0...
# write recursively # ie # 10 > 7+3 or 5+5 # 7+3 is done # 5+5 -> 3 + 2 + 5 # 3+ 2 + 5 -> 3 + 2 + 3 + 2 is done # if the number youre breaking is even you get 2 initially, if its odd you get 1 more sum def solve(): raise NotImplementedError if __name__ == '__main__': print(solve())
def solve(): raise NotImplementedError if __name__ == '__main__': print(solve())
guest = input() host = input() pile = input() print("YES" if sorted(pile) == sorted(guest + host) else "NO")
guest = input() host = input() pile = input() print('YES' if sorted(pile) == sorted(guest + host) else 'NO')
# -*- coding: utf-8 -*- def write_out(message): with open('/tmp/out', 'w') as f: f.write("We have triggered.") f.write(message)
def write_out(message): with open('/tmp/out', 'w') as f: f.write('We have triggered.') f.write(message)
class Arithmatic: #This function does adding to integer def Add(self, x, y): return x + y #This fnction does su def Subtraction(self, x, y): return x - y
class Arithmatic: def add(self, x, y): return x + y def subtraction(self, x, y): return x - y
def category(cat): def set_cat(cmd): cmd.category = cat.title() return cmd return set_cat
def category(cat): def set_cat(cmd): cmd.category = cat.title() return cmd return set_cat
class Solution: def isAdditiveNumber(self, num: str) -> bool: def isValid(str1, str2, num): if not num: return True res = str(int(str1) + int(str2)) # print(str1, str2, res, num) str1, str2 = str2, res l = len(res) retur...
class Solution: def is_additive_number(self, num: str) -> bool: def is_valid(str1, str2, num): if not num: return True res = str(int(str1) + int(str2)) (str1, str2) = (str2, res) l = len(res) return num.startswith(res) and is_vali...
if __name__ == '__main__': if (1!=1) : print("IF") else : print("InnerElse") else: print("OuterElse")
if __name__ == '__main__': if 1 != 1: print('IF') else: print('InnerElse') else: print('OuterElse')
num = int(input()) lista = [[0] * num for i in range(num)] for i in range(num): for j in range(num): if i < j: lista[i][j] = 0 elif i > j: lista[i][j] = 2 else: lista[i][j] = 1 for r in lista: print(' '.join([str(elem) for elem in r]))
num = int(input()) lista = [[0] * num for i in range(num)] for i in range(num): for j in range(num): if i < j: lista[i][j] = 0 elif i > j: lista[i][j] = 2 else: lista[i][j] = 1 for r in lista: print(' '.join([str(elem) for elem in r]))
def aumentar(preco=0, taxa=0, formato=False): res = preco + (preco * taxa/100) return res if formato is False else moeda(res) def diminuir(preco=0, taxa=0, formato=False): res = preco - (preco * taxa/100) return res if formato is False else moeda(res) def dobro(preco=0, formato=False): res = pre...
def aumentar(preco=0, taxa=0, formato=False): res = preco + preco * taxa / 100 return res if formato is False else moeda(res) def diminuir(preco=0, taxa=0, formato=False): res = preco - preco * taxa / 100 return res if formato is False else moeda(res) def dobro(preco=0, formato=False): res = preco...
def test(): # Here we can either check objects created in the solution code, or the # string value of the solution, available as __solution__. A helper for # printing formatted messages is available as __msg__. See the testTemplate # in the meta.json for details. # If an assertion fails, the messag...
def test(): assert first_author_name == dataset_description['Authors'][0]['Name'], 'That is not the authors name from the original dictionary' assert 'first_author_name = output' in __solution__, 'Did you just typed the name in?' __msg__.good('Well done!')
class PartyAnimal: x = 0 def party(self): self.x = self.x + 1 print(f'So far {self.x}') an = PartyAnimal() an.party() an.party() an.party() print(dir(an))
class Partyanimal: x = 0 def party(self): self.x = self.x + 1 print(f'So far {self.x}') an = party_animal() an.party() an.party() an.party() print(dir(an))
with open("./build-scripts/opcodes.txt", "r") as f: opcodes = f.readlines() opcodes_h = open("./src/core/bc_data/opcodes.txt", "w") opcodes_h.write("enum au_opcode {\n") callbacks_h = open("./src/core/bc_data/callbacks.txt", "w") callbacks_h.write("static void *cb[] = {\n") dbg_h = open("./src/core/bc_data/dbg.t...
with open('./build-scripts/opcodes.txt', 'r') as f: opcodes = f.readlines() opcodes_h = open('./src/core/bc_data/opcodes.txt', 'w') opcodes_h.write('enum au_opcode {\n') callbacks_h = open('./src/core/bc_data/callbacks.txt', 'w') callbacks_h.write('static void *cb[] = {\n') dbg_h = open('./src/core/bc_data/dbg.txt'...
# lets make a Player class class Player: def __init__(self, name, starting_room): self.name = name self.current_room = starting_room
class Player: def __init__(self, name, starting_room): self.name = name self.current_room = starting_room
#!/usr/local/bin/python3 # Frequency queries def freqQuery(queries): result = [] numbers = {} occurrences = {} for operation, value in queries: if operation == 1: quantity = numbers.get(value, 0) if quantity > 0: occurrences[quantity] = occurrences[quantity] - 1 numbers[value] = numbers.get(value...
def freq_query(queries): result = [] numbers = {} occurrences = {} for (operation, value) in queries: if operation == 1: quantity = numbers.get(value, 0) if quantity > 0: occurrences[quantity] = occurrences[quantity] - 1 numbers[value] = number...
#GuestList: names = ['tony','steve','thor'] message = ", You are invited!" print(names[0]+message) print(names[1]+message) print(names[2]+message)
names = ['tony', 'steve', 'thor'] message = ', You are invited!' print(names[0] + message) print(names[1] + message) print(names[2] + message)
general = { 'provide-edep-targets' : True, } edeps = { 'zmdep-b' : { 'rootdir': '../zmdep-b', 'export-includes' : '../zmdep-b', 'buildtypes-map' : { 'debug' : 'mydebug', 'release' : 'myrelease', }, }, } subdirs = [ 'libs/core', 'libs/engine' ] ta...
general = {'provide-edep-targets': True} edeps = {'zmdep-b': {'rootdir': '../zmdep-b', 'export-includes': '../zmdep-b', 'buildtypes-map': {'debug': 'mydebug', 'release': 'myrelease'}}} subdirs = ['libs/core', 'libs/engine'] tasks = {'main': {'features': 'cxxprogram', 'source': 'main/main.cpp', 'includes': 'libs', 'use'...
#exercicio 63 termos = int(input('Quantos termos vc quer na sequencia de fibonacci? ')) c = 1 sequencia = 1 sequencia2 = 0 while c != termos: fi = (sequencia+sequencia2) - ((sequencia+sequencia2)-sequencia2) print ('{}'.format(fi), end='- ') sequencia += sequencia2 sequencia2 = sequencia - sequencia2 ...
termos = int(input('Quantos termos vc quer na sequencia de fibonacci? ')) c = 1 sequencia = 1 sequencia2 = 0 while c != termos: fi = sequencia + sequencia2 - (sequencia + sequencia2 - sequencia2) print('{}'.format(fi), end='- ') sequencia += sequencia2 sequencia2 = sequencia - sequencia2 c += 1
##Create a target array in the given order def generate_target_array(nums, index): length_of_num = len(nums) target_array = [] for i in range(0, length_of_num): if index[i] >= length_of_num: target_array.append(nums[i]) else: target_array.insert(index[i], nums[i]) ...
def generate_target_array(nums, index): length_of_num = len(nums) target_array = [] for i in range(0, length_of_num): if index[i] >= length_of_num: target_array.append(nums[i]) else: target_array.insert(index[i], nums[i]) return target_array if __name__ == '__main...
def Capital_letter(func): #This function receive another function def Wrapper(text): return func(text).upper() return Wrapper @Capital_letter def message(name): return f'{name}, you have received a message' print(message('Yery'))
def capital_letter(func): def wrapper(text): return func(text).upper() return Wrapper @Capital_letter def message(name): return f'{name}, you have received a message' print(message('Yery'))
# Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. class Encumbrance: speed_multiplier = 1 to_hit_modifier = 0 @classmethod def get_encumbrance_state(cls, w...
class Encumbrance: speed_multiplier = 1 to_hit_modifier = 0 @classmethod def get_encumbrance_state(cls, weight, capacity): if weight <= capacity: return Unencumbered elif weight <= 1.5 * capacity: return Burdened elif weight <= 2 * capacity: r...
_base_ = [ '../_base_/models/r50_multihead.py', '../_base_/datasets/imagenet_color_sz224_4xbs64.py', '../_base_/default_runtime.py', ] # model settings model = dict( backbone=dict(frozen_stages=4), head=dict(num_classes=1000)) # optimizer optimizer = dict( type='SGD', lr=0.01, momentum...
_base_ = ['../_base_/models/r50_multihead.py', '../_base_/datasets/imagenet_color_sz224_4xbs64.py', '../_base_/default_runtime.py'] model = dict(backbone=dict(frozen_stages=4), head=dict(num_classes=1000)) optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001, nesterov=True, paramwise_options={'(bn|ln...
n = int(input()) if n == 2: print(2) else: if n%2 == 0: n -= 1 for i in range(n, 1, -2): flag = True size = int(pow(i,0.5)) for j in range(3, size+1): if i % j == 0: flag = False break if flag: prin...
n = int(input()) if n == 2: print(2) else: if n % 2 == 0: n -= 1 for i in range(n, 1, -2): flag = True size = int(pow(i, 0.5)) for j in range(3, size + 1): if i % j == 0: flag = False break if flag: print(i) ...
height = int(input()) for i in range(height,0,-1): for j in range(i,height): print(end=" ") for j in range(1,i+1): if(i%2 != 0): c = chr(i+64) print(c,end=" ") else: print(i,end=" ") print() # Sample Input :- 5 # Output :- # E E E E E ...
height = int(input()) for i in range(height, 0, -1): for j in range(i, height): print(end=' ') for j in range(1, i + 1): if i % 2 != 0: c = chr(i + 64) print(c, end=' ') else: print(i, end=' ') print()
# ---------------------------------------------------------------------------- # CLASSES: nightly # # Test Case: moveoperators.py # # Tests: plots - Pseudocolor, Mesh, FilledBoundary # operators - Erase, Isosurface, Reflect, Slice, Transform # # Defect ID: '1837 # # Programmer: Brad Whitloc...
def init_annotation(): a = annotation_attributes() turn_off_all_annotations(a) a.axes2D.visible = 1 a.axes2D.xAxis.label.visible = 0 a.axes2D.yAxis.label.visible = 0 a.axes2D.xAxis.title.visible = 0 a.axes2D.yAxis.title.visible = 0 a.axes3D.bboxFlag = 1 set_annotation_attributes(a) ...
gibber = input("What's the gibberish?: ") direction = input("Left/Right?: ") retry = int(input("How much do you want to try?: ")) charlist = "abcdefghijklmnopqrstuvwxyz " dictionary = {} index = 0 for e in charlist: dictionary[e] = index index += 1 jump = 1 if direction == "Right": for cycle in range(retr...
gibber = input("What's the gibberish?: ") direction = input('Left/Right?: ') retry = int(input('How much do you want to try?: ')) charlist = 'abcdefghijklmnopqrstuvwxyz ' dictionary = {} index = 0 for e in charlist: dictionary[e] = index index += 1 jump = 1 if direction == 'Right': for cycle in range(retry)...
def find(f, df, ddf, a, b, eps): fa = f(a) dfa = df(a) ddfa = ddf(a) fb = f(b) dfb = df(b) ddfb = ddf(b) if not ( (fa * fb < 0) and ((dfa > 0 and dfb > 0) or (dfa < 0 and dfb < 0)) and ((ddfa > 0 and ddfb > 0) or (ddfa < 0 and ddfb < 0)) ): return cu...
def find(f, df, ddf, a, b, eps): fa = f(a) dfa = df(a) ddfa = ddf(a) fb = f(b) dfb = df(b) ddfb = ddf(b) if not (fa * fb < 0 and (dfa > 0 and dfb > 0 or (dfa < 0 and dfb < 0)) and (ddfa > 0 and ddfb > 0 or (ddfa < 0 and ddfb < 0))): return currx = a if fa * ddfa > 0 else b pr...
class Card: # Game card. def __init__(self, number, color, ability, wild): # Number on the face of the card self.number = number # Which color is the thing self.color = color # Draw 2 / Reverse etc self.ability = ability # Wild card? self.wild = wild def __eq__(self, other): return (self.num...
class Card: def __init__(self, number, color, ability, wild): self.number = number self.color = color self.ability = ability self.wild = wild def __eq__(self, other): return self.number == other.number and self.color == other.color and (self.ability == other.ability) an...
#!/usr/bin/env python3 def get_input() -> list[str]: with open('./input', 'r') as f: return [v for v in [v.strip() for v in f.readlines()] if v] def _get_input_raw() -> list[str]: with open('./input', 'r') as f: return [v.strip() for v in f.readlines()] def get_input_by_chunks() -> list[lis...
def get_input() -> list[str]: with open('./input', 'r') as f: return [v for v in [v.strip() for v in f.readlines()] if v] def _get_input_raw() -> list[str]: with open('./input', 'r') as f: return [v.strip() for v in f.readlines()] def get_input_by_chunks() -> list[list[str]]: raw_input = _...
#Anagram Detection #reads 2 strings st1 = input("Enter a string: ") st2 = input("Enter another string: ") #check if their lengths are equal if len(st1) == len(st2): #create a list n = len(st1)-1 list1 = list() while n >= 0: list1.append(st1[n]) n -= 1 m = len(st2)-1 list2 = list() while m >= 0:...
st1 = input('Enter a string: ') st2 = input('Enter another string: ') if len(st1) == len(st2): n = len(st1) - 1 list1 = list() while n >= 0: list1.append(st1[n]) n -= 1 m = len(st2) - 1 list2 = list() while m >= 0: list2.append(st2[m]) m -= 1 list1.sort() ...
TURNS = {"R": -1j, "L": 1j} instructions = tuple((inst[0], int(inst[1:])) for inst in open("input").read().strip().split(", ")) position, direction = (0 + 0j), (0 + 1j) visited_locations = set() first_twice_location = 0 + 0j for turn, dist in instructions: direction *= TURNS[turn] for _ in range(dist): ...
turns = {'R': -1j, 'L': 1j} instructions = tuple(((inst[0], int(inst[1:])) for inst in open('input').read().strip().split(', '))) (position, direction) = (0 + 0j, 0 + 1j) visited_locations = set() first_twice_location = 0 + 0j for (turn, dist) in instructions: direction *= TURNS[turn] for _ in range(dist): ...
#!/usr/bin/env python3 # Define n n = 5 # Store Outputs sum = 0 facr = 1 # Loop for i in range(1,n+1): sum = sum + i facr = facr * i print(n,sum,facr)
n = 5 sum = 0 facr = 1 for i in range(1, n + 1): sum = sum + i facr = facr * i print(n, sum, facr)
AppLayout(header=header_button, left_sidebar=None, center=center_button, right_sidebar=None, footer=footer_button)
app_layout(header=header_button, left_sidebar=None, center=center_button, right_sidebar=None, footer=footer_button)
class Result: def __init__(self, result: bool, error = None, item = None, list = [], comment = None): self.result = result self.error = error self.item = item self.list = list self.comment = comment
class Result: def __init__(self, result: bool, error=None, item=None, list=[], comment=None): self.result = result self.error = error self.item = item self.list = list self.comment = comment
# Copyright 2019 StreamSets Inc. # # 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 writi...
batch = sdc.createBatch() record = sdc.createRecord('bindings test') record.value = {} record.value['batchSize'] = sdc.batchSize record.value['numThreads'] = sdc.numThreads record.value['lastOffsets'] = sdc.lastOffsets record.value['params'] = sdc.userParams record.value['isStopped()'] = sdc.isStopped() record.value['p...
def select_outside(low, high, *values): result = [] for v in values: if (v < low) or (v > high): result.append(v) return result print(select_outside(0, 1.0, 0.3, -0.2, -0.5, 0.4, 1.7))
def select_outside(low, high, *values): result = [] for v in values: if v < low or v > high: result.append(v) return result print(select_outside(0, 1.0, 0.3, -0.2, -0.5, 0.4, 1.7))
''' Python tuple is a sequence, which can store heterogeneous data types such as integers, floats, strings, lists, and dictionaries. Tuples are written with round brackets and individual objects within the tuple are separated by a comma. The two biggest differences between a tuple and a list are that a tup...
""" Python tuple is a sequence, which can store heterogeneous data types such as integers, floats, strings, lists, and dictionaries. Tuples are written with round brackets and individual objects within the tuple are separated by a comma. The two biggest differences between a tuple and a list are that a tuple is im...
'''Exceptions. :copyright: 2021, Jeroen van der Heijden <jeroen@cesbit.com> ''' class CompileError(Exception): pass class KeywordError(CompileError): pass class ReKeywordsChangedError(CompileError): pass class NameAssignedError(CompileError): pass class MissingRefError(CompileError): pass...
"""Exceptions. :copyright: 2021, Jeroen van der Heijden <jeroen@cesbit.com> """ class Compileerror(Exception): pass class Keyworderror(CompileError): pass class Rekeywordschangederror(CompileError): pass class Nameassignederror(CompileError): pass class Missingreferror(CompileError): pass cla...
class sensorVariables: def __init__(self): self.elevation = None self.vfov = None self.north = None self.roll = None self.range = None self.azimuth = None self.model = None self.fov = None self.type = None self.version = None @cla...
class Sensorvariables: def __init__(self): self.elevation = None self.vfov = None self.north = None self.roll = None self.range = None self.azimuth = None self.model = None self.fov = None self.type = None self.version = None @cla...
glossary = { 'and' : 'Logical and operator', 'or' : 'Logical or operator', 'False' : 'Boolean false value', 'True' : 'Boolean true value', 'for' : 'To create for loop', } print("and: " + glossary['and'] + "\n") print("or: " + glossary['or'] + "\n") print("False: " + glossary['False'] + "\n") pr...
glossary = {'and': 'Logical and operator', 'or': 'Logical or operator', 'False': 'Boolean false value', 'True': 'Boolean true value', 'for': 'To create for loop'} print('and: ' + glossary['and'] + '\n') print('or: ' + glossary['or'] + '\n') print('False: ' + glossary['False'] + '\n') print('True: ' + glossary['True'] +...
def test_add(): class Number: def __add__(self, other): return 4 + other def __radd__(self, other): return other + 4 a = Number() assert 3 + a == 7 assert a + 3 == 7
def test_add(): class Number: def __add__(self, other): return 4 + other def __radd__(self, other): return other + 4 a = number() assert 3 + a == 7 assert a + 3 == 7
MinZoneNum = 0 MaxZoneNum = 999 UberZoneEntId = 0 LevelMgrEntId = 1000 EditMgrEntId = 1001
min_zone_num = 0 max_zone_num = 999 uber_zone_ent_id = 0 level_mgr_ent_id = 1000 edit_mgr_ent_id = 1001
allwords=[] for category in bag_of_words.keys(): for word in bag_of_words[category].keys(): if word not in allwords: allwords.append(word) freq_term_matrix=[] for category in bag_of_words.keys(): new=[] for column in range(0,len(allwords)): if allwords[column] in bag_of_words[category].keys(): new.append(...
allwords = [] for category in bag_of_words.keys(): for word in bag_of_words[category].keys(): if word not in allwords: allwords.append(word) freq_term_matrix = [] for category in bag_of_words.keys(): new = [] for column in range(0, len(allwords)): if allwords[column] in bag_of_wo...
fh = open("Headlines", 'r') Word = input("Type your Word Here:") S = " " count = 1 while S: S = fh.readline() L = S.split() if Word in L: print("Line Number:", count, ":", S) count += 1
fh = open('Headlines', 'r') word = input('Type your Word Here:') s = ' ' count = 1 while S: s = fh.readline() l = S.split() if Word in L: print('Line Number:', count, ':', S) count += 1
string = "ugknbfddgicrmopn" string = "aaa" string = "jchzalrnumimnmhp" string = "haegwjzuvuyypxyu" string = "dvszwmarrgswjxmb" def check_vowels(string): vowels = 0 vowels += string.count("a") vowels += string.count("e") vowels += string.count("i") vowels += string.count("o") vowels += string.count("u") r...
string = 'ugknbfddgicrmopn' string = 'aaa' string = 'jchzalrnumimnmhp' string = 'haegwjzuvuyypxyu' string = 'dvszwmarrgswjxmb' def check_vowels(string): vowels = 0 vowels += string.count('a') vowels += string.count('e') vowels += string.count('i') vowels += string.count('o') vowels += string.co...
def lonely_integer(m): answer = 0 for x in m: answer = answer ^ x return answer a = int(input()) b = map(int, input().strip().split(" ")) print(lonely_integer(b))
def lonely_integer(m): answer = 0 for x in m: answer = answer ^ x return answer a = int(input()) b = map(int, input().strip().split(' ')) print(lonely_integer(b))
#!/usr/bin/python3 # -*- coding: utf-8 -*- def main(): age = 30 print(age) print(30) # Variable name snake case friend_age = 23 print(friend_age) PI = 3.14159 print(PI) RADIANS_TO_DEGREES = 180/PI print(RADIANS_TO_DEGREES) if __name__ == "__main__": main()
def main(): age = 30 print(age) print(30) friend_age = 23 print(friend_age) pi = 3.14159 print(PI) radians_to_degrees = 180 / PI print(RADIANS_TO_DEGREES) if __name__ == '__main__': main()
# -*- coding: utf-8 -*- # Every time function slice return a new object students = ['Tom', 'Mary', 'Ken', 'Billy', 'Mike'] # Get continuously subset of a range slice1 = students[0:3] print(slice1) slice2 = students[:3] print(slice2) slice3 = students[-3:] # last three print(slice3) slice4 = students[2:4] # 3rd ...
students = ['Tom', 'Mary', 'Ken', 'Billy', 'Mike'] slice1 = students[0:3] print(slice1) slice2 = students[:3] print(slice2) slice3 = students[-3:] print(slice3) slice4 = students[2:4] print(slice4) slice5 = students[:] print(slice5) print(list(range(100)[0:20:2])) print(list(range(100)[::5])) print('abcde'[0:3])
class LogHolder(): def __init__(self, dirpath, name): self.dirpath = dirpath self.name = name self.reset(suffix='train') def write_to_file(self): with open(self.dirpath + f'{self.name}-metrics-{self.suffix}.txt', 'a') as file: for i in self.metric_holder: file.write(str(i) + ' ') with open(self.di...
class Logholder: def __init__(self, dirpath, name): self.dirpath = dirpath self.name = name self.reset(suffix='train') def write_to_file(self): with open(self.dirpath + f'{self.name}-metrics-{self.suffix}.txt', 'a') as file: for i in self.metric_holder: ...
# This program calculates the sum of a series # of numbers entered by the user. max = 5 # The maximum number # Initialize an accumulator variable. total = 0.0 # Explain what we are doing. print('This program calculates the sum of') print(max, 'numbers you will enter.') # Get the numbers and accumulate them. fo...
max = 5 total = 0.0 print('This program calculates the sum of') print(max, 'numbers you will enter.') for counter in range(max): number = int(input('Enter a number: ')) total = total + number print('The total is', total)
class Solution: def maximum69Number (self, num: int) -> int: try: numstr = list(str(num)) numstr[numstr.index('6')]='9' return int("".join(numstr)) except: return num
class Solution: def maximum69_number(self, num: int) -> int: try: numstr = list(str(num)) numstr[numstr.index('6')] = '9' return int(''.join(numstr)) except: return num
class CurvedUniverse(): def __init__(self, shape_or_k = 0): self.shapes = {'o': -1, 'f': 0, 'c': 1} self.set_shape_or_k(shape_or_k) def set_shape_or_k(self, shape_or_k): if type(shape_or_k) == str: self.__dict__['shape'] = shape_or_k self.__dict__['k'] = self.shapes[shape_or_k] else: self.__dict__['...
class Curveduniverse: def __init__(self, shape_or_k=0): self.shapes = {'o': -1, 'f': 0, 'c': 1} self.set_shape_or_k(shape_or_k) def set_shape_or_k(self, shape_or_k): if type(shape_or_k) == str: self.__dict__['shape'] = shape_or_k self.__dict__['k'] = self.shapes...
keep_going = "y" while keep_going.startswith("y"): a_name = input("Enter a name: ").strip() with open("users.txt", "a") as file: file.write(a_name + "; ") keep_going = input("Insert another name? (y/n) ").strip()
keep_going = 'y' while keep_going.startswith('y'): a_name = input('Enter a name: ').strip() with open('users.txt', 'a') as file: file.write(a_name + '; ') keep_going = input('Insert another name? (y/n) ').strip()
# Conditional Statements in Python # If-else statements age = int(input("Input your age: ")) if age > 17: print("You are an adult") else: print("You are a minor") #If-elif-else statements number = int(input("Input a number: ")) if number > 5: print("Is greater than 5") elif number == 5: print("Is eq...
age = int(input('Input your age: ')) if age > 17: print('You are an adult') else: print('You are a minor') number = int(input('Input a number: ')) if number > 5: print('Is greater than 5') elif number == 5: print('Is equal to 5') else: print('Is less than 5')
# Your App secret key SECRET_KEY = "TXxWqZHAILwElJF2bKR8" DEFAULT_FEATURE_FLAGS: Dict[str, bool] = { # Note that: RowLevelSecurityFilter is only given by default to the Admin role # and the Admin Role does have the all_datasources security permission. # But, if users create a specific role with access to R...
secret_key = 'TXxWqZHAILwElJF2bKR8' default_feature_flags: Dict[str, bool] = {'ROW_LEVEL_SECURITY': True} superset_webserver_port = 8088 favicons = [{'href': '/static/assets/images/favicon.png'}] app_icon = '/static/assets/images/superset-logo-horiz.png' app_icon_width = 126 babel_default_locale = 'en' babel_default_fo...
N, Q = tuple(map(int, input().split())) LRT = [tuple(map(int, input().split())) for _ in range(Q)] A = [0 for _ in range(N)] for left, right, t in LRT: for i in range(left - 1, right): A[i] = t print(*A, sep="\n")
(n, q) = tuple(map(int, input().split())) lrt = [tuple(map(int, input().split())) for _ in range(Q)] a = [0 for _ in range(N)] for (left, right, t) in LRT: for i in range(left - 1, right): A[i] = t print(*A, sep='\n')
# AUTHOR: Dharma Teja # Python3 Concept:sum of digits in given number # GITHUB: https://github.com/dharmateja03 number=int(input()) #enter input l=list(str(number)) nums=list(map(int,l)) print(sum(nums))
number = int(input()) l = list(str(number)) nums = list(map(int, l)) print(sum(nums))
class DataThing: def __init__(self, _x): self.y = int(input("Enter a Y Value: ")) self.x = _x def __str__(self): ret = "{} {}".format(self.x, self.y) return ret def createSome(): x = int(input("Enter a X Value: ")) ret = DataThing(x) return ret ...
class Datathing: def __init__(self, _x): self.y = int(input('Enter a Y Value: ')) self.x = _x def __str__(self): ret = '{} {}'.format(self.x, self.y) return ret def create_some(): x = int(input('Enter a X Value: ')) ret = data_thing(x) return ret a = data_thi...
class Graph(): def __init__(self, vertices): self.V=vertices self.graph=[[0 for col in range(vertices)] for row in range(vertices)] def printSolution(self, dist): print ("Vertex \tDistance from Source") for node in range(self.V): print (node, "\t\t\t", dist[node]) def minDistance(self, d...
class Graph: def __init__(self, vertices): self.V = vertices self.graph = [[0 for col in range(vertices)] for row in range(vertices)] def print_solution(self, dist): print('Vertex \tDistance from Source') for node in range(self.V): print(node, '\t\t\t', dist[node]) ...
#input_column: b,string,VARCHAR(100),100,None,None #input_type: SET #output_column: b,string,VARCHAR(100),100,None,None #output_type: EMITS #!/bin/bash ls -l /tmp
ls - l / tmp
class BaseGenerator: pass class CharGenerator(BaseGenerator): pass
class Basegenerator: pass class Chargenerator(BaseGenerator): pass
# The self keyword is used when you want a method or # attribute to be for a specific object. This means that, # down below, each Tesla object can have different maxSpeed # and colors from each other. class Tesla: def __init__(self, maxSpeed=120, color="red"): self.maxSpeed = maxSpeed self.color =...
class Tesla: def __init__(self, maxSpeed=120, color='red'): self.maxSpeed = maxSpeed self.color = color def change(self, c): self.color = c p1 = tesla(140, 'blue') p2 = tesla(100, 'blue') p1.change('green') print(p1.color) p2.change('yellow') print(p2.color)