content
stringlengths
7
1.05M
#! /usr/bin/python3 def a(k, x1, x2, x3, x4, x5): def b(): def c(): return a(k, x1, x2, x3, x4, x5) nonlocal k k -= 1 return a(k, c(), x1, x2, x3, x4) return x4 + x5 if k <= 0 else b() for i in range(0,8): print(a(i,1,-1,-1,1,0))
""" 57. Insert Interval Example 1: Input: intervals = [[1,3],[6,9]], newInterval = [2,5] Output: [[1,5],[6,9]] Example 2: Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8] Output: [[1,2],[3,10],[12,16]] Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10]. """ # Definition for an interval. # class Interval: # def __init__(self, s=0, e=0): # self.start = s # self.end = e class Solution: def insert(self, intervals, newInterval): """ :type intervals: List[Interval] :type newInterval: Interval :rtype: List[Interval] """ out = [] i, n = 0, len(intervals) while i<n and intervals[i].end < newInterval.start: out+=[intervals[i]] i+=1 while i<n and intervals[i].start<=newInterval.end: newInterval.start = min(newInterval.start, intervals[i].start) newInterval.end = max(newInterval.end, intervals[i].end) i+=1 out+=[newInterval] if i<n: out += intervals[i:] return out class Solution: def insert(self, intervals, newInterval): """ :type intervals: List[Interval] :type newInterval: Interval :rtype: List[Interval] """ s, e = newInterval.start, newInterval.end left, right = [], [] for i in intervals: if i.end < s: left += i, elif i.start > e: right += i, else: s = min(s, i.start) e = max(e, i.end) return left + [Interval(s, e)] + right def insert(self, intervals, newInterval): s, e = newInterval.start, newInterval.end parts = merge, left, right = [], [], [] for i in intervals: parts[(i.end < s) - (i.start > e)].append(i) if merge: s = min(s, merge[0].start) e = max(e, merge[-1].end) return left + [Interval(s, e)] + right
class Solution: def fizzBuzz(self, n): """ :type n: int :rtype: List[str] """ list = [] for i in range(1, n + 1): div3 = i % 3 == 0 div5 = i % 5 == 0 if div3 and div5: list.append("FizzBuzz") elif div3: list.append("Fizz") elif div5: list.append("Buzz") else: list.append(str(i)) return list if __name__ == '__main__': sol = Solution() print(sol.fizzBuzz(15))
""" * Create Image. * * The createImage() function provides a fresh buffer of pixels to play with. * This example creates an image gradient. """ def setup(): size(640, 360) global img img = createImage(230, 230, ARGB) pixCount = len(img.pixels) for i in range(pixCount): a = map(i, 0, pixCount, 255, 0) img.pixels[i] = color(0, 153, 204, a) def draw(): background(0) image(img, 90, 80) image(img, mouseX - img.width / 2, mouseY - img.height / 2)
class Match(): def __init__(self, span, value): self.span = span self.token = span.text self.value = value self.start = span[0].idx self.end = span[0].idx + len(span.text) def contains(self, other): return self.start <= other.start and self.end >= other.end def __repr__(self): return 'Match (%s, %d, %d)' % \ (self.value, self.start, self.end)
def thesaurus(*args, sort=False) -> dict: """Формирует словарь, в котором ключи — первые буквы слов, а значения — списки, содержащие слова, начинающиеся с соответствующей буквы :param *args: перечень слов :param sort: признак необходимости сортировки словаря по алфавиту (True - сортировать, False - не сортировать) :return: словарь слов по первым буквам""" if sort: args = sorted(list(args)) # Changed in version 3.7: Dictionary order is guaranteed to be insertion order dict_out = {} for word in args: dict_value = dict_out.setdefault(word[0], list()) if word not in dict_value: dict_value.append(word) dict_out[word[0]] = dict_value return dict_out print(thesaurus("Иван", "Мария", "Петр", "Илья"))
class Mapping(): # TODO: add support for one_of=str(group) which extends required # It should be used to group multiple mappings together and only one of # the mapping of the group can and has to be set. Mappings of one_of # cannot have default value. def __init__(self, name, source=None, required=True, default=None, inherited=False, func=None, allowed_types=str): self.name = name self.source = source if source is not None else name self.required = required self.default = default self.inherited = inherited self.func = func self.allowed_types = allowed_types if not isinstance(allowed_types, tuple): self.allowed_types = (self.allowed_types, ) if self.required == False and self.default is None and type(None) not in self.allowed_types: self.allowed_types = self.allowed_types + (type(None), ) # Enable using mapping in dict constructor def __iter__(self): yield self.name yield self
# generated from genmsg/cmake/pkg-genmsg.context.in messages_str = "/home/ubuntu/catkin_ws/src/navigation/costmap_2d/msg/VoxelGrid.msg" services_str = "" pkg_name = "costmap_2d" dependencies_str = "std_msgs;geometry_msgs;map_msgs" langs = "gencpp;genlisp;genpy" dep_include_paths_str = "costmap_2d;/home/ubuntu/catkin_ws/src/navigation/costmap_2d/msg;std_msgs;/opt/ros/indigo/share/std_msgs/cmake/../msg;geometry_msgs;/opt/ros/indigo/share/geometry_msgs/cmake/../msg;map_msgs;/opt/ros/indigo/share/map_msgs/cmake/../msg;sensor_msgs;/opt/ros/indigo/share/sensor_msgs/cmake/../msg;nav_msgs;/opt/ros/indigo/share/nav_msgs/cmake/../msg;actionlib_msgs;/opt/ros/indigo/share/actionlib_msgs/cmake/../msg" PYTHON_EXECUTABLE = "/usr/bin/python" package_has_static_sources = '' == 'TRUE' genmsg_check_deps_script = "/opt/ros/indigo/share/genmsg/cmake/../../../lib/genmsg/genmsg_check_deps.py"
# Language: Python 3 i = 4 d = 4.0 s = 'HackerRank ' int2 = int(input()) double2 = float(input()) string2 = input() int2_i = i + int2 double2_d = d + double2 string2_s = s + string2 print(int2_i, double2_d, string2_s, sep="\n")
a = list(map(int,input().split())) def heapsort(arr,e): i=1 while i<e: upheap(arr,i) i+=1 i-=1 while i>0: tmp=arr[0] arr[0]=arr[i] arr[i]=tmp i-=1 downheap(arr,i) def leftC(i): return int(((i) + 1) * 2 - 1) def rightC(i): return int(((i) + 1) * 2) def parent(i): return int(((i) + 1) / 2 - 1) def upheap(arr,n): while n>0: m = parent(n) if arr[m]<arr[n]: tmp=arr[m] arr[m]=arr[n] arr[n]=tmp else: break n=m def downheap(arr,n): m=0 tmp=0 while True: lc=leftC(m) rc=rightC(m) if lc>=n: break if arr[lc]>arr[tmp]: tmp=lc if rc<n and arr[rc]>arr[tmp]: tmp=rc if tmp==m: break swp=arr[tmp] arr[tmp]=arr[m] arr[m]=swp m=tmp heapsort(a,len(a)) #print(a)
fname = input('Enter the file name') try: f = open(fname) except: print('The file could not be opened') quit() total = 0 count = 0 for line in f: if 'X-DSPAM-Confidence' in line: print(line) i = line.find(': ') + 1 total += float(line[i:len(line)]) count += 1 print('Average spam confidence:', total / count)
# -*- coding: utf-8 -*- # @Author : Ecohnoch(xcy) # @File : configs.py # @Function : TODO app_redis_hostname = 'my_redis' app_redis_port = 6379 app_info_key = 'INFO_KEY' app_response_key = 'RESPONSE_KEY' app_error_key = 'ERROR_KEY' app_kafka_host = 'my_kafka:9092' app_kafka_topic = 'user_queue' app_kafka_key = 'user_requests' app_group_id = 'calculator' app_web_host = 'http://face_storage:12350' app_file_interface = '/get_image_file' call_interval = 1 sleep_interval = 7
# DROP TABLES songplay_table_drop = "DROP TABLE IF EXISTS songplays" user_table_drop = "DROP TABLE IF EXISTS users" song_table_drop = "DROP TABLE IF EXISTS songs" artist_table_drop = "DROP TABLE IF EXISTS artists" time_table_drop = "DROP TABLE IF EXISTS time" # CREATE TABLES songplay_table_create = ("""CREATE TABLE IF NOT EXISTS songplays (songplay_id SERIAL PRIMARY KEY, start_time bigint NOT NULL, user_id int NOT NULL, level varchar NOT NULL, song_id varchar, artist_id varchar, session_id int NOT NULL, location varchar NOT NULL, user_agent varchar NOT NULL) """) user_table_create = ("""CREATE TABLE IF NOT EXISTS users ( user_id int PRIMARY KEY, first_name varchar NOT NULL, last_name varchar NOT NULL, gender varchar NOT NULL, level varchar NOT NULL) """) song_table_create = ("""CREATE TABLE IF NOT EXISTS songs ( song_id varchar PRIMARY KEY, title varchar NOT NULL, artist_id varchar NOT NULL, year int, duration float) """) artist_table_create = ("""CREATE TABLE IF NOT EXISTS artists ( artist_id varchar PRIMARY KEY, name varchar NOT NULL, location varchar, latitude float, longitude float) """) time_table_create = ("""CREATE TABLE IF NOT EXISTS time ( start_time bigint NOT NULL, hour int NOT NULL, day int NOT NULL, week int NOT NULL, month int NOT NULL, year int NOT NULL, weekday int NOT NULL) """) # INSERT RECORDS songplay_table_insert = ("""INSERT INTO songplays (start_time, user_id, level, song_id, artist_id, session_id, location, user_agent) VALUES (%s, %s, %s, %s, %s, %s, %s, %s) ON CONFLICT DO NOTHING """) user_table_insert = ("""INSERT INTO users (user_id, first_name, last_name, gender, level) VALUES (%s, %s, %s, %s, %s) ON CONFLICT(user_id) DO UPDATE SET level = excluded.level """) song_table_insert = ("""INSERT INTO songs (song_id, title, artist_id, year, duration) VALUES (%s, %s, %s, %s, %s) ON CONFLICT DO NOTHING """) artist_table_insert = ("""INSERT INTO artists (artist_id, name, location, latitude, longitude) VALUES (%s, %s, %s, %s, %s) ON CONFLICT DO NOTHING """) time_table_insert = ("""INSERT INTO time (start_time, hour, day, week, month, year, weekday) VALUES (%s, %s, %s, %s, %s, %s, %s) ON CONFLICT DO NOTHING """) # FIND SONGS song_select = ("""SELECT song_id, artists.artist_id FROM songs JOIN artists ON songs.artist_id=artists.artist_id WHERE title = %s AND name = %s AND duration = %s """) # QUERY LISTS create_table_queries = [songplay_table_create, user_table_create, song_table_create, artist_table_create, time_table_create] drop_table_queries = [songplay_table_drop, user_table_drop, song_table_drop, artist_table_drop, time_table_drop]
""" * * Author: Juarez Paulino(coderemite) * Email: juarez.paulino@gmail.com * """ for _ in [0]*int(input()): n,x,*a=map(int,input().split()) a=sorted(a) b=a[0]-a[1] print(min(x,n-1+b)-b)
""" pierre de fermat 17th frensh mathematician century: * a^p -a --> a is all numbers from 1 to p not including p * if all the outcome from the quation are divisble by p then p is a prime * note:we dont need to include the number it self because the outcome will be always divisble by the number """ number = 5 def fermate(number): for i in range(1, number): m = i ** number - i print(m) if m % number == 0: continue else: return False return True x = fermate(number) print(x) #-->ture
class DjangoUser(object): def dangerous_method(self): pass def safe_method(self): pass def get_user(): # without an inference tip, this will be un-inferrable return DjangoUser.objects.get(id=1337) user = get_user() # dangerous_method call #1 user.dangerous_method() def get_users(): return DjangoUser.objects.bulk_create() # dangerous_method call #2 users = get_users() for user in users: user.dangerous_method() # dangerous_method call #3 # Chained call all_users = DjangoUser.objects.all() all_users.latest().dangerous_method() # dangerous_method call #4 all_users.filter().order_by().all().first().dangerous_method() # dangerous_method call #5 # vanilla python method call DjangoUser().dangerous_method() # not a call DjangoUser.dangerous_method def dangerous_method(): pass # not a call on DjangoUser dangerous_method() DjangoUser().safe_method()
[ i+j for i in range(1) for j in range(2) ] { x * x for x in seq } { y.attr : z() for y, z in mapping }
# Adding a new method during runtime: class A: def foo(self): print('A.foo()') x = A() y = A() x.foo() # A.foo() y.foo() # A.foo() def foo2(self): print('A.foo2()') A.foo2 = foo2 x.foo2() # A.foo2() y.foo2() # A.foo2()
# imgur key client_id = '757aa7465befd6c' client_secret = '83a2c6c8c7465d26236561a4e9bd15edb326805c' fgoAlbum_id = 'b3ylv' gmAlbum_id = '0HaTw' foodAlbum_id = 'XGsgM' access_token = '3b74c308d3d087d3b14518d24ffe92d0f5162f3f' refresh_token = '804352730072e91b4f0f0d1ebad4620c30837912' # line bot key line_channel_access_token = 'DAFd0LtkvMBe8q9eiyI9sVwf2ROonRaG5MlrjBFIfifpmgHjQPEwWuVpy336Id5l1xVgYlWRb2dHfizeP4TEPvGNcNyIPV8qBpTO7GqKGxIzk3ernbRem0nIEIhvvHQpnTEa29jFfDzpiBzDlyZtIgdB04t89/1O/w1cDnyilFU=' line_channel_secret = '4f9d63b51a6a67bf20235f282a8c0843' #Get Content List clientDrawList = ["抽", "抽卡"] clientEatList = ["吃", "吃什麼", "要吃啥", "甲三小"] clientDoList = ["要乾麻", "杯沖啥", "接下來?"] clientGmList = ["早", "早安", "morning", "good morning", "早r"] #Reply Content List foodList = ["麥噹噹", "肯德雞", "拿坡里", "胖老爹", "小火鍋", "鐵板類", "咖哩飯", "肉燥飯", "刀削麵", "拉麵", "炒飯", "飯捲", "炸物", "湯包", "鍋貼"] entertainmentList = ["打街機", "玩桌遊", "書店", "逛百貨", "回家", "看電影", "唱歌"]
#!/usr/bin/python3.7+ # -*- coding:utf-8 -*- """ @auth: cml @date: 2021/2/23 @desc: ... """
# -*- coding: utf-8 -*- def main(): a = int(input()) b = int(input()) c = int(input()) d = int(input()) p = int(input()) print(min(a * p, b + max(0, (p - c)) * d)) if __name__ == '__main__': main()
score_configs = { 'CHEAT' : 1, 'TRUST' : -1, 'single_cheat' : 3, 'single_trust' : -1, 'both_trust' : 2, 'both_cheat' : 0, } players_configs = { 'Bot': 3, 'Follower': 3, 'Gambler': 3, 'Pink': 3, 'Follower_2': 3, 'Black': 3, 'Single_Mind': 3, 'Sherlock': 3, } total_num = 0 for v in players_configs.values(): total_num += v game_configs = { 'total_player_num': total_num, 'each_game_num': 10, 'update_player_num': 5, 'mistake_prob': 5, 'total_rounds': 15, }
class PillowtopCheckpointReset(Exception): pass class PillowNotFoundError(Exception): pass class PillowtopIndexingError(Exception): pass class PillowConfigError(Exception): pass class BulkDocException(Exception): pass
# -*- coding: utf-8 -*- """ @File : __init__.py @Time : 2019/12/22 下午8:52 @Author : yizuotian @Description : """
nome = input('Digite seu nome completo: ') apenasletras = nome.replace(" ","") dividido = nome.split() primeironome = dividido[0] print('''Em maiusculo: {} Em minúsculo: {} Nº de letras total: {} Nº de letras primeiro nome: {} '''.format(nome.upper(),nome.lower(),len(apenasletras),len(primeironome)))
# Write a program, which keeps a dictionary with synonyms. The key of the dictionary will be the word. The value will # be a list of all the synonyms of that word. You will be given a number n – the count of the words. After each word, # you will be given a synonym, so the count of lines you have to read from the console is 2 * n. You will be receiving a # word and a synonym each on a separate line like this: #  {word} #  {synonym} # If you get the same word twice, just add the new synonym to the list. # Print the words in the following format: # {word} - {synonym1, synonym2… synonymN} n_inputs = int(input()) dict_synonyms = {} while not n_inputs == 0: word = input() synonym = input() if word not in dict_synonyms: dict_synonyms[word] = [] dict_synonyms[word].append(synonym) n_inputs -= 1 for word, synonym in dict_synonyms.items(): print(f"{word} - ", end="") print(*synonym, sep=", ") # # INPUT # 3 # cute # adorable # cute # charming # smart # clever # # OUTPUT # cute - adorable, charming # smart - clever # # INPUT 1 # 2 # task # problem # task # assignment # # OUTPUT # task – problem, assignment
"""Configuration file for mapping counting and detection tasks.""" file_mapping_counting = { "Columbus_CSUAV_AFRL": "COWC_Counting_Columbus_CSUAV_AFRL.tbz", "Potsdam_ISPRS": "COWC_Counting_Potsdam_ISPRS.tbz", "Selwyn_LINZ": "COWC_Counting_Selwyn_LINZ.tbz", "Toronto_ISPRS": "COWC_Counting_Toronto_ISPRS.tbz", "Utah_AGRC": "COWC_Counting_Utah_AGRC.tbz", "Vaihingen_ISPRS": "COWC_Counting_Vaihingen_ISPRS.tbz", } file_mapping_detection = { "Columbus_CSUAV_AFRL": "COWC_Detection_Columbus_CSUAV_AFRL.tbz", "Potsdam_ISPRS": "COWC_Detection_Potsdam_ISPRS.tbz", "Selwyn_LINZ": "COWC_Detection_Selwyn_LINZ.tbz", "Toronto_ISPRS": "COWC_Detection_Toronto_ISPRS.tbz", "Utah_AGRC": "COWC_Detection_Utah_AGRC.tbz", "Vaihingen_ISPRS": "COWC_Detection_Vaihingen_ISPRS.tbz", }
class Solution: def licenseKeyFormatting(self, S: str, K: int) -> str: result = [] for c in reversed(S): if c != '-': if len(result) % (K + 1) == K: result.append('-') result.append(c.upper()) return ''.join(reversed(result))
class Solution: def myAtoi(self, str: str) -> int: s = str if not s: return 0 s = s.strip() print(s) if s == "": return 0 multiplier = 1 if s[0] == '+': multiplier = 1 s = s[1:] elif s[0] == '-': multiplier = -1 s = s[1:] elif not s[0].isdigit(): return 0 result = "" print (s) for char in s: if char.isdigit(): result = result+char else: break if result != "": int_max = (2**31) - 1 int_min = -(2**31) number = int(result) * multiplier if number > int_max: return int_max elif number < int_min : return int_min else: return number else: return 0
age = 40 # tipo inteiro age_text = "40" # tipo string print(age) print(age_text) print(type(age)) # type -> retorna o tipó de dado print(type(age_text)) # As estruturas de dados tem atributos e metodos # dir -> retorna a lista de metodo do objeto. my_name = ('Carl') print(my_name) print(dir(my_name)) print(help(my_name.capitalize)) # Help -> explica o metodo
def isprime(n): c=0 for i in range(1,n+1): if n%i==0: c+=1 if c==2: print("prime number") else: print("not a prime number") def factorial(n): f=1 for i in range(1,n+1): f*=i print(f)
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode: def postdfs(stop): if postorder and inorder[-1] != stop: root = TreeNode(postorder.pop()) root.right = postdfs(root.val) inorder.pop() root.left = postdfs(stop) return root return postdfs(None)
SYSTEMS = "root.properties.systems" ITEMS = f"{SYSTEMS}.items" ID = f"{SYSTEMS}.items.properties.id" NAME = f"{SYSTEMS}.items.properties.name" VENDOR = f"{SYSTEMS}.items.properties.vendor" MODEL = f"{SYSTEMS}.items.properties.model" TYPE = f"{SYSTEMS}.items.properties.type" SERIAL_NUMBER = f"{SYSTEMS}.items.properties.serial_number" FIRMWARE = f"{SYSTEMS}.items.properties.firmware" FIRMWARE_ITEMS = f"{FIRMWARE}.items" FIRMWARE_NAME = f"{FIRMWARE}.items.properties.name" FIRMWARE_VERSION = f"{FIRMWARE}.items.properties.version" FIRMWARE_LAST_UPDATE = f"{FIRMWARE}.items.properties.last_updated_timestamp" SOFTWARE = f"{SYSTEMS}.items.properties.software" SOFTWARE_ITEMS = f"{SOFTWARE}.items" SOFTWARE_NAME = f"{SOFTWARE}.items.properties.name" SOFTWARE_VERSION = f"{SOFTWARE}.items.properties.version" SOFTWARE_SERIAL_NUMBER = f"{SOFTWARE}.items.properties.serial_number" SOFTWARE_LAST_UPDATE = f"{SOFTWARE}.items.properties.last_updated_timestamp" systems_rules = { SYSTEMS: { "type": "array", "min_properties": [ "vendor", "model", "type", ], }, ITEMS: { "type": "object", "min_required": ["vendor", "model", "type"], }, ID: {"type": ["string", "null"]}, NAME: {"type": ["string", "null"]}, VENDOR: {"type": ["string", "null"]}, MODEL: {"type": ["string", "null"]}, TYPE: {"type": ["string", "null"]}, SERIAL_NUMBER: {"type": ["string", "null"]}, FIRMWARE: { "type": "array", "min_properties": [ "name", "version", ], }, FIRMWARE_ITEMS: { "type": "object", "min_required": ["name", "version"], }, FIRMWARE_NAME: {"type": ["string", "null"]}, FIRMWARE_VERSION: {"type": ["string", "null"]}, FIRMWARE_LAST_UPDATE: {"type": ["string", "null"]}, SOFTWARE: { "type": "array", "min_properties": [ "name", "version", ], }, SOFTWARE_ITEMS: { "type": "object", "min_required": ["name", "version"], }, SOFTWARE_NAME: {"type": ["string", "null"]}, SOFTWARE_VERSION: {"type": ["null", "string"]}, SOFTWARE_LAST_UPDATE: {"type": ["string", "null"]}, }
""" A pacman package builder. .. moduleauthor:: James Reed <jcrd@tuta.io> """
# Project Description located @ https://www.dumas.io/teaching/2021/fall/mcs260/nbview/projects/project3.html # MCS 260 Fall 2021 Project 3 # Umar Chaudhry # I completed this project completely with my own work and followed the project description to the best of my ability. " Create functions that help analyze orbits/cycles " def orbit(f,x0,n): """ Compute the first `n` terms of the orbit of `x0` under the function `f`. Arguments: `f` - a function (should take one integer argument and return an integer) `x0` - a value of the type that `f` accepts as its argument `n` - the number of points to compute (a positive integer) Returns: A list of length `n` containing the values [ x0, f(x0), f(f(x0)), f(f(f(x0))), ... ] """ values = [x0] for i in range(n-1): values.append(f(x0)) # update 'x0' so the function can be applied repeatedly 'n' amount of times x0 = f(x0) return values def orbit_data(f,x0): """ Repeatedly apply function `f` to initial value `x0` until some value is seen twice. Return dictionary of data about the observed behavior. Arguments: `f` - a function (should take one integer argument and return an integer) `x0` - a value of the type that `f` accepts as its argument Returns: Dictionary with the following keys (after each key is a description of the associated value): "initial": The part of the orbit up to, but not including, the first value that is ever repeated. "cycle": The part of the orbit between the first and second instances of the first value that appears twice, including the first but not the second. In other words, the entire orbit consits of the "initial" part followed by the "cycle" repeating over and over again. Example: Suppose that applying f repeatedly to start value 11 gives this sequence: 11, 31, 12, 5, 6, 2, 8, 19, 17, 8, 19, 17, 8, 19, 17, 8, ... Then the return value would be: { "initial":[11, 31, 12, 5, 6, 2], "cycle": [8,19,17] } (If the orbit of `x0` doesn't end up in a cycle, it's ok for this function to run forever trying to find one.) """ results = {} # 'sequence' will be used to track output of 'f(x0)' called repeatedly on itself and # determine the data under the "initial" and "cycle" keys of 'results' sequence = [x0] # 'seen' will be a boolean to test if a value in the output has been repeated seen = False # indice counter will be used to determine the indice in 'sequence' where # a value has been repeated and use that information to find the 'initial' and 'cycle' keys indice_counter = 0 while True: # increment the indice at the start as 'sequence' already has one element indice_counter += 1 # if a value has been repeated, the 'initial' and 'cycle' keys can be assigned to 'results' if seen == True: # assign all the values from the beginning of 'sequence' up until the indice where a cycle occurs results["initial"] = sequence[:-(len(sequence[sequence.index(seen_value):(indice_counter+1)]))] # assign all the values from where the first instance of the repeated value was mentioned up until when it was repeated results["cycle"] = sequence[sequence.index(seen_value):indice_counter] break if f(x0) not in sequence: sequence.append(f(x0)) else: # still add repeated element to the list but make note of its indice by decreasing 'indice_counter' # in order to have the correct indice of the repeated value in the next iteration of the while loop sequence.append(f(x0)) # assign the repeated value of 'f(x0)' to 'seen_value' to use sequence.index() method in the next iteration seen_value = f(x0) # boolean triggers the condition of a repeated value seen = True indice_counter -= 1 # update 'x0' so the function can be applied repeatedly 'n' amount of times x0 = f(x0) return results def eventual_period(f,x0): """ Determine the length of the periodic cycle that `x0` ends up in. Arguments: `f` - a function (should take one integer argument and return an integer) `x0` - a value of the type that `f` accepts as its argument Returns: The length of the periodic cycle that the orbit of `x0` ends up in. Example: Suppose that applying f repeatedly to start value 11 gives this sequence: 11, 31, 12, 5, 6, 2, 8, 19, 17, 8, 19, 17, 8, 19, 17, 8, ... Then the return value of eventual_period(f,11) would be 3, since the periodic cycle contains the 3 values 8,19,17. (If the orbit of `x0` doesn't end up in a cycle, it's ok for this function to run forever trying to find one.) """ data = orbit_data(f,x0) return len(data["cycle"]) def steps_to_enter_cycle(f,x0): """ Determine the length of the intial part of the orbit of `x0` under `f` before it enters a periodic cycle. Arguments: `f` - a function (should take one integer argument and return an integer) `x0` - a value of the type that `f` accepts as its argument Returns: The number of elements of the orbit of `f` before the first value that repeats. Example: Suppose that applying f repeatedly to start value 11 gives this sequence: 11, 31, 12, 5, 6, 2, 8, 19, 17, 8, 19, 17, 8, 19, 17, 8, ... Then the return value of steps_to_enter_cycle(f,11) would be 6, because there are 6 values in the intial segment of the orbit (i.e. 11, 31, 12, 5, 6, 2) which are followed by a periodic cycle. (If the orbit of `x0` doesn't end up in a cycle, it's ok for this function to run forever trying to find one.) """ data = orbit_data(f,x0) return len(data["initial"]) def eventual_cycle(f,x0): """ Return the periodic cycle that the orbit of x0 ends up in as a list. Arguments: `f` - a function (should take one integer argument and return an integer) `x0` - a value of the type that `f` accepts as its argument Returns: The earliest segment from the orbit of `x0` under `f` that repeats indefinitely thereafter, as a list. Example: Suppose that applying f repeatedly to start value 11 gives this sequence: 11, 31, 12, 5, 6, 2, 8, 19, 17, 8, 19, 17, 8, 19, 17, 8, ... Then eventual_cycle(f,x0) would return [8, 19, 17]. (If the orbit of `x0` doesn't end up in a cycle, it's ok for this function to run forever trying to find one.) """ data = orbit_data(f,x0) return data["cycle"] def smallest_first(L): """ Rotates a list so that its smallest element appears first. Arguments: `L`: A list of integers, no two of them equal Returns: A list that is the result of moving the first element of `L` to the end, repeatedly, until the first element of `L` is the smallest element of the list. Example: smallest_first([46,41,28]) returns [28,46,41] Example: smallest_first([4,2,1]) returns [1,4,2] Example: smallest_first([9,8,7,6,5,4,3,2,1]) returns [1,9,8,7,6,5,4,3,2] """ while True: if L[0] != min(L): L.append(L[0]) L.remove(L[0]) elif L[0] == min(L): break return L def find_cycles(f,start_vals): """ Find all the periodic cycles of the function `f` that appear when you consider orbits of the elements of `start_vals`. Arguments: `f` - a function (should take one integer argument and return an integer) `start_vals` - a list of integers to use as starting values Returns: A list of lists, consisting of all the periodic cycles that are seen in the orbits of the start values from `start_vals`. Each cycle is given with its smallest entry appearing first, and any given cycle appears only once in the list. e.g. If `mwdp` is the mean with digit power function, then find_cycles(mwdp,[65,66,67]) would return [ [28,46,41], [38,51] ] because both 65 and 67 end up in the [28,46,41] cycle and 66 ends up in the [38,51] cycle. """ periodic_cycles = [] for value in start_vals: data = orbit_data(f,value) # use smallest_first() so a repeated cycle is not confused to be new and added to 'periodic cycles' data = smallest_first(data["cycle"]) if data not in periodic_cycles: periodic_cycles.append(data) return periodic_cycles
''' SHORT URLS BOT CONFIGURATION FILE Edit me before start Bot.py! ''' # Token of the bot. Get it one from https://telegram.me/BotFather TOKEN = "992522370:AAGK3lfg3SFjtWgWHoo6pz9BCy8Liiwvmms" # Telegram IDs list of admins of the bot (that can issue /users command) ADMINS = [] # Insert absolute path to database file (.db) DATABASE_PATH = "" # Goo.gl API key. Get it one from https://console.developers.google.com/ GOOGLE_API_KEY = "" # AdfLy UserID and API key. Get it one from https://adf.ly/publisher/tools#tools-api ADFLY_UID = "" ADFLY_API_KEY = "" # BitLy access token. Get it one from https://bitly.com/a/oauth_apps BITLY_ACCESS_TOKEN = ""
my_room = { 'plaats': "Vlijmen", 'straat naam': "Molenstraat" , 'postcode': "5251 EN", 'huisnummer': 9, 'surface': 20, 'hoogte': 3, 'lengte': 5, 'breedte': 4, 'banken': 1, 'bureaus': 1, 'kasten': 1, 'deur': 1, 'ramen': 4, 'bed': 1, }
# coding=utf8 # Copyright 2018 JDCLOUD.COM # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # NOTE: This class is auto generated by the jdcloud code generator program. class TopicModel(object): def __init__(self, topic=None, target=None, parameterList=None): """ :param topic: (Optional) :param target: (Optional) :param parameterList: (Optional) 归档相关的具体参数,需要对归档进行新建,更新,删除,修改对应参数值即可。<br>ossFlag,bucketName,directory,objectName 这四个参数值与ossFlag有关,若ossFlag为false,后面三个可为空,若为true,后面三个为异常数据保存位置,按需要填写即可。<br> 1)如果归档到数据计算服务需要传database,table,type,example,delimiter,targetColumn,analysisColumn,partsTargetColumn,partsAnalysisColumn。<br>2)如果归档到JFS需要传bucket,prefix,infix。<br>3)如果归档到京东云 Elasticsearch需要传host,port,indexType,idType,indexName,indexReferField,timestampFieldFormat,timestampIndexFormat,typeName,idReferField,noResolve,username,password。<br> 4)如果归档到mysql,则需要传host,database,table,username,password,type,example,delimiter。 <br>5)如果要归档到京东云数据库则需要传rdsId,database,table,username,password,type,example,delimiter。 """ self.topic = topic self.target = target self.parameterList = parameterList
#pattern printing #pattern triangle pattern # print("hi pradeep") #Qn-1 ************************************************************ """I=1 #OUTPUT while i<=5: #* j=1 #** while j<=i: #*** print("*",end=" ") #**** j=j+1 #***** print() i=i+1 """ """for i in range (1,6): for j in range(0,i): print("*",end="") print() """ #Qn-2 ****************************************************** """i=1 #OUTPUT while i<=5: #1 j=1 #22 while j<=i: #333 print(i,end=" ") #4444 j=j+1 #55555 print() i=i+1 """ """for i in range (1,6): for j in range(0,i): print(i,end="") print() """ #Qn-3 """i=1 #OUTPUT while i<=5: #1 j=1 #12 while j<=i: #123 print(j,end=" ") #1234 j=j+1 #12345 print() i=i+1 """ '''for i in range (0,7): for j in range(1,i): print(j,end="") print() ''' # i=1 # while i<=5: # b=1 # while b<=5-i: # print(" ",end="") # b=b+1 # j=1 # while j<=i: # print("*",end="") # j=j+1 # print() # i=i+1 # print('pradeep') #Qn-4 ******************************************* # k=1 # i=1 # while i<=5: # b=1 # while b<=5-i: # print(" ",end="") #not working # b=b+1 # j=1 # while j<=k: # print("*",end="") # j=j+1 # print() # k=k+1 # #print() # i=i+1 # #print() #Qn-5 ***************************************** # strl = input("enter string :") # length=len(strl) # for i in range (length): # for j in range (length-i-1): # print(" ",end=" ") # for j in range (i+1): # print(strl[j],end=" ") # print() #output # p # p y # p y t # p y t h # p y t h o # p y t h o n # strl = input("enter string :") # length=len(strl) # for i in range (length): # for j in range (length-i-1): # print(" ",end=" ") # for j in range (i+1): # print(strl[i],end=" ") #we take i in # print() #place of j #output # p # y y # t t t # h h h h # o o o o o # n n n n n n # strl = input("enter string :") # length=len(strl) # for i in range (length): # for j in range (length-i-1): # print(" ",end="") #we remove space # for j in range (i+1): #from(" ") to ("") # print(strl[i],end=" ") # print() # p # y y # t t t # h h h h # o o o o o # n n n n n n # for row in range(7): # for col in range(6): # if col==0 or (col==4 and (row!=1 and row!=2)) or (row==0 or row==6) and (col>0 and col<4)) or(row==3 and (col==3 or col==5)): # print("*",end="") # else: # print(end=" ") # print() #Qn- ************************************** # for row in range(7): # for col in range(5): # if (row in {0,6}) and (col in {1,2,3}): # print("*",end=" ") # elif (row in {1,4,5}) and (col in {0,4}): # print("*",end=" ") # elif (row==2) and (col==0): # print("*",end=" ") # elif (row==3) and (col!=1): # print("*",end=" ") # else: # print(" ",end=" ") # print() #OUTPUT # * * * # * * # * # * * * * # * * # * * # * * * # 2nd method ******************************* #n=5 #for i in range(n): #Qn- *************************************** # s=7 # for r in range(s): # for c in range(s): # if (r==c) or (r+c==s-1): # print("*",end=" ") # else: # print(" ",end=" ") # print() # #output # * * # * * # * * # * # * * # * * # * * #Qn-print z pattern******************************* # i=1 # j=4 # for row in range(0,6): # for col in range(0,6): # if row==0 or row==5: # print("*",end="") # elif row==i and col==j: # print("*",end="") # i=i+1 # j=j-1 # else: # print(end=" ") # print() # output # ****** # * # * # * # * # ****** #2nd method ************************************* # for row in range(0,6): # for col in range(0,6): # if (row==0 or row==5) or (row+col==5): # print("*",end=" ") # else: # print(end=" ") # print() # 3rd metod ************************************** # s=6 # for row in range(s): # for col in range(s): # if (row==0 or row==s-1) or (row+col==s-1): # print("*",end=" ") # else: # print(end=" ") # print() # k=1 # i=1 # while i<=5: # b=1 # while b<=5-i: #remaind # print(" ",end="") # b=b+1 # j=1 # while j<=k: # print("*",end=" ") # j=j+1 # k=k+1 # print() # i=i+1 # #output # * # * * # * * * # * * * * # * * * * * # k=1 # i=1 # while i<=5: # b=1 # while b<=5-i: #remaind # print(" ",end="") # b=b+1 # j=1 # while j<=k: # print("A",end=" ") # j=j+1 # k=k+1 # print() # i=i+1 # A # A A # A A A # A A A A # A A A A A #UNIVERSAL CODE FOR PYRAMID # n=int(input("enter your number")) # k=1 # i=1 # while i<=n: # b=1 # while b<=n-i: #remaind # print(" ",end="") # b=b+1 # j=1 # while j<=k: # print("A",end=" ") # j=j+1 # k=k+1 # print() # i=i+1 #*********************************************** #ALPHABET BY USING ROW COLUMN METHOD # for r in range(4): # for c in range(4): # if (r==0 and (c==0 or c==1 or c==2 or c==3)) or(r==1 and c==2) or (r==2 and c==1) or (r==3 and (c==0 or c==1 or c==2 or c==3)): # print("*",end=" ") # else: # print(" ",end=" ") # print() # * * * * # * # * # * * * * # for r in range(3): # for c in range(4): # if (r==0 and (c==0 or c==2)) or (r==c) or (r==2 and (c==0 or c==2)): # print("*",end=" ") # else: # print(" ", end=" ") # print( ) #print(ord("A")) # PRINT ALPHABET PATTERN BY USING ASCCI VALUE # n=int(input("enter your number :")) # for i in range(n): # for z in range(1,n-i): # print(' ',end='') # for j in range(i+1): # print(chr(65+i),end=" ") # print(" ") # n=int(input("enter your number")) # k=1 # i=0 # while i<=n: # b=1 # while b<=n-i: #remaind # print(" ",end="") # b=b+1 # j=1 # while j<=k: # print(chr(65+i),end=" ") # j=j+1 # k=k+1 # print() # i=i+1 #SNACK PATTERN ***************************** #n=int(input("enter your number")) for i in range(0,15,-1): for j in range(i+1): print(i,end=" ") print() # PALINDROME NUMBER(153=1^2+5^2+3^2=153 THAT IS PALI) # i=int(input("enter number")) # orgi=i # sum=0 # while i>0: # sum=sum+(i%10)*(i%10)*(i%10) # i=i//10 # if sum==orgi: # print(orgi,"it is armstrong no") # else: # print(orgi,"it is not a armstrong no")
class AsyncnotiException(Exception): def __init__(self, message, code): super(Exception, self).__init__(message) self.message = message self.code = code
# class Tree: # def __init__(self, val, left=None, right=None): # self.val = val # self.left = left # self.right = right # class LLNode: # def __init__(self, val, next=None): # self.val = val # self.next = next class Solution: prev = None head = None def solve(self, root): def solve1(root): if root: solve1(root.left) cur = LLNode(root.val) if self.prev: self.prev.next = cur if not self.head: self.head = cur self.prev = cur solve1(root.right) return root solve1(root) return self.head
class Solution: def getNoZeroIntegers(self, n: int) -> List[int]: for A in range(n): B = n - A if '0' not in str(A) and '0' not in str(B): return A, B
print("Teste WHILE") #O numero factorial é como 5 = 5*4*3*2*1 factorial_number = input("Entre com um número:") factorial_number = int(factorial_number) if factorial_number > 0: step = factorial_number total = factorial_number while step > 1: step -= 1 total *= step print("O fatorial de %d é %d"%(factorial_number, total)) elif factorial_number == 0: print("O fatorial de 0 é 1") else: print("O fatorial de um número negativo é inválido")
# output: ok a = {} assert(len(a) == 0) for i in range(0, 100): a[i] = i * 2 assert(len(a) == 100) for i in range(0, 100): assert i in a assert(a[i] == i * 2) assert 101 not in a for i in range(0, 100, 2): del a[i] assert(len(a) == 50) for i in range(0, 100): assert (i in a) == ((i % 2) != 0) a = {} for i in range(0, 100): a[str(i)] = i assert(len(a) == 100) for i in range(0, 100): k = str(i) assert k in a assert(a[k] == i) assert '101' not in a for i in range(0, 100, 2): del a[str(i)] assert(len(a) == 50) for i in range(0, 100): assert (str(i) in a) == ((i % 2) != 0) print('ok')
#CONFIG FILE #Made by Luka Dragar #@thelukadragar operatingmode="xyz" #"xy"---move only in xy #"xyz"--move in xy and z #---------------------------------------------- sendinginterval=0.15 #interval to send points[seconds] #try changing if there are problems myIP= "127.0.0.1" # localhost or your ip "192.168.64.101" myPort=55555 #limit coordinates for moving #change if robot out of reach xmax=600 xmin=0 ymin=0 ymax=600 zmax=300 zmin=-500 zrange=1000 #difference betwen max and min zoffsetcamera=-500#offset according to where you want Z0 to be areatocompare=120000#compares area of your hand to this value #scale in percent livefeedwindowscalex=100 livefeedwindowscaley=100 #camera you can use ip camera like this. #cameratouse="http://192.168.64.102:8080/video" #for ip camera cameratouse=0 #default camera #coordinatemultiplier cormultiplyx=1 cormultiplyy=1 cormultiplyz=1 #sensitivity send move if object moves by px +-1 default sensitivity=1
# the most common user agents by https://techblog.willshouse.com/2012/01/03/most-common-user-agents/ DEFAULT_USER_AGENTS = [ "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/601.6.17 (KHTML, like Gecko) Version/9.1.1 Safari/601.6.17", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/601.5.17 (KHTML, like Gecko) Version/9.1 Safari/601.5.17", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36", "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko", "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:46.0) Gecko/20100101 Firefox/46.0", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:46.0) Gecko/20100101 Firefox/46.0", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Safari/537.36 Edge/13.10586", "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:46.0) Gecko/20100101 Firefox/46.0", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.84 Safari/537.36", "Mozilla/5.0 (Windows NT 6.1; rv:46.0) Gecko/20100101 Firefox/46.0", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/601.6.17 (KHTML, like Gecko) Version/9.1.1 Safari/601.6.17", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.84 Safari/537.36", "Mozilla/5.0 (X11; Linux x86_64; rv:46.0) Gecko/20100101 Firefox/46.0", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/601.4.4 (KHTML, like Gecko) Version/9.0.3 Safari/601.4.4", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.63 Safari/537.36", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36", "Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/50.0.2661.102 Chrome/50.0.2661.102 Safari/537.36", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; Trident/5.0)", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.0; Trident/5.0; Trident/5.0)", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:46.0) Gecko/20100101 Firefox/46.0", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/601.5.17 (KHTML, like Gecko) Version/9.1 Safari/601.5.17", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.84 Safari/537.36", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36", "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko", "Mozilla/5.0 (iPad; CPU OS 9_3_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13E238 Safari/601.1", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.63 Safari/537.36", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/49.0.2623.108 Chrome/49.0.2623.108 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.63 Safari/537.36", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36", "Mozilla/5.0 (iPad; CPU OS 9_3_2 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13F69 Safari/601.1", "Mozilla/5.0 (Windows NT 5.1; rv:46.0) Gecko/20100101 Firefox/46.0", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:46.0) Gecko/20100101 Firefox/46.0", "Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Gecko/20100101 Firefox/45.0", "Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:46.0) Gecko/20100101 Firefox/46.0", "Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.63 Safari/537.36", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0", "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:45.0) Gecko/20100101 Firefox/45.0", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.86 Safari/537.36", "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36", "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:45.0) Gecko/20100101 Firefox/45.0", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/600.5.17 (KHTML, like Gecko) Version/8.0.5 Safari/600.5.17", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/600.8.9 (KHTML, like Gecko) Version/8.0.8 Safari/600.8.9", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/601.3.9 (KHTML, like Gecko) Version/9.0.2 Safari/601.3.9", "Mozilla/5.0 (Windows NT 6.1; rv:38.0) Gecko/20100101 Firefox/38.0", "Mozilla/5.0 (X11; Fedora; Linux x86_64; rv:46.0) Gecko/20100101 Firefox/46.0", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.84 Safari/537.36", ]
class PlayerCharacter: membership = True def __init__(self, name, age): self.name = name self.age = age def shout(self): print(f"My name is {self.name}") @classmethod def adding_things(cls, num1, num2): return cls('Teddy', num1 + num2) @staticmethod def adding_things(cls, num1, num2): return cls('Teddy', num1 + num2) #player1 = PlayerCharacter("Tom", 20) player3 = PlayerCharacter.adding_things(2,3) print(player3.age)
# 42. Trapping Rain Water # Runtime: 131 ms, faster than 12.45% of Python3 online submissions for Trapping Rain Water. # Memory Usage: 15.7 MB, less than 35.74% of Python3 online submissions for Trapping Rain Water. class Solution: # Using Stacks def trap(self, height: list[int]) -> int: ans = 0 stack = [] for i in range(len(height)): while stack and height[i] > height[stack[-1]]: top = stack.pop(-1) if not stack: break # The bar at the top of the stack is bounded by the current bar and a previous bar in the stack. dist = i - stack[-1] - 1 bounded_height = min(height[i], height[stack[-1]]) - height[top] ans += dist * bounded_height stack.append(i) return ans
n=int(input()) for i in range(n): brackets = input() stack=[] dictt={'(':')', '[':']', '{':'}'} flag=0 for b in brackets: #print(stack) if (len(stack)==0) and b in dictt.values(): flag=1 break elif (len(stack)==0) or b in dictt.keys(): stack.append(b) else: if (b in dictt.values()) and (b == dictt[stack[-1]]): del stack[-1] if len(stack)==0 and flag!=1: print("YES") else: print("NO")
def export_docs(documents, output_path): """ Exports a list of dictionaries to a single csv file :param documents: list of dictionaries :param output_path: file path to csv file """ for doc in documents: export_dict(doc, output_path) def export_dict(dictionary, output_path): """ Exports an ordered dictionary to a csv file :param dictionary: dictionary with words as keys and the number of appearances as values :param output_path: file path to csv file """ with open(output_path, 'a', encoding='utf-8') as f: for key in dictionary.keys(): try: f.write('{}:{},'.format(key, dictionary[key])) except UnicodeEncodeError: print("Couldn't encode {}. Skip".format(key)) f.write('\n') f.close() def import_docs(file_path): """ Imports a csv file and returns a list of dictionaries :param file_path: Path of csv file """ with open(file_path, 'r', encoding='utf-8') as f: content = f.read().splitlines() f.close() docs = [] for line in content: docs.append(import_dict(line)) return docs def import_dict(line): """ Converts line of a csv file to a dict :param line: line of csv file :return: dictionary """ dictionary = {} elements = line.split(',') for element in elements: try: key, value = element.split(':') dictionary[key] = int(value) except ValueError: pass return dictionary
{ "targets": [ { "target_name": "index", "sources": ["src/index.cc"], "defines": [ 'ENC_PUBLIC_KEY="<!(echo $ENC_PUBLIC_KEY)"' ] }, ], }
OCTICON_THUMBSDOWN = """ <svg class="octicon octicon-thumbsdown" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path fill-rule="evenodd" d="M7.083 15.986c1.34.153 2.334-.982 2.334-2.183v-.5c0-1.329.646-2.123 1.317-2.614.329-.24.66-.403.919-.508a1.75 1.75 0 001.514.872h1a1.75 1.75 0 001.75-1.75v-7.5a1.75 1.75 0 00-1.75-1.75h-1a1.75 1.75 0 00-1.662 1.2c-.525-.074-1.068-.228-1.726-.415L9.305.705C8.151.385 6.765.053 4.917.053c-1.706 0-2.97.152-3.722 1.139-.353.463-.537 1.042-.669 1.672C.41 3.424.32 4.108.214 4.897l-.04.306c-.25 1.869-.266 3.318.188 4.316.244.537.622.943 1.136 1.2.495.248 1.066.334 1.669.334h1.422l-.015.112c-.07.518-.157 1.17-.157 1.638 0 .921.151 1.718.655 2.299.512.589 1.248.797 2.011.884zm4.334-13.232c-.706-.089-1.39-.284-2.072-.479a63.914 63.914 0 00-.441-.125c-1.096-.304-2.335-.597-3.987-.597-1.794 0-2.28.222-2.529.548-.147.193-.275.505-.393 1.07-.105.502-.188 1.124-.295 1.93l-.04.3c-.25 1.882-.19 2.933.067 3.497a.921.921 0 00.443.48c.208.104.52.175.997.175h1.75c.685 0 1.295.577 1.205 1.335-.022.192-.049.39-.075.586-.066.488-.13.97-.13 1.329 0 .808.144 1.15.288 1.316.137.157.401.303 1.048.377.307.035.664-.237.664-.693v-.5c0-1.922.978-3.127 1.932-3.825a5.862 5.862 0 011.568-.809V2.754zm1.75 6.798a.25.25 0 01-.25-.25v-7.5a.25.25 0 01.25-.25h1a.25.25 0 01.25.25v7.5a.25.25 0 01-.25.25h-1z"></path></svg> """
''' Version Checker module entry point ''' __version__ = '0.2.2-alpha.2'
""" Classes and functions used to create and download LBRY Files. LBRY Files are Crypt Streams created from any regular file. The whole file is read at the time that the LBRY File is created, so all constituent blobs are known and included in the stream descriptor file. """
def main(): while True: try: print(''.join(list(chr(ord(word) - 7) for word in input()))) except EOFError: break pass if __name__ == '__main__': main()
print(""" Witaj, w prostym kalkulatorze ;)""") print("""wybierz porzadana operacje : + - dodawanie - - odejmowanie / - dzielenie * - mnozenie ** - potegowanie """) operacja = input("wybrana operacja : ") a = int(input("Podaj pierwsza liczbe : ")) b = int(input("Podaj druga liczbe : ")) if (operacja == '+'): print("Wynik dodawania", a, "do", b, "wynosi :", a + b) elif (operacja == '-'): print("Wynik odejmowania", a, "od", b, "wynosi :", a - b) elif (operacja == '/'): if (b == 0): print("Nie dziel przez zero !") else: print("Wynik dzielenia", a, "przez", b, "wynosi :", a / b) elif (operacja == '*'): print("Wynik mnozenia", a, "przez", b, "wynosi :", a * b) elif (operacja == '**'): print("Wynik potegowania", a, "do potegi", b, "wynosi :", a ** b) else: print("Wybrano niepoprawna operacje!")
""" 使用封装数据的思想 创建员工类/部门类,修改实现下列功能. 1. 定义函数,打印所有员工信息, 格式:xx的员工编号是xx,部门编号是xx,月薪xx元. 2. 定义函数,打印所有月薪大于2w的员工信息, 格式:xx的员工编号是xx,部门编号是xx,月薪xx元. 3. 定义函数,打印所有员工的部门信息, 格式:xx的部门是xx,月薪xx元. 4. 定义函数,查找薪资最少的员工 5. 定义函数,根据薪资对员工列表升序排列 # 员工列表 list_employees = [ {"eid": 1001, "did": 9002, "name": "师父", "money": 60000}, {"eid": 1002, "did": 9001, "name": "孙悟空", "money": 50000}, {"eid": 1003, "did": 9002, "name": "猪八戒", "money": 20000}, {"eid": 1004, "did": 9001, "name": "沙僧", "money": 30000}, {"eid": 1005, "did": 9001, "name": "小白龙", "money": 15000}, ] # 部门列表 list_departments = [ {"did": 9001, "title": "教学部"}, {"did": 9002, "title": "销售部"}, ] """ class Emplyee: def __init__(self, eid=0, did=0, name="", money=0): self.eid = eid self.did = did self.name = name self.money = money class Departments: def __init__(self, did=0, title=""): self.did = did self.title = title def print_detail(i): print(f"{i.name}的员工编号是{i.eid},部门编号是{i.did},月薪{i.money}元") list_employees = [ Emplyee(1001, 9002, "师父", 60000), Emplyee(1002, 9001, "孙悟空", 50000), Emplyee(1003, 9002, "猪八戒", 20000), Emplyee(1004, 9001, "沙僧", 30000), Emplyee(1005, 9001, "小白龙", 15000), ] list_departments = [Departments(9001, "教学部"), Departments(9002, "销售部"), ] def print_all_member(): for i in list_employees: print_detail(i) print_all_member() # 1 def print_salary_2w(): for i in list_employees: if i.money > 20000: print_detail(i) print_salary_2w()#2 def print_all_eandd_infp(): for l in list_employees: for l2 in list_departments: if l.did == l2.did: l.did = l2.title print(f"{l.name}的部门是{l.did},月薪{l.money}元.") print_all_eandd_infp() # 3 def find_mallist_wage(): min1_wage = list_employees[0] for c in range(len(list_employees)): for c1 in range(1,len(list_employees)): if min1_wage.money>list_employees[c1].money: min1_wage=list_employees[c1] print(min1_wage.name) find_mallist_wage()#4 def descending_list(): for c2 in range(len(list_employees)-1): for c3 in range(c2+1,len(list_employees)): if list_employees[c2].money>list_employees[c3].money: list_employees[c2].money,list_employees[c3].money=list_employees[c3].money,list_employees[c2].money descending_list() for k in list_employees:#5 print_detail(k)
class Request: def __init__(self): self.app = None self.base_url = None self.body = None self.cookies = {} self.fresh = None self.hostname = None self.ip = None self.ips = None self.method = None self.original_url = None self.params = {} # named router parameters self.path = None self.protocol = None self.query = {} self.route = None # contains the currently-matched route, a string self.secure = None self.signed_cookies = None self.stale = None self.subdomains = None self.xhr = None self._headers = {} self._body = None self.locals = {} self.environ = {} def accetpts(self, types): pass def accepts_charsets(self, *charsets): pass def accepts_encodings(self, *encodings): pass def accepts_languages(self, *langs): pass def get(self, field): '''Aliased as request.header(field)''' pass def header(self, field): pass def is_type(self, content_type): pass def range(self, size, *options): pass
#! /usr/bin/env python3 def are_same(serial): if (serial[0] != serial[1] and serial[1] != serial[2] and serial[0] != serial[2]): return False return True def check_serial(serial): try: serials = serial.split('-') except: return False if len(serials) != 3: return False try: X = [ord(a) for a in list(serials[0])] Y = [ord(a) for a in list(serials[1])] Z = int(serials[2]) except ValueError: return False except: return False if not len(X) == 3 or not len(Y) == 3: return False for a in X+Y: if a < 65 or a > 90: return False if are_same(X) or are_same(Y): return False if X[1] + 10 > X[2]: return False if Y[1] - 10 < Y[2]: return False sum1 = X[0] + X[1] + X[2] sum2 = Y[0] + Y[1] + Y[2] if sum1 == sum2: return False if sum1+sum2 != Z: return False if Z % 3 != 0: return False return True
""" Functionality which could be shared among various serializes. """ class InjectUserMixin(object): """ Inject a user to object being created from the logged in user such that the Front-end does not need to supply the value """ def __init__(self, *args, **kwargs): super(InjectUserMixin, self).__init__(*args, **kwargs) self.fields.pop('user') def create(self, validated_data): user = self.context.get('request').user validated_data['user'] = user return super(InjectUserMixin, self).create(validated_data)
class wordsServant: """class to look at words can remove repeadted words""" def __init__(self, text): self.text = text self.deleteWords = ["like", "maybe", "just"] # TODO lowercase for delete words self.list_text = self.text.split(" ") def repeatedWords(self): """ Deletes repeadted words in text """ # so whenever i delete a word # the length of the list goes down by 1 # so that changes everything, so i need to keep track of them LMAO deletionCounter = 0 for counter in range(1, len(self.list_text)): # for every word in the string # if that word is repeated, delete it try: if self.list_text[counter - 1].strip().lower() == self.list_text[counter].strip().lower(): self.list_text.remove(self.list_text[counter - deletionCounter]) deletionCounter += 1 except IndexError as e: # basically if the counter == len of list, it errors out so we just skip it lol pass print(self.list_text) def checkForBadWords(self): """removes bad words from the text""" for word in self.deleteWords: if word in self.list_text: self.list_text.remove(word) if __name__ == "__main__": print("and this runs oops") ws = wordsServant("hello hello and I I yours") ws.repeatedWords() ws.checkForBadWords()
#Exclude variants not in hearing loss panel if Panels not in {ACMG59}: return False
def check_palindrome_rearrangement(string): chars = set() for char in string: if char not in chars: chars.add(char) else: chars.remove(char) return len(chars) < 2 # Tests assert check_palindrome_rearrangement("carrace") assert not check_palindrome_rearrangement("daily") assert not check_palindrome_rearrangement("abac") assert check_palindrome_rearrangement("abacc") assert check_palindrome_rearrangement("aabb") assert not check_palindrome_rearrangement("aabbcccd")
class Solution: def XXX(self, n: int) -> int: # 首先求出到达顶楼时,步长为2最大次数 step_2_max = n//2 # cnt表示爬到顶楼的方法种类 cnt = 0 for i in range(step_2_max+1): if i==0: cnt = 1 else: # i个步长为二的情况下,步长为1的个数为step_1_num step_1_num = n - i*2 # 步长为2的个数 step_2_num step_2_num = i # 共有step_sum步到达山顶 step_sum = step_1_num + step_2_num # 当前步长为2的个数下,求出排列组合数 Cnm = n!/(m! * (n-m)!) cnt += math.factorial(step_sum)/(math.factorial(step_2_num) * math.factorial(step_sum-step_2_num)) return int(cnt)
WEEKLY_STRADDLE_COLUMNS = ['TIMESTAMP', 'OPEN', 'HIGH', 'LOW', 'CLOSE', 'STRIKE', 'OPEN_C', 'HIGH_C', 'LOW_C', 'CLOSE_C', 'H-O_C', 'L-O_C', 'C-O_C', 'OPEN_P', 'HIGH_P', 'LOW_P', 'CLOSE_P', 'H-O_P', 'L-O_P', 'C-O_P'] OPTIONS_COLUMNS = ['TIMESTAMP', 'EXPIRY_DT', 'SYMBOL', 'STRIKE_PR', 'OPTION_TYP', 'OPEN', 'HIGH', 'LOW', 'CLOSE', 'OPEN_INT', 'CHG_IN_OI'] CANDLE_COLUMNS = ['OPEN', 'HIGH', 'LOW', 'CLOSE'] CALL_CANDLE_COLUMNS = [f'{x}_C' for x in CANDLE_COLUMNS] PUT_CANDLE_COLUMNS = [f'{x}_P' for x in CANDLE_COLUMNS] PL_CANDLE_COLUMNS = [f'PL_{x}' for x in CANDLE_COLUMNS] CONSTANT_COLUMNS = ['LOT_SIZE', 'NUM_LOTS', 'TOTAL_LOTS', 'MARGIN_PER_LOT', 'MARGIN_REQUIRED', 'STOP_LOSS', 'STOP_LOSS_TRIGGER'] PL_NET_COLUMNS = ['NET_PL_LO', 'NET_PL_HI', 'NET_PL_CL'] STOP_LOSS_TRUTH_COLUMNS = ['STOP_LOSS_HIT', 'SL_HI_GT_CL'] NET_COLUMNS = ['NET', '%', 'LOSE_COUNT', 'CUM_LOSE_COUNT', 'CUM_NET'] CONVERSION = {'SYMBOL':'first', 'OPEN':'first', 'HIGH':'max', 'LOW':'min', 'CLOSE':'last'} CHAIN_CONVERSION = {'OPEN_C':'first', 'HIGH_C':'max', 'LOW_C':'min', 'CLOSE_C':'last', 'OPEN_P':'first', 'HIGH_P':'max', 'LOW_P':'min', 'CLOSE_P':'last'} STRADDLE_CONVERSION = {'OPEN_C':'first', 'HIGH_C': 'max', 'LOW_C':'min', 'CLOSE_C':'last', 'OPEN_P':'first', 'HIGH_P':'max', 'LOW_P':'min', 'CLOSE_P':'last','PL_OPEN':'first', 'PL_HIGH':'max', 'PL_LOW':'min', 'PL_CLOSE':'last'} STRANGLE_CONVERSION = {'STRIKE_C':'first', 'OPEN_C':'first', 'HIGH_C':'max', 'LOW_C':'min', 'CLOSE_C':'last', 'STRIKE_P':'first', 'OPEN_P':'first', 'HIGH_P':'max', 'LOW_P':'min', 'CLOSE_P':'last', 'PL_OPEN':'first', 'PL_HIGH':'max', 'PL_LOW':'min', 'PL_CLOSE':'last'} IRON_BUTTERFLY_CONVERSION = {'OPEN_C':'first', 'HIGH_C':'max', 'LOW_C':'min', 'CLOSE_C':'last', 'OPEN_P':'first', 'HIGH_P':'max', 'LOW_P':'min', 'CLOSE_P':'last', 'STRIKE_CL':'first', 'OPEN_CL':'first', 'HIGH_CL':'max', 'LOW_CL':'min', 'CLOSE_CL':'last', 'STRIKE_PR':'first', 'OPEN_PR':'first', 'HIGH_PR':'max', 'LOW_PR':'min', 'CLOSE_PR':'last', 'PL_OPEN':'first', 'PL_HIGH':'max', 'PL_LOW':'min', 'PL_CLOSE':'last'} CALENDAR_SPREAD_CONVERSION = {'OPEN_C':'first', 'HIGH_C':'max', 'LOW_C':'min', 'CLOSE_C':'last', 'OPEN_P':'first', 'HIGH_P':'max', 'LOW_P':'min', 'CLOSE_P':'last', 'OPEN_CN':'first', 'HIGH_CN':'max', 'LOW_CN':'min', 'CLOSE_CN':'last', 'OPEN_PN':'first', 'HIGH_PN':'max', 'LOW_PN':'min', 'CLOSE_PN':'last', 'PL_OPEN':'first', 'PL_HIGH':'max', 'PL_LOW':'min', 'PL_CLOSE':'last'} DOUBLE_RATIO_COLUMNS = ['STRIKE_ATM', 'OPEN_CA','HIGH_CA', 'LOW_CA', 'CLOSE_CA', 'OPEN_PA', 'HIGH_PA', 'LOW_PA', 'CLOSE_PA', 'STRIKE_CS', 'OPEN_CS', 'HIGH_CS','LOW_CS', 'CLOSE_CS', 'STRIKE_PS', 'OPEN_PS', 'HIGH_PS', 'LOW_PS', 'CLOSE_PS', 'STRIKE_CL', 'OPEN_CL', 'HIGH_CL','LOW_CL', 'CLOSE_CL', 'STRIKE_PL', 'OPEN_PL', 'HIGH_PL', 'LOW_PL', 'CLOSE_PL'] DOUBLE_RATIO_CONVERSION = {'STRIKE_ATM':'first', 'OPEN_CA':'first', 'HIGH_CA':'max', 'LOW_CA':'min', 'CLOSE_CA':'last', 'OPEN_PA':'first', 'HIGH_PA':'max', 'LOW_PA':'min', 'CLOSE_PA':'last', 'STRIKE_CS':'first', 'OPEN_CS':'first', 'HIGH_CS':'max','LOW_CS':'min', 'CLOSE_CS':'last', 'STRIKE_PS':'first', 'OPEN_PS':'first', 'HIGH_PS':'max', 'LOW_PS':'min', 'CLOSE_PS':'last', 'STRIKE_CL':'first', 'OPEN_CL':'first', 'HIGH_CL':'max','LOW_CL':'min', 'CLOSE_CL':'last', 'STRIKE_PL':'first', 'OPEN_PL':'first', 'HIGH_PL':'max', 'LOW_PL':'min', 'CLOSE_PL':'last', 'PL_OPEN':'first', 'PL_HIGH':'max', 'PL_LOW':'min', 'PL_CLOSE':'last'} RATIO_WRITE_AT_MAX_OI_COLUMNS = ['STRIKE_C', 'OPEN_C', 'HIGH_C', 'LOW_C', 'CLOSE_C', 'STRIKE_P', 'OPEN_P', 'HIGH_P', 'LOW_P', 'CLOSE_P', 'STRIKE_CS', 'OPEN_CS', 'HIGH_CS','LOW_CS', 'CLOSE_CS', 'STRIKE_PS', 'OPEN_PS', 'HIGH_PS', 'LOW_PS', 'CLOSE_PS'] RATIO_WRITE_AT_MAX_OI_CONVERSION = {'STRIKE_C':'first', 'OPEN_C':'first', 'HIGH_C':'max', 'LOW_C':'min', 'CLOSE_C':'last', 'STRIKE_P':'first', 'OPEN_P':'first', 'HIGH_P':'max', 'LOW_P':'min', 'CLOSE_P':'last', 'STRIKE_CS':'first', 'OPEN_CS':'first', 'HIGH_CS':'max','LOW_CS':'min', 'CLOSE_CS':'last', 'STRIKE_PS':'first', 'OPEN_PS':'first', 'HIGH_PS':'max', 'LOW_PS':'min', 'CLOSE_PS':'last', 'PL_OPEN':'first', 'PL_HIGH':'max', 'PL_LOW':'min', 'PL_CLOSE':'last'}
# HAUL strings def startsWith(s, prefix): return s.startswith(prefix) def sub(s, startIndex, endIndex): return s[startIndex:endIndex] def rest(s, startIndex): return s[startIndex:] def length(s): return len(s) class _strings: def __init__(self, data): self.data = data def length(self): return len(self.data) def sub(self, startIndex, endIndex): return self.data[startIndex:endIndex] def new(s): return _strings(s) #print(str(startsWith('lala', 'lo'))) #print(sub('012345', 0, 0))
#!python def linear_search(array, item): """return the first index of item in array or None if item is not found""" # implement linear_search_iterative and linear_search_recursive below, then # change this to call your implementation to verify it passes all tests return linear_search_iterative(array, item) # return linear_search_recursive(array, item) def linear_search_iterative(array, item): # loop over all array values until item is found for index, value in enumerate(array): if item == value: return index # found return None # not found def linear_search_recursive(array, item, index=0): if list[index] == item: return index if index == len(list): return None else: return linear_search_recursive(array, item, index + 1) # once implemented, change linear_search to call linear_search_recursive # to verify that your recursive implementation passes all tests def binary_search(array, item): """return the index of item in sorted array or None if item is not found""" # implement binary_search_iterative and binary_search_recursive below, then # change this to call your implementation to verify it passes all tests # return binary_search_iterative(array, item) return binary_search_recursive(array, item, left=0, right=len(array)-1) def binary_search_iterative(array, item): # once implemented, change binary_search to call binary_search_iterative # to verify that your iterative implementation passes all tests #find the middle position/item #have a start or end (left or right) #check if the middle item is the target, if so return #else compare the target to the item in the middle #if target is less than ite, at the middle we ignore right half #if target is greater, we ignore the left half #repeat until target found ot we looked through everything # [5, 6, 7, 10, 12] item 6 - middle item is 7 # go to middle, is the item to the right greater or less than the target left_index = 0 right_index = len(array) - 1 while left_index <= right_index: mid_index = (right_index + left_index) // 2 if array[mid_index] == item: return mid_index #if item < array[mid_index] ignore right elif item < array[mid_index]: # change right index to right_index = mid_index -1 #if item < array[mid_index] ignore right elif item > array[mid_index]: #change left index to left_index = mid_index + 1 def binary_search_recursive(array, item, left=None, right=None): mid_index = (left + right) // 2 if array[mid_index] == item: return mid_index elif left > right: return None if array[mid_index] < item: return binary_search_recursive(array, item, left + 1, right) if array[mid_index] > item: return binary_search_recursive(array, item, left, right - 1) # once implemented, change binary_search to call binary_search_recursive # to verify that your recursive implementation passes all tests
def printGraph(graph): for node in graph: print(node.toString()) def drawAsMatrix(graph, size = 3): ret = list() line = list() lastLine = 0 for i in range(0, len(graph)): ii = int(i/size) if not lastLine == ii: ret.append(line) lastLine = ii line = list() if(graph[i].notEmpty): line.append(' ') else: line.append('O') ret.append(line) finished = "" for i in range(0,size): line = "" for j in range(0,size): if(j == 0): line = f"{ret[size-i-1][j]}" else: line = f"{line} ][ {ret[size-i-1][j]}" finished = f"{finished}\n[ {line} ]" return finished;
# # PySNMP MIB module ATM-FORUM-TC-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ATM-FORUM-TC-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:15:02 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueSizeConstraint, ConstraintsUnion, ConstraintsIntersection, ValueRangeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "ConstraintsUnion", "ConstraintsIntersection", "ValueRangeConstraint", "SingleValueConstraint") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") Integer32, Counter64, ModuleIdentity, MibIdentifier, iso, ObjectIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, Gauge32, Unsigned32, IpAddress, Bits, Counter32, enterprises, NotificationType, TimeTicks = mibBuilder.importSymbols("SNMPv2-SMI", "Integer32", "Counter64", "ModuleIdentity", "MibIdentifier", "iso", "ObjectIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Gauge32", "Unsigned32", "IpAddress", "Bits", "Counter32", "enterprises", "NotificationType", "TimeTicks") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") class TruthValue(TextualConvention, Integer32): status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2)) namedValues = NamedValues(("true", 1), ("false", 2)) class ClnpAddress(TextualConvention, OctetString): status = 'current' subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(1, 21) class AtmServiceCategory(TextualConvention, Integer32): status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6)) namedValues = NamedValues(("other", 1), ("cbr", 2), ("rtVbr", 3), ("nrtVbr", 4), ("abr", 5), ("ubr", 6)) class AtmAddress(TextualConvention, OctetString): status = 'current' subtypeSpec = OctetString.subtypeSpec + ConstraintsUnion(ValueSizeConstraint(8, 8), ValueSizeConstraint(20, 20), ) class NetPrefix(TextualConvention, OctetString): status = 'current' subtypeSpec = OctetString.subtypeSpec + ConstraintsUnion(ValueSizeConstraint(8, 8), ValueSizeConstraint(13, 13), ) atmForum = MibIdentifier((1, 3, 6, 1, 4, 1, 353)) atmForumAdmin = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 1)) atmfTransmissionTypes = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 1, 2)) atmfMediaTypes = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 1, 3)) atmfTrafficDescrTypes = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 1, 4)) atmfSrvcRegTypes = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 1, 5)) atmForumUni = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 2)) atmfPhysicalGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 2, 1)) atmfAtmLayerGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 2, 2)) atmfAtmStatsGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 2, 3)) atmfVpcGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 2, 4)) atmfVccGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 2, 5)) atmfAddressGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 2, 6)) atmfNetPrefixGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 2, 7)) atmfSrvcRegistryGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 2, 8)) atmfVpcAbrGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 2, 9)) atmfVccAbrGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 2, 10)) atmfAddressRegistrationAdminGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 2, 11)) atmfUnknownType = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 1, 2, 1)) atmfSonetSTS3c = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 1, 2, 2)) atmfDs3 = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 1, 2, 3)) atmf4B5B = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 1, 2, 4)) atmf8B10B = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 1, 2, 5)) atmfSonetSTS12c = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 1, 2, 6)) atmfE3 = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 1, 2, 7)) atmfT1 = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 1, 2, 8)) atmfE1 = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 1, 2, 9)) atmfMediaUnknownType = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 1, 3, 1)) atmfMediaCoaxCable = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 1, 3, 2)) atmfMediaSingleMode = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 1, 3, 3)) atmfMediaMultiMode = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 1, 3, 4)) atmfMediaStp = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 1, 3, 5)) atmfMediaUtp = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 1, 3, 6)) atmfNoDescriptor = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 1, 4, 1)) atmfPeakRate = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 1, 4, 2)) atmfNoClpNoScr = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 1, 4, 3)) atmfClpNoTaggingNoScr = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 1, 4, 4)) atmfClpTaggingNoScr = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 1, 4, 5)) atmfNoClpScr = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 1, 4, 6)) atmfClpNoTaggingScr = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 1, 4, 7)) atmfClpTaggingScr = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 1, 4, 8)) atmfClpNoTaggingMcr = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 1, 4, 9)) mibBuilder.exportSymbols("ATM-FORUM-TC-MIB", atmfMediaUtp=atmfMediaUtp, atmfVccAbrGroup=atmfVccAbrGroup, atmfAddressRegistrationAdminGroup=atmfAddressRegistrationAdminGroup, atmfAtmLayerGroup=atmfAtmLayerGroup, NetPrefix=NetPrefix, atmfSonetSTS12c=atmfSonetSTS12c, atmfSrvcRegistryGroup=atmfSrvcRegistryGroup, atmfDs3=atmfDs3, atmfE3=atmfE3, atmfUnknownType=atmfUnknownType, atmf8B10B=atmf8B10B, atmfPeakRate=atmfPeakRate, TruthValue=TruthValue, atmfClpTaggingScr=atmfClpTaggingScr, atmForum=atmForum, atmfMediaMultiMode=atmfMediaMultiMode, atmfMediaCoaxCable=atmfMediaCoaxCable, atmfNoDescriptor=atmfNoDescriptor, atmf4B5B=atmf4B5B, atmfAddressGroup=atmfAddressGroup, atmfMediaStp=atmfMediaStp, atmForumUni=atmForumUni, atmfTrafficDescrTypes=atmfTrafficDescrTypes, atmfSrvcRegTypes=atmfSrvcRegTypes, atmfE1=atmfE1, atmfNoClpNoScr=atmfNoClpNoScr, AtmAddress=AtmAddress, atmfPhysicalGroup=atmfPhysicalGroup, atmfNetPrefixGroup=atmfNetPrefixGroup, atmfMediaSingleMode=atmfMediaSingleMode, atmfClpNoTaggingMcr=atmfClpNoTaggingMcr, AtmServiceCategory=AtmServiceCategory, atmfClpTaggingNoScr=atmfClpTaggingNoScr, atmfClpNoTaggingScr=atmfClpNoTaggingScr, atmfClpNoTaggingNoScr=atmfClpNoTaggingNoScr, atmfAtmStatsGroup=atmfAtmStatsGroup, atmfMediaUnknownType=atmfMediaUnknownType, atmfNoClpScr=atmfNoClpScr, atmForumAdmin=atmForumAdmin, atmfTransmissionTypes=atmfTransmissionTypes, atmfVccGroup=atmfVccGroup, ClnpAddress=ClnpAddress, atmfSonetSTS3c=atmfSonetSTS3c, atmfVpcAbrGroup=atmfVpcAbrGroup, atmfT1=atmfT1, atmfMediaTypes=atmfMediaTypes, atmfVpcGroup=atmfVpcGroup)
weight = input('Please input your weight(kg)...>') height = input('Please input your height(cm)...>') weight = float(weight) height = float(height) / 100 bmi = weight / (height ** 2) print('{:>7s}\t{:> 3.2f}\tkg'.format('Weight', weight)) print('{:>7s}\t{:> 3.2f}\tcm'.format('Height', height*100)) print('{:>7s}\t{:> 3.2f}'.format('BMI', bmi)) if 18.5 <= bmi < 24: print("It's good!")
class BuildLog: FILE = 0 LINE_NUMBER = 1 WARNING_CODE = 2 MESSAGE = 3 def __init__(self, filePath): self._file = open(filePath, 'r') self._parseLog() def _parseLog(self): self._lines = self._file.readlines() self._lines[:] = [line for line in self._lines if ": warning" in line] self.warnings = [[0 for i in range(4)] for y in range(len(self._lines))] for index, line in enumerate(self._lines): self._lines[index] = line.split(":") self._lines[index][0] = self._lines[index][0][:-1].split("(") self.warnings[index][self.FILE] = self._lines[index][0][0] self.warnings[index][self.LINE_NUMBER] = int(self._lines[index][0][1].split(",")[0]) self.warnings[index][self.WARNING_CODE] = self._lines[index][1] self.warnings[index][self.MESSAGE] = self._lines[index][2].split("[/")[0] def __del__(self): self._file.close() if __name__ == "__main__": logPath = "../../build.log" logs = BuildLog(logPath) print(logs.warnings)
DEBUG = True SECRET_KEY = "Some secret key" HOST = "127.0.0.1" PORT = 5000
# !/usr/bin/env python3 # -*- cosing: utf-8 -*- fileprt = open("file2.txt", "r") content1 = fileptr.readline() content2 = fileptr.readline() print(content1) print(content2) fileprt.close()
human = { "PSSM_folder": '../data/Malonylation/Human/PSSM/', "SPD3_folder": '../data/Malonylation/Human/SPD3/', "encoded_file": '../data/Malonylation/Human/HM_encoded.csv', "data_folder": '../data/Malonylation/Human/HSA+SPD3/', "output": '../data/lemp/human/lemp_features.npz', "output_lemp_compare": '../data/lemp/human/semal_features.npz', "model": "../data/rotation_forest_human.pkl", } mice = { "PSSM_folder": '../data/Malonylation/Mice/PSSM/', "SPD3_folder": '../data/Malonylation/Mice/SPD3/', "encoded_file": '../data/Malonylation/Mice/MM_encoded.csv', "data_folder": '../data/Malonylation/Mice/HSA+SPD3/', "output": '../data/lemp/mice/lemp_features.npz', "output_lemp_compare": '../data/lemp/mice/semal_features.npz', "model": "../data/rotation_forest_mice.pkl", }
#It will print the index of e vowels = ['a', 'e', 'i', 'o', 'i'] index = vowels.index("e") print(index) #It will print the index of o vowels = ['a', 'e', 'i', 'o', 'i'] index=vowels.index("o") print(index)
print('Welcome to the tip calculator!') bill = float(input('What was the total bill? $')) tip = float(input('What percentage tip would you like to give? 10%, 12% or 15% ')) / 100 n_people = int(input('How many people to split the bill? ')) bill_person = (bill + bill * tip) / n_people print(f'Each person should pay ${bill_person:.2f}')
"""This is for opening and closing files with a few other features tucked in for fun""" def addToFile(filename, information, overwrite=False): '''(str, str [, bool]) -> True add content to the end of a file, or create a new file''' if overwrite: file = open(filename, "w") file.write(information) file.close() else: try: file = open(filename, "r") filetowrite =file.read()+information file.close() file = open(filename, "w") file.write(filetowrite) file.close() except: file = open(filename, "w") file.write(information) file.close() return True def retrieveFile(filename, binary=False): '''(str [, bool]) -> str retrieve file at location filename, return file contents''' if binary: file = open(filename, "rb") else: file = open(filename, "r") fileInfo = file.read() file.close() #always close your files, kids! return fileInfo def retrieveFileLines(filename, binary=False): '''(str [, bool]) -> list of str retrieve file a location filename, return file line by line''' if binary: file = open(filename, "rb") else: file = open(filename, "r") fileInfo = file.readlines() file.close() #always close your files, kids! return fileInfo def writeFile(filename, information, binary=False, returnFile=False): '''(str, str [, bool, bool]) -> str (if returnFile == True) or True write information to file a location filename''' if binary: file = open(filename, "wb") else: file = open(filename, "w") file.write(information) file.close() if returnFile: if binary: file = open(filename, "rb") fileInfo=file.read() else: file = open(filename, "r") fileInfo=file.read() file.close() return fileInfo else: return True
arr = list(map(int, input().split())) n = int(input()) for i in range(n, len(arr)): print(arr[i], end = ' ') for i in range(n): print(arr[i], end = ' ')
class BreakingTheCode: def decodingEncoding(self, code, message): if 'a' <= message[0] <= 'z': return ''.join('{0:02}'.format(code.index(e)+1) for e in message) d = dict(('{0:02}'.format(i), e) for i, e in enumerate(code, 1)) return ''.join(d[message[i:i+2]] for i in xrange(0, len(message), 2))
def leia_float (): while True: try: num = float(input('Digite um numero real: ').replace(',', '.')) except (ValueError, TypeError): print('Por favor, digite um numero real valido! ') else: return num def leia_int (): while True: try: num = int(input('Digite um numero inteiro valido: ')) except (ValueError, TypeError): print('Por favor digite um numero inteiro valido! ') else: return num n1 = leia_int() n2 = leia_float() print(f'O numero inteiro digitado foi {n1} e o real {n2} ')
with open('foo.txt', 'r') as file_read: for line in file_read: # NOTA: mejor que file_read.readlines(): print(line, end='')
# basic generator function # def myGen(n): # yield n # yield n+1 # g = myGen(1) # print(next(g)) # print(next(g)) # print(next(g)) def myGen(): yield "These" yield "words" yield "come" yield "one" yield "at" yield "a" yield "time" gen = myGen() for i in range(1, 9): print(next(gen))
class Solution: def arrayNesting(self, nums: List[int]) -> int: result = 0 for i in range(len(nums)): if nums[i] != -1: start, count = nums[i], 0 while nums[start] != -1: temp = start start = nums[start] count += 1 nums[temp] = -1 result = max(result, count) return result
# Practice_#1 # Quick Brown Fox # Use a for loop to take a list and print each element of the list in its own line. sentence = ["the", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog"] # Method_#1 for word in sentence: print(word) # Method_#2 ''' for index in range(0, len(sentence) ): print( sentence[index] ) ''' # Practice_#2 # Multiples of 5 # Write a for loop below # that will print out every whole number that is a multiple of 5 and less than or equal to 30. for number in range( 5, 31, 5): print(number)
#!/usr/bin/env python3 a = int(input("a = ")) b = int(input("b = ")) print("A válasz: " + str(a + b))
# The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832. # # 73167176531330624919225119674426574742355349194934 # 96983520312774506326239578318016984801869478851843 # 85861560789112949495459501737958331952853208805511 # 12540698747158523863050715693290963295227443043557 # 66896648950445244523161731856403098711121722383113 # 62229893423380308135336276614282806444486645238749 # 30358907296290491560440772390713810515859307960866 # 70172427121883998797908792274921901699720888093776 # 65727333001053367881220235421809751254540594752243 # 52584907711670556013604839586446706324415722155397 # 53697817977846174064955149290862569321978468622482 # 83972241375657056057490261407972968652414535100474 # 82166370484403199890008895243450658541227588666881 # 16427171479924442928230863465674813919123162824586 # 17866458359124566529476545682848912883142607690042 # 24219022671055626321111109370544217506941658960408 # 07198403850962455444362981230987879927244284909188 # 84580156166097919133875499200524063689912560717606 # 05886116467109405077541002256983155200055935729725 # 71636269561882670428252483600823257530420752963450 # # Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product? number = 7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450 def kta_stevka ( k ) : stevka = ( number // (10 ** ( 1000 - k ) ) ) % 10 return stevka def produkti_trinajstih ( k ) : produkt = 1 for i in range ( k, k + 13): produkt = produkt * ( kta_stevka ( i ) ) return produkt produkti = list () k = 1 while k < 987 : produkti.append ( produkti_trinajstih ( k ) ) k += 1 produkti.sort () print ( produkti [ - 1] )
## Based off of example at http://pro.arcgis.com/en/pro-app/tool-reference/data-management/calculate-field-examples.htm#ESRI_SECTION1_F3F8CD77A9F647ABBA678A76ADB86E15 ## Goal: calculate the percent increase of a numeric field ## Example use case: identify the rate of temperate increase as weather stations move inland ## Steps: # 1. save the current value as "lastValue" # 2. define the value in the next row as "newValue" # 3. calculate the percent change between the two values ## Example list of field value (replace to try out various numbers): fieldValue = [50.5, 50.6, 55.7, 60, 70.1] ## Code Block: lastValue = 0 def percentIncrease(newValue): global lastValue if lastValue: percentage = ((newValue - lastValue) / lastValue) * 100 else: percentage = 0 lastValue = newValue return percentage ## Expression: # In ArcGIS, the expression will be: # percentIncrease(float(!fieldname!)) # In a standard Python editor, exclaimation points are uncessary # and we have to iterate over each value in the list (ArcGIS does this automatically # for the selected field, !fieldname!) for value in fieldValue : percentage = percentIncrease(value) print(percentage)
word = input('') word_count = 0 start = 0 croatia_word = [['c=', 'c-', 'dz=', 'd-', 'lj', 'nj', 's=', 'z=']] for i in range(len(croatia_word[0])): for j in range(len(croatia_word[0])): croatia = str(croatia_word[0][j]) if word.find(croatia, start) != -1: word_count += 1 start += len(croatia) word_count += len(word) - start print(word_count)
class SimpleWeightedEnsemble(object): def __init__(self): super(SimpleWeightedEnsemble, self).__init__() class XGBoostEnsemble(object): def __init__(self): super(XGBoostEnsemble, self).__init__() class MLPEnsemble(object): def __init__(self): super(MLPEnsemble, self).__init__()
""" LEETCODE 278 - FIRST BAD VERSION coded by Fatih Cinar on January 13th, 2020 """ # The isBadVersion API is already defined for you. # @param version, an integer # @return a bool # def isBadVersion(version): class Solution: def recFindFirstBadVersion(self, low, high): """ This method will figure out the first bad version using Binary Search Algorimthm RECURSIVE IMPLEMENTATION """ middle = int((low + high) / 2) if(high == low + 1): # EXIT CASE # if high is only one greater than low # this means that high has been diagnosed as BAD Before # so HIGH IS THE FIRST BAD VERSION return high elif(isBadVersion(middle)): # if the middle element is BAD # do not further search successor version of the middle return self.recFindFirstBadVersion(low, middle) else: # if the middle elemeent is CLEAN # do not search for the previous versions # because they are also clean return self.recFindFirstBadVersion(middle, high) def firstBadVersion(self, numberOfVersions): """ :type numberOfVersions: int :rtype: int """ # for low we pass 0 return self.recFindFirstBadVersion(0, numberOfVersions)
class MyMath: def add(self, a, b): if type(a) == list: if type(b) == list: return [i + j for i,j in zip(a,b)] else: return [i + b for i in a] else: return a + b def pow(self, base, power): if type(base) == list: # ALL YOUR BASE ARE BELONG TO US! return [i ** power for i in base] else: return base ** power def scale(self, val, src, dst): # Thanks, Stackoverflow http://stackoverflow.com/a/4155197/1778122 return ((val - src[0]) / (src[1]-src[0])) * (dst[1] - dst[0]) + dst[0]
# Configuration file of staticmapservice HEADERS = {'User-Agent':'staticmapservice/0.0.1'} TILE_SERVER = 'http://a.tile.osm.org/{z}/{x}/{y}.png' IS_TMS = False # True if you use a TMS instead of OSM XYZ tiles # Default values can be overwritten in each request DEFAULT_WIDTH = '300' DEFAULT_HEIGHT = '200' DEFAULT_ZOOM = '10' # Maximum values can't be overwritten MAX_WIDTH = '800' MAX_HEIGHT = '800' MAX_ZOOM = 19 MAX_PNV = '30' # Map won't contain more points, nodes and vertices than this value
#!/usr/bin/python2.7 ############################################################################## # Global settings ############################################################################## # Describes all the garage doors being monitored GARAGE_DOORS = [ # { # 'pin': 16, # 'name': "Garage Door 1", # 'alerts': [ # { # 'state': 'open', # 'time': 120, # 'recipients': [ 'sms:+11112223333', 'sms:+14445556666' ] # }, # { # 'state': 'open', # 'time': 600, # 'recipients': [ 'sms:+11112223333', 'sms:+14445556666' ] # } # ] # }, { 'pin': 7, 'name': "Example Garage Door", 'alerts': [ # { # 'state': 'open', # 'time': 120, # 'recipients': [ 'sms:+11112223333', 'email:someone@example.com', 'twitter_dm:twitter_user', 'pushbullet:access_token', 'gcm', 'tweet', 'ifttt:garage_door' ] # }, # { # 'state': 'open', # 'time': 600, # 'recipients': [ 'sms:+11112223333', 'email:someone@example.com', 'twitter_dm:twitter_user', 'pushbullet:access_token', 'gcm', 'tweet', 'ifttt:garage_door' ] # } ] } ] # All messages will be logged to stdout and this file LOG_FILENAME = "/var/log/pi_garage_alert.log" ############################################################################## # Email settings ############################################################################## SMTP_SERVER = 'localhost' SMTP_PORT = 25 SMTP_USER = '' SMTP_PASS = '' EMAIL_FROM = 'Garage Door <user@example.com>' EMAIL_PRIORITY = '1' # 1 High, 3 Normal, 5 Low ############################################################################## # Cisco Spark settings ############################################################################## # Obtain your access token from https://developer.ciscospark.com, click # on your avatar at the top right corner. SPARK_ACCESSTOKEN = "" #put your access token here between the quotes. ############################################################################## # Twitter settings ############################################################################## # Follow the instructions on http://talkfast.org/2010/05/31/twitter-from-the-command-line-in-python-using-oauth/ # to obtain the necessary keys TWITTER_CONSUMER_KEY = '' TWITTER_CONSUMER_SECRET = '' TWITTER_ACCESS_KEY = '' TWITTER_ACCESS_SECRET = '' ############################################################################## # Twilio settings ############################################################################## # Sign up for a Twilio account at https://www.twilio.com/ # then these will be listed at the top of your Twilio dashboard TWILIO_ACCOUNT = '' TWILIO_TOKEN = '' # SMS will be sent from this phone number TWILIO_PHONE_NUMBER = '+11234567890' ############################################################################## # Jabber settings ############################################################################## # Jabber ID and password that status updates will be sent from # Leave this blank to disable Jabber support JABBER_ID = '' JABBER_PASSWORD = '' # Uncomment to override the default server specified in DNS SRV records #JABBER_SERVER = 'talk.google.com' #JABBER_PORT = 5222 # List of Jabber IDs allowed to perform queries JABBER_AUTHORIZED_IDS = [] ############################################################################## # Google Cloud Messaging settings ############################################################################## GCM_KEY = '' GCM_TOPIC = '' ############################################################################## # IFTTT Maker Channel settings # Create an applet using the "Maker" channel, pick a event name, # and use the event name as a recipient of one of the alerts, # e.g. 'recipients': [ 'ifft:garage_event' ] # # Get the key by going to https://ifttt.com/services/maker/settings. # The key is the part of the URL after https://maker.ifttt.com/use/. # Do not include https://maker.ifttt.com/use/ in IFTTT_KEY. ############################################################################## IFTTT_KEY = '' ############################################################################## # Slack settings # Send messages to a team slack channel # e.g. 'recipients': [ 'slack:<your channel ID>'] # where <your channel ID> is the name or ID of the slack channel you want to # send to # # To use this functionality you will need to create a bot user to do the posting # For information on how to create the bot user and get your API token go to: # https://api.slack.com/bot-users # # Note that the bot user must be added to the channel you want to post # notifications in ############################################################################## SLACK_BOT_TOKEN = ''
# 6. Escreva um programa que receba o preço de dois produtos. Calcule um desconto de # 8% no primeiro produto, 11% no segundo e apresente o valor final a ser pago. produto1 = float(input("Digite o valor do produto 1: ")) produto2 = float(input("Digite o valor do produto 2: ")) valor1 = produto1 - (produto1 * 0.08) valor2 = produto2 - (produto2 * 0.11) total = valor1 + valor2 print("O valor final a ser pago é", total)
class Baggage_classify_mod: def __init__(self,modelname,save_modelname): self.modelname = modelname self.save_modelname = save_modelname def fit_func(modelname,x_train,y_train): modelname.fit(x_train,y_train) return modelname def predict_func(model,x_test): pred = model.predict(x_test) return pred
ficha = dict() ficha['nome'] = str(input('Nome: ')) ficha['média'] = float(input(f'Média de {ficha["nome"]}: ')) if ficha['média'] >= 7: ficha['situação'] = 'Aprovado' elif ficha['média'] <= 5: ficha['situação'] = 'Reprovado' else: ficha['situação'] = 'Recuperação' print('-=' * 30) for k, v in ficha.items(): print(f' - {k} é igual a {v}')
num = int(input("Digite um número: ")) lista = [] cont = 0 for i in range(1, num): div = [] for j in range(2, i): if i % j == 0 and i != j: div.append(i) cont += 1 if len(div) == 0: lista.append(i) print(lista) print(f"Foram realizadas {cont} divisões")
class Solution: def plusOne(self, digits): """ :type digits: List[int] :rtype: List[int] """ digits.reverse() ld = len(digits) index = 0 c = 1 while index < ld and c == 1: digits[index] += c c, digits[index] = digits[index] // 10, digits[index] % 10 index += 1 if c == 1: digits.append(c) digits.reverse() return digits if __name__ == "__main__": print(Solution().plusOne([1, 2, 3])) print(Solution().plusOne([4, 3, 2, 1])) print(Solution().plusOne([9, 9, 9]))
class Sorting: def swap(self, arr, pos1, pos2): arr[pos1], arr[pos2] = arr[pos2], arr[pos1] return def selection_sort(self, arr): for i in range(len(arr)): min_ind = i for j in range(i + 1, len(arr)): if arr[j] < arr[min_ind]: min_ind = j if arr[i] != arr[min_ind]: arr[i], arr[min_ind] = arr[min_ind], arr[i] return arr if __name__ == "__main__": obj = Sorting() print(obj.selection_sort([2, 7, 5, 4, 3]))
class Atributo: def __init__(self,nombre,tipo): self.columnNumber = None self.nombre = nombre self.tipo = tipo self.isPrimary = False self.ForeignTable = None self.default = None self.isNull = True self.isUnique = False #Punteros self.siguiente = None self.anterior = None @classmethod def iniciar_esPrimary(cls,nombre,tipo): nuevo = cls.__new__(cls) nuevo.nombre = nombre nuevo.tipo = tipo nuevo.isPrimary = True nuevo.ForeignTable = None nuevo.default = None nuevo.isNull = False nuevo.isUnique = True #Punteros nuevo.siguiente = None nuevo.anterior = None return nuevo @classmethod def iniciar_esForeign(cls,nombre,tipo, tabla): nuevo = cls.__new__(cls) nuevo.nombre = nombre nuevo.tipo = tipo nuevo.isPrimary = False nuevo.ForeignTable = tabla nuevo.default = None nuevo.isNull = False nuevo.isUnique = False #Punteros nuevo.siguiente = None nuevo.anterior = None return nuevo @classmethod def iniciar_Default(cls,nombre,tipo,default): nuevo = cls.__new__(cls) nuevo.nombre = nombre nuevo.tipo = tipo nuevo.isPrimary = False nuevo.foreignTable = None nuevo.default = default nuevo.isNull = False nuevo.isUnique = False #Punteros nuevo.siguiente = None nuevo.anterior = None return nuevo @classmethod def iniciar_NotNull(cls,nombre,tipo): nuevo = cls.__new__(cls) nuevo.nombre = nombre nuevo.tipo = tipo nuevo.isPrimary = False nuevo.ForeignTable = None nuevo.default = None nuevo.isNull = True nuevo.isUnique = False #Punteros nuevo.siguiente = None nuevo.anterior = None return nuevo @classmethod def iniciar_esUnique(cls,nombre,tipo): nuevo = cls.__new__(cls) nuevo.nombre = nombre nuevo.tipo = tipo nuevo.isPrimary = False nuevo.ForeignTable = None nuevo.default = None nuevo.isNull = True nuevo.isUnique = True #Punteros nuevo.siguiente = None nuevo.anterior = None return nuevo @classmethod def iniciar_Primary_Default(cls,nombre,tipo,default): nuevo = cls.__new__(cls) nuevo.nombre = nombre nuevo.tipo = tipo nuevo.isPrimary = True nuevo.ForeignTable = None nuevo.default = default nuevo.isNull = False nuevo.isUnique = True #Punteros nuevo.siguiente = None nuevo.anterior = None return nuevo @classmethod def iniciar_Default_NotNull_Unique(cls,nombre,tipo,default): nuevo = cls.__new__(cls) nuevo.nombre = nombre nuevo.tipo = tipo nuevo.isPrimary = False nuevo.ForeignTable = None nuevo.default = default nuevo.isNull = False nuevo.isUnique = True #Punteros nuevo.siguiente = None nuevo.anterior = None return nuevo @classmethod def iniciar_Default_Null(cls,nombre,tipo,default): nuevo = cls.__new__(cls) nuevo.nombre = nombre nuevo.tipo = tipo nuevo.isPrimary = False nuevo.ForeignTable = None nuevo.default = default nuevo.isNull = True nuevo.isUnique = False #Punteros nuevo.siguiente = None nuevo.anterior = None return nuevo @classmethod def iniciar_Solo_Default(cls,default:any): nuevo = cls.__new__(cls) nuevo.columnNumber = None nuevo.nombre = None nuevo.tipo = None nuevo.isPrimary = False nuevo.ForeignTable = None nuevo.default = default nuevo.isNull = True nuevo.isUnique = False # Punteros nuevo.siguiente = None nuevo.anterior = None return nuevo