content
stringlengths
7
1.05M
localproibidoCalcada=430 localproibidofaixa=580 velocidademulta=70 falarnocel=830 tipodeinfracao=str(input('TIPO DE INFRAÇÃO: (calçada),(faixa),(celular)? ')).upper() velocidade=int(input('velocidade: ')) if tipodeinfracao=='CALÇADA': print('o valor a ser pago é {}R$ por estacionar na calçada'.format(localproibidoCalcada)) elif tipodeinfracao=='FAIXA': print('o valor a ser pago é {}R$ por estacionar em faixa de pedestre'.format(localproibidofaixa)) else: print('o valor a ser pago é {}R$ pela multa de falar no celular'.format(falarnocel)) print() if velocidade>50: velocidade=(velocidade-50)*70 print('Você ultrapassou o limite de velocidade, o valor a ser pago é {}R$'.format(velocidade)) print('fim ')
def wordPattern(self, pattern: str, str: str) -> bool: m = {} words = str.split() if len(pattern) != len(words): return False result = True for i in range(len(pattern)): if pattern[i] not in m: if words[i] in m.values(): return False m[pattern[i]] = words[i] elif m[pattern[i]] != words[i]: result = False return result
class ParseError(RuntimeError): """Exception to raise when parsing fails.""" class SyncError(RuntimeError): """Error class for general errors relating to the project sync process."""
# -*- coding: utf-8 -*- """ idfy_rest_client.models.file_format_331 This file was automatically generated for Idfy by APIMATIC v2.0 ( https://apimatic.io ) """ class FileFormat331(object): """Implementation of the 'fileFormat331' enum. TODO: type enum description here. Attributes: ENUM_NATIVE: TODO: type description here. PACKAGED: TODO: type description here. """ ENUM_NATIVE = 'native' PACKAGED = 'packaged'
#!usr/bin/python3.4 #!/usr/bin/python3.4 # Problem Set 0 # Name: xin zhong # Collaborators: # Time: 8:58-9:03 # last_name = input("Enter your last name:\n**") first_name = input("Enter your first name:\n**") print(first_name) print(last_name)
""" Exibe quantos produtos são maiores de R$1.000 e qual o mais barato """ print('-' * 50) print('ESTATISTICAS DE PRODUTOS') total = 0 mais_caros = 0 # mais de 1000 mais_barato = 0 n_barato = '' while True: produto = str(input('Nome de produto: ')).strip() preco = float(input('Preço do produto: R$')) total += preco if preco > 1000: mais_caros += 1 if mais_barato == 0: mais_barato = preco n_barato = produto if preco < mais_barato: mais_barato = preco n_barato = produto parada = str(input('Quer continuar? [S/N] ')) if parada in 'Sims': pass if parada in 'Naon': break print(f'O total foi de R${total:.2f}') print(f'Teve {mais_caros} produtos mais caros que R$1.000.') print(f'O produto mais barato foi {n_barato} com o valor de R${mais_barato:.2f}')
class Solution: def solveNQueens(self, n: int) -> List[List[str]]: ans = [] cols = [False] * n diag1 = [False] * (2 * n - 1) diag2 = [False] * (2 * n - 1) def dfs(i: int, board: List[int]) -> None: if i == n: ans.append(board) return for j in range(n): if cols[j] or diag1[i + j] or diag2[j - i + n - 1]: continue cols[j] = diag1[i + j] = diag2[j - i + n - 1] = True dfs(i + 1, board + ['.' * j + 'Q' + '.' * (n - j - 1)]) cols[j] = diag1[i + j] = diag2[j - i + n - 1] = False dfs(0, []) return ans
var = 'foo' def ex2(): var = 'bar' print('inside the function var is ', var) ex2() print('outside the function var is ', var) # should be bar, foo
class Hello: def __init__(self, name): self.name = name def greeting(self): print(f'Hello {self.name}')
listA = [1] listB = [1, 2, 3, 4, listA] listC = [1] listB *= 3 print(listB) print(listB[9] == listA) print(listB[4] is listA) print(listB[9] is listA) print(listB[9] is listC) print('-------------------------') print(listB.count(listA)) print(listB.count(listC)) print(listB.index(listC, 5)) print(listB.index(listC, 5, 10)) print('-------------------------') listA *= 3 print(listB)
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright SquirrelNetwork def string_generator(data_incoming): data = data_incoming.copy() del data['hash'] keys = sorted(data.keys()) string_arr = [] for key in keys: string_arr.append(key+'='+data[key]) string_cat = '\n'.join(string_arr) return string_cat
class UWB (Radio): """ Abstracts all communication over UWB options include: Ranging frequency | range after message """ def __init__(self): self._name = 'UWB' pass #
def fizzbuzz(x): if x % 3 == 0 and x % 5 != 0: r = 'Fizz' elif x % 3 != 0 and x % 5 ==0: r = 'Buzz' elif x % 3 == 0 and x % 5 ==0: r = 'FizzBuzz' else: r = x return r
class Tile: def __init__(self): self.first_visit = True self.tree_fallen = False def describe(self): print("You are walking through the trees. It looks like the path on " "your west leads to a small wooden hut.\n") if not self.first_visit and not self.tree_fallen: print("You saw a tree fall and it didn't make any sound and " "WOW... that was weird because you were there and " "observed it!\n") self.tree_fallen = True self.first_visit = False # "If a tree falls in a forest and no one is around to hear it, # does it make a sound?" is a philosophical thought experiment that # raises questions regarding observation and knowledge of reality. def action(self, player, do): print("Wat?!") def leave(self, player, direction): if direction == "s": print("Careful now! Nasty rocks all over to the south.\n" "(Meaning you just can't go to that direction. Sorry!)") return False else: return True
#ces fonctions sont importées dans "graphique.py" def intersect(a1, b1, a2, b2): """ Détection d'intersection entre deux intervalles : renvoie `false` si l'intersection de [a1;a2] et [b1;b2] est vide. Arguments: a1 et b1 (float): bornes du premier intervalle a2 et b2 (float): bornes du second intervalle """ return b1 > a2 and b2 > a1 def collision(x1, y1, w1, h1, x2, y2, w2, h2): """ Détection d'intersection entre deux rectangles : renvoie `true` si les deux rectangles se rencontrent Arguments: x1 et y1 (float): coordonnées du centre du premier rectangle w1 et h1 (float): largeur et hauteur du premier rectangle x2 et y2 (float): coordonnées du centre du second rectangle w2 et h2 (float): largeur et hauteur du second rectangle Alias: collisionRR() """ return intersect(x1 - w1 / 2, x1 + w1 / 2, x2 - w2 / 2, x2 + w2 / 2)\ and intersect(y1 - h1 / 2, y1 + h1 / 2, y2 - h2 / 2, y2 + h2 / 2) def collisionRR(x1, y1, w1, h1, x2, y2, w2, h2): collision(x1, y1, w1, h1, x2, y2, w2, h2) def collisionRC(x1, y1, w, h, x2, y2, r): """ Détection d'intersection entre un rectangle et un cercle : renvoie `true` si les deux objets se rencontrent Arguments: x1 et y1 (float): coordonnées du centre du rectangle w et h (float): largeur et hauteur du rectangle x2 et y2 (float): coordonnées du centre du cercle r (float): rayon du cercle """ if x2 > x1 + w / 2 + r: return False #le cercle est trop à droite du rectangle if x2 < x1 - w / 2 - r: return False #il est trop à gauche du rectangle if y2 > y1 + h / 2 + r: return False #cercle trop haut if y2 < y1 - h / 2 - r: return False #cercle trop haut if (x1 + w / 2 - x2) ** 2 + (y1 + h / 2 - y2) ** 2 > r ** 2: return False #cercle en haut à droite du rectangle, mais un peu trop loin du coin haut-droite if (x1 - w / 2 - x2) ** 2 + (y1 + h / 2 - y2) ** 2 > r ** 2: return False #cercle en haut à gauche du rectangle, mais un peu trop loin du coin haut-gauche if (x1 + w / 2 - x2) ** 2 + (y1 - h / 2 - y2) ** 2 > r ** 2: return False #cercle en bas à droite du rectangle, mais un peu trop loin du coin bas-droite if (x1 - w / 2 - x2) ** 2 + (y1 - h / 2 - y2) ** 2 > r ** 2: return False #cercle en bas à gauche du rectangle, mais un peu trop loin du coin bas-gauche return True
#!/usr/bin/python3 """matrix multiplication""" def matrix_mul(m_a, m_b): """matrix multiplication""" if not isinstance(m_a, list): raise TypeError("m_a must be a list") elif not isinstance(m_b, list): raise TypeError("m_b must be a list") elif not all(isinstance(row, list) for row in m_a): raise TypeError("m_a must be a list of lists") elif not all(isinstance(row, list) for row in m_b): raise TypeError("m_b must be a list of lists") elif m_a == [] or m_a == [[]]: raise ValueError("m_a can't be empty") elif m_b == [] or m_b == [[]]: raise ValueError("m_b can't be empty") elif not all((isinstance(ele, int) or isinstance(ele, float)) for ele in [x for row in m_a for x in row]): raise TypeError("m_a should contain only integers or floats") elif not all((isinstance(ele, int) or isinstance(ele, float)) for ele in [x for row in m_b for x in row]): raise TypeError("m_b should contain only integers or floats") if not all(len(row) == len(m_a[0]) for row in m_a): raise TypeError("each row of m_a must be of the same size") if not all(len(row) == len(m_b[0]) for row in m_b): raise TypeError("each row of m_b must be of the same size") if len(m_a[0]) != len(m_b): raise ValueError("m_a and m_b can't be multiplied") inverted_b = [] for row in range(len(m_b[0])): new_row = [] for column in range(len(m_b)): new_row.append(m_b[column][row]) inverted_b.append(new_row) new_matrix = [] for row in m_a: new_row = [] for col in inverted_b: prod = 0 for i in range(len(inverted_b[0])): prod += row[i] * col[i] new_row.append(prod) new_matrix.append(new_row) return new_matrix
#!/usr/bin/python3 with open('input.txt') as f: input = list(map(int, f.read().splitlines())) PREMABLE_LENGTH = 25 idx = PREMABLE_LENGTH while idx < len(input): section = input[idx - PREMABLE_LENGTH:idx] target = input[idx] found = False for i, j in enumerate(section): if target - j in section[i+1:]: idx += 1 found = True break if not found: print(target) break invalid = input[idx] section = input[:idx] start = 0 end = 1 tot = sum(section[start:end]) while tot != invalid: if tot < invalid: end += 1 if tot > invalid: start += 1 tot = sum(section[start:end]) print(min(section[start:end]) + max(section[start:end]))
FRAGMENT_LOG = ''' fragment fragmentLog on Log { id_ level message time } '''
#! Занятие по книге Python Crash Course, chapter 6, "Dictionaries". # Занятие первое. alien_0 = {} print(alien_0) # Начинаем с пустой библиотеки. alien_0[0], alien_0[1], alien_0[2] = {}, {}, {} alien_0[0]['color'], alien_0[0]['points'] = 'green', 5 alien_0[1]['color'], alien_0[1]['points'] = 'yellow', 10 alien_0[2]['color'], alien_0[2]['points'] = 'red', 15 print(alien_0) # Добавляем первые связки ' key - value '. # КЛЮЧ БИБЛИОТЕКИ МОЖЕТ БЫТЬ СПИСКОМ ИЛИ ДРУГОЙ БИБЛИОТЕКОЙ КАК value? print(alien_0[1]['color'], '\t', alien_0[2]['points']) print("You just earned " + str(alien_0[2]['points']) + " points!") # Координаты стартуют обычно из верхнего левого угла. alien_0[0]['x_position'], alien_0[0]['y_position'] = 0, 25 alien_0[1]['x_position'], alien_0[1]['y_position'] = 20, 25 alien_0[2]['x_position'], alien_0[2]['y_position'] = 50, 35 alien_0[0]['speed'], alien_0[1]['speed'] = 'slow', 'medium' alien_0[2]['speed'] = 'fast' # В библиотеках хранение имеет значение относительно доступа не по # "порядку", а по связке " key - value ". print(alien_0) # Eщё связочки ' key - value '. for alien in alien_0: if alien_0[alien]['speed'] == 'slow': x_increment = 1 elif alien_0[alien]['speed'] == 'medium': x_increment = 2 else: x_increment = 3 alien_0[alien]['x_position'] = (alien_0[alien]['x_position'] + x_increment) print("Aliens are running!") # Инопланетяне побежали прочь! for alien in alien_0: print("Alien", alien_0[alien]['color'], "have just moved to", alien_0[alien]['x_position'], "!") # ДАВНО ХОТЕЛ СПРОСИТЬ : МОЖНО ЛИ В КОДЕ ВЕРНУТЬСЯ К ВЫПОЛНЕНИЮ КАКОГО # НИБУДЬ КОНКРЕТНОГО УЧАСТКА, ЧТО БЫЛ ПРЕЖДЕ? ТИПА НАПИСАТЬ - ЧТОБЫ # ВЫПОЛНИИСЬ lines С 31 ПО 38 И ТОЛЬКО ОНИ, КОГДА НАДО ПОСЛЕ УЖЕ # ВЫПОЛНИТЬ. ТО ЕСТЬ, Я ПОНИМАЮ, ЧТО МОЖНО ИХ ЗАСУНУТЬ В ОТДЕЛЬНЫЙ # СКРИПТ И ВЫЗЫВАТЬ КОГДА НАДО. А МНЕ ИМЕННО ИНТЕРЕСНО - ИЗ ЭТОГО ЖЕ # КОДА МОЖНО ВЫЗВАТЬ ОТДЕЛЬНЫЕ ВЫШЕЗАПИСАННЫЕ СТРОКИ?
def LevenshteinDistance(v, w): v = '-' + v w = '-' + w S = [[0 for i in range(len(w))] for j in range(len(v))] for i in range(1, len(S)): S[i][0] = S[i - 1][0] + 1 for j in range(1, len(S[0])): S[0][j] = S[0][j - 1] + 1 for i in range(1, len(v)): for j in range(1, len(w)): diag = S[i - 1][j - 1] + (1 if v[i] != w[j] else 0) down = S[i - 1][j] + 1 right = S[i][j - 1] + 1 S[i][j] = min([down, right, diag]) return S[len(v) - 1][len(w) - 1] if __name__ == "__main__": v = input().rstrip() w = input().rstrip() print(LevenshteinDistance(v, w))
"""Collection of small helper functions""" def create_singleton(name): """Helper function to create a singleton class""" type_dict = {'__slots__': (), '__str__': lambda self: name, '__repr__': lambda self: name} return type(name, (object,), type_dict)()
input = [4, 6, 2, 9, 1] # for i in range(len(array) - 1): # for j in range(i + 1, len(array)): # if array[i] > array[j]: # array[i], array[j] = array[j], array[i] def bubble_sort(array): # 이 부분을 채워보세요! n = len(array) for i in range(n - 1): for j in range(n - i - 1): if array[j] > array[j + 1]: array[j], array[j + 1] = array[j + 1], array[j] return bubble_sort(input) print(input) # [1, 2, 4, 6, 9] 가 되어야 합니다!
print('{:#^40}'.format(' Medidor de Tinta ')) altura = float(input('Qual a alura da sua parede?')) largura = float(float(input('Qual a altura da sua parede?'))) m2 = altura * largura tinta = m2 / 2 print(f"""\nSua parede tem {altura:.2f}m de altura e {largura:.2f}m de largura totalizando {m2:.2f}m2 Dessa forma serão necessários {tinta:.2f} litros de tinta para pintá-la""")
DEBUG = False def set_verbose(value: bool) -> None: """Change the DEBUG value to be verbose or not. Args: value (bool): Verbosity on or off. """ global DEBUG DEBUG = value def log(message: str) -> None: """Logs the message to stdout if DEBUG is enabled. Args: message (str): Message to be logged. """ global DEBUG if DEBUG: print(message)
with open("water.in", "r") as input_file: input_list = [line.strip() for line in input_file] with open("water.out", "w") as output_file: for binary_diameter in input_list: print(round((2/3 * 3.14 * (int(binary_diameter, 2) ** 3)) / 1000), file=output_file)
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Copyright (c) 2016 Vobile Inc. All Rights Reserved. Author: xu_xiaorong Email: xu_xiaorong@mycompany.cn Created_at: 2016-08-10 13:46:10 ''' LOG_HANDLER = None # None means stdout, syslog means syslog LOG_LEVEL = 'INFO' QUEUE_NAME = "querier_queue" QUEUE_EXCHANGE = "querier_exchange" QUEUE_ROUTING_KEY = "querier_routing_key" MATCH_THRESHOLD = "22 22" #"sample reference"
def get_unithash(n: int): int(n) if (n == 0): return 0 elif (n % 9 == 0): return 9 else: return n % 9 def set_unithash(num: str, l: int): sanitation=[] sanitation[:0]=num for i in range(0,len(sanitation)): if (sanitation[i].isdigit())==False: sanitation[i]=abs(ord(sanitation[i])-96) num = ''.join([str(j) for j in sanitation]) hash = [(num[i:i+int(l)]) for i in range(0, len(num), int(l))] final_hash = [] for i in range(0,len(hash)): final_hash.append(get_unithash(int(hash[i]))) fin_hash = ''.join([str(i) for i in final_hash]) return int(fin_hash) #l = length of each group after number is broken #num = the actual number to be hashed
american_holidays = """1,2012-01-02,New Year Day 2,2012-01-16,Martin Luther King Jr. Day 3,2012-02-20,Presidents Day (Washingtons Birthday) 4,2012-05-28,Memorial Day 5,2012-07-04,Independence Day 6,2012-09-03,Labor Day 7,2012-10-08,Columbus Day 8,2012-11-12,Veterans Day 9,2012-11-22,Thanksgiving Day 10,2012-12-25,Christmas Day 11,2013-01-01,New Year Day 12,2013-01-21,Martin Luther King Jr. Day 13,2013-02-18,Presidents Day (Washingtons Birthday) 14,2013-05-27,Memorial Day 15,2013-07-04,Independence Day 16,2013-09-02,Labor Day 17,2013-10-14,Columbus Day 18,2013-11-11,Veterans Day 19,2013-11-28,Thanksgiving Day 20,2013-12-25,Christmas Day 21,2014-01-01,New Year Day 22,2014-01-20,Martin Luther King Jr. Day 23,2014-02-17,Presidents Day (Washingtons Birthday) 24,2014-05-26,Memorial Day 25,2014-07-04,Independence Day 26,2014-09-01,Labor Day 27,2014-10-13,Columbus Day 28,2014-11-11,Veterans Day 29,2014-11-27,Thanksgiving Day 30,2014-12-25,Christmas Day 31,2015-01-01,New Year Day 32,2015-01-19,Martin Luther King Jr. Day 33,2015-02-16,Presidents Day (Washingtons Birthday) 34,2015-05-25,Memorial Day 35,2015-07-03,Independence Day 36,2015-09-07,Labor Day 37,2015-10-12,Columbus Day 38,2015-11-11,Veterans Day 39,2015-11-26,Thanksgiving Day 40,2015-12-25,Christmas Day 41,2016-01-01,New Year Day 42,2016-01-18,Martin Luther King Jr. Day 43,2016-02-15,Presidents Day (Washingtons Birthday) 44,2016-05-30,Memorial Day 45,2016-07-04,Independence Day 46,2016-09-05,Labor Day 47,2016-10-10,Columbus Day 48,2016-11-11,Veterans Day 49,2016-11-24,Thanksgiving Day 50,2016-12-25,Christmas Day 51,2017-01-02,New Year Day 52,2017-01-16,Martin Luther King Jr. Day 53,2017-02-20,Presidents Day (Washingtons Birthday) 54,2017-05-29,Memorial Day 55,2017-07-04,Independence Day 56,2017-09-04,Labor Day 57,2017-10-09,Columbus Day 58,2017-11-10,Veterans Day 59,2017-11-23,Thanksgiving Day 60,2017-12-25,Christmas Day 61,2018-01-01,New Year Day 62,2018-01-15,Martin Luther King Jr. Day 63,2018-02-19,Presidents Day (Washingtons Birthday) 64,2018-05-28,Memorial Day 65,2018-07-04,Independence Day 66,2018-09-03,Labor Day 67,2018-10-08,Columbus Day 68,2018-11-12,Veterans Day 69,2018-11-22,Thanksgiving Day 70,2018-12-25,Christmas Day 71,2019-01-01,New Year Day 72,2019-01-21,Martin Luther King Jr. Day 73,2019-02-18,Presidents Day (Washingtons Birthday) 74,2019-05-27,Memorial Day 75,2019-07-04,Independence Day 76,2019-09-02,Labor Day 77,2019-10-14,Columbus Day 78,2019-11-11,Veterans Day 79,2019-11-28,Thanksgiving Day 80,2019-12-25,Christmas Day 81,2020-01-01,New Year Day 82,2020-01-20,Martin Luther King Jr. Day 83,2020-02-17,Presidents Day (Washingtons Birthday) 84,2020-05-25,Memorial Day 85,2020-07-03,Independence Day 86,2020-09-07,Labor Day 87,2020-10-12,Columbus Day 88,2020-11-11,Veterans Day 89,2020-11-26,Thanksgiving Day 90,2020-12-25,Christmas Day"""
# Base node class class Node: """Master node class.""" def __str__(self): return f"{type(self).__name__}"
class md_description: def __init__(self, path, prefix_ref, repetion_number, title_output, total_running): self.path = path self.prefix_ref = prefix_ref self.repetion_number = repetion_number self.title_output = title_output self.total_running = total_running # path where MD files are def get_path(self): return self.path # prefix for reference files: md for md.xtc, md.tpr and md.edr def get_prefix_ref(self): return self.prefix_ref # number of MD repetion def get_repetion_number(self): return self.repetion_number # title for output file name def get_title_output(self): return self.title_output # total running time in ps def get_total_running(self): return self.total_running # MD files must be prefix.rep. Ex: md.1, md.2 def get_simulation_prefix(self): return str(self.get_prefix_ref()) + "." + str(self.get_repetion_number())
class Solution: def minimumTotal(self, triangle: List[List[int]]) -> int: if triangle == []: return 0 for idx in range(1, len(triangle)): row = triangle[idx] prev_row = triangle[idx - 1] row[0] += prev_row[0] row[-1] += prev_row[-1] for idx in range(2, len(triangle)): row = triangle[idx] prev_row = triangle[idx - 1] for col in range(1, len(row) - 1): row[col] += min(prev_row[col - 1], prev_row[col]) return min(triangle[-1])
# -*- coding: utf-8 -*- AMOUNT_INDEX = 0 TYPE_INDEX = 1 RAT_TYPE = 'R' RABBIT_TYPE = 'C' FROG_TYPE = 'S' def main(): n = int(input()) animal_total = 0 rat_total = 0 rabbit_total = 0 frog_total = 0 for i in range(n): input_line = input().split() amount = int(input_line[AMOUNT_INDEX]) type = input_line[TYPE_INDEX] animal_total += amount if type == RAT_TYPE: rat_total += amount elif type == RABBIT_TYPE: rabbit_total += amount elif type == FROG_TYPE: frog_total += amount print('Total: {:d} cobaias'.format(animal_total)) print('Total de coelhos: {:d}'.format(rabbit_total)) print('Total de ratos: {:d}'.format(rat_total)) print('Total de sapos: {:d}'.format(frog_total)) print('Percentual de coelhos: {:.2f} %'.format((rabbit_total * 100) / animal_total)) print('Percentual de ratos: {:.2f} %'.format((rat_total * 100) / animal_total)) print('Percentual de sapos: {:.2f} %'.format((frog_total * 100) / animal_total)) if __name__ == '__main__': main()
# # This is a smaller script to just test the servos in the head # Start all services arduino = Runtime.start("arduino","Arduino") jaw = Runtime.start("jaw","Servo") rothead = Runtime.start("RotHead","Servo") leftEyeX = Runtime.start("LeftEyeX","Servo") rightEyeX = Runtime.start("RightEyeX","Servo") eyeY = Runtime.start("EyeY","Servo") # # Connect the Arduino arduino.connect("/dev/ttyACM0") # # Start of main script jaw.attach(arduino,9) jaw.setMinMax(80,120) # Connect the head turn left and right rothead.setRest(100) rothead.attach(arduino,8) rothead.setVelocity(20) rothead.rest() # Connect the left eye leftEyeX.setMinMax(50,110) leftEyeX.setRest(80) leftEyeX.attach(arduino,10) leftEyeX.rest() # Connect the right eye rightEyeX.setMinMax(60,120) rightEyeX.setRest(90) rightEyeX.attach(arduino,11) rightEyeX.rest() # Make the left eye follow the right # runtime.subscribe("rightEyeX","publishServoEvent","leftEyeY","MoveTo") # rightEyeX.eventsEnabled(True) # Connect eyes up/down eyeY.setMinMax(60,140) eyeY.setRest(90) eyeY.attach(arduino,12) eyeY.rest() def lookRight(): rightEyeX.moveTo(120) def lookLeft(): rightEyeX.moveTo(60) def lookForward(): rightEyeX.rest() eyeY.rest() def lookDown(): EyeY.moveTo(60) def lookUp(): EyeY.moveTo(140) def headRight(): rothead.moveTo(70) def headLeft(): rothead.moveTo(130) def headForward(): rothead.rest() lookRight() sleep(2) lookLeft() sleep(2) lookForward() sleep(2) lookUp() sleep(2) lookDown() sleep(2) lookForward() sleep(2) headRight() sleep(5) headLeft() # sleep(5) # headForward() # sleep(5)
''' Given a string, return a new string made of every other char starting with the first, so "Hello" yields "Hlo". ''' def string_bits(str): return str[0::2] # string_bits('Hello') → 'Hlo' # string_bits('Hi') → 'H' # string_bits('Heeololeo') → 'Hello'
post1 = {"_id": 2, 'name': {'first': 'Dave', 'last': 'Ellis'}, 'contact': {'address': '510 N Division Street, Carson City, MI 48811', 'phone': '(989) 220-8277', 'location': 'Carson City'}, 'position': 'Disciple', 'mentor': 'Seth Roberts', 'status': 'Meeting' #Contacted, Meeting, Interests, Surveys } post2 = {"_id": 3, 'name': {'first': 'Steve', 'last': 'Williams'}, 'contact': {'address': '6039 E. Lake Moncalm Road, Edmore, MI 48829', 'phone': '(989) 565-0174', 'location': 'Cedar Lake'}, 'position': 'Disciple', 'mentor': 'Seth Roberts', 'status': 'Contacted' #Contacted, Meeting, Interests, Surveys } post3 = {"_id": 4, 'name': {'first': 'Nancy', 'last': 'Coon'}, 'contact': {'address': '11960 E. Edgar Road, Vestaburg, MI 48891', 'phone': '(989) 268-1001', 'location': 'Vestaburg'}, 'position': 'Disciple', 'mentor': 'Seth Roberts', 'status': 'Contacted' #Contacted, Meeting, Interests, Surveys }
print ("hello world") print ("hello again") print ("I like typing this.") print("This is fun") print('Yay! Printing.') print ("I'd much rather you 'not'.") print ('I "said" do not touch this.')
# coding=utf-8 class SelectionSort: def find_minimum_idx(self, array: list) -> int: min_element = array[0] min_idx = 0 for idx in range(1, len(array)): if array[idx] < min_element: min_idx = idx min_element = array[idx] return min_idx def sort(self, array: list) -> list: result = [] for _ in range(len(array)): min_idx = self.find_minimum_idx(array) result.append(array.pop(min_idx)) return result
def part_1(raw_data): raw_data.sort() median = raw_data[len(raw_data)//2] ans = 0 for val in raw_data: ans += abs(val - median) return ans def part_2(raw_data): average = int(round(sum(raw_data) / len(raw_data), 0)) adjusted_average = average - 1 ans = 0 for val in raw_data: distance = abs(val - adjusted_average) ans += (distance * (distance + 1)) // 2 return ans def file_reader(file_name): input_file = open(file_name, 'r') inputs_raw = input_file.readlines()[0].replace('\n', '').split(',') return [int(i) for i in inputs_raw] print(part_1(file_reader('input_07.txt'))) print(part_2(file_reader('input_07.txt')))
def h(): print('Wen Chuan') m = yield 5 print(m) d = yield 12 print('We are one') c = h() next(c) c.send('Fight') # next(c) def h1(): print('Wen Cha') m = yield 5 print(m) d = yield 12 print('We are together') c = h1() m = next(c) d = c.send('Fighting') print('We will never forger the date', m, '.', d)
test_list = [1, 2, 3, 4, 5, 6, 7] def rotate_by_one_left(array): temp = array[0] for i in range(len(array)-1): array[i] = array[i+1] array[-1] = temp def rotate_list(array, count): print("Rotate list {} by {}".format(array, count)) for i in range(count): # rotate_by_one_left(array) rotate_by_one_right(array) print("Rotated list {} by {}".format(array, count)) def rotate_by_one_right(array): temp = array[-1] for i in range(len(array)-1, 0, -1): array[i] = array[i-1] array[0] = temp # [1,2,3,4,5,6,7] = [7,1,2,3,4,5,6] if __name__ == "__main__": rotate_list(test_list, 1)
__author__ = "Dariusz Izak, Agnieszka Gromadka IBB PAS" __version__ = "1.6.3" __all__ = ["utilities"]
while True: n = int(input()) if n == 0: break for q in range(n): e = str(input()).split() nome = e[0] ano = int(e[1]) dif = int(e[2]) if q == 0: menor = ano - dif ganha = nome if menor > ano - dif: menor = ano - dif ganha = nome print(ganha)
n = int(input()) narr = list(map(int,input().split())) mi = narr.index(min(narr)) ma = narr.index(max(narr)) narr[mi] , narr[ma] = narr[ma] , narr[mi] print(*narr)
class Lcg(object): def __init__(self, seed): self.seed = seed self.st = seed def cur(self): return (self.st & 0b1111111111111110000000000000000) >> 16 def adv(self): self.st = (1103515245 * self.st + 12345) % (0b100000000000000000000000000000000) def gen(self): x = self.cur() self.adv() return x
def tournamentWinner(competitions, results): ''' This fuction takes two arrays one of which contains competitions, another array contains results of the competitions and returns a string which is the winning team. This implementation has O(n) time complexity where n is the number of competitions, O(i) space complexity where i is the number of team. args: ------------- competitions (list) : nested array. Each element in the outer most list contains two teams. First one is home team and second one is awy team. results (list) : contains result of each competition. 0 if away team wins and 1 if home team wins. output: ------------- winner (str) : name of the champion of the tournament. ''' # dictionary 'scores' stores all team scores scores = {} #updating scores of each team by iteration over results and competitions. for i in range(len(results)): if results[i] == 0: if competitions[i][1] in scores: scores[competitions[i][1]] += 3 else: scores[competitions[i][1]] = 3 else: if competitions[i][0] in scores: scores[competitions[i][0]] += 3 else: scores[competitions[i][0]] = 3 # finding the max scorer from 'scores' dictionary max_score = 0 winner = '' for key in scores: score = scores[key] if score > max_score: max_score = score winner = str(key) return winner
""" author: Fang Ren (SSRL) 5/1/2017 """
class BlenderAddonManager(): ''' Class to manage all workflows around addon installation and update. ''' def __init__(self): pass def index(self): ''' Indexes all addons and save its metadata into the addon database. ''' pass def poll_remote_sources(self): ''' Polls remote addon sources to gather recent addon versions. ''' pass def download_addon(self): pass def install_addon(self): pass def remove_addon(self): pass
class Solution(object): def fourSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[List[int]] """ res = set() nums.sort() for i, v in enumerate(nums[:-3]): for j, vv in enumerate(nums[i + 1:-2]): t = target - v - vv d = {} for x in nums[i + j + 2:]: if x not in d: d[t - x] = 1 else: res.add((v, vv, t - x, x)) return [list(i) for i in res] def test_four_sum(): s = Solution() res = s.fourSum([1, 0, -1, 0, -2, 2], 0) assert 3 == len(res) assert [-1, 0, 0, 1] in res assert [-2, -1, 1, 2] in res assert [-2, 0, 0, 2] in res res = s.fourSum([-3, -1, 0, 2, 4, 5], 0) assert [[-3, -1, 0, 4]] == res
input = """acc +17 acc +37 acc -13 jmp +173 nop +100 acc -7 jmp +447 nop +283 acc +41 acc +32 jmp +1 jmp +585 jmp +1 acc -5 nop +71 acc +49 acc -18 jmp +527 jmp +130 jmp +253 acc +11 acc -11 jmp +390 jmp +597 jmp +1 acc +6 acc +0 jmp +588 acc -17 jmp +277 acc +2 nop +163 jmp +558 acc +38 jmp +369 acc +13 jmp +536 acc +38 acc +39 acc +6 jmp +84 acc +11 nop +517 acc +48 acc +47 jmp +1 acc +42 acc +0 acc +2 acc +24 jmp +335 acc +44 acc +47 jmp +446 nop +42 nop +74 acc +45 jmp +548 jmp +66 acc +1 jmp +212 acc +18 jmp +1 acc +4 acc -16 jmp +366 acc +0 jmp +398 acc +45 jmp +93 acc +40 acc +38 acc +21 nop +184 jmp -46 nop -9 jmp +53 acc +46 acc +36 jmp +368 acc +16 acc +8 acc -9 acc -4 jmp +328 acc -15 acc -5 acc +21 jmp +435 acc -5 acc +36 jmp +362 acc +26 jmp +447 jmp +1 jmp +412 acc +11 acc +41 nop -32 acc +17 jmp -63 jmp +1 nop +393 jmp +62 acc +18 acc +30 nop +417 jmp +74 acc +29 acc +23 jmp +455 jmp +396 jmp +395 acc +33 nop +137 nop +42 jmp +57 jmp +396 acc +7 acc +0 jmp +354 acc +15 acc +50 jmp -12 jmp +84 nop +175 acc +5 acc -2 jmp -82 acc +1 acc +26 jmp +288 nop -113 nop +366 acc +45 jmp +388 acc +21 acc +38 jmp +427 acc +33 jmp -94 nop -118 nop +411 jmp +472 nop +231 nop +470 acc +48 jmp -124 jmp +1 acc +5 acc +37 acc +42 jmp +301 acc -11 acc -17 acc +14 jmp +357 acc +6 acc +20 acc +13 jmp +361 jmp -65 acc +29 jmp +26 jmp +329 acc +32 acc +32 acc +17 jmp -102 acc -6 acc +33 acc +9 jmp +189 acc +3 jmp -128 jmp -142 acc +24 acc -5 jmp +403 acc +28 jmp +310 acc +34 acc +4 acc +33 acc +18 jmp +227 acc -8 acc -15 jmp +112 jmp +54 acc +21 acc +23 acc +20 jmp +320 acc +13 jmp -77 acc +15 nop +310 nop +335 jmp +232 acc -3 nop +50 acc +41 jmp +112 nop -10 acc +29 acc +27 jmp +52 acc +40 nop -132 acc -16 acc +27 jmp +309 acc -8 nop +147 acc +20 acc +46 jmp +202 acc +27 jmp -43 jmp +1 acc +33 acc -13 jmp +300 acc +1 jmp -202 acc -17 acc +0 acc +34 jmp -5 nop +335 acc -16 acc -17 jmp -120 acc -19 acc -13 acc +4 jmp +368 jmp +21 acc +39 acc +39 acc -18 jmp -157 nop +280 acc +33 nop -37 jmp +32 acc -16 acc +18 acc +46 jmp -121 acc -19 jmp +195 acc +28 jmp +124 jmp +331 jmp -228 jmp -146 jmp +85 jmp +60 acc +20 acc -9 jmp +303 jmp -122 jmp +111 acc +32 acc +0 acc +39 acc +29 jmp -31 nop +320 jmp -63 jmp +223 nop -149 acc -12 acc -11 acc +32 jmp +309 jmp -13 acc -19 jmp -123 acc +21 acc +18 acc +49 jmp +175 acc -14 nop -129 acc -2 acc +31 jmp +79 acc +23 acc +50 acc +39 acc +7 jmp -235 jmp -166 acc +9 jmp +293 acc -11 jmp +76 acc +44 acc +3 acc +37 jmp +123 nop -104 jmp -157 acc +14 acc +10 acc +28 jmp +25 acc +37 jmp +188 jmp -49 acc -11 jmp -90 acc -8 jmp +197 acc +5 jmp +115 acc +44 jmp -228 nop -2 acc +46 jmp +130 nop +183 nop +106 acc +27 acc +37 jmp -309 acc +28 acc -4 acc -12 acc +38 jmp +93 acc +8 acc +23 acc -9 acc +6 jmp -42 acc +10 acc +35 acc +4 jmp -231 acc +19 acc +7 acc +23 acc +11 jmp -90 acc +0 nop +158 nop -150 acc +33 jmp +107 acc +48 acc -2 jmp -104 acc +6 nop -57 nop +172 acc -11 jmp -7 acc +6 acc +50 acc -9 acc +12 jmp -171 acc +3 jmp +26 acc +42 acc +31 acc +20 acc +32 jmp -48 acc +13 jmp -6 jmp +178 acc +47 jmp -153 acc +28 nop +74 jmp -162 acc -15 nop -104 acc -9 jmp -227 acc +49 acc -19 acc +41 jmp -318 acc +9 acc +12 acc +7 jmp +34 jmp +137 nop -143 acc -8 acc +5 acc +31 jmp -20 jmp -237 acc +39 acc +0 jmp -298 acc +45 acc -19 acc +11 jmp -151 acc +40 acc +27 nop +150 nop -391 jmp -341 acc +1 acc +11 acc +18 nop -234 jmp +77 nop +104 jmp -65 acc +32 jmp -27 nop -317 nop +159 acc +14 acc -10 jmp -348 acc +29 jmp +32 acc +48 acc -19 jmp +17 jmp -201 jmp -224 nop +26 acc -7 acc +23 acc +46 jmp -6 acc +22 acc +39 acc +9 acc +23 jmp -30 jmp -243 acc +47 acc -15 jmp -298 jmp -393 jmp +1 acc +3 nop -24 acc +7 jmp -59 acc -6 acc +26 jmp -102 acc +34 acc +24 jmp -207 acc +36 acc +40 acc +41 jmp +1 jmp -306 jmp +57 jmp +1 nop +99 acc +28 jmp -391 acc +50 jmp -359 acc -5 jmp +9 jmp -355 acc +5 acc +2 jmp -77 acc +40 acc +28 acc +22 jmp -262 nop -287 acc +34 acc -4 nop +112 jmp -195 acc +29 nop -94 nop -418 jmp +24 jmp -190 acc +2 jmp -311 jmp -178 jmp -276 acc -12 acc -18 jmp +62 jmp -174 nop +31 acc +33 nop -158 jmp -417 acc +3 acc +21 acc +47 jmp +87 acc +45 jmp -77 acc +6 acc -10 jmp +1 jmp -240 acc +7 acc +47 jmp -379 acc -14 acc +50 nop -75 acc +30 jmp +70 jmp -392 jmp -430 acc +22 acc -2 jmp -492 jmp +1 acc -6 acc +38 jmp -36 nop -336 jmp -32 jmp +61 acc +20 acc -9 acc +2 jmp -175 acc +21 acc -2 jmp -6 jmp -527 acc +11 acc +16 jmp -262 jmp +1 nop -327 acc +29 jmp -114 acc +11 acc +17 acc +26 nop -104 jmp -428 nop -178 nop -242 acc +29 acc +5 jmp -245 jmp -417 jmp -278 acc +35 acc +21 jmp +1 nop -263 jmp +8 acc +42 jmp -95 nop -312 acc -11 acc +34 acc +0 jmp +19 acc +8 acc -13 acc +32 acc +21 jmp -208 acc +15 acc +39 nop -194 jmp -280 jmp +24 nop -516 acc +21 acc +48 jmp -367 jmp -121 acc +49 acc -16 jmp -136 acc +0 jmp -148 jmp -85 jmp -103 nop -446 jmp -242 acc -12 acc +13 acc +31 acc -1 jmp -435 nop -420 acc +22 acc -5 jmp -567 nop -354 acc +11 acc +33 acc +45 jmp -76 acc -2 acc +0 acc +25 acc +46 jmp -555 acc +0 acc +11 nop -2 jmp -394 jmp -395 acc +8 acc +14 acc +47 acc +22 jmp +1""" instructions = [i for i in input.split("\n")] """one""" accumulator = 0 executed_instructions = [] def execute(instructions_list, id, executed_list, accumulator): if id >= len(instructions_list): return ['end', accumulator] if id in executed_list: return ['looped', accumulator] else: executed_list.append(id) instruction = instructions_list[id] num = int(instruction[5:len(instruction)]) sign = 1 if instruction[4] == '+' else -1 if 'acc' in instruction: accumulator += num * sign elif 'jmp' in instruction: next_id = id + (num * sign) return execute(instructions_list, next_id, executed_list, accumulator) return execute(instructions_list, id + 1, executed_list, accumulator) print(execute(instructions, 0, executed_instructions, 0)) """two""" """It's 1am and I want to sleep, so I'm brute forcing this""" for i in range(0, len(instructions)): executed_instructions = [] ins = instructions.copy() if 'acc' in ins[i]: continue elif 'nop' in ins[i]: ins[i] = ins[i].replace('nop', 'jmp') else: ins[i] = ins[i].replace('jmp', 'nop') res = execute(ins, 0, executed_instructions, 0) if res[0] == 'end': print(res[1]) break
""" The Self-Taught Programmer - Chapter 6 Challenges Author: Dante Valentine Date: 1 June, 2021 """ # CHALLENGE 1 for c in "camus": print(c) # CHALLENGE 2 str1 = input("What did you write? ") str2 = input("Who did you send it to? ") str3 = "Yesterday I wrote a {}. I sent it to {}!".format(str1, str2) print(str3) # CHALLENGE 3 # print("aldous Huxley was born in 1894.".capitalize()) # CHALLENGE 4 str4 = "Where now? Who now? When now?" questions = str4.split("? ") for i in range(0,len(questions)-1): questions[i] += "?" print(questions) # CHALLENGE 5 list1 = ["The", "fox", "jumped", "over", "the", "fence", "."] list1 = " ".join(list1[0:6]) + list1[6] print(list1) # CHALLENGE 6 print("A screaming comes across the sky".replace("s","$")) # CHALLENGE 7 str5 = "Hemingway" print(str5.index("m")) # CHALLENGE 8 str6 = "\"That's not fair.\" I wrap my arms around myself. \"I'm fighting, too.\"\n\"Well, seeing as your father created this mess, if I were you, I'd fight a little harder.\"" print(str6) # CHALLENGE 9 str7 = "three" + " " + "three" + " " + "three" print(str7) str8 = "three " * 3 str8 = str8[0:(len(str8)-1)] print(str8) # CHALLENGE 10 str8 = "It was a bright cold day in April, abd the clocks were striking thirteen." sliceindex = str8.index(",") str9 = str8[0:sliceindex] print(str9)
class MyClass: def add(self, a, b): return a + b obj = MyClass() ret = obj.add(3, 4) print(ret)
class Solution: def numUniqueEmails(self, emails: List[str]) -> int: def f(email): (localname, domain) = email.split('@') localname = localname.split('+')[0] localname = localname.replace('.','') return localname + "@" + domain return len(set(map(f, emails)))
# count from zero to 10 for i in range(0,10): print (i) print("") # count by 2 for i in range(0,10,2): print(i) print("") # count by 5 start at 50 to 100 for i in range(50,100,5): print(i)
str_btn_prev = "Previous" str_btn_next = "Next" str_btn_download = "Download" str_btn_reset = "Reset Annotation" str_btn_delete_bbox = "Delete Bbox" srt_validation_not_ok = "<b style=\"color:green\">NO ACTION REQUIRED</b>" srt_validation_ok = "<b style=\"color:RED\">ACTION REQUIRED</b>" info_new_ds = "New dataset with meta_annotations" info_missing = "Missing image" info_no_more_images = "No available images" info_total = "Total" info_class = "Class" info_class_name = "Class name" info_ann_images = "Annotated images" info_ann_objects = "Annotated objects" info_positions = "Positions:" info_completed = "Completed images:" info_incomplete = "Incomplete images:" info_completed_obj = "Completed objects:" info_incomplete_obj = "Incomplete objects:" info_ds_output = "Generated dataset will be saved at: " warn_select_class = "<b style=\"color:RED\">You must assing a class to all bbox before continuing</b>" warn_skip_wrong = "Skipping wrong annotation" warn_img_path_not_exits = "Image path does not exists " warn_task_not_supported = "Task type not supported" warn_no_images = "No images provided" warn_little_classes = "At least one class must be provided" warn_binary_only_two = "Binary datasets contain only 2 classes" warn_display_function_needed = "Non image data requires the definition of the custom display function" warn_no_images_criteria = "No images meet the specified criteria" warn_incorrect_class = "Class not present in dataset" warn_incorrect_property = "Meta-Annotation not present in dataset"
# User inputs database = input(f'\nEnter the name of the database you want to create: ') environment = input(f'\nEnter the name of the environment (DTAP) you want to create: ') # Setting variables strdatabase = str(database) strenvironment = str(environment) # Composing the code line10 = ('CREATE ROLE IF NOT EXISTS RL_' + strdatabase + '_' + strenvironment +'_ADMIN;') line13 = ('GRANT ALL PRIVILEGES ON ACCOUNT TO ROLE RL_' + strdatabase + '_' + strenvironment +'_ADMIN;') line15 = ('GRANT ROLE RL_' + strdatabase + '_' + strenvironment +'_ADMIN TO USER JOHAN;') line20 = ('USE ROLE RL_' + strdatabase + '_' + strenvironment +'_ADMIN;') line30 = ('CREATE DATABASE DB_' + strdatabase + '_' + strenvironment +';') # Writing the lines to file file1='V1.1__createdatabase.sql' with open(file1,'w') as out: out.write('{}\n{}\n{}\n{}\n{}\n'.format(line10,line13,line15,line20,line30)) # Checking if the data is # written to file or not file1 = open('V1.1__createdatabase.sql', 'r') print(file1.read()) file1.close()
# twitter hashtag to find TWITTER_HASHTAG = "#StarWars" # twitter api credentials (https://apps.twitter.com/) TWITTER_CONSUMER_KEY = "" TWITTER_CONSUMER_SECRET = "" TWITTER_ACCESS_TOKEN = "" TWITTER_ACCESS_TOKEN_SECRET = "" # delay in seconds between reading tweets DELAY_TO_READ_TWEET = 30.0
# -*- coding: utf-8 -*- __author__ = 'Michael Odintsov' __email__ = 'templarrrr@gmail.com' __version__ = '0.1.0'
class UnionFind(object): def __init__(self, n): self.parent = list(range(n)) self.rank = [0] * n def find(self, u): if u != self.parent[u]: self.parent[u] = self.find(self.parent[u]) return self.parent[u] def isConnected(self, u, v): return self.find(u) == self.find(v) def union(self, u, v): pu = self.find(u) pv = self.find(v) if pu == pv: return False if self.rank[pv] > self.rank[pu]: self.parent[pu] = pv elif self.rank[pu] > self.rank[pv]: self.parent[pv] = pu else: self.parent[pu] = pv self.rank[pv] += 1 return True u = UnionFind(6) u.union(3, 4) u.union(2, 3) u.union(1, 2) u.union(0, 1)
with open('input') as input: lines = input.readlines() number_sequence = lines[0].split(',') board_numbers = [] called_indexes = [] # Flatten data structure for boards for i, line in enumerate(lines): if i == 0: continue if line == '\n': continue stripped_line = line.strip('\n') num_list = line.split() for num in num_list: board_numbers.append(num) def checkForWin(board_numbers, called_indexes, num): for i, space in enumerate(board_numbers): if space == num: # print(f"Space at index {i} contains called number {num}") called_indexes.append(i) # Check for win based on indexes board_index = i // 25 row_pos = i % 5 row_start = i - row_pos col_start = i - (i % 25 - row_pos) # print(f"X value = {i % 5}") # print(f"line_start = {line_start}") horizontal_win = True for j in range(row_start, row_start+5): if j not in called_indexes: horizontal_win = False vertical_win = True for j in range(col_start, col_start+25, 5): if j not in called_indexes: vertical_win = False if horizontal_win or vertical_win: print(f"Winner on board {board_index}") return board_index # "Call" numbers and check for winner winner = None for num in number_sequence: winner = checkForWin(board_numbers, called_indexes, num) if winner != None: board_start = winner*25 unmarked_sum = 0 for i in range(board_start, board_start+25): if i not in called_indexes: unmarked_sum += int(board_numbers[i]) print(f"SOLUTION = {unmarked_sum} * {num} = {int(unmarked_sum) * int(num)}") break
"""Longest Collatz sequence The following iterative sequence is defined for the set of positive integers: n -> n/2 (n is even) n -> 3n + 1 (n is odd) Using the rule above and starting with 13, we generate the following sequence: 13 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1 It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1. Which starting number, under one million, produces the longest chain? Note: Once the chain starts, the terms are allowed to go above one million. """ def collatz_sequence(n): length = 1 # Implementing this recursively would allow memoization, but Python isn't # the best language to attempt this in. Doing so causes a RecursionError # to be raised. Also of note: using a decorator like `functools.lru_cache` # for memoization causes the recursion limit to be reached more quickly. # See: http://stackoverflow.com/questions/15239123/maximum-recursion-depth-reached-faster-when-using-functools-lru-cache. while n > 1: length += 1 if n%2 == 0: n /= 2 else: n = (3 * n) + 1 return length def longest_collatz_sequence(ceiling): longest_chain = { 'number': 1, 'length': 1 } for i in range(ceiling): length = collatz_sequence(i) if length > longest_chain['length']: longest_chain = { 'number': i, 'length': length } return longest_chain
class AchievementDigest(object): ID = 0 SERIAL_NUM_READS = "c1" SERIAL_NUM_PUBLISH = "c2" SERIAL_NUM_REUSES = "c3" SERIAL_LAST_READS = "u1" SERIAL_LAST_PUBLISH = "u2" SERIAL_LAST_REUSES = "u3" def __init__(self): self.num_reads = 0 self.num_publish = 0 self.num_reuses = 0 self._last_reads = [] self._last_published = [] self._last_reuses = [] @staticmethod def deserialize(doc): digest = AchievementDigest() digest.num_reads = doc.get(AchievementDigest.SERIAL_NUM_READS, 0) digest.num_publish = doc.get(AchievementDigest.SERIAL_NUM_PUBLISH, 0) digest.num_reuses = doc.get(AchievementDigest.SERIAL_NUM_REUSES, 0) digest._last_reads = doc.get(AchievementDigest.SERIAL_LAST_READS, []) digest._last_published = doc.get(AchievementDigest.SERIAL_LAST_PUBLISH, []) digest._last_reuses = doc.get(AchievementDigest.SERIAL_LAST_REUSES, []) return digest @property def last_reads(self): tmp = [el for el in self._last_reads] # copy tmp.reverse() return tmp @property def last_published(self): tmp = [el for el in self._last_published] # copy tmp.reverse() return tmp @property def last_reuses(self): tmp = [el for el in self._last_reuses] # copy tmp.reverse() return tmp class AchievementDigestMongoStore(object): COLLECTION = "achievement_digest" DOCUMENT_ID = 1 COUNTERS_DOC_KEY = "c" def __init__(self, mongo_server_store): self.server_store = mongo_server_store def read_achievement_digest(self): dbcol = self.server_store.db[self.COLLECTION] doc = dbcol.find_one({"_id": self.DOCUMENT_ID}) return AchievementDigest.deserialize(doc) if doc else None def increment_total_read_counter(self, brl_user): """brl_user has readed from biicode for the first time, store it""" self._increment_counter(AchievementDigest.SERIAL_NUM_READS, AchievementDigest.SERIAL_LAST_READS, brl_user) def increment_total_publish_counter(self, brl_user): """brl_user has published from biicode for the first time, store it""" self._increment_counter(AchievementDigest.SERIAL_NUM_PUBLISH, AchievementDigest.SERIAL_LAST_PUBLISH, brl_user) def increment_total_reuse_counter(self, brl_user): """brl_user has published from biicode for the first time, store it""" self._increment_counter(AchievementDigest.SERIAL_NUM_REUSES, AchievementDigest.SERIAL_LAST_REUSES, brl_user) def _increment_counter(self, counter_field_name, user_list_field_name, brl_user): query = {"_id": self.DOCUMENT_ID} set_q = {"$inc": {counter_field_name: 1}, "$push": {user_list_field_name: brl_user}} self.server_store._update_collection(self.COLLECTION, query, set_q, True, None)
# Found here: # https://github.com/gabtremblay/pysrec/ # srecutils.py # # Copyright (C) 2011 Gabriel Tremblay - initnull hat gmail.com # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ Motorola S-Record utis - Kudos to Montreal CISSP Groupies """ # Address len in bytes for S* types # http://www.amelek.gda.pl/avr/uisp/srecord.htm __ADDR_LEN = {'S0' : 2, 'S1' : 2, 'S2' : 3, 'S3' : 4, 'S5' : 2, 'S7' : 4, 'S8' : 3, 'S9' : 2} def int_to_padded_hex_byte(integer): """ Convert an int to a 0-padded hex byte string example: 65 == 41, 10 == 0A Returns: The hex byte as string (ex: "0C") """ to_hex = hex(integer) xpos = to_hex.find('x') hex_byte = to_hex[xpos+1 : len(to_hex)].upper() if len(hex_byte) == 1: hex_byte = ''.join(['0', hex_byte]) return hex_byte def compute_srec_checksum(srec): """ Compute the checksum byte of a given S-Record Returns: The checksum as a string hex byte (ex: "0C") """ # Get the summable data from srec # start at 2 to remove the S* record entry data = srec[2:len(srec)] sum = 0 # For each byte, convert to int and add. # (step each two character to form a byte) for position in range(0, len(data), 2): current_byte = data[position : position+2] int_value = int(current_byte, 16) sum += int_value # Extract the Least significant byte from the hex form hex_sum = hex(sum) least_significant_byte = hex_sum[len(hex_sum)-2:] least_significant_byte = least_significant_byte.replace('x', '0') # turn back to int and find the 8-bit one's complement int_lsb = int(least_significant_byte, 16) computed_checksum = (~int_lsb) & 0xff return computed_checksum def validate_srec_checksum(srec): """ Validate if the checksum of the supplied s-record is valid Returns: True if valid, False if not """ checksum = srec[len(srec)-2:] # Strip the original checksum and compare with the computed one if compute_srec_checksum(srec[:len(srec) - 2]) == int(checksum, 16): return True else: return False def get_readable_string(integer): r""" Convert an integer to a readable 2-character representation. This is useful for reversing examples: 41 == ".A", 13 == "\n", 20 (space) == "__" Returns a readable 2-char representation of an int. """ if integer == 9: #\t readable_string = "\\t" elif integer == 10: #\r readable_string = "\\r" elif integer == 13: #\n readable_string = "\\n" elif integer == 32: # space readable_string = '__' elif integer >= 33 and integer <= 126: # Readable ascii readable_string = ''.join([chr(integer), '.']) else: # rest readable_string = int_to_padded_hex_byte(integer) return readable_string def offset_byte_in_data(target_data, offset, target_byte_pos, readable = False, wraparound = False): """ Offset a given byte in the provided data payload (kind of rot(x)) readable will return a human-readable representation of the byte+offset wraparound will wrap around 255 to 0 (ex: 257 = 2) Returns: the offseted byte """ byte_pos = target_byte_pos * 2 prefix = target_data[:byte_pos] suffix = target_data[byte_pos+2:] target_byte = target_data[byte_pos:byte_pos+2] int_value = int(target_byte, 16) int_value += offset # Wraparound if int_value > 255 and wraparound: int_value -= 256 # Extract readable char for analysis if readable: if int_value < 256 and int_value > 0: offset_byte = get_readable_string(int_value) else: offset_byte = int_to_padded_hex_byte(int_value) else: offset_byte = int_to_padded_hex_byte(int_value) return ''.join([prefix, offset_byte, suffix]) # offset can be from -255 to 255 def offset_data(data_section, offset, readable = False, wraparound = False): """ Offset the whole data section. see offset_byte_in_data for more information Returns: the entire data section + offset on each byte """ for pos in range(0, len(data_section)/2): data_section = offset_byte_in_data(data_section, offset, pos, readable, wraparound) return data_section def parse_srec(srec): """ Extract the data portion of a given S-Record (without checksum) Returns: the record type, the lenght of the data section, the write address, the data itself and the checksum """ record_type = srec[0:2] data_len = srec[2:4] addr_len = __ADDR_LEN.get(record_type) * 2 addr = srec[4:4 + addr_len] data = srec[4 + addr_len:len(srec)-2] checksum = srec[len(srec) - 2:] return record_type, data_len, addr, data, checksum
# @Title: 最短无序连续子数组 (Shortest Unsorted Continuous Subarray) # @Author: KivenC # @Date: 2018-07-17 16:11:42 # @Runtime: 128 ms # @Memory: N/A class Solution(object): def findUnsortedSubarray(self, nums): """ :type nums: List[int] :rtype: int """ left_index, right_index = 0, len(nums)-1 # 为了保证当该数组原本就是升序时返回0 i, j = 0, -1 min_num, max_num = nums[-1], nums[0] while(right_index >= 0): max_num = max(max_num, nums[left_index]) # 记录不符合升序规则的最大索引 if nums[left_index] != max_num: j = left_index left_index += 1 min_num = min(min_num, nums[right_index]) # 记录不符合规则的最小索引 if nums[right_index] != min_num: i = right_index right_index -= 1 return j - i + 1
ten_things = "Apples Oranges Crows Telephone Light Sugar" print ("Wait there's not 10 things in that list, let's fix that.") stuff = ten_things.split(' ') more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"] while len(stuff) != 10: next_one = more_stuff.pop() print ("Adding: ", next_one) stuff.append(next_one) print ("There's %d items now." % len(stuff)) print ("There we go: ", stuff) print ("Let's do some things with stuff.") print (stuff[1]) print (stuff[-1]) # whoa! fancy print (stuff.pop()) print (' '.join(stuff)) # what? cool print ('#'.join(stuff[3:5])) # super stellar!
# "Common block" loaded by the cfi and the cfg to communicate egmID parameters electronVetoId = 'egmGsfElectronIDs:cutBasedElectronID-Summer16-80X-V1-veto' electronLooseId = 'egmGsfElectronIDs:cutBasedElectronID-Summer16-80X-V1-loose' electronMediumId = 'egmGsfElectronIDs:cutBasedElectronID-Summer16-80X-V1-medium' electronTightId = 'egmGsfElectronIDs:cutBasedElectronID-Summer16-80X-V1-tight' electronHLTId = 'egmGsfElectronIDs:cutBasedElectronHLTPreselection-Summer16-V1' electronMVAWP90 = 'egmGsfElectronIDs:mvaEleID-Spring16-GeneralPurpose-V1-wp90' electronMVAWP80 = 'egmGsfElectronIDs:mvaEleID-Spring16-GeneralPurpose-V1-wp80' electronCombIsoEA = 'RecoEgamma/ElectronIdentification/data/Summer16/effAreaElectrons_cone03_pfNeuHadronsAndPhotons_80X.txt' electronEcalIsoEA = 'RecoEgamma/ElectronIdentification/data/Summer16/effAreaElectrons_HLT_ecalPFClusterIso.txt' electronHcalIsoEA = 'RecoEgamma/ElectronIdentification/data/Summer16/effAreaElectrons_HLT_hcalPFClusterIso.txt' photonLooseId = 'egmPhotonIDs:cutBasedPhotonID-Spring16-V2p2-loose' photonMediumId = 'egmPhotonIDs:cutBasedPhotonID-Spring16-V2p2-medium' photonTightId = 'egmPhotonIDs:cutBasedPhotonID-Spring16-V2p2-tight' photonCHIsoEA = 'RecoEgamma/PhotonIdentification/data/Spring16/effAreaPhotons_cone03_pfChargedHadrons_90percentBased.txt' photonNHIsoEA = 'RecoEgamma/PhotonIdentification/data/Spring16/effAreaPhotons_cone03_pfNeutralHadrons_90percentBased.txt' photonPhIsoEA = 'RecoEgamma/PhotonIdentification/data/Spring16/effAreaPhotons_cone03_pfPhotons_90percentBased.txt' # https://twiki.cern.ch/twiki/bin/view/CMS/EGMSmearer#Energy_smearing_and_scale_correc # https://github.com/ECALELFS/ScalesSmearings/tree/Moriond17_23Jan_v2 electronSmearingData = { "Prompt2015":"SUEPProd/Producer/data/ScalesSmearings/74X_Prompt_2015", "76XReReco" :"SUEPProd/Producer/data/ScalesSmearings/76X_16DecRereco_2015_Etunc", "80Xapproval" : "SUEPProd/Producer/data/ScalesSmearings/80X_ichepV1_2016_ele", "Moriond2017_JEC" : "SUEPProd/Producer/data/ScalesSmearings/Winter_2016_reReco_v1_ele" #only to derive JEC corrections } photonSmearingData = { "Prompt2015":"SUEPProd/Producer/data/ScalesSmearings/74X_Prompt_2015", "76XReReco" :"SUEPProd/Producer/data/ScalesSmearings/76X_16DecRereco_2015_Etunc", "80Xapproval" : "SUEPProd/Producer/data/ScalesSmearings/80X_ichepV2_2016_pho", "Moriond2017_JEC" : "SUEPProd/Producer/data/ScalesSmearings/Winter_2016_reReco_v1_ele" #only to derive JEC correctionsb }
#!/usr/bin/env python # @file levenshtein.py # @author Michael Foukarakis # @version 0.1 # @date Created: Thu Oct 16, 2014 10:57 EEST # Last Update: Thu Oct 16, 2014 11:01 EEST #------------------------------------------------------------------------ # Description: Levenshtein string distance implementation #------------------------------------------------------------------------ # History: <+history+> # TODO: <+missing features+> #------------------------------------------------------------------------ # -*- coding: utf-8 -*- #------------------------------------------------------------------------ def levenshtein(s1, s2): """Returns the Levenshtein distance of S1 and S2. >>> levenshtein('aabcadcdbaba', 'aabacbaaadb') 6 """ if len(s1) < len(s2): return levenshtein(s2, s1) if not s1: return len(s2) previous_row = range(len(s2) + 1) for i, c1 in enumerate(s1): current_row = [i + 1] for j, c2 in enumerate(s2): insertions = previous_row[j + 1] + 1 # j+1 instead of j since previous_row and current_row are one character longer deletions = current_row[j] + 1 # than s2 substitutions = previous_row[j] + (c1 != c2) current_row.append(min(insertions, deletions, substitutions)) previous_row = current_row return previous_row[-1]
class Plugin(object): def __init__(self, myarg): self.myarg = myarg def do_it(self): print("doing it with myarg={} inside plugin1".format(self.myarg))
load("//:packages.bzl", "CDK_PACKAGES") # Base rollup globals for dependencies and the root entry-point. CDK_ROLLUP_GLOBALS = { 'tslib': 'tslib', '@angular/cdk': 'ng.cdk', } # Rollup globals for subpackages in the form of, e.g., {"@angular/cdk/table": "ng.cdk.table"} CDK_ROLLUP_GLOBALS.update({ "@angular/cdk/%s" % p: "ng.cdk.%s" % p for p in CDK_PACKAGES })
balance = 1000 pin = input("Ustaw swój 4 cyfrowy pin: ") while len(pin) != 4: print("PIN nie jest 4 cyfrowy, proszę podać jeszcze raz") pin = input("Ustaw swój 4 cyfrowy pin: ") pin = int(pin) def check_pin(): security = int(input("Wprowadź swój PIN: ")) while security != pin: print("Zły numer pin") security = int(input("Wprowadź swój PIN: ")) while True: print("Witamy w Bankomacie/Wpłatomacie!") print("1. Wpłata \n2. Wypłata \n3. Sprawdź saldo" ) operation = int(input("Co Chcesz zrobić (1,2,3)? ")) if operation == 1: check_pin() deposit = int(input("Ile chcesz wpłacić: ")) balance += deposit elif operation == 2: check_pin() withdraw = int(input("Ile chcesz wypłacić: ")) if withdraw > balance: print("Nie masz tyle na koncie!!") else: balance -= withdraw elif operation == 3: check_pin() print(balance) what_to_do = int(input("Co chcesz zrobić w kolejnym kroku \n1. Rozpocząć od nowa \n2. Zakończyć program \n >")) if what_to_do == 2: break
# https://leetcode.com/problems/peeking-iterator/ class PeekingIterator: def __init__(self, iterator): """ Initialize your data structure here. :type iterator: Iterator """ self.iterator = iterator self.seen = deque() def peek(self): """ Returns the next element in the iteration without advancing the iterator. :rtype: int """ if not self.seen: self.seen.append(self.iterator.next()) return self.seen[0] def next(self): """ :rtype: int """ if self.seen: return self.seen.popleft() return self.iterator.next() def hasNext(self): """ :rtype: bool """ if self.seen: return True return self.iterator.hasNext() # Efficient class PeekingIterator: def __init__(self, iterator): self.iter = iterator self.buffer = self.iter.next() if self.iter.hasNext() else None def peek(self): return self.buffer def next(self): ret = self.buffer self.buffer = self.iter.next() if self.iter.hasNext() else None return ret def hasNext(self): return self.buffer is not None
res = client.get_smtp_servers() # The SMTP properties are related to alert routing print(res) if type(res) == pypureclient.responses.ValidResponse: print(list(res.items)) # Valid fields: continuation_token, filter, ids, limit, names, offset, sort # See section "Common Fields" for examples
mimic_tables_dir = './mimic_tables/' # location of the metadata tables of the mimic-cxr dataset. Inside this folder:'mimic-cxr-2.0.0-chexpert.csv' and 'mimic-cxr-2.0.0-split.csv' jpg_path = './dataset_mimic_jpg/' # location of the full mimic-cxr-jpg dataset. Inside this folder: "physionet.org" folder dicom_path = './dataset_mimic/' # location of the dicom images of the mimic-cxr dataset that were included in the eyetracking dataset. Inside this folder: "physionet.org" folder h5_path = '/scratch/' # folder where to save hdf5 files containing the full resized mimic dataset to speed up training eyetracking_dataset_path = './dataset_et/main_data/' # location of the eye-tracking dataset. Inside this folder: metadata csv and all cases folders segmentation_model_path = './segmentation_model/' #Inside this folder: trained_model.hdf5, from https://github.com/imlab-uiip/lung-segmentation-2d
{ 'name': "odoo_view_advanced", 'summary': "Advanced concepts about views", 'description': "Advanced concepts about views...", 'author': "Stiven Ramírez Arango", 'website': "https://stivenramireza.com//", 'category': 'Uncategorized', 'version': '0.1', 'depends': ['base'], 'data': [ 'views/views.xml', 'views/templates.xml', ], 'demo': [ 'demo/demo.xml', ], 'qweb': [ 'static/src/xml/button.xml' ] }
class SpriteHandler: """draws the sprites for all objects with updated position, rotation and scale each draw step""" def __init__(self): self.sprite_scale_factor = 0.03750000000000002 self.rotation_factor = 0.0000000 self.debug_draw = 1 def toggle_debug_draw(self): self.debug_draw += 1 if self.debug_draw > 2: self.debug_draw = 0 print(f"debug_draw: {self.debug_draw}") def change_scale_factor(self, value): """modifies the sprite scale factor used for sprite drawing""" self.sprite_scale_factor += value if self.sprite_scale_factor < 0.02: self.sprite_scale_factor = 0.02 if self.sprite_scale_factor > 0.06: self.sprite_scale_factor = 0.06 print(f"scale_factor: {self.sprite_scale_factor}") def change_rotation_factor(self, value): """modifies the sprite rotation factor used for sprite drawing""" self.rotation_factor += value print(f"rotation_factor: {self.rotation_factor}") def draw(self, object_list, batch): # update all the sprite values and then draw them as a batch if self.debug_draw == 1: for object in object_list: object.update_sprite( self.sprite_scale_factor, self.rotation_factor ) batch.draw()
""" [easy] challenge #14 Source / Reddit Post - https://www.reddit.com/r/dailyprogrammer/comments/q2v2k/2232012_challenge_14_easy/ """ a = [1, 2, 3, 4, 5, 6, 7, 8] k = 2 print([x for i in range(0, len(a), k) for x in a[i:i+k][::-1]])
class bufferPair: # a ping-pong buffer for gpu computation def __init__(self, cur, nxt): self.cur = cur self.nxt = nxt def swap(self): self.cur, self.nxt = self.nxt, self.cur class MultiBufferPair: """ Specifically designed for FaceGrid """ def __init__(self, cur, nxt): """ :param cur: one FaceGrid :param nxt: another """ assert(len(cur.fields) == len(nxt.fields)) self.cur = cur self.nxt = nxt def swap(self): for w_c, w_n in zip(self.cur.fields, self.nxt.fields): w_c, w_n = w_n, w_c self.cur, self.nxt = self.nxt, self.cur
"""Factories for the mobileapps_store app.""" # import factory # from ..models import YourModel
class GCode(object): def comment(self): return "" def __str__(self) -> str: return f"{self.code()}{self.comment()}" class G0(GCode): def __init__(self, x=None, y=None, z=None) -> None: if (x is None and y is None and z is None): raise TypeError("G0 needs at least one axis") self.x = x self.y = y self.z = z def coordinate(self): result = [] if self.x is not None: result.append(f"X{self.x}") if self.y is not None: result.append(f"Y{self.y:.4f}") if self.z is not None: result.append(f"Z{self.z}") return result def code(self): return f"G0 {' '.join(self.coordinate())}" class G1(GCode): def __init__(self, x=None, y=None, z=None, feedrate=None) -> None: if (x is None and y is None and z is None and feedrate is None): raise TypeError("G1 needs at least one axis, or a feedrate") self.x = x self.y = y self.z = z self.feedrate = feedrate def coordinate(self): result = [] if self.x is not None: result.append(f"X{self.x}") if self.y is not None: result.append(f"Y{self.y:.4f}") if self.z is not None: result.append(f"Z{self.z}") return result def comment(self): return f"; Set feedrate to {self.feedrate} mm/min" if self.feedrate else "" def code(self): attributes = self.coordinate() if self.feedrate: attributes.append(f"F{self.feedrate}") return f"G1 {' '.join(attributes)}" class G4(GCode): def __init__(self, duration) -> None: self.duration = duration def comment(self): return f"; Wait for {self.duration} seconds" def code(self): return f"G4 P{self.duration}" class G21(GCode): def comment(self): return f"; mm-mode" def code(self): return f"G21" class G54(GCode): def comment(self): return f"; Work Coordinates" def code(self): return f"G54" class G90(GCode): def comment(self): return f"; Absolute Positioning" def code(self): return f"G90" class G91(GCode): def comment(self): return f"; Relative Positioning" def code(self): return f"G91" class M3(GCode): def __init__(self, spindle_speed) -> None: self.spindle_speed = spindle_speed def comment(self): return f"; Spindle on to {self.spindle_speed} RPM" def code(self): return f"M3 S{self.spindle_speed}" class M5(GCode): def comment(self): return f"; Stop spindle" def code(self): return f"M5 S0"
class ListNode: def __init__(self, data): self.data= data self.next= None class Solution: def delete_nth_from_last(self, head: ListNode, n: int) -> ListNode: ans= ListNode(0) ans.next= head first= ans second= ans for i in range(1, n+2): first= first.next while(first is not None): first= first.next second= second.next second.next= second.next.next return ans.next def print_list(self, head: ListNode) -> None: while (head): print(head.data) head = head.next s= Solution() ll_1= ListNode(1) ll_2= ListNode(2) ll_3= ListNode(3) ll_4= ListNode(4) ll_5= ListNode(5) ll_1.next= ll_2 ll_2.next= ll_3 ll_3.next= ll_4 ll_4.next= ll_5 s.print_list(ll_1) new_head= s.delete_nth_from_last(ll_1,2) print() s.print_list(new_head)
#functions with output def format_name(f_name, l_name): if f_name == '' or l_name == '': return "You didn't privide valid inputs" formated_f_name = f_name.title() formated_l_name = l_name.title() #print(f'{formated_f_name} {formated_l_name}') return f'{formated_f_name} {formated_l_name}' #formated_string = format_name('eDgar', 'CanRo') #print(formated_string) #print(format_name('eDgar', 'CanRo')) #output = len('Edgar') print(format_name(input('What is you firts name?: '), input('What is your last name?: ')))
marks=[] passed=[] fail=[] s1=int(input("what did you score?")) marks.append(s1) s2=int(input("what did you score?")) marks.append(s2) s3=int(input("what did you score?")) marks.append(s3) s4=int(input("what did you score?")) marks.append(s4) s5=int(input("what did you score?")) marks.append(s5) s6=int(input("what did you score?")) marks.append(s6) s7=int(input("what did you score?")) marks.append(s7) s8=int(input("what did you score?")) marks.append(s8) s9=int(input("what did you score?")) marks.append(s9) s10=int(input("what did you score?")) marks.append(s10) #print(marks) for mark in marks: if mark>50: passed.append(mark) else: fail.append(mark) """ print(passed) print(fail) """ list_which_failed=int(len(fail)) list_which_passed=int(len(passed)) """ print() print(list_which_passed)""" print("The list of students who failed is " + list_which_failed) print("The list of students who passed is " + list_which_passed)
def Sum(value1, value2=200, value3=300): return value1 + value2 + value3 print(Sum(10)) print(Sum(10, 20)) print(Sum(10, 20, 30)) print(Sum(10, value2=20)) print(Sum(10, value3=30)) print(Sum(10, value2=20, value3=30))
liste = [] entiers = 0 somme = 0 isZero = False while not isZero: number = float(input("Entrez un nombre: ")) if number == 0: isZero = True elif number - int(number) == 0: entiers += 1 somme += number liste += [number] print("Liste:", liste) print("Nombre d'entiers:", entiers) print("Somme des entiers:", somme)
# lis = [x*x for x in range(10)] # print(lis) # #生成器 # generator_ex = (x*x for x in range(10)) # print(generator_ex) # generator_ex = (x*x for x in range(10)) # print(next(generator_ex)) # print(next(generator_ex)) # print(next(generator_ex)) # print(next(generator_ex)) # print(next(generator_ex)) # print(next(generator_ex)) # print(next(generator_ex)) # print(next(generator_ex)) # print(next(generator_ex)) # print(next(generator_ex)) # print(next(generator_ex)) def fib(max): n,a,b =0,0,1 while n < max: a,b =b,a+b yield b n = n+1 # print(a) return 'done' def test_fib(): #fibonacci数列 a = fib(10) print(fib(10)) if __name__ == "__main__": test_fib()
# -*- coding:utf-8 -*- # author: lyl def get_age(): age = 18 name = 'Alex' return age print()
#!/usr/bin/env python3 pwd=os.walk(os.getcwd()) for a,b,c in pwd: for i in c: if re.search('.*\.txt$',i): file_FullPath=os.path.join(a,i) file_open=open(file_FullPath,'r',encoding='gbk') file_read=file_open.read() file_open.close() file_write=open(file_FullPath,'w',encoding='utf-8') file_write.write(file_read) file_write.close()
class Australia(): state_dict = {"NSW": "New South Wales", "V": "Victoria", "Q": "Queensland", "SA": "South Australia", "WA": "Western Australia", "T": "Tasmania", "NT": "Northern Territory", "ACT": "Australian Capital Territory"} constraints = {"NSW": ["V", "Q", "SA", "ACT"], "V": ["SA", "NSW"], "Q": ["NT", "SA", "NSW"], "SA": ["WA", "NT", "Q", "V", "NSW"], "WA": ["SA", "NT"], "T": ["V"], "NT": ["WA", "SA", "Q"], "ACT": ["NSW"]} variables = ["NSW", "WA", "NT", "SA", "Q", "V", "T", "ACT"] geojson = 'geojson/australia.geojson' name = 'australia' class Germany(): state_dict = {"BB": "Brandenburg", "BE": "Berlin", "BW": "Baden-Württemberg", "BY": "Bayern", "HB": "Bremen", "HE": "Hessen", "HH": "Hamburg", "MV": "Mecklenburg-Vorpommern", "NI": "Niedersachsen", "NW": "Nordrhein-Westfalen", "RP": "Rheinland-Pfalz", "SH": "Schleswig-Holstein", "SL": "Saarland", "SN": "Sachsen", "ST": "Sachsen-Anhalt", "TH": "Thüringen"} constraints = {"BB": ["BE", "MV", "SN", "NI", "ST"], "BE": ["BB"], "BW": ["BY", "HE", "RP"], "BY": ["BW", "HE", "TH", "SN"], "HB": ["NI"], "HE": ["NI", "NW", "RP", "BW", "BY", "TH"], "HH": ["NI", "SH"], "MV": ["SH", "NI", "BB"], "NI": ["SH", "HH", "HB", "NW", "HE", "TH", "ST", "BB", "MV"], "NW": ["NI", "HE", "RP"], "RP": ["NW", "HE", "BW", "SL"], "SH": ["NI", "HH", "MV"], "SL": ["RP"], "SN": ["BB", "ST", "TH", "BY"], "ST": ["BB", "NI", "TH", "SN"], "TH": ["ST", "NI", "HE", "BY", "SN"]} variables = ["BB", "BE", "BW", "BY", "HB", "HE", "HH", "MV", "NI", "NW", "RP", "SH", "SL", "SN", "ST", "TH"] geojson = 'geojson/germany.geojson' name = 'germany'
""" Copyright (c) 2018, Ankit R Gadiya BSD 3-Clause License Project Euler Problem 1: Multiples of 3 and 5 Q. If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ def sumAP(x, l): n = int(l / x) return int((x * n * (n + 1)) / 2) if __name__ == "__main__": result = sumAP(3, 999) + sumAP(5, 999) - sumAP(15, 999) print(result)
# -*- coding: utf-8 -*- """ Created on Wed Feb 1 23:41:54 2017 @author: Roberto Piga Version 1 Recursive method Failed because test parser can not call a function """ # define starting variables balance = a = 5000 annualInterestRate = b = 0.18 monthlyPaymentRate = c = 0.02 month = m = 0 def balancer(balance, annualInterestRate, monthlyPaymentRate, month = 0): # base case # 12th month print remaining balance and exit if month == 12: print("Remaining balance:",round(balance, 2)) return True else: # calculate unpaid balance as balance minus the minimum payment unpaidBalance = balance - (balance * monthlyPaymentRate) # add monthly interest to calculate remaining balance remainBalance = unpaidBalance + (annualInterestRate/12.0 * unpaidBalance) # loop to the next month return balancer(remainBalance, annualInterestRate, monthlyPaymentRate, month + 1) balancer(a, b, c)
class ValidationError(Exception): def __init__(self, message): super().__init__(message) class FieldError(Exception): def __init__(self, field_name, available_fields): msg = (f"The field '{field_name}' is not present on your model. " f"Available fields are: {', '.join(available_fields)}") super().__init__(msg) class ParserError(Exception): def __init__(self): msg = (f"You should provide one of html_document, html_tag or HTMLResponse " "object to the model in order to resolve fields with a " "value from the HTML document") super().__init__(msg) class ProjectExistsError(FileExistsError): def __init__(self): super().__init__('The project path does not exist.') class ProjectNotConfiguredError(Exception): def __init__(self): super().__init__(("You are trying to run a functionnality that requires " "you project to be fully configured via your settings file.")) class ModelNotImplementedError(Exception): def __init__(self, message: str=None): super().__init__(("Conditional (When), aggregate (Add, Substract, Multiply, Divide)" f" functions should point to a model. {message}")) class ModelExistsError(Exception): def __init__(self, name: str): super().__init__((f"Model '{name}' is already registered.")) class ImproperlyConfiguredError(Exception): def __init__(self): super().__init__('Your project is not properly configured.') class SpiderExistsError(Exception): def __init__(self, name: str): super().__init__(f"'{name}' does not exist in the registry. " f"Did you create '{name}' in your spiders module?") class ResponseFailedError(Exception): def __init__(self): super().__init__("Zineb will not be able to generate a BeautifulSoup object from the response. " "This is due to a response with a fail status code or being None.") class RequestAborted(Exception): pass class ModelConstrainError(Exception): def __init__(self, field_name, value): super().__init__(f"Constraint not respected on '{field_name}'. '{value}' already present in the model.")
a = int(input()) if a > 0: print(1) elif a== 0: print(0) else: print(-1)
txhash = "0xb538eabb6cea1fc3af58f1474c2b8f1adbf36a209ec8dc5534618b1f2d860c8e" version = "1.1.0" network = "ropsten" address = 'bc1qzse3hm25w3nx70e8nlss6nlfusj7wd4q3m8gax' transaction_data = { 'txid': '6cc808a28150482f783fdff7c99a6245a59437f55bb85575aa31c99ab2b0898b', 'hash': '6cc808a28150482f783fdff7c99a6245a59437f55bb85575aa31c99ab2b0898b', 'version': 2, 'size': 222, 'vsize': 222, 'weight': 888, 'locktime': 1865235, 'vin': [{ 'txid': '3c1324004cf55aff8d4153bda4b6059a82f6fdc4aa43b5b2d26fa3a97eed0e4f', 'vout': 0, 'scriptSig': { 'asm': '3044022052d0875f4412e26e2db1470126f5ccc537e8998bcb5b203e6346ca9b1bf847d2022039182a20dd4c2a30b4155d4b72426aaa6c6cf97c02928c7c06fd4cff89251043[ALL] 0299b7faf388c5d8e6ba1654476083098e896bd2ec384aba20484b8a82d01496b6', 'hex': '473044022052d0875f4412e26e2db1470126f5ccc537e8998bcb5b203e6346ca9b1bf847d2022039182a20dd4c2a30b4155d4b72426aaa6c6cf97c02928c7c06fd4cff8925104301210299b7faf388c5d8e6ba1654476083098e896bd2ec384aba20484b8a82d01496b6' }, 'sequence': 4294967293 }], 'vout': [{ 'value': 0.01, 'n': 0, 'scriptPubKey': { 'asm': '0 89c82f97d743d939d5c9f4068e3a53dfd09ec5fc', 'hex': '001489c82f97d743d939d5c9f4068e3a53dfd09ec5fc', 'reqSigs': 1, 'type': 'witness_v0_keyhash', 'addresses': ['tb1q38yzl97hg0vnn4wf7srguwjnmlgfa30uq3nrwt']} }, { 'value': 1.989997, 'n': 1, 'scriptPubKey': { 'asm': 'OP_DUP OP_HASH160 4c8bda34fa519008db22b421711ee6b9fb52b559 OP_EQUALVERIFY OP_CHECKSIG', 'hex': '76a9144c8bda34fa519008db22b421711ee6b9fb52b55988ac', 'reqSigs': 1, 'type': 'pubkeyhash', 'addresses': ['mnVhBkEWwvP4MMeTBZoZa3GGTVsNm135eG']} }], 'hex': '02000000014f0eed7ea9a36fd2b2b543aac4fdf6829a05b6a4bd53418dff5af54c0024133c000000006a473044022052d0875f4412e26e2db1470126f5ccc537e8998bcb5b203e6346ca9b1bf847d2022039182a20dd4c2a30b4155d4b72426aaa6c6cf97c02928c7c06fd4cff8925104301210299b7faf388c5d8e6ba1654476083098e896bd2ec384aba20484b8a82d01496b6fdffffff0240420f000000000016001489c82f97d743d939d5c9f4068e3a53dfd09ec5fc947edc0b000000001976a9144c8bda34fa519008db22b421711ee6b9fb52b55988ac13761c00', 'blockhash': '0000000005629b78403c6b58bf094b1987dd9e62a9349f71ff4882c05f0ad517', 'confirmations': 24854, 'time': 1603872469, 'blocktime': 1603872469 }
class CognitiveAbilitiesGroupingPolicy: @staticmethod def group(filename: str) -> str: return filename.split(".")[0].split("-")[0]
n=int(input());s=input();r=0;l=len(s) for i in range(l): r+=(ord(s[i])-ord('a')+1)*31**i print(r%1234567891)
# Aula 21 - 09-12-2019 # Como Tratar e Trabalhar Erros!!! # Com base no seguinte dado bruto: dadobruto = '1;Arnaldo;23;m;alexcabeludo2@hotmail.com;014908648117' # 1) Faça uma classe cliente que receba como parametro o dado bruto. # 2) A classe deve iniciar (__init__) guardando o dado bruto nume variável chamada self.dado_bruto # 3) As variáveis código cliente (inteiro), nome, idade (inteiro), sexo, email, telefone # devem iniciar com o valor None # 4) Crie um metodo que pegue o valor bruto e adicione nas variáveis: # código cliente (inteiro), nome, idade (inteiro), sexo, email, telefone # convertendo os valores de string para inteiros quando necessários. # (Faça da forma que vocês conseguirem! O importante é o resultado e não como chegaram nele!) # 5) Crie um metodo salvar que pegue os seguintes dados do cliente e salve em um arquivo. # código cliente (inteiro), nome, idade (inteiro), sexo, email, telefone # 6) crie um metodo que possa atualizar os dados do cliente (código cliente (inteiro), # nome, idade (inteiro), sexo, email, telefone). Este metodo deverá alterar tambem o dado bruto para # que na hora de salvar o dado num arquivo, o mesmo não estaja desatualizado.
#!/usr/bin/env python3 def edit_distance(s1: str, s2: str) -> int: n = len(s1) m = len(s2) edit = [[None for i in range(1 + m)] for j in range(1 + n)] for i in range(1 + m): edit[0][i] = i for i in range(1, 1 + n): edit[i][0] = i for j in range(1, 1 + m): replace = edit[i-1][j-1] insert = 1 + edit[i][j - 1] delete = 1 + edit[i - 1][j] if not (s1[i - 1] == s2[j - 1]): replace += 1 edit[i][j] = min(insert, delete, replace) return edit[n][m] if __name__ == '__main__': s1 = input('s1: ') s2 = input('s2: ') print(edit_distance(s1, s2))
class Rtm: def __init__(self): # As próximas 3 variáveis servem apenas para checagem self.states = [] self.input_alphabet = [] self.output_alphabet = [] self.tapes = { 'input': [], 'history': [], 'output': [] } self.heads = { 'input': 0, 'history': 0 } self.current_state = None self.start_state = None self.final_state = None self.transitions = [] self.blank = 'B' class Transition: def __init__(self, from_state, input_symbol, to_state, output_symbol, shift_direction): self.from_state = from_state self.input_symbol = input_symbol self.to_state = to_state self.output_symbol = output_symbol self.shift_direction = shift_direction # Essas quádruplas só são necessárias para emularmos de forma verossímil a máquina reversível self.set_rw_quadruple() self.set_shift_quadruple() def __str__(self): return "(" + self.from_state + "," + self.input_symbol + ")=(" + self.to_state + "," + self.output_symbol + "," + self.shift_direction + ")" def set_rw_quadruple(self): self.rw_quadruple = { 'from_state': self.from_state, 'input_symbol': self.input_symbol, 'output_symbol': self.output_symbol, 'temporary_state': self.from_state + "_" } def set_shift_quadruple(self): self.shift_quadruple = { 'temporary_state': self.from_state + "_", 'blank_space': '/', 'shift_direction': self.shift_direction, 'to_state': self.to_state } def get_transition(self, state, symbol): index = 0 for transition in self.transitions: if transition.from_state == state and transition.input_symbol == symbol: return transition, index index += 1 exit("Nenhuma transição encontrada para o estado e símbolo atuais") def add_state(self, name): name = name.strip() if self.current_state is None: self.start_state = name self.current_state = name self.states.append(name) self.final_state = name def add_transition(self, from_state, input_symbol, to_state, output_symbol, shift_direction): if from_state in self.states: if to_state in self.states: transition = self.Transition(from_state, input_symbol, to_state, output_symbol, shift_direction) self.transitions.append(transition) else: exit("O estado ", to_state, " não existe") else: exit("O estado ", from_state, " não existe") def set_input_alphabet(self, input_alphabet): for symbol in input_alphabet: self.input_alphabet.append(symbol) self.input_alphabet.append(self.blank) def set_output_alphabet(self, output_alphabet): for symbol in output_alphabet: self.output_alphabet.append(symbol) def set_input_tape(self, tape): for symbol in tape: if symbol not in self.input_alphabet: exit("O símbolo ", symbol, " não pertence ao alfabeto de input.") self.tapes['input'] = tape self.tapes['input'].append(self.blank) def execute(self, transition: Transition, backward=False): if backward: # Avança a cabeça da fita if transition.shift_quadruple['shift_direction'] == 'L': self.heads['input'] += 1 elif transition.shift_quadruple['shift_direction'] == 'R': self.heads['input'] -= 1 self.tapes['input'][self.heads['input']] = transition.rw_quadruple['input_symbol'] self.current_state = transition.rw_quadruple['from_state'] else: # Escreve o output no fita do input self.tapes['input'][self.heads['input']] = transition.rw_quadruple['output_symbol'] # Avança para o próximo estado self.current_state = transition.shift_quadruple['to_state'] # Avança a cabeça da fita if transition.shift_quadruple['shift_direction'] == 'R': self.heads['input'] += 1 elif transition.shift_quadruple['shift_direction'] == 'L': self.heads['input'] -= 1 def retraced_computation(self): while True: if self.current_state == self.start_state and self.heads['input'] == 0: return transition_index = self.tapes['history'][self.heads['history']] self.execute(self.transitions[transition_index], backward=True) print(self.tapes['input'], "\t", self.tapes['history']) # Avança para o próximo estado self.tapes['history'].pop() self.heads['history'] -= 1 def forward_computation(self): while True: if self.current_state == self.final_state and self.heads['input'] >= len(self.tapes['input']): # Atualiza a cabeça da fita history para o final da fita self.heads['history'] = len(self.tapes['history']) - 1 return current_symbol = self.tapes['input'][self.heads['input']] transition, transition_index = self.get_transition(self.current_state, current_symbol) # Salva a transição self.tapes['history'].append(transition_index) print(self.tapes['input'], "\t", self.tapes['history']) self.execute(transition) def copy_output(self): # Salva o output na fita output self.tapes['output'] = self.tapes['input'].copy() def run(self): # Fase 1 print("Computing...") print("Input Tape", "\t\t\t", "History Tape") self.forward_computation() # Fase 2 print("Copying from input to output...") self.copy_output() # Fase 3 print("Retracing...") print("Input Tape", "\t\t\t", "History Tape") self.retraced_computation() print('Input: ', self.tapes['input']) print('History: ', self.tapes['history']) print('Output: ', self.tapes['output'])
FILTERS = [ [4, 1, 2], [2, 2, 4], [1, 4, 4], [1, 4, 1] ] MSG_LEN = 16 KEY_LEN = 16 BATCH_SIZE = 512 NUM_EPOCHS = 60 LEARNING_RATE = 0.0008
def metade(preco=0, formato=False): res = preco / 2 return res if formato is False else moeda(res) def dobro(preco=0, formato=False): res = preco * 2 return res if formato is False else moeda(res) def aumento(preco=0, taxa=0, formato=False): res = preco * (1 + taxa/100) return res if formato is False else moeda(res) def reducao(preco=0, taxa=0, formato=False): res = preco * (1 - taxa/100) return res if formato is False else moeda(res) def moeda(preco=0, moeda='R$'): return f' {moeda} {preco:7.2f}'.replace('.',',')
# 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 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. """ Utilities for managing globals for the environment. """ def create_initial_globals(path): """ Emulates a ``globals()`` call in a freshly loaded module. The implementation of this function is likely to raise a couple of questions. If you read the implementation and nothing bothered you, feel free to skip the rest of this docstring. First, why is this function in its own module and not, say, in the same module of the other environment-related functions? Second, why is it implemented in such a way that copies the globals, then deletes the item that represents this function, and then changes some other entries? Well, these two questions can be answered with one (elaborate) explanation. If this function was in the same module with the other environment-related functions, then we would have had to delete more items in globals than just ``create_initial_globals``. That is because all of the other function names would also be in globals, and since there is no built-in mechanism that return the name of the user-defined objects, this approach is quite an overkill. *But why do we rely on the copy-existing-globals-and-delete-entries method, when it seems to force us to put ``create_initial_globals`` in its own file?* Well, because there is no easier method of creating globals of a newly loaded module. *How about hard coding a ``globals`` dict? It seems that there are very few entries: ``__doc__``, ``__file__``, ``__name__``, ``__package__`` (but don't forget ``__builtins__``).* That would be coupling our implementation to a specific ``globals`` implementation. What if ``globals`` were to change? """ copied_globals = globals().copy() copied_globals.update({ '__doc__': 'Dynamically executed script', '__file__': path, '__name__': '__main__', '__package__': None }) del copied_globals[create_initial_globals.__name__] return copied_globals