content
stringlengths
7
1.05M
#program to find the position of the second occurrence of a given string in another given string. def find_string(txt, str1): return txt.find(str1, txt.find(str1)+1) print(find_string("The quick brown fox jumps over the lazy dog", "the")) print(find_string("the quick brown fox jumps over the lazy dog", "the"))
lines = [] header = "| " for multiplikator in range(1,11): line = "|" + f"{multiplikator}".rjust(3) header += "|" + f"{multiplikator}".rjust(3) for multiplikand in range(1,11): line += "|" + f"{multiplikator * multiplikand}".rjust(3) lines.append("|---" + "+---"*10 + "|") lines.append(line+ "|") print ("/" + "-"*43 + "\\") print (header + "|") for line in lines: print (line) print("\\" + "-"*43 + "/")
def foo(a, b): return a + b print("%d" % 10, end='')
def test_training(): pass
""" [2017-05-18] Challenge #315 [Intermediate] Game of life that has a twist https://www.reddit.com/r/dailyprogrammer/comments/6bumxo/20170518_challenge_315_intermediate_game_of_life/ So for the first part of the description I am borrowing /u/Elite6809 challenge of a while ago [link](https://www.reddit.com/r/dailyprogrammer/comments/271xyp/622014_challenge_165_easy_ascii_game_of_life/) This challenge is based on a game (the mathematical variety - not quite as fun!) called [Conway's Game of Life](http://en.wikipedia.org/wiki/Conway%27s_Game_of_Life). This is called a cellular automaton. This means it is based on a 'playing field' of sorts, made up of lots of little cells or spaces. For Conway's game of life, the grid is square - but other shapes like hexagonal ones could potentially exist too. Each cell can have a value - in this case, on or off - and for each 'iteration' or loop of the game, the value of each cell will change depending on the other cells around it. This might sound confusing at first, but looks easier when you break it down a bit. * A cell's "neighbours" are the 8 cells around it. * If a cell is 'off' but exactly 3 of its neighbours are on, that cell will also turn on - like reproduction. * If a cell is 'on' but less than two of its neighbours are on, it will die out - like underpopulation. * If a cell is 'on' but more than three of its neighbours are on, it will die out - like overcrowding. Fairly simple, right? This might sound boring, but it can generate fairly complex patterns - [this one, for example](http://upload.wikimedia.org/wikipedia/commons/e/e5/Gospers_glider_gun.gif), is called the Gosper Glider Gun and is designed in such a way that it generates little patterns that fly away from it. There are other examples of such patterns, like ones which grow indefinitely. We are going to extend this by giving it some additional rules: There are two parties on the grid, say red and blue. When a cell only has neighbours that are of his own color, nothing changes and it will folow the rules as explained before. When a cell has neighbours that are not of his own 1 of two things can happen: - The total amount of cells in his neighbourhood of his color (including himself) is greater then the amount of cells not in his color in his neighbourhood -> apply normal rules, meaning that you have to count in the cells of other colors as alive cells - If the amout of the other colors is greater then amount of that cell's own color then it just changes color. Last if a cell is 'off' and has 3 neighbour cells that are alive it will be the color that is the most represented. Your challenge is, given a width and heigth to create a grid and a number of turns to simulate this variant # Formal Inputs and Outputs ## Input Description You will be given three numbers **W** and **H** and **N**. These will present the width and heigth of the grid. With this you can create a grid where on the grid, a period or full-stop `.` will represent 'off', and a hash sign `#`/`*` will represent 'on' (for each color). These states you can generate at random. The grid that you are using must 'wrap around'. That means, if something goes off the bottom of the playing field, then it will wrap around to the top, like this: http://upload.wikimedia.org/wikipedia/en/d/d1/Long_gun.gif See how those cells act like the top and bottom, and the left and right of the field are joined up? In other words, the neighbours of a cell can look like this - where the lines coming out are the neighbours: #-...- ...... ../|\. |\.../ ...... ...... ...... |/...\ ...... ...... #-...- ...... ...... |\.../ ..\|/. |/...\ ...... ..-#-. ## Output Description Using that starting state, simulate **N** iterations of Conway's Game of Life. Print the final state in the same format as above - `.` is off and `#` is on. # Sample Inputs & Output ## Sample Input 10 10 7 # Challenge ## Challenge Input 32 17 17 50 50 21 ## note For the initial state I would give it a 45% procent chance of being alive with dividing the red and blue ones to be 50/50 Also look what happens if you change up these numbers """ def main(): pass if __name__ == "__main__": main()
files = "newsequence.txt" write = "compress.txt" reverse = "reversed.txt" seq = dict() global key_max #Stores the sequence in a dictionary def store_seq(key, value): if key not in seq: seq.update({key:value}) #breaks each line down into sequences and counts the number of occurence of each sequence def check_exists(data): data = data.strip() size = len(data) start = 0 endpoint = size - 7 dna = open(files, "r") info = dna.read() while start < endpoint: end = start+8 curr = data[start:end] count = info.count(curr) store_seq(curr, count) start = start+1 dna.close() #reads the dna data from the file line by line def read_file(file_name): f = open(file_name, "r") for content in f: check_exists(content) f.close() #prints out the sequence with the maximum occurence def show_max_val(): global key_max key_max = max(seq.keys(), key=(lambda k: seq[k])) print("The sequence "+key_max+" has the highest occurence of ", seq[key_max]) #Reads the dna file and replaces the sequence with the highest occurence with a define letter def compress_file(): w = open(write, "a") dna = open(files, "r") info = dna.read() if info.find(key_max) != -1: info = info.replace(key_max, 'P') w.write("%s\r\n" % info) w.close() dna.close() #Reverses the file from the function above def reverse_data(): global key_max f = open(write, "r") data = f.read() data = data.replace('P', key_max) w = open(reverse, "a") w.write("%s\r\n" % data) w.close() f.close() if __name__ == "__main__": read_file(files) show_max_val() compress_file() reverse_data()
man = 1 wives = man * 7 madai = wives * 7 cats = madai * 7 kitties = cats * 7 total = man + wives + madai + cats + kitties print(total)
ES_HOST = 'localhost:9200' ES_INDEX = 'pending-gwascatalog' ES_DOC_TYPE = 'variant' API_PREFIX = 'gwascatalog' API_VERSION = ''
def sumall(upto): sumupto = 0 for i in range(1, upto + 1): sumupto = sumupto + i return sumupto print("The sum of the values from 1 to 50 inclusive is: ", sumall(50)) print("The sum of the values from 1 to 5 inclusive is: ", sumall(5)) print("The sum of the values from 1 to 10 inclusive is: ", sumall(10)) # above function replaces the below 2 sum5 = 0 for i in range(1, 6): sum5 = sum5 + i print("The sum of the vaules from 1 to 5 is inclusive: ", sum5) sum10 = 0 for i in range(1, 11): sum10 = sum10 + i print("The sum of the vaules from 1 to 10 is inclusive: ", sum10)
class BatchClassifier: # Implement methods of this class to use it in main.py def train(self, filenames, image_classes): ''' Train the classifier. :param filenames: the list of filenames to be used for training :type filenames: [str] :param image_classes: a mapping of filename to class :type image_classes: {str: int} ''' raise NotImplemented def classify_test(self, filenames, image_classes): ''' Test the accuracy of the classifier with known data. :param filenames: the list of filenames to be used for training :type filenames: [str] :param image_classes: a mapping of filename to class :type image_classes: {str: int} ''' raise NotImplemented def classify_single(self, data): ''' Classify a given image. :param data: the image data to classify :type data: cv2 image representation ''' raise NotImplemented def save(self): ''' Save the classifier to 'classifier/<name>.pkl' ''' raise NotImplemented
# Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. # # (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). # # Find the minimum element. # # You may assume no duplicate exists in the array. # # Example 1: # # Input: [3,4,5,1,2] # Output: 1 # Example 2: # # Input: [4,5,6,7,0,1,2] # Output: 0 class Solution(object): def findMin(self, nums): """ :type nums: List[int] :rtype: int """ if not nums or len(nums) == 0: return 0 if len(nums) == 1: return nums[0] begin, end = 0, len(nums) - 1 return self.search(nums, begin, end) def search(self, nums, begin, end): if begin == end: return nums[begin] mid = (begin + end) // 2 return min(self.search(nums, begin, mid), self.search(nums, mid + 1, end)) s = Solution() print(s.findMin([3,5,4,1,2]))
carros = ["audi", "bmw", "ferrari","honda"] for carro in carros: if carro == "bmw": print(carro.upper()) else: print(carro.title())
setup( name="earthinversion", version="1.0.0", description="Go to earthinversion blog", long_description=README, long_description_content_type="text/markdown", url="https://github.com/earthinversion/", author="Utpal Kumar", author_email="office@earthinversion.com", license="MIT", classifiers=[ "License :: OSI Approved :: MIT License", "Programming Language :: Python", "Programming Language :: Python :: 3", ], packages=["pyqt"], include_package_data=True, install_requires=[ "matplotlib", "PyQt5", "sounddevice", ], entry_points={"console_scripts": ["pyqt=gui.__main__:voicePlotter"]}, )
API_LOGIN = "/users/sign_in" API_DEVICE_RELATIONS = "/device_relations" API_SYSTEMS = "/systems" API_ZONES = "/zones" API_EVENTS = "/events" # 2020-04-18: extracted from https://airzonecloud.com/assets/application-506494af86e686bf472b872d02048b42.js MODES_CONVERTER = { "0": {"name": "stop", "description": "Stop"}, "1": {"name": "cool-air", "description": "Air cooling"}, "2": {"name": "heat-radiant", "description": "Radiant heating"}, "3": {"name": "ventilate", "description": "Ventilate"}, "4": {"name": "heat-air", "description": "Air heating"}, "5": {"name": "heat-both", "description": "Combined heating"}, "6": {"name": "dehumidify", "description": "Dry"}, "7": {"name": "not_exit", "description": ""}, "8": {"name": "cool-radiant", "description": "Radiant cooling"}, "9": {"name": "cool-both", "description": "Combined cooling"}, } SCHEDULE_MODES_CONVERTER = { "0": {"name": "", "description": ""}, "1": {"name": "stop", "description": "Stop"}, "2": {"name": "ventilate", "description": "Ventilate"}, "3": {"name": "cool-air", "description": "Air cooling"}, "4": {"name": "heat-air", "description": "Air heating"}, "5": {"name": "heat-radiant", "description": "Radiant heating"}, "6": {"name": "heat-both", "description": "Combined heating"}, "7": {"name": "dehumidify", "description": "Dry"}, "8": {"name": "cool-radiant", "description": "Radiant cooling"}, "9": {"name": "cool-both", "description": "Combined cooling"}, } VELOCITIES_CONVERTER = { "0": {"name": "auto", "description": "Auto"}, "1": {"name": "velocity-1", "description": "Low speed"}, "2": {"name": "velocity-2", "description": "Medium speed"}, "3": {"name": "velocity-3", "description": "High speed"}, } AIRFLOW_CONVERTER = { "0": {"name": "airflow-0", "description": "Silence"}, "1": {"name": "airflow-1", "description": "Standard"}, "2": {"name": "airflow-2", "description": "Power"}, } ECO_CONVERTER = { "0": {"name": "eco-off", "description": "Eco off"}, "1": {"name": "eco-m", "description": "Eco manual"}, "2": {"name": "eco-a", "description": "Eco A"}, "3": {"name": "eco-aa", "description": "Eco A+"}, "4": {"name": "eco-aaa", "description": "Eco A++"}, } SCENES_CONVERTER = { "0": { "name": "stop", "description": "The air-conditioning system will remain switched off regardless of the demand status of any zone, all the motorized dampers will remain opened", }, "1": { "name": "confort", "description": "Default and standard user mode. The desired set point temperature can be selected using the predefined temperature ranges", }, "2": { "name": "unocupied", "description": "To be used when there is no presence detected for short periods of time. A more efficient set point temperature will be set. If the thermostat is activated, the zone will start running in comfort mode", }, "3": { "name": "night", "description": "The system automatically changes the set point temperature 0.5\xba C/1\xba F every 30 minutes in up to 4 increments of 2\xba C/4\xba F in 2 hours. When cooling, the system increases the set point temperature; when heating, the system decreases the set point temperature", }, "4": { "name": "eco", "description": "The range of available set point temperatures change for more efficient operation", }, "5": { "name": "vacation", "description": "This mode feature saves energy while the user is away for extended periods of time", }, }
''' The MADLIBS QUIZ Use string concatenation (putting strings together) Ex: I ama traveling to ____ using ___ and its carrying ____ passegers for ____ kilometers Thank you for watching ________ channel please ________ ''' youtube_channel = "" print("thank you for watching " + youtube_channel + "Channel ") print(f"thank you for watching {youtube_channel}") print("Thank you for watching {}".format(youtube_channel)) #soln 2:---->Get user input name = input("Name: ") coding = input("coding: ") verb = input("Verb: ") madlib = "my name is {name} and I love {coding} because it is {verb}".format(name,coding,verb) print(madlib) #soln 2:---->Get user input # f formating name = input("Name: ") coding = input("coding: ") verb = input("Verb: ") madlib = "my name is {} and I love {} because it is {}".format(name,coding,verb) print(madlib) #soln f string #soln 2:---->Get user input name = input("Name: ") coding = input("coding: ") verb = input("Verb: ") madlib = f"my name is {name} and I love {coding} because it is {verb}" print(madlib)
# PEMDAS is followed for calculations. # Exponentiation print("2^2 = " + str(2 ** 2)) # Division always returns a float print ("1 / 2 = " + str(1 / 2)) # For integer division, use double forward-slashes print ("1 // 2 = " + str(1 // 2)) # Modulo is like division except it returns the remainder print ("10 % 3 = " + str(10 % 3))
""" Demonstrates a try...except statement """ #Prompts the user to enter a number. line = input("Enter a number: ") try: #Converts the input to an int. number = int(line) #Prints the number the user entered. print(number) except ValueError: #This statement will execute if the input could not be #converted to an int (raised a ValueError) print("Invalid value") #Prints goodbye to show the program has ended. print("Goodbye!")
#!/usr/bin/env python3 # Write a program that compares two files of names to find: # Names unique to file 1 # Names unique to file 2 # Names shared in both files """ python3 checklist.py --file1 --file2 """
class Solution: def fib(self, n: int) -> int: prev, cur = 0, 1 if n == 0: return prev if n == 1: return cur for i in range(n): prev, cur = cur, prev + cur return prev
""" django-faktura Homepage: https://github.com/ricco386/django-faktura See the LICENSE file for copying permission. """ __version__ = "0.1" __author__ = "Richard Kellner" default_app_config = "faktura.apps.FakturaConfig"
def test_countries_and_timezones(app_adm): app_adm.home_page.open_countries() country_page = app_adm.country_page countries_list = country_page.get_countries() sorted_countries = sorted(countries_list) for country in range(len(countries_list)): assert countries_list[country] == sorted_countries[country] if country_page.amount_tzs_by_index(country + 1) > 0: timezones = country_page.get_timezones_for_country(country + 1) sorted_timezones = sorted(timezones) for timezone in range(len(timezones)): assert timezones[timezone] == sorted_timezones[timezone]
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None self.node_count = 0 def __str__(self): curr = self.head temp = [] while curr is not None: temp.append(str(curr.data)) curr = curr.next temp.append(str(None)) return " -> ".join(temp) def insert_at_beginning(self, data): temp = Node(data) if self.head is None: self.head = temp else: # set head to new node temp.next = self.head self.head = temp self.node_count += 1 def insert_at_end(self, data): temp = Node(data) if self.head is None: self.head = temp else: # set next of last item to new node curr = self.head while curr.next is not None: curr = curr.next curr.next = temp self.node_count += 1 def insert_at_position(self, data, position): temp = Node(data) if self.head is None: self.head = temp elif position <= 1: self.insert_at_beginning(data) elif position > self.node_count: self.insert_at_end(data) else: count = 1 curr = self.head while count < position - 1: # inserting after curr = curr.next count += 1 temp.next = curr.next curr.next = temp self.node_count += 1 def delete_from_beginning(self): if self.head is not None: temp = self.head self.head = self.head.next del temp self.node_count -= 1 def delete_from_end(self): if self.head is not None: if self.head.next is None: self.delete_from_beginning() else: # need reference to last and next to last. delete last and update next of the next to last to None curr = self.head prev = None while curr.next is not None: # 1 item list falls through here immediately prev = curr curr = curr.next prev.next = None # does not work on one item list, prev = None del curr self.node_count -= 1 def delete_at_position(self, position): if self.head is not None: if position <= 1: self.delete_from_beginning() elif position >= self.node_count: self.delete_from_end() else: curr = self.head prev = None count = 1 while count < position: prev = curr curr = curr.next count += 1 prev.next = curr.next del curr self.node_count -= 1 # simple demo list1 = LinkedList() print(list1) list1.insert_at_beginning(5) list1.insert_at_beginning(6) list1.insert_at_end(7) list1.insert_at_end(8) list1.insert_at_position(1, 1) list1.insert_at_position(3, 4) print(list1) list1.delete_from_beginning() list1.delete_from_end() list1.delete_at_position(2) print(list1)
class HowLongToBeatEntry: def __init__(self,detailId,gameName,description,playableOn,imageUrl,timeLabels,gameplayMain,gameplayMainExtra,gameplayCompletionist): self.detailId = detailId self.gameName = gameName self.description = description self.playableOn = playableOn self.imageUrl = imageUrl self.timeLabels = timeLabels self.gameplayMain = gameplayMain self.gameplayMainExtra = gameplayMainExtra self.gameplayCompletionist = gameplayCompletionist
''' You are given an n x n 2D matrix representing an image. Rotate the image by 90 degrees (clockwise). Follow up: Could you do this in-place? ''' class Solution(object): def rotate(self, matrix): """ :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. """ n = len(matrix) for row in range(n): for column in range(n - row): matrix[row][column], matrix[n - 1 - column][n - 1 - row] = matrix[n - 1 - column][n - 1 - row], \ matrix[row][column] for row in range(n // 2): for column in range(n): matrix[row][column], matrix[n - 1 - row][column] = matrix[n - 1 - row][column], matrix[row][column] # No need, just to test return matrix if __name__ == "__main__": assert Solution().rotate([[1, 2, 3], [8, 9, 4], [7, 6, 5]]) == [[7, 8, 1], [6, 9, 2], [5, 4, 3]]
class MyDeque: def __init__(self, max_size): self.max_size = max_size self.items = [None] * self.max_size self.size = 0 self.head = 0 self.tail = 0 def push_back(self, value): if self.size == self.max_size: raise IndexError('error') self.items[self.tail] = value self.size += 1 self.tail = (self.tail + 1) % self.max_size def push_front(self, value): if self.size == self.max_size: raise IndexError('error') self.head = self.max_size-1 if self.head == 0 else self.head-1 self.size += 1 self.items[self.head] = value def pop_front(self): if self.size == 0: raise IndexError('error') self.size -= 1 head = self.head self.head = (self.head + 1) % self.max_size return self.items[head] def pop_back(self): if self.size == 0: raise IndexError('error') self.size -= 1 self.tail = self.max_size-1 if self.tail == 0 else self.tail-1 return self.items[self.tail] def run_command(deque: MyDeque, command): try: if 'push' in command[0]: getattr(deque, command[0])(int(command[1])) else: print(getattr(deque, command[0])()) except IndexError as e: print(e) def main(): operations = int(input()) deque_size = int(input()) deque = MyDeque(deque_size) for _ in range(operations): command = input().strip().split() run_command(deque, command) if __name__ == '__main__': main()
""" Collection of miscellaneous functions and utilities for admin tasks. """ __version__ = '0.1.0dev2'
def findadjacent(y,x): global horizontal global vertical global map countlocal=0 for richtingy in range(-1,2): for richtingx in range(-1,2): if richtingx!=0 or richtingy!=0: offsetcounter=0 found=0 while found==0: found=1 offsetcounter+=1 if richtingy*offsetcounter+y>=0 and richtingy*offsetcounter+y<vertical: if richtingx*offsetcounter+x>=0 and richtingx*offsetcounter+x<horizontal: if map[richtingy*offsetcounter+y][richtingx*offsetcounter+x]=="#": countlocal+=1 elif map[richtingy*offsetcounter+y][richtingx*offsetcounter+x]==".": found=0 return countlocal f=open("./CoA/2020/data/11a.txt","r") #f=open("./CoA/2020/data/test.txt","r") count=0 horizontal=0 vertical=0 map=[] tmpmap=[] go_looking=True while go_looking: go_looking=False for line in f: # line=line.strip() map.append(line) count+=1 horizontal=len(line) vertical=count tmpmap=map.copy() for i in range(vertical): for j in range(horizontal): tmp=findadjacent(i,j) #print(i,j,tmp) if map[i][j]=="L": if tmp==0: line=tmpmap[i][:j]+"#"+tmpmap[i][j+1:] go_looking=True tmpmap[i]=line elif map[i][j]=="#": if tmp>=5: line=tmpmap[i][:j]+"L"+tmpmap[i][j+1:] go_looking=True tmpmap[i]=line #print(tmpmap) map=tmpmap.copy() count=0 for i in range(vertical): for j in range(horizontal): if map[i][j]=="#": count+=1 print(count)
class Solution: def fourSum(self, nums: List[int], target: int) -> List[List[int]]: nums.sort() ans=[] st=set() for i in range(0,len(nums)-2): for j in range(i+1,len(nums)-2): l=j+1 r=len(nums)-1 while(l<r): s=nums[i]+nums[j]+nums[l]+nums[r] if s<target: l+=1 elif s>target: r-=1 else: if (nums[i],nums[j],nums[l],nums[r]) not in st: st.add((nums[i],nums[j],nums[l],nums[r])) ans.append([nums[i],nums[j],nums[l],nums[r]]) l+=1 r-=1 return ans
Alonso_Position=1 if (Alonso_Position==1): print("Espectacular Alonso, se ha hecho justicia a pesar del coche") print("Ya queda menos para ganar el mundal") elif (Alonso_Position>1): print("Gran carrera de Alonso, lástima que el coche no esté a la altura") else: print("No ha podido terminar la carrera por una avería mecánica")
n = int(input("Please enter a positive integer : ")) print(n) while n != 1: n = n // 2 if n % 2 == 0 else 3*n + 1 print(n)
class A : pass class B(A): pass print(issubclass(B,A)) print(issubclass(A,object)) # issubclass(b,a)判断a是不是b的子类 # 所有的类都是object类的子类 # isinstance (b,B)判断是不是该类的实例化对象,第二个元素可以是一个元组 class C: def __init__(self,x,y): self.x=x self.y=y b=B() print(isinstance(b,B)) print(isinstance(b,C)) print(isinstance(b,(A,B,C))) # hasattr判断是否为该类的属性,用双引号标记,区分大小写 c1= C(1,2) print(hasattr(c1, 'x')) # getattr获取类中的属性 print(getattr(c1,'y',"你访问的属性不存在")) # delattr 删除类中的属性 print(delattr(c1,'y')) # print(delattr(c1,'y')) 删除不存在的属性会报错 class D: def __init__(self,size=100): self.size=size def getSize(self): return self.size def setSize(self,size): self.size=size def delSize(self): del self.size x=property(getSize,setSize,delSize) d=D() print(d.x) d.x=11 print(d.x) del d.x # 把属性删除了,再打印会报错 # print(d.x) """ 对象实例化的第一个方法__new__(cls),第一个参数默认为cls一般情况下不需要重写, 是一个静态方法,当继承不可变类型时才需要重写这个类方法,会返回一个实例化对象 """ class CapStr(str): def __new__(cls, string): string=string.upper() return str.__new__(cls,string) ss=CapStr("I like njucm.") print(ss) # 演示方法__init__()和__del__() class Show(): def __init__(self): print("调用init方法") def __del__(self): print("del的方法") # 这个方法是最后调用的,当程序运行结束时回收内存 show=Show() s1=show del s1
print('Vamos analisar 3 números para saber qual será o menor e o maior deles. ') numero = float(input('Informe o primeiro número: ')) maior = numero menor = numero numero = float(input('Informe o segundo número: ')) if numero > maior: maior = numero else: menor = numero numero = float(input('Informe o terceiro número: ')) if numero > maior: maior = numero else: if numero < menor: menor = numero print('Dentre os números digitados o MAIOR foi {} e o MENOR foi {}'.format(maior, menor))
def hip(a, b, c): if b < a > c and a ** 2 == b ** 2 + c ** 2: return True elif a < b > c and b ** 2 == a ** 2 + c ** 2: return True elif a < c > b and c ** 2 == a ** 2 + b ** 2: return True else: return False e = str(input()).split() a = int(e[0]) b = int(e[1]) c = int(e[2]) if(a < b + c and b < a + c and c < a + b): if(a == b == c): print('Valido-Equilatero') elif(a == b or a == c or b == c): print('Valido-Isoceles') else: print('Valido-Escaleno') if hip(a, b, c): print('Retangulo: S') else: print('Retangulo: N') else: print('Invalido')
class CNF: def __init__(self, n_variables, clauses, occur_list, comments): self.n_variables = n_variables self.clauses = clauses self.occur_list = occur_list self.comments = comments def __str__(self): return f"""Number of variables: {self.n_variables} Clauses: {str(self.clauses)} Comments: {str(self.comments)}""" def to_file(self, filename): with open(filename, 'w') as f: f.write(self.to_string()) def to_string(self): string = f'p cnf {self.n_variables} {len(self.clauses)}\n' for clause in self.clauses: string += ' '.join(str(literal) for literal in clause) + ' 0\n' return string @classmethod def from_file(cls, filename): with open(filename) as f: return cls.from_string(f.read()) @classmethod def from_string(cls, string): n_variables, clauses, occur_list, comments = CNF.parse_dimacs(string) return cls(n_variables, clauses, occur_list, comments) @staticmethod def parse_dimacs(string): n_variables = 0 clauses = [] comments = [] occur_list = [] for line in string.splitlines(): line = line.strip() if not line: continue elif line[0] == 'c': comments.append(line) elif line.startswith('p cnf'): tokens = line.split() n_variables, n_remaining_clauses = int(tokens[2]), int(tokens[3]) occur_list = [[] for _ in range(n_variables * 2 + 1)] elif n_remaining_clauses > 0: clause = [] clause_index = len(clauses) for literal in line.split()[:-1]: literal = int(literal) clause.append(literal) occur_list[literal].append(clause_index) clauses.append(clause) n_remaining_clauses -= 1 else: break return n_variables, clauses, occur_list, comments
# 1573. Алхимия # solved # reagents amount reagents_amount = input().split(' ') # blue b = int(reagents_amount[0]) # red r = int(reagents_amount[1]) # yellow y = int(reagents_amount[2]) # recipe k = int(input()) result = 1 for i in range(k): color = input() if color == 'Blue': result *= b if color == 'Red': result *= r if color == 'Yellow': result *= y print(result)
#!/usr/bin/env python3 def left_join(phrases): return ','.join(phrases).replace("right", "left") if __name__ == '__main__': print(left_join(["right", "right", "left", "left", "forward"])) assert left_join(["right", "right", "left", "left", "forward"]) == "left,left,left,left,forward" assert left_join(["alright outright", "squirrel"]) == "alleft outleft,squirrel" assert left_join(["frightened", "eyebright"]) == "fleftened,eyebleft" assert left_join(["little", "squirrel"]) == "little,squirrel"
#!/usr/bin/env python # -*- coding:utf-8 _*- """ @author: Lu Chong @file: __init__.py @time: 2021/8/17/11:38 """
DATABASE_NAME = "lzhaoDemoDB" TABLE_NAME = "MarketPriceGTest" HT_TTL_HOURS = 24 CT_TTL_DAYS = 7 ONE_GB_IN_BYTES = 1073741824
# -*- encoding=utf-8 -*- """ # ********************************************************************************** # Copyright (c) Huawei Technologies Co., Ltd. 2020-2020. All rights reserved. # [openeuler-jenkins] is licensed under the Mulan PSL v1. # You can use this software according to the terms and conditions of the Mulan PSL v1. # You may obtain a copy of Mulan PSL v1 at: # http://license.coscl.org.cn/MulanPSL # THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR # PURPOSE. # See the Mulan PSL v1 for more details. # Author: # Create: 2020-09-23 # Description: access control list base class # ********************************************************************************** """ class ACResult(object): """ Use this variables (FAILED, WARNING, SUCCESS) at most time, and don't new ACResult unless you have specific needs. """ def __init__(self, val): self._val = val def __add__(self, other): return self if self.val >= other.val else other def __str__(self): return self.hint def __repr__(self): return self.__str__() @classmethod def get_instance(cls, val): """ :param val: 0/1/2/True/False/success/fail/warn :return: instance of ACResult """ if isinstance(val, int): return {0: SUCCESS, 1: WARNING, 2: FAILED}.get(val) if isinstance(val, bool): return {True: SUCCESS, False: FAILED}.get(val) try: val = int(val) return {0: SUCCESS, 1: WARNING, 2: FAILED}.get(val) except ValueError: return {"success": SUCCESS, "fail": FAILED, "failed": FAILED, "failure": FAILED, "warn": WARNING, "warning": WARNING}.get(val.lower(), FAILED) @property def val(self): return self._val @property def hint(self): return ["SUCCESS", "WARNING", "FAILED"][self.val] @property def emoji(self): return [":white_check_mark:", ":bug:", ":x:"][self.val] FAILED = ACResult(2) WARNING = ACResult(1) SUCCESS = ACResult(0)
class Solution: def recursion(self,idx,arr,n,maxx,size,k): if idx == n: return maxx * size if (idx,size,maxx) in self.dp: return self.dp[(idx,size,maxx)] ch1 = self.recursion(idx+1,arr,n,max(maxx,arr[idx]),size+1,k) if size < k else 0 ch2 = self.recursion(idx+1,arr,n,arr[idx],1,k) + maxx*size best = ch1 if ch1 > ch2 else ch2 self.dp[(idx,size,maxx)] = best return best def maxSumAfterPartitioning(self, arr: List[int], k: int) -> int: self.dp = {} return self.recursion(1,arr,len(arr),arr[0],1,k)
class Action: def do(self) -> None: raise NotImplementedError def undo(self) -> None: raise NotImplementedError def redo(self) -> None: raise NotImplementedError
# ------------------------------------------------------------------------------- # Name: palindromes # # Author: mourad mourafiq # ------------------------------------------------------------------------------- def longest_subpalindrome(string): """ Returns the longest subpalindrome string from the current string Return (i,j) """ #first we check if string is "" if string == "": return (0, 0) def length(slice): a, b = slice; return b - a slices = [grow(string, start, end) for start in range(len(string)) for end in (start, start + 1) ] return max(slices, key=length) def grow(string, start, end): """ starts with a 0 or 1 length palindrome and try to grow bigger """ while (start > 0 and end < len(string) and string[start - 1].upper() == string[end].upper()): start -= 1; end += 1 return (start, end)
# 这是一段空代码,仅创建一个循环并输出log log("接下来将输出3次”Hello Love!“") for k in range (3): log("Hello Love!") wait(800)
""" Description: Provides ESPA specific exceptions to the processing code. License: NASA Open Source Agreement 1.3 """ class ESPAException(Exception): """Provides an ESPA specific exception specifically for ESPA processing""" pass
# # PySNMP MIB module INCOGNITO-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/INCOGNITO-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:42:01 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") SingleValueConstraint, ValueSizeConstraint, ValueRangeConstraint, ConstraintsUnion, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ValueSizeConstraint", "ValueRangeConstraint", "ConstraintsUnion", "ConstraintsIntersection") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") Bits, enterprises, TimeTicks, MibScalar, MibTable, MibTableRow, MibTableColumn, Integer32, ModuleIdentity, ObjectIdentity, Gauge32, Counter64, iso, IpAddress, NotificationType, MibIdentifier, Unsigned32, Counter32 = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "enterprises", "TimeTicks", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Integer32", "ModuleIdentity", "ObjectIdentity", "Gauge32", "Counter64", "iso", "IpAddress", "NotificationType", "MibIdentifier", "Unsigned32", "Counter32") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") incognito = ModuleIdentity((1, 3, 6, 1, 4, 1, 3606)) if mibBuilder.loadTexts: incognito.setLastUpdated('200304151442Z') if mibBuilder.loadTexts: incognito.setOrganization('Incognito Software Inc.') incognitoSNMPObjects = ObjectIdentity((1, 3, 6, 1, 4, 1, 3606, 1)) if mibBuilder.loadTexts: incognitoSNMPObjects.setStatus('obsolete') incognitoReg = ObjectIdentity((1, 3, 6, 1, 4, 1, 3606, 2)) if mibBuilder.loadTexts: incognitoReg.setStatus('current') incognitoGeneric = ObjectIdentity((1, 3, 6, 1, 4, 1, 3606, 3)) if mibBuilder.loadTexts: incognitoGeneric.setStatus('current') incognitoProducts = ObjectIdentity((1, 3, 6, 1, 4, 1, 3606, 4)) if mibBuilder.loadTexts: incognitoProducts.setStatus('current') incognitoCaps = ObjectIdentity((1, 3, 6, 1, 4, 1, 3606, 5)) if mibBuilder.loadTexts: incognitoCaps.setStatus('current') incognitoReqs = ObjectIdentity((1, 3, 6, 1, 4, 1, 3606, 6)) if mibBuilder.loadTexts: incognitoReqs.setStatus('current') incognitoExpr = ObjectIdentity((1, 3, 6, 1, 4, 1, 3606, 7)) if mibBuilder.loadTexts: incognitoExpr.setStatus('current') mibBuilder.exportSymbols("INCOGNITO-MIB", incognitoSNMPObjects=incognitoSNMPObjects, incognitoReqs=incognitoReqs, incognitoGeneric=incognitoGeneric, incognitoReg=incognitoReg, PYSNMP_MODULE_ID=incognito, incognitoProducts=incognitoProducts, incognitoCaps=incognitoCaps, incognito=incognito, incognitoExpr=incognitoExpr)
def arraySumAdjacentDifference(inputArray): answer = 0 for i in range(1, len(inputArray)): answer += abs(inputArray[i] - inputArray[i-1]) return answer ''' Given array of integers, find the sum of absolute differences of consecutive numbers. Example For inputArray = [4, 7, 1, 2], the output should be arraySumAdjacentDifference(inputArray) = 10. |4 - 7| = 3; |7 - 1| = 6; |1 - 2| = 1 So, the answer is 3 + 6 + 1 = 10. Input/Output [time limit] 4000ms (py) [input] array.integer inputArray Constraints: 3 ≤ inputArray.length ≤ 10, 1 ≤ inputArray[i] ≤ 15. [output] integer Sum of absolute differences of consecutive numbers from inputArray. '''
""" Events are called by the :class:`libres.db.scheduler.Scheduler` whenever something interesting occurs. The implementation is very simple: To add an event:: from libres.modules import events def on_allocations_added(context_name, allocations): pass events.on_allocations_added.append(on_allocations_added) To remove the same event:: events.on_allocations_added.remove(on_allocations_added) Events are called in the order they were added. """ class Event(list): """Event subscription. By http://stackoverflow.com/a/2022629 A list of callable objects. Calling an instance of this will cause a call to each item in the list in ascending order by index. """ def __call__(self, *args, **kwargs): for f in self: f(*args, **kwargs) on_allocations_added = Event() """ Called when an allocation is added, with the following arguments: :context: The :class:`libres.context.core.Context` used when adding the allocations. :allocations: The list of :class:`libres.db.models.Allocation` allocations to be commited. """ on_reservations_made = Event() """ Called when a reservation is made, with the following arguments: :context: The :class:`libres.context.core.Context` used when adding the reservation. :reservations: The list of :class:`libres.db.models.Reservation` reservations to be commited. This is a list because one reservation can result in multiple reservation records. All those records will have the same reservation token and the same reservee email address. """ on_reservations_confirmed = Event() """ Called when a reservation bound to a browser session is confirmed, with the following arguments: :context: The :class:`libres.context.core.Context` used when confirming the reservation. :reservations: The list of :class:`libres.db.models.Reservation` reservations being confirmed. :session_id: The session id that is being confirmed. """ on_reservations_approved = Event() """ Called when a reservation is approved, with the following arguments: :context: The :class:`libres.context.core.Context` used when approving the reservation. :reservations: The list of :class:`libres.db.models.Reservation` reservations being approved. """ on_reservations_denied = Event() """ Called when a reservation is denied, with the following arguments: :context: The :class:`libres.context.core.Context` used when denying the reservation. :reservations: The list of :class:`libres.db.models.Reservation` reservations being denied. """ on_reservations_removed = Event() """ Called when a reservation is removed, with the following arguments: :context: The :class:`libres.context.core.Context` used when removing the reservation. :reservations: The list of :class:`libres.db.models.Reservation` reservations being removed. """ on_reservation_time_changed = Event() """ Called when a reservation's time changes , with the following arguments: :context: The :class:`libres.context.core.Context` used when changing the reservation time. :reservation: The :class:`libres.db.models.Reservation` reservation whose time is changing. :old_time: A tuple of datetimes containing the old start and the old end. :new_time: A tuple of datetimes containing the new start and the new end. """
#list example for insertion order and the dupicates l1 = [] print(type(l1)) l1.append(1) l1.append(2) l1.append(3) l1.append(4) l1.append(1) print(l1)
"""AyudaEnPython: https://www.facebook.com/groups/ayudapython En una estación de servicio se conoce la cantidad de nafta común y super vendida en el corriente mes. El usuario deberá ingresar las ventas totales de cada tipo de nafta por cada día del mes. Al finalizar debe informar la venta total del mes y el porcentaje vendido de cada tipo de nafta (en el mes actual). Nota: Se puede optar por dos alternativas, pedir la cantidad de días que tiene el mes o solicitar al usuario que indique en cada carga si es el último día. """ comun = 0 super_ = 0 dias = int(input("Ingrese la cantidad de días del mes: ")) for i in range(dias): print(f"Día {i+1}") comun += int(input("Venta total de nafta comun: ")) super_ += int(input("Venta total de nafta super: ")) total = comun + super_ porcentaje_comun = round(comun / total * 100, 2) porcentaje_super = round(super_ / total * 100, 2) print(f"La venta total del mes es de: {total}") print(f"El porcentaje de nafta común vendida es de: {porcentaje_comun}") print(f"El porcentaje de nafta super vendida es de: {porcentaje_super}")
class Shodan: """Get any Shodan information """ def __init__(self): # TODO: move key to config self.api_key = 'yKIZ2L54cQxIfnebD4V2qgPp0QQsJLpK' # TODO: add shodan api def request(self): pass
def maximum_subarray_sum(lst): '''Finds the maximum sum of all subarrays in lst in O(n) time and O(1) additional space. >>> maximum_subarray_sum([34, -50, 42, 14, -5, 86]) 137 >>> maximum_subarray_sum([-5, -1, -8, -101]) 0 ''' current_sum = 0 maximum_sum = 0 for value in lst: current_sum = max(current_sum + value, 0) maximum_sum = max(maximum_sum, current_sum) return maximum_sum
""" * Use an input_boolean to change between views, showing or hidding groups. * Check some groups with a connectivity binary_sensor to hide offline devices. """ # Groups visibility (expert_view group / normal view group): GROUPS_EXPERT_MODE = { 'group.salon': 'group.salon_simple', 'group.estudio_rpi2h': 'group.estudio_rpi2h_simple', 'group.dormitorio_rpi2mpd': 'group.dormitorio_rpi2mpd_simple', 'group.cocina': 'group.cocina_simple', 'group.caldera': 'group.caldera_simple', 'group.links': 'group.links_simple', 'group.cacharros': 'group.cacharros_simple', 'group.hass_control': 'group.hass_control_simple', 'group.weather': 'group.weather_simple', 'group.esp8266_3': 'group.esp8266_3_simple', 'group.enerpi_max_power_control': None, 'group.scripts': None, 'group.host_rpi3': None, 'group.host_rpi2_hat': None, 'group.host_rpi2_mpd': None, 'group.conectivity': None, 'group.esp8266_2': None, 'group.menu_automations_1': None, 'group.menu_automations_2': None, 'group.menu_automations_3': None, } GROUPS_WITH_BINARY_STATE = { 'group.esp8266_2': 'binary_sensor.esp2_online', 'group.esp8266_3': 'binary_sensor.esp3_online', 'group.cocina': 'binary_sensor.cocina_online' } # Get new value of 'expert mode' expert_mode = data.get( 'expert_mode_state', hass.states.get('input_boolean.show_expert_mode').state) == 'on' for g_expert in GROUPS_EXPERT_MODE: visible_expert = expert_mode visible_normal = not expert_mode g_normal = GROUPS_EXPERT_MODE.get(g_expert) # Hide groups of devices offline if g_expert in GROUPS_WITH_BINARY_STATE: bin_sensor = GROUPS_WITH_BINARY_STATE.get(g_expert) bin_state = hass.states.get(bin_sensor).state if bin_state is None or bin_state == 'off': visible_expert = visible_normal = False # Show and hide hass.services.call( 'group', 'set_visibility', {"entity_id": g_expert, "visible": visible_expert}) if g_normal is not None: hass.services.call( 'group', 'set_visibility', {"entity_id": g_normal, "visible": visible_normal})
''' 输入两棵二叉树A和B,判断B是不是A的子结构。(约定空树不是任意一个树的子结构) B是A的子结构, 即 A中有出现和B相同的结构和节点值。 例如: 给定的树 A: 3 / \ 4 5 / \ 1 2 给定的树 B: 4 / 1 返回 true,因为 B 与 A 的一个子树拥有相同的结构和节点值。 示例 1: 输入:A = [1,2,3], B = [3,1] 输出:false 示例 2: 输入:A = [3,4,5,1,2], B = [4,1] 输出:true 限制: 0 <= 节点个数 <= 10000 ''' # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def isSubStructure(self, A: TreeNode, B: TreeNode) -> bool: if not A or not B: return False if A.val != B.val: if self.isSubStructure(A.left, B) or self.isSubStructure(A.right, B): return True else: if self.isSubTree(A, B): return True return False def isSubTree(self, A, B): # when roots of A an B are same. if A and A.val == B.val: left, right = 0, 0 if not B.left and not B.right: return True if B.left: left = self.isSubTree(A.left, B.left) if B.right: right = self.isSubTree(A.right, B.right) if B.left and B.right: return left and right else: return left or right else: return False A = TreeNode(10) A.left = TreeNode(12) A.right = TreeNode(6) A.left.left = TreeNode(8) A.left.right = TreeNode(3) A.right.left = TreeNode(11) B = TreeNode(10) B.left = TreeNode(12) B.right = TreeNode(6) B.left.left = TreeNode(8) print(Solution().isSubStructure(A, B))
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Ce module permet d'obtenir la liste des pays valides, a partir d'un fichier donnee. """ __auteur__ = "Thefuture2092" def obtenirListePays(langue): """ cette fonction prend un argument langue et retourne la liste de pays dans cette langue. """ # ouvrir un fichier selon la langue fournie fin = open('countrylist.txt', encoding="utf-8") if langue.lower() == 'en' else open('listepays.txt', encoding="utf-8") listepays = [] prelistepays = [] for l in fin: prelistepays.append(l.replace('\x00','').strip().lower()) for l in prelistepays: if l: listepays.append(l) listepays[0]=listepays[0][2:] fin.close() return listepays #print(listepays)
""" Lab 8 """ #3.1 demo='hello world!' def cal_words(input_str): return len(input_str.split()) #3.2 demo_str='Hello world!' print(cal_words(demo_str)) #3.3 def find_min(inpu_list): min_item = inpu_list[0] for num in inpu_list: if type(num) is not str: if min_item >= num: min_item = num return min_item #3.4 demo_list = [1,2,3,4,5,6] print(find_min(demo_list)) #3.5 mix_list = [1,2,3,4,'a',6] print(find_min(mix_list))
# Alternative solution using compound conditional statement in_class_test = int(input('Please enter your mark for the In Class Test: ')) exam_mark = int(input('Please input your mark for the exam: ')) coursework_mark = int(input('Please enter your mark for Component B: ')) # Calculating mark by adding the marks together and dividing by 2 component_a_mark = (in_class_test * 0.25) + (exam_mark * 0.75) module_mark = (component_a_mark + coursework_mark) / 2 print('Your mark is', module_mark, 'Calculating your result') # Uses compound boolean proposition if coursework_mark < 35 and component_a_mark < 35: print('You have not passed the module') elif module_mark < 40: print('You have failed the module') else: print('You have passed the module')
class SarlaccPlugin: def __init__(self, logger, store): """Init method for SarlaccPlugin. Args: logger -- sarlacc logger object. store -- sarlacc store object. """ self.logger = logger self.store = store def run(self): """Runs the plugin. This method should be overridden if a plugin needs to do any initial work that isn't purely initialization. This could include starting any long running jobs / threads. """ pass def stop(self): """Stops the plugin. This method should be overridden if a plugin needs to do any extra cleanup before stopping. This could include stopping any previously started jobs / threads. """ pass async def new_attachment(self, _id, sha256, content, filename, tags): """New attachment signal. This method is called when a new, previously unseen attachment is detected. Override this method to be informed about this event. Args: _id -- the attachment postgresql record id. sha256 -- the sha256 hash of the attachment. content -- the raw file. filename -- the filename of the attachment. tags -- any tags attached to the attachment. """ pass async def new_email_address(self, _id, email_address): """New email address signal. This method is called when a new, previously unseen recipient email address is detected. Override this method to be informed about this event. Args: _id -- the email address postgresql record id. email_address -- the email address. """ pass async def new_mail_item(self, _id, subject, recipients, from_address, body, date_sent, attachments): """New email signal. This method is called when an email is received. Override this method to be informed about this event. Args: _id -- the mail item postgresql record id. subject -- the email subject. recipients -- a list of recipient email addresses. from_address -- the email address in the email's "from" header. body -- the body of the email. date_sent -- the date and time the email was sent. attachments -- a list of attachment objects in the following format: { content: the content of the attachment (raw file), filename: the name of the attachment filename } """ pass
#%% """ - Reverse Nodes in k-group - https://leetcode.com/problems/reverse-nodes-in-k-group/ - Hard Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is. Example: Given this linked list: 1->2->3->4->5 For k = 2, you should return: 2->1->4->3->5 For k = 3, you should return: 3->2->1->4->5 Note: Only constant extra memory is allowed. You may not alter the values in the list's nodes, only nodes itself may be changed. """ #%% class ListNode: def __init__(self, data=0, next=None): self.data = data self.next = next #%% class S: def reverseKGroup(self, head: ListNode, k: int) -> ListNode: if not head or not head.next: return head cnt, pre, cur, nex = 1, None, head, head.next p = head while p: cnt += 1 p = p.next if cnt-1 >= k: cnt = 1 while cnt < k and nex: cnt += 1 cur.next = pre pre = cur cur = nex nex = nex.next cur.next = pre else: return cur if nex: head.next = self.reverseKGroup(nex, k) return cur #%%
def leiaint(txt): while True: try: num = int(input(txt)) except (ValueError, TypeError): print('\033[31mERRO. Digite um número inteiro válido.\033[m') continue else: return num
# Implementation of a singly linked list data structure # By: Jacob Rockland # node class for linked list class Node(object): def __init__(self, data): self.data = data self.next = None # implementation of singly linked list class SinglyLinkedList(object): # initializes linked list def __init__(self, head = None, tail = None): self.head = head self.tail = tail # returns a string representation of linked list [data1, data2, ...] def __repr__(self): return repr(self.array()) # returns an array representation of linked list def array(self): array = [] curr = self.head while curr is not None: array.append(curr.data) curr = curr.next return array # adds node to end of list, O(1) def append(self, item): node = Node(item) if self.head is None: self.head = node self.tail = node else: self.tail.next = node self.tail = node # adds node to front of list, O(1) def prepend(self, item): node = Node(item) if self.head is None: self.head = node self.tail = node else: node.next = self.head self.head = node # inserts node into list after given position, O(1) def insert_after(self, curr, item): node = Node(item) if self.head is None: self.head = node self.tail = node elif curr is None: node.next = self.head self.head = node elif curr is self.tail: self.tail.next = node self.tail = node else: node.next = curr.next curr.next = node # inserts node into list in sorted position, O(n) def insert_sorted(self, item): node = Node(item) if self.head is None: self.head = node self.tail = node else: last = None curr = self.head while curr is not None and item > curr.data: last = curr curr = curr.next if curr is None: self.tail.next = node self.tail = node elif last is None: node.next = self.head self.head = node else: last.next = node node.next = curr # removes node from list after given position, O(1) def remove_after(self, curr): if self.head is None: return elif curr is None: succ = self.head.next self.head = succ if succ is None: # checks if removed last item self.tail = None elif curr.next is not None: succ = curr.next.next curr.next = succ if succ is None: # checks if removed tail item self.tail = curr # searches for a given data value in list and returns first node if found, O(n) def search(self, key): curr = self.head while curr is not None: if curr.data == key: return curr curr = curr.next return None # reverses linked list in place, O(n) def reverse(self): self.tail = self.head prev = None curr = self.head while curr is not None: succ = curr.next curr.next = prev prev = curr curr = succ self.head = prev # remove duplicates from linked list def remove_duplicates(self): if self.head is None: return curr = self.head while curr.next is not None: if curr.data == curr.next.data: curr.next = curr.next.next else: curr = curr.next
def print_formatted(number): width = len("{0:b}".format(number)) for num in range(1, number+1): print("{0:{w}}\t{0:{w}o}\t{0:{w}X}\t{0:{w}b}".format(num, w=width)) if __name__ == '__main__': n = int(input()) print_formatted(n)
####################################################### # Author: Mwiza Simbeye # # Institution: African Leadership University Rwanda # # Program: Playing Card Sorting Algorithm # ####################################################### cards = [9, 10, 'J', 'K', 'Q', 'Q', 4, 5, 6, 7, 8,'A', 2, 3] ####################################################### # Convert cars to their numerical equivalent # # Example:[9, 10, 11, 12, 13, 4, 5, 6, 7, 8, 1, 2, 3] # ####################################################### converted_cards = [] for i in cards: if i == 'A': converted_cards.append(1) elif i == 'J': converted_cards.append(11) elif i == 'K': converted_cards.append(12) elif i == 'Q': converted_cards.append(13) else: converted_cards.append(i) sort = [] z = 0 while z < len(cards): smallest = converted_cards[0] for x in converted_cards: if x < smallest: smallest = x else: pass converted_cards.remove(smallest) #print (converted_cards) sort.append(smallest) #print (sort) z+=1 ####################################################### # Convert numerical values to their card equivalent # # Example: [A, 2, 3, 4, 5, 6, 7, 8, 9, 10, J, K, Q] # ####################################################### sorted_cards = [] for i in sort: if i == 1: sorted_cards.append('A') elif i == 11: sorted_cards.append('J') elif i == 12: sorted_cards.append('K') elif i == 13: sorted_cards.append('Q') else: sorted_cards.append(i) print ("The sorted cards are: "+str(sorted_cards))
# Copyright: 2005-2008 Brian Harring <ferringb@gmail.com> # License: GPL2/BSD """ repository subsystem """
def create_image_annotation(file_name, width, height, image_id): # file_name = file_name.split('/')[-1] # ~~~.jpg가 file_name이 되도록 문자열 split images = { 'file_name': file_name[2:], 'height': height, 'width': width, 'id': image_id } return images def create_annotation_yolo_format(min_x, min_y, width, height, image_id, category_id, annotation_id): bbox = (min_x, min_y, width, height) area = width * height annotation = { 'id': annotation_id, 'image_id': image_id, 'bbox': bbox, 'area': area, 'iscrowd': 0, 'category_id': category_id, 'segmentation': [] } return annotation # Create the annotations of the ECP dataset (Coco format) coco_format = { "images": [ { } ], "categories": [ ], "annotations": [ { } ] }
def DPLL(B, I): if len(B) == 0: return True, I for i in B: if len(i) == 0: return False, [] x = B[0][0] if x[0] != '!': x = '!' + x Bp = [[j for j in i if j != x] for i in B if not(x[1:] in i)] Ip = [i for i in I] Ip.append('Valor de ' + x[1:] + ': ' + str(True)) V, I1 = DPLL(Bp, Ip) if V: return True, I1 Bp = [[j for j in i if j != x[1:]] for i in B if not(x in i)] Ip = [i for i in I] Ip.append('Valor de ' + x[1:] + ': ' + str(False)) V, I2 = DPLL(Bp, Ip) if V: return True, I2 return False, [] expresion =[['!p', '!r', '!s'], ['!q', '!p', '!s'], ['p'], ['s']] t,r = DPLL(expresion, []) print(t) print(r)
#multiplicar a nota pelo peso, depois divide a soma das notas pela soma dos pesos nota1=float(input())*2 nota2=float(input())*3 nota3=float(input())*5 media=float((nota1+nota2+nota3))/10 print("MEDIA =","%.1f"%media)
VALUES_CONSTANT = "values" PREVIOUS_NODE_CONSTANT = "previous_vertex" START_NODE = "A" END_NODE = "F" # GRAPH IS 1A graph = { "A": { "B" : 5, "C" : 2 }, "B": { "E" : 4 , "D": 2 , }, "C" : { "B" : 8, "D" : 7 }, "E" : { "F" : 3 , "D" : 6 }, "D" : { "F" : 1 }, "F" : { } } # GRAPH 1B # graph = { # "A": { # "B" : 10 # }, # "B": { # "C" : 20 , # }, # "C" : { # "D" : 1 , # "E" : 30 # }, # "D" : { # "B" : 1, # }, # "E" : { # } # } # GENERATES SCORE TABLE FOR DIJKSTRA ALGORITHM def generate_score_table(): SCORE_TABLE = {} QUEUE = [START_NODE] SCORE_TABLE[START_NODE] = { VALUES_CONSTANT : 0 } VISITED = [] NEXT_FIRST_NEIGHBOR= list(graph[QUEUE[0]].keys())[0] shortest_path_length = 0 shortest_path_found_bool = False # IMPLEMENT BFS while len(QUEUE) > 0: # TRAVERSE THE EDGES for node in graph[QUEUE[0]].keys(): # IF THE !EXIST IN THE TABLE IT SHOULD INCLUDE IN THE TABLE, OTHERWISE CHECK THE VALUE cost = graph[QUEUE[0]][node] + SCORE_TABLE[QUEUE[0]][VALUES_CONSTANT] if node not in SCORE_TABLE: SCORE_TABLE[node] = { VALUES_CONSTANT : cost, PREVIOUS_NODE_CONSTANT : QUEUE[0] } else: if cost < SCORE_TABLE[node][VALUES_CONSTANT]: SCORE_TABLE[node] = { VALUES_CONSTANT: cost, PREVIOUS_NODE_CONSTANT : QUEUE[0]} if node not in VISITED and node not in QUEUE: if(NEXT_FIRST_NEIGHBOR==node and shortest_path_found_bool == False): shortest_path_length += 1 if(node == END_NODE): shortest_path_found_bool = True else: NEXT_FIRST_NEIGHBOR= list(graph[node].keys())[0] QUEUE += [node] VISITED += QUEUE[0] QUEUE.pop(0) return SCORE_TABLE,shortest_path_length def get_fastest_path(START_NODE, END_NODE, SCORE_TABLE,shortest_path): path = [] boolean_similar = False node = END_NODE while node != START_NODE: path.insert(0,node) node = SCORE_TABLE[node][PREVIOUS_NODE_CONSTANT] path.insert(0,node) if(len(path)-1 == shortest_path): boolean_similar = True else: boolean_similar = False return path, boolean_similar SCORE_TABLE,shortest_path_len = generate_score_table() fastest_path,boolean = get_fastest_path(START_NODE, END_NODE, SCORE_TABLE,shortest_path_len) print("FASTEST PATH:",fastest_path) print("BOOLEAN FOR SIMILARITY OF SHORTEST AND FASTEST:",boolean)
# -*- coding: utf-8 -*- # Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # This program is free software; you can redistribute it and/or modify # it under the terms of the MIT License. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MIT License for more details. csv = 'perf_Us_3' cfg_dict = { 'aux_no_0': { 'dataset': 'aux_no_0', 'p': 3, 'd': 1, 'q': 1, 'taus': [1533, 8], 'Rs': [5, 5], 'k': 15, 'tol': 0.001, 'testsize': 0.1, 'loop_time': 5, 'info': 'v2', 'Us_mode': 3, 'filename': csv }, 'aux_smooth': { 'dataset': 'aux_smooth', 'p': 3, 'd': 1, 'q': 1, 'taus': [319, 8], 'Rs': [5, 5], 'k': 15, 'tol': 0.001, 'testsize': 0.1, 'loop_time': 5, 'info': 'v2', 'Us_mode': 3, 'filename': csv }, 'aux_raw': { 'dataset': 'aux_raw', 'p': 3, 'd': 1, 'q': 1, 'taus': [2246, 8], 'Rs': [5, 8], 'k': 15, 'tol': 0.001, 'testsize': 0.1, 'loop_time': 5, 'info': 'v2', 'Us_mode': 3, 'filename': csv }, 'D1': { 'dataset': 'D1_qty', 'p': 3, 'd': 1, 'q': 1, 'taus': [607, 10], 'Rs': [20, 5], 'k': 15, 'tol': 0.001, 'testsize': 0.1, 'loop_time': 5, 'info': 'v2', 'Us_mode': 3, 'filename': csv }, 'PC_W': { 'dataset': 'PC_W', 'p': 3, 'd': 1, 'q': 1, 'taus': [9, 10], 'Rs': [5, 5], 'k': 15, 'tol': 0.001, 'testsize': 0.1, 'loop_time': 5, 'info': 'v2', 'Us_mode': 3, 'filename': csv }, 'PC_M': { 'dataset': 'PC_M', 'p': 3, 'd': 1, 'q': 1, 'taus': [9, 10], 'Rs': [5, 5], 'k': 15, 'tol': 0.001, 'testsize': 0.1, 'loop_time': 5, 'info': 'v2', 'Us_mode': 3, 'filename': csv }, 'ele40': { 'dataset': 'ele40', 'p': 3, 'd': 2, 'q': 1, 'taus': [321, 20], 'Rs': [5, 5], 'k': 15, 'tol': 0.001, 'testsize': 0.1, 'loop_time': 5, 'info': 'v2', 'Us_mode': 3, 'filename': csv }, 'ele200': { 'dataset': 'ele_small', 'p': 3, 'd': 2, 'q': 1, 'taus': [321, 20], 'Rs': [5, 5], 'k': 15, 'tol': 0.001, 'testsize': 0.1, 'loop_time': 5, 'info': 'v2', 'Us_mode': 3, 'filename': csv }, 'ele_big': { 'dataset': 'ele_big', 'p': 3, 'd': 2, 'q': 1, 'taus': [321, 20], 'Rs': [5, 5], 'k': 15, 'tol': 0.001, 'testsize': 0.1, 'loop_time': 5, 'info': 'v2', 'Us_mode': 1, 'filename': csv }, 'traffic_40': { 'dataset': 'traffic_40', 'p': 3, 'd': 2, 'q': 1, 'taus': [228, 5], 'Rs': [20, 5], 'k': 15, 'tol': 0.001, 'testsize': 0.1, 'loop_time': 5, 'info': 'v2', 'Us_mode': 3, 'filename': csv }, 'traffic_80': { 'dataset': 'traffic_small', 'p': 3, 'd': 2, 'q': 1, 'taus': [228, 5], 'Rs': [20, 5], 'k': 15, 'tol': 0.001, 'testsize': 0.1, 'loop_time': 5, 'info': 'v2', 'Us_mode': 3, 'filename': csv }, 'traffic_big': { 'dataset': 'traffic_big', 'p': 3, 'd': 2, 'q': 1, 'taus': [862, 10], 'Rs': [20, 5], 'k': 15, 'tol': 0.001, 'testsize': 0.1, 'loop_time': 5, 'info': 'v2', 'Us_mode': 1, 'filename': csv } }
sal = float(input('Qual o seu salario? ')) if sal > 1250.00: print('Com o aumento seu salario sera R${:.2f}'.format(sal + (sal / 100) * 10)) else: print('Com o aumento seu salario sera R${:.2f}'.format(sal + (sal / 100) * 15))
""" Given a nested list of integers represented as a string, implement a parser to deserialize it. Each element is either an integer, or a list -- whose elements may also be integers or other lists. Note: You may assume that the string is well-formed: String is non-empty. String does not contain white spaces. String contains only digits 0-9, [, - ,, ]. Example 1: Given s = "324", You should return a NestedInteger object which contains a single integer 324. Example 2: Given s = "[123,[456,[789]]]", Return a NestedInteger object containing a nested list with 2 elements: 1. An integer containing value 123. 2. A nested list containing two elements: i. An integer containing value 456. ii. A nested list with one element: a. An integer containing value 789. """ __author__ = 'Daniel' # """ # This is the interface that allows for creating nested lists. # You should not implement it, or speculate about its implementation # """ class NestedInteger(object): def __init__(self, value=None): """ If value is not specified, initializes an empty list. Otherwise initializes a single integer equal to value. """ def isInteger(self): """ @return True if this NestedInteger holds a single integer, rather than a nested list. :rtype bool """ def add(self, elem): """ Set this NestedInteger to hold a nested list and adds a nested integer elem to it. :rtype void """ def setInteger(self, value): """ Set this NestedInteger to hold a single integer equal to value. :rtype void """ def getInteger(self): """ @return the single integer that this NestedInteger holds, if it holds a single integer Return None if this NestedInteger holds a nested list :rtype int """ def getList(self): """ @return the nested list that this NestedInteger holds, if it holds a nested list Return None if this NestedInteger holds a single integer :rtype List[NestedInteger] """ class Solution(object): def deserialize(self, s): """ NestedInteger is a UnionType in functional programming jargon. [1, [1, [2]], 3, 4] From a general example, develop an algorithm using stack The algorithm itself is easy, but the string parsing contains lots of edge cases :type s: str :rtype: NestedInteger """ if not s: return None stk = [] i = 0 while i < len(s): if s[i] == '[': stk.append(NestedInteger()) i += 1 elif s[i] == ']': ni = stk.pop() if not stk: return ni stk[-1].add(ni) i += 1 elif s[i] == ',': i += 1 else: j = i while j < len(s) and (s[j].isdigit() or s[j] == '-'): j += 1 ni = NestedInteger(int(s[i: j]) if s[i: j] else None) if not stk: return ni stk[-1].add(ni) i = j return stk.pop() if __name__ == "__main__": Solution().deserialize("[123,[456,[789]]]")
class QuizQuestion: def __init__(self, text, answer): self.text = text self.answer = answer @property def text(self): return self.__text @text.setter def text(self, text): self.__text = text @property def answer(self): return self.__answer @answer.setter def answer(self, answer): self.__answer = answer
class Model: def __init__(self): self._classes = {} self._relations = {} self._generalizations = {} self._associationLinks = {} def addClass(self, _class): self._classes[_class.uid()] = _class def classByUid(self, uid): return self._classes[uid] def addRelation(self, relation): lClass = relation.leftAssociation()._class().relate(relation) rClass = relation.rightAssociation()._class().relate(relation) self._relations[relation.uid()] = relation def addGeneralization(self, generalization): self._generalizations[generalization.uid()] = generalization def addAssociationLink(self, assoclink): self._associationLinks[assoclink.uid()] = assoclink def relationByUid(self, uid): return self._relations[uid] def classes(self): return self._classes def relations(self): return self._relations def generalizations(self): return self._generalizations def associationLinks(self): return self._associationLinks def superClassOf(self, _class): superclass = None for generalization in self._generalizations.values(): if generalization.subclass() == _class: superclass = generalization.superclass() break return superclass
''' 08 - Finding ambiguous datetimes At the end of lesson 2, we saw something anomalous in our bike trip duration data. Let's see if we can identify what the problem might be. The data is loaded as onebike_datetimes, and tz has already been imported from dateutil. Instructions - Loop over the trips in onebike_datetimes: - Print any rides whose start is ambiguous. - Print any rides whose end is ambiguous. ''' # Loop over trips for trip in onebike_datetimes: # Rides with ambiguous start if tz.datetime_ambiguous(trip['start']): print("Ambiguous start at " + str(trip['start'])) # Rides with ambiguous end if tz.datetime_ambiguous(trip['end']): print("Ambiguous end at " + str(trip['end'])) # Ambiguous start at 2017-11-05 01:56:50-04:00 # Ambiguous end at 2017-11-05 01: 01: 04-04: 00
_base_ = [ '../_base_/models/faster_rcnn_r50_fpn.py', '../_base_/datasets/openBrand_detection.py', '../_base_/default_runtime.py' ] data = dict( samples_per_gpu=4, workers_per_gpu=2, ) # model settings model = dict( neck=[ dict( type='FPN', in_channels=[256, 512, 1024, 2048], out_channels=256, num_outs=5), dict( type='BFP', in_channels=256, num_levels=5, refine_level=2, refine_type='non_local') ], roi_head=dict( bbox_head=dict( num_classes=515, loss_bbox=dict( _delete_=True, type='BalancedL1Loss', alpha=0.5, gamma=1.5, beta=1.0, loss_weight=1.0))), # model training and testing settings train_cfg=dict( rpn=dict(sampler=dict(neg_pos_ub=5), allowed_border=-1), rcnn=dict( sampler=dict( _delete_=True, type='CombinedSampler', num=512, pos_fraction=0.25, add_gt_as_proposals=True, pos_sampler=dict(type='InstanceBalancedPosSampler'), neg_sampler=dict( type='IoUBalancedNegSampler', floor_thr=-1, floor_fraction=0, num_bins=3) ) ) ) ) # optimizer optimizer = dict(type='SGD', lr=0.04, momentum=0.9, weight_decay=0.0001) optimizer_config = dict(grad_clip=None) # learning policy lr_config = dict( policy='step', warmup='linear', warmup_iters=10000, warmup_ratio=0.001, step=[8, 11]) runner = dict(type='EpochBasedRunner', max_epochs=12)
''' Problem statement: Given a binary tree, find if it is height balanced or not. A tree is height balanced if difference between heights of left and right subtrees is not more than one for all nodes of tree. ''' class Node: # Constructor to create a new Node def __init__(self, data): self.data = data self.left = None self.right = None def get_height(root): if root is None: return 0 return 1 + max(get_height(root.left), get_height(root.right)) def isBalanced(root): if root is None: return 1 left_tree_height = get_height(root.left) right_tree_height = get_height(root.right) if abs(left_tree_height - right_tree_height) > 1: return False return isBalanced(root.left) and isBalanced(root.right) # Initial Template for Python 3 if __name__ == '__main__': root = None t = int(input()) for i in range(t): # root = None n = int(input()) arr = input().strip().split() if n == 0: print(0) continue dictTree = dict() for j in range(n): if arr[3 * j] not in dictTree: dictTree[arr[3 * j]] = Node(arr[3 * j]) parent = dictTree[arr[3 * j]] if j is 0: root = parent else: parent = dictTree[arr[3 * j]] child = Node(arr[3 * j + 1]) if (arr[3 * j + 2] == 'L'): parent.left = child else: parent.right = child dictTree[arr[3 * j + 1]] = child if isBalanced(root): print(1) else: print(0)
# Copyright 2016 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. inas = [('ina219', '0x40', 'pp1050_s', 1.05, 0.010, 'rem', True), ('ina219', '0x41', 'pp1800_a', 1.80, 0.010, 'rem', True), ('ina219', '0x42', 'pp1200_vddq', 1.20, 0.010, 'rem', True), ('ina219', '0x43', 'pp3300_a', 3.30, 0.010, 'rem', True), ('ina219', '0x44', 'ppvbat', 7.50, 0.010, 'rem', True), ('ina219', '0x47', 'ppvccgi', 1.00, 0.010, 'rem', True), ('ina219', '0x49', 'ppvnn', 1.00, 0.010, 'rem', True), ('ina219', '0x4a', 'pp1240_a', 1.24, 0.010, 'rem', True), ('ina219', '0x4b', 'pp5000_a', 5.00, 0.010, 'rem', True)]
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. load("//antlir/bzl:shape.bzl", "shape") conf_t = shape.shape( nameservers = shape.list(str), search_domains = shape.list(str), )
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None def __repr__(self): if self: return "{} -> {}".format(self.val, self.next) class Solution: def deleteDuplicates(self, head): """ :type head: ListNode :rtype: ListNode """ current = head dummy = head while current: runner = current.next while runner and current.val == runner.val: runner = runner.next current.next = runner current = runner return head if __name__ == "__main__": head, head.next, head.next.next = ListNode(1), ListNode(1), ListNode(2) head.next.next.next, head.next.next.next.next = ListNode(3), ListNode(3) print(head) print(Solution().deleteDuplicates(head)) """ Time Complexity = O(n) Space Complexity = O(1) Given a sorted linked list, delete all duplicates such that each element appear only once. Example: Input: 1->1->2->3->3 Output: 1->2->3 """
# Sudoku problem solved using backtracking def solve_sudoku(array): is_empty_cell_found = False; # Finding if there is any empty cell for i in range(0, 9): for j in range(0, 9): if array[i][j] == 0: row, col = i, j is_empty_cell_found = True break if is_empty_cell_found: break # print('row', row, 'col', col, 'is_empty_cell_found', is_empty_cell_found) if not is_empty_cell_found: return True for num in range(1, 10): # print(num) if _is_valid_move(array, row, col, num): # print('is valid move') array[row][col] = num if solve_sudoku(array): return True else: array[row][col] = 0 return False def _is_valid_move(array, row, col, num): # Checking row if same num already exists for i in range(0, 9): if array[row][i] == num: return False # Checking column if same num already exists for i in range(0, 9): if array[i][col] == num: return False # Checking the current cube row_start = row - row % 3 column_start = col - col % 3 # print(row_start, column_start) for i in range(row_start, row_start + 3): for j in range(column_start, column_start + 3): if array[i][j] == num: # print('matched in grid') return False return True def print_array(array): for i in range(0, 9): for j in range(0, 9): print(sudoku_array[i][j], end = " ") print() if __name__ == '__main__': sudoku_array = [[3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0]] solve_sudoku(sudoku_array) print_array(sudoku_array)
# All rights reserved by forest fairy. # You cannot modify or share anything without sacrifice. # If you don't agree, keep calm and don't look at code bellow! __author__ = "VirtualV <https://github.com/virtualvfix>" __date__ = "03/22/18 15:40" class InstallError(Exception): """ Install exception base class. """ def __init__(self, value): self.value = value def __str__(self): return repr(self.value) class ApkNotFoundError(InstallError): def __init__(self, value): super(ApkNotFoundError, self).__init__(value)
""" /* * * Crypto.BI Toolbox * https://Crypto.BI/ * * Author: José Fonseca (https://zefonseca.com/) * * Distributed under the MIT software license, see the accompanying * file COPYING or http://www.opensource.org/licenses/mit-license.php. * */ """ class CBInfoNode: def __init__(self, cin_id, block_hash, tx_hash, address, content): self.cin_id = cin_id self.block_hash = block_hash self.tx_hash = tx_hash self.address = address self.content = content
#SetExample4.py ------difference between discard() & remove() #from both remove() gives error if value not found nums = {1,2,3,4} #remove using discard() nums.discard(5) print("After discard(5) : ",nums) #reove using remove() try: nums.remove(5) print("After remove(5) : ",nums) except KeyError: print("KeyError : Value not found")
class Item: def __init__(self, name, price, quantity): self._name = name self.set_price(price) self.set_quantity(quantity) def get_name(self): return self._name def get_price(self): return self._price def get_quantity(self): return self._quantity def set_price(self, price): if price > 0: self._price = price # todo - defensive checks def set_quantity(self, quantity): if quantity >= 0: self._quantity = quantity # todo - defensive checks def buy(self, quantity_to_buy): if quantity_to_buy <= self._quantity: self._quantity -= quantity_to_buy return quantity_to_buy * self._price return 0
""" Constants for django Organice. """ ORGANICE_DJANGO_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin', ] ORGANICE_CMS_APPS = [ 'cms', 'mptt', 'menus', 'sekizai', 'treebeard', 'easy_thumbnails', 'djangocms_admin_style', # 'djangocms_file', 'djangocms_maps', 'djangocms_inherit', 'djangocms_link', 'djangocms_picture', # 'djangocms_teaser', 'djangocms_text_ckeditor', # 'media_tree', # 'media_tree.contrib.cms_plugins.media_tree_image', # 'media_tree.contrib.cms_plugins.media_tree_gallery', # 'media_tree.contrib.cms_plugins.media_tree_slideshow', # 'media_tree.contrib.cms_plugins.media_tree_listing', # 'form_designer.contrib.cms_plugins.form_designer_form', ] ORGANICE_BLOG_APPS = [ 'cmsplugin_zinnia', 'django_comments', 'tagging', 'zinnia', ] ORGANICE_NEWSLETTER_APPS = [ # 'emencia.django.newsletter', 'tinymce', ] ORGANICE_UTIL_APPS = [ 'analytical', 'simple_links', 'todo', ] ORGANICE_AUTH_APPS = [ 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.amazon', # 'allauth.socialaccount.providers.angellist', 'allauth.socialaccount.providers.bitbucket', 'allauth.socialaccount.providers.bitly', 'allauth.socialaccount.providers.dropbox_oauth2', 'allauth.socialaccount.providers.facebook', # 'allauth.socialaccount.providers.flickr', # 'allauth.socialaccount.providers.feedly', 'allauth.socialaccount.providers.github', 'allauth.socialaccount.providers.gitlab', 'allauth.socialaccount.providers.google', 'allauth.socialaccount.providers.instagram', 'allauth.socialaccount.providers.linkedin_oauth2', # 'allauth.socialaccount.providers.openid', 'allauth.socialaccount.providers.pinterest', 'allauth.socialaccount.providers.slack', 'allauth.socialaccount.providers.soundcloud', 'allauth.socialaccount.providers.stackexchange', # 'allauth.socialaccount.providers.tumblr', # 'allauth.socialaccount.providers.twitch', 'allauth.socialaccount.providers.twitter', 'allauth.socialaccount.providers.vimeo', # 'allauth.socialaccount.providers.vk', # 'allauth.socialaccount.providers.weibo', 'allauth.socialaccount.providers.windowslive', 'allauth.socialaccount.providers.xing', ]
""" dp """ class Solution: def uniquePaths(self, row: int, col: int) -> int: """ Since only 2 options are possible, either from the cell above or left, it is a dp problem. """ def is_valid(i, j): if i >= row or j >= col or i < 0 or j < 0: return False else: return True dp = [[0 for j in range(col)] for i in range(row)] for i in range(row): for j in range(col): if i ==0 and j ==0: dp[i][j] = 1 if is_valid(i -1, j): dp[i][j] += dp[i-1][j] if is_valid(i, j-1): dp[i][j] += dp[i][j-1] return dp[row-1][col-1] inp = (3,2) s = Solution() res = s.uniquePaths(*inp) print(res)
class Solution: def makeConnected(self, n: int, connections: List[List[int]]) -> int: if len(connections) < n-1: return -1 adjacency = [set() for _ in range(n)] for x,y in connections: adjacency[x].add(y) adjacency[y].add(x) components = 0 visited = [False]*n for i in range(n): if visited[i]: continue stack = [i] components += 1 while stack: x = stack.pop() visited[x]=True for neighbor in adjacency[x]: if not visited[neighbor]: stack.append(neighbor) return components - 1
class Config: Sector = [ "Food", "Agriculture", "Clothing", "Construction", "Health", "Services", "Retail", "Arts", "Housing", "Transportation", "Manufacturing", "Entertainment", "Wholesale", "Education", "Personal Use" ] Activity = [ "Butcher Shop", "Food Production/Sales", "Animal Sales", "Clothing Sales", "Restaurant", "Fish Selling", "Cereals", "Bricks", "Livestock", "Pharmacy", "Dairy", "Secretarial Services", "Grocery Store", "Carpentry", "General Store", "Bakery", "Used Clothing", "Pigs", "Beauty Salon", "Home Products Sales", "Crafts", "Tailoring", "Farming", "Poultry", "Construction Supplies", "Bicycle Repair", "Fishing", "Farm Supplies", "Cobbler", "Electrician", "Construction", "Retail", "Cosmetics Sales", "Sewing", "Shoe Sales", "Cheese Making", "Barber Shop", "Printing", "Party Supplies", "Services", "Personal Housing Expenses", "Transportation", "Photography", "Taxi", "Traveling Sales", "Phone Accessories", "Furniture Making", "Office Supplies", "Sporting Good Sales", "Veterinary Sales", "Machine Shop", "Electronics Sales", "Paper Sales", "Electronics Repair", "Water Distribution", "Land Rental", "Cement", "Cattle", "Phone Use Sales", "Catering", "Musical Instruments", "Vehicle Repairs", "Health", "Patchwork", "Charcoal Sales", "Computers", "Food Market", "Blacksmith", "Decorations Sales", "Metal Shop", "Plastics Sales", "Bicycle Sales", "Laundry", "Cafe", "Musical Performance", "Soft Drinks", "Textiles", "Dental", "Perfumes", "Milk Sales", "Motorcycle Transport", "Quarrying", "Air Conditioning", "Medical Clinic", "Fuel/Firewood", "Agriculture", "Arts", "Utilities", "Pub", "Manufacturing", "Bookstore", "Phone Repair", "Mobile Phones", "Timber Sales", "Hardware", "Food", "Child Care", "Electrical Goods", "Tourism", "Religious Articles", "Auto Repair", "Recycling", "Spare Parts", "Personal Products Sales", "Natural Medicines", "Goods Distribution", "Weaving", "Souvenir Sales", "Embroidery", "Well digging", "Music Discs & Tapes", "Motorcycle Repair", "Rickshaw", "Primary/secondary school costs", "Hotel", "Liquor Store / Off-License", "Bookbinding", "Call Center", "Movie Tapes & DVDs", "Waste Management", "Film", "Knitting", "Fruits & Vegetables", "Jewelry", "Cloth & Dressmaking Supplies", "Upholstery", "Internet Cafe", "Personal Purchases", "Games", "Entertainment", "Education provider", "Flowers", "Wholesale", "Clothing", "Food Stall", "Machinery Rental", "Balut-Making", "Vehicle", "Funeral Expenses", "Property", "Home Appliances", "Personal Medical Expenses", "Renewable Energy Products", "Recycled Materials", "Wedding Expenses", "Home Energy", "Consumer Goods", "Used Shoes", "Higher education costs" ] Country = [ "Uganda", "Tanzania", "Kenya", "Gaza", "Bulgaria", "Senegal", "Nicaragua", "Honduras", "Ecuador", "Cambodia", "Samoa", "Mexico", "Moldova", "Nigeria", "Togo", "Ghana", "Mozambique", "Azerbaijan", "Ukraine", "Afghanistan", "Indonesia", "Cameroon", "Dominican Republic", "The Democratic Republic of the Congo", "Tajikistan", "Vietnam", "Bolivia", "Haiti", "Cote D'Ivoire", "Guatemala", "Iraq", "Sierra Leone", "Paraguay", "Peru", "Pakistan", "Nepal", "Lebanon", "El Salvador", "Bosnia and Herzegovina", "Benin", "Mali", "South Sudan", "Rwanda", "Philippines", "Palestine", "Mongolia", "Costa Rica", "United States", "Kyrgyzstan", "Liberia", "Armenia", "Colombia", "Chile", "Sri Lanka", "Burundi", "Congo", "Jordan", "South Africa", "Israel", "Georgia", "Zimbabwe", "Burkina Faso", "Turkey", "Yemen", "Zambia", "Kosovo", "Albania", "Timor-Leste", "Belize" ] Town = [ "Rare_Town", "Managua", "Danli", "Tegucigalpa", "Guayaquil", "Kampala", "Phnom Penh City", "Dar es Salaam", "Kandal Province", "Kiambu", "Vailele", "Monterrey", "Nuevo Laredo", "Linares", "Escobedo, N. L.", "Apodaca, N. L.", "Yucatán", "Mérida, Yucatán", "Pedro Escobedo, Querétaro", "Tampico, Tamaulipas", "Guadalupe, Nuevo Leon", "Santa Catarina, Nuevo Leon", "Benin City", "Victoria, Tamaulipas", "Lomé", "Aného", "Nairobi", "Nakuru", "Kisumu", "Embu", "Kakamega", "Catembe, Maputo, Mozambique", "Boane, Maputo", "Monclova,Coahuila", "Acuna", "Tsévié", "Sekondi-Takoradi", "Cadereyta, Nuevo León, México", "Sumgayit city", "Accra", "Fizuli district", "Zaporozhye", "Absheron region", "Baku, city", "Faleula", "Salyan region", "Vaitele", "Faleasiu", "Eldoret, Rift Valley", "Novaya Kahovka", "Kabul Afghanistan", "Melitopol", "Berdyansk", "Choluteca", "Nikopol", "Saltillo, Coahuila", "Tangerang", "Los Alcarrizos", "Khachmaz", "Baku", "Beylagan", "Agsu", "Kinshasa", "Khujand", "Duc Linh, Binh Thuan", "Ivano-Frankivsk", "Migori", "Busia", "Kampong Cham", "Machakos", "Kitale", "Malie", "Spitamen", "J.Rasulov", "Ham Thuan Nam", "Nkurankan, Yilo Krobo District", "Istaravshan", "Pavlograd", "La Paz", "Agoe", "San Pedro de Macorís", "Kostakoz", "Monterrey, Nuevo León", "Trou-du-Nord", "Kanibadam", "Isfara", "Hato Mayor", "Shama", "El Alto", "Saatli", "kirkuk", "Phnom Penh", "Imishli", "Bilasuvar", "Makeni", "Kabala", "Magburaka, Tonkolili", "Asunción", "Kampong Chnang province, Cambodia", "La Romana", "Kamenka-Dneprovskaya", "Samaná", "Muk Kampoul district", "SiemReap province", "Legok, Tangerang", "Caacupe", "Khsach Kandal district", "Carapegua", "Khuroson", "Yavan", "Uromi, Edo State", "Dushanbe", "Gissar", "Coronel Oviedo", "Paraguari", "Ita", "Kean Svay district", "Pon-Nhea Leu district", "Sabirabad", "Yamasa", "Puerto Plata", "Gafurov, Tajikistan", "Nghi Loc", "Hung Nguyen", "Ybycuí", "San Lorenzo", "Ta Khmao district", "Kandal Steung district", "Vahdat", "San Ignacio", "Siem Reap Province", "Ninh Giang", "Asaba, Delta State", "Santaní", "Kim Dong", "Prey Veng Province", "Villa Elisa", "Juliaca", "Encarnación", "Pakpattan", "Caaguazú", "Ayacucho", "Soc Son", "Ciudad del Este", "Luque", "Bokhtar", "Mariano R. Alonso", "Santo Domingo", "Montemorelos, Nuevo León", "Khachmaz region", "Tursun-zoda", "San Martín", "Lahore", "Nansana", "Tangal", "SainbuBhaishepati", "Thecho", "Santa Cruz de la Sierra", "Saatli town", "Cochabamba", "Callería - Ucayali", "Badung", "Hédzranawoé", "Quang Xuong", "Moyobamba - San Martin", "Melaya, Bali", "Borj Barajneh", "HUANCAYO", "TARMA", "PUCALLPA", "Tripoli", "Vehari", "Leuwiliang, Bogor", "Rudaki", "Kayunga", "Novomoskovsk", "Aley", "Trujillo - La Libertad", "Bluefields.", "Baalback", "El Seybo", "Saida", "Tyre", "Multan", "Chinandega", "Phuc Yen", "Leon", "Nabatieh", "San Martín - San Martín", "Tarapoto - San Martin", "Juanjui - San Martin", "Huaraz - Ancash", "Batambong", "Bekaa", "San Cristobal", "Namaacha", "Shahrinav", "Yarinacocha - Ucayali", "Lima", "Bac Ninh", "Lagos State", "Mampong", "Kot Radha Kishan", "Asht", "Cape Coast", "Arifwala", "Obuasi", "Elmina", "Mankessim", "Abdurahmon Jomi", "Offinsu", "Tema", "Kasoa", "San Martin Jilotepeque, Chimaltenango", "Santo Domingo Norte", "Raiwind", "Kpalimé", "Lugazi", "Adéta", "Rajeg, Tangerang", "La Libertad, La Libertad", "Kireka", "Sarajevo", "Ntungamo", "Kasubi", "Kyengara", "Nateete", "Mukono", "Fuzuli region", "Huarochiri", "Lima Norte", "Huaycan", "San Juan de Lurigancho", "Faisalabad", "Y Yen", "Kasur", "Mbeya", "Beirut", "Borewala", "Chichawatni", "Kalerwe", "Mwanza", "Mubende", "Cotonou Agence principale", "Kyela", "Vitarte", "Barcenas,Villa Nueva", "Ibanda", "Agence de Thiès", "Mpigi", "Tursunzade", "THIES", "Mbour", "Kampong Thom", "Shahrituz", "Kumsangir", "Bushenyi", "Agence de Ziguinchor", "ZIGUINCHOR", "Kator, Juba, Southern", "Buluk, Juba, Southern", "Siem Reap", "Munuki, Juba, Southern", "Jinja", "Esteli", "Banteay Meanchey", "Panjakent", "Pursat", "Chontales", "Mityana", "Adidogomé", "Sunyani", "Jebel kujur,Juba", "Agence de Kolda", "Zanzibar", "Tanga", "Atlabara,Juba,southern", "Morogoro", "Arusha", "Hai-gabat,Juba,southern", "Santiago", "Nkawkaw", "Koforidua", "Kisii", "DAKAR", "San Juan Sacatepèquez", "Jalalabad", "Abura", "Goaso", "Utkansoi", "Dj.Rasulov", "Totonicapan", "Segou", "Sikasso", "Bougouni", "Yunguyo-Puno", "J.Rumy", "Sa Ang, Phnom Penh", "Dong Anh- Ha Noi", "Koutiala", "Wome", "Fana ", "SEME-PODJI", "Piedras Negras", "Kigali", "Zanzibar (Mikunguni)", "Zanzibar (Kikwajuni)", "Zanzibar (Jang'ombe)", "Zanzibar (Melinne)", "Siwdo", "CUSCO", "Huancavelica", "Kulob", "Prey Chhor, Kampong Cham", "Mombasa", "Calca - Calca - Cusco", "Tboung Khmum District", "PILAR", "Telica", "Pisac - Calca - Cusco", "Nindiri", "Jilikul", "Masaya", "Puno", "Gonchi", "Kampong Chhnang", "Thanh Hoá", "Chanchamayo", "San Jose, Antique", "Sta. Josefa, Agusan del Sur", "Plaridel - Plaridel, Misamis Occidental", "Ilagan", "Surallah, South Cotabato", "Bint Jbeil", "Sto Niño, South Cotabato", "Plaridel-Lopez Jaena, Misamis Occidental", "Calamba - Baliangao, Misamis Occidental", "Calamba, Misamis Occidental", "Oroquieta-Misamis Occidental ", "Dipolog City", "Bunawan, Agusan Del Sur", "Hamtic, Antique", "Jauja", "Chinchero - Urubamba - Cusco", "Gumbo", "Gudele", "Isabela", "Porto-Novo", "Dipolog-Dapitan City", "Jimenez, Misamis Occidental", "Zanna", "kyengera", "gaza", "Trento, Agusan Del Sur", "Ejura", "Thanh Hoa City", "Ulaanbaatar", "Banga, South Cotabato", "Ahuachapán, Ahuachapan", "Ibadan, Oyo State", "Soyapango, departamento de San Salvador", "Alajuela", "Panglao, Bohol", "Talibon, Bohol", "Bien Unido, Bohol", "Andahuaylillas - Quispicanchi - Cusco", "Ogbomoso, Oyo State", "Trinidad, Bohol", "San Miguel, Bohol", "Ibadan,oyo state", "Urcos - Quispicanchi - Cusco", "Urubamba - Urubamba - Cusco", "Anta - Anta - Cusco", "Santiago City, Isabela", "Norala, South Cotabato", "Tumpagon, Cagayan de Oro, Misamis Oriental", "Valencia City, Bukidnon", "Arvaiheer, Uvurhangai", "Takeo province", "Takeo", "Cauayan City, Isabela", "Waterloo", "Agbor, Delta state", "Calamba-Sapang Dalaga Misamis Occidental", "Tsetserleg, Arhangai", "Ocongate - Quispicanchi - Cusco", "Cachimayo - Anta - Cusco", "Oroquieta - Aloran", "Warri, Delta State", "Uvurhangai", "San Salvador, San Salvador", "Baclayon, Bohol", "Ollantaytambo - Urubamba - Cusco", "Veruela, Agusan Del Sur", "Oda", "Dormaa", "Clarin, Misamis Occidental", "Clarin Misamis Occidental", "baguida", "Oroquieta City Misamis Occidental", "Ozamiz City", "Sto. Niño, Tukuran, Zamboanga del Sur", "Hoima", "Calamba Misamis Occidental", "Hamadoni", "Arkhangai", "Tangub City, Misamis Occidental", "Aurora, Zamboanga del Sur", "Kochkor", "Sapele, Delta state", "Wiawso", "Binangonan, Rizal", "Hohoe", "Tuv", "Iligan City, Lanao del Norte", "Sefwi Wiawso", "Pasay City", "Caloocan City", "West Point", "Kasese", "Cuenca", "Tokmak", "Payatas-B, Commonwealth, Quezon City", "Monrovia North", "Tudela, Misamis Occidental", "Ozamis City, Misamis Occidental", "Bago, Negros Occidental", "Karabalta", "Lopez Jaena, Misamis Occidental", "Kilifi", "Silang, Cavite", "Naivasha", "Intramuros, Manila City", "Dasmarinas, Cavite", "Kangemi, Nairobi", "Bonifacio, Misamis Occidental", "South of Monrovia", "HINIGARAN, NEGROS OCCIDENTAL", "Ozamis, City, Misamis Occidental", "La Castellana, Negros Occidental", "Valladolid, Negros Occidental", "Mariakani", "Kapsabet", "Cadiz, Negros Occidental", "Manta", "Portoviejo", "Binalbagan, Negros Occidental", "Sevan", "Yerevan", "Thika", "Zitacuaro, Estado de Michoacán.", "Chiclayo", "José Leonardo Ortíz - Chiclayo", "Lofa Co. Northern Liberia", "Narok", "Lambayeque", "Escalante, Negros Occidental", "Mórrope - Lambayeque", "Camiguin", "Ijevan", "Tagbilaran, Bohol", "Talakag, Bukidnon", "Konongo", "Gingoog City, Misamis Oriental", "Agence de Diourbel", "Hovd", "Tukuran, Zamboanga Del Sur", "Bayanhongor", "Fort Portal", "Tosontsengel, Zavhan", "Granada", "Bayan-Ulgii", "Balykchi", "Bo", "Narantuul, Ulaanbaatar", "malindi", "KABARNET", "San Rafael", "Ica", "Thika-Town", "Freetown Central", "SANTIAGO", "Ongata-Rongai", "Kyenjojo", "Kitengela", "Chinandega El Bisne", "Guayaquil (Isla)", "Guayaquil (Paraiso)", "Olmos - Lambayeque", "El Sauce", "Murang'a", "Jogoo Road", "Guayaquil (Fortin)", "Kade", "Oropesa - Quispicanchi - Cusco", "Agence de Louga", "Uvs", "Paijan - Ascope - La Libertad", "Cayaltí - Chiclayo", "Nairobi Central", "Parcona", "Nueva Guinea, RAAS", "Mayoreo", "San Miguel, San Miguel", "Allada", "COPAINALÁ, CHIAPAS", "Talim Island, Binangonan Rizal", "huvsgul", "Kihihi", "Masindi", "Bayawan, Negros Oriental", "Barranquilla", "Soledad Atlàntico", "GMA, Cavite", "Hinobaan, Negros Occidental", "Cartagena de Indias", "Red Light, Paynesville", "Cauayan, Negros Occidental", "Kabankalan, Negros Occidental", "San Miguel", "litein", "Tanza, Cavite", "Malambo-Atlántico", "Rukungiri", "Nairobi East", "Aravan", "Bogotà", "Nkubu", "Nyamira", "Chillanes", "San Carlos, Negros Occidental", "Uzgen", "Monrovia South", "Guayaquil (Suburbio)", "Estefania, Amulung, Cagayan", "Nairobi West", "Guaranda", "Olkalou", "Ndunyu Njeru", "Kadamjai", "Goma, North Kivu province", "Bujumbura", "Chepén, La Libertad", "Bais, Negros Oriental", "Guayaquil (Guasmo)", "Tup", "Songinohairhan, Ulaanbaatar", "Kisauni", "Eastern Wao, Lanao del Sur", "Likoni", "Guayaquil (Orquideas)", "Kagadi", "El Transito, San Miguel", "Tanjay, Negros Oriental", "Duran (Primavera)", "Juticalpa, Olancho", "Brazzaville", "Chtoura", "Tambogrande - Piura", "Santander, Cebu", "San Francisco Gotera, Morazan", "Toktogul", "Villarrica", "Dalaguete, Cebu", "Bundibugyo", "Tashkomur", "Minglanilla, Cebu", "Cordova, Cebu", "Bogo, Cebu", "Compostela, Cebu", "San Rafael de Oriente, San Miguel", "Usulután", "Ventanas", "Toledo, Cebu", "Puerto Princesa, Palawan", "Brookes Point, Palawan", "Sansar, Ulaanbaatar", "Narra, Palawan", "Hai Gwafa, Yei", "Dar es Salaam, Yei", "Roxas Palawan", "Hai Mahad, Yei", "Jigomoni, Yei", "Batasan, Quezon City", "Khanewal", "Samburu", "Concepción", "Bacoor, Cavite", "Mwingi", "Matuu", "Reussey Keo", "Kracheh", "Tala", "Playas (Villamil)", "Jiquilisco, Usulutan", "Boaco", "Victorias, Negros Occidental", "Msambweni", "Oloitoktok", "Emali", "Akodessewa", "San Francisco, Agusan Del Sur", "Kamwenge", "Al-Hashmi-Amman", "Prey Chor", "Medellín", "Bello", "Kaloleni", "Itagui", "Gitega", "Kenema", "Rionegro", "Dangara", "Freetown East", "Curuguaty", "Ain", "Baqaa", "Salt", "Ornlong Veng", "Gweru", "Zarqa", "Paynesville South", "Congo Town", "Gounghin, Ouagadougou", "Kaya-Road-South Sudan", "Madaba", "Masvingo", "Ho Chi Minh City", "SIGNOGHIN", "Mwambalazi", "Camana", "Tiribe", "CHINCHA", "Nazca", "VEDOKO, COTONOU", "Airport", "Irbid", "Chwele", "Koidu/Kono", "Sana'a", "Pinto Alfonso Lista, Ifugao", "Munuki", "Changamwe", "Taguig City", "Battambang province, Thmor Koul district", "Kampong Cham province, Ponhea Krek district", "Kongowea", "Maua", "Battambang province, Moung Russey district", "Webuye", "Montecristi", "Langber Bor", "Dokuru bor", "Buchanan", "Air port yambio", "Huatusco", "Teshie, Accra", "Kampong Cham province, Dambae district", "Antequera, Bohol" ] FundedTime = True PartnerID = True LoanAmount = True LoanTerm = True @staticmethod def has(name): return hasattr(Config, name) @staticmethod def get(name): if Config.has(name): return getattr(Config, name) return None
class Solution: def bitwiseComplement(self, N: int) -> int: if N == 0: return 1 ans = 0 i = 0 while N: r = N % 2 ans += 2 ** i * (1 - r) i += 1 N //= 2 return ans
"""Utils related to urls.""" def uri_scheme_behind_proxy(request, url): """ Fix uris with forwarded protocol. When behind a proxy, django is reached in http, so generated urls are using http too. """ if request.META.get("HTTP_X_FORWARDED_PROTO", "http") == "https": url = url.replace("http:", "https:", 1) return url def build_absolute_uri_behind_proxy(request, url=None): """build_absolute_uri behind a proxy.""" return uri_scheme_behind_proxy(request, request.build_absolute_uri(url))
a, b, c = input().split(' ') d, e, f = input().split(' ') g, h, i = input().split(' ') a = int(a) b = int(b) c = int(c) d = int(d) e = int(e) f = int(f) g = int(g) h = int(h) i = int(i) def resto(a, b, c): return (a + b) % c resultado_1 = resto(a, b, c) resultado_2 = resto(d, e, f) resultado_3 = resto(g, h, i) print(resultado_1) print(resultado_2) print(resultado_3)
jogador = {} time = [] lista = [] total = 0 while True: jogador.clear() jogador['Nome'] = input('Nome do jogador: ') quantidade = int(input('Quantas partidas {} jogou ? '.format(jogador['Nome']))) lista.clear() for i in range(0, quantidade): gol_quantidade = int(input('Quantos gols na partida {} ? '.format(i + 1))) total += gol_quantidade lista.append(gol_quantidade) jogador['Gols'] = lista jogador['Total'] = total time.append(jogador.copy()) resposta = str(input('Quer continuar ? [S/N] ')) if resposta in 'Nn': break for k, v in enumerate(time): print(f'{k:>3} ', end='') for d in v.values(): print(f'{str(d):<15}', end='') print('') print('-=' * 30) print('O jogador {} jogou {} partidas'.format(jogador['Nome'], quantidade)) for i, valor in enumerate(jogador['Gols']): print(' => Na partida {} , fez {} gols'.format(i + 1, valor)) print('Foi um total de {} gols'.format(total))
def df_restructure_values(data, structure='list', destructive=False): '''Takes in a dataframe, and restructures the values so that the output dataframe consist of columns where the value is coupled with the column header. data | DataFrame | a pandas dataframe structure | str | 'list', 'str', 'tuple', or 'dict' destructive | bool | if False, the original dataframe will be retained ''' if destructive is False: data = data.copy(deep=True) for col in data: if structure == 'list': data[col] = [[col, i] for i in data[col]] elif structure == 'str': data[col] = [col + ' ' + i for i in data[col].astype(str)] elif structure == 'dict': data[col] = [{col: i} for i in data[col]] elif structure == 'tuple': data[col] = [(col, i) for i in data[col]] return data
""" Автор: Моисеенко Павел, группа № 1, подгруппа № 2. Задание: вывести таблицу истинности для and, or, xor, equality. Таблица введена с помощью символа "*", int и bool преведены к строкам, и выведены результаты для коньюнкции, дизюнкции, строгой дизъюнкции и эквиваленции. """ logical_false = 0 logical_true = 1 delimiter = "*" space_symbol = " " header = "* A *" + "* B *" + "* " + " A and B " + "*" table_width = len(header) # print (logical_A and logical_B) print(delimiter * table_width) print(header) print(delimiter * table_width) inp_str = "* " + str(logical_true) + " ** " + str(logical_true) + " *" res1 = "* " + str(int((bool(logical_true) and bool(logical_true)))) + " *" print(inp_str + res1) print(delimiter * table_width) inp_str = "* " + str(logical_true) + " ** " + str(logical_false) + " *" res2 = "* " + str(int((bool(logical_true) and bool(logical_false)))) + " *" print(inp_str + res2) print(delimiter * table_width) inp_str = "* " + str(logical_false) + " ** " + str(logical_true) + " *" res3 = "* " + str(int((bool(logical_false) and bool(logical_true)))) + " *" print(inp_str + res3) print(delimiter * table_width) inp_str = "* " + str(logical_false) + " ** " + str(logical_false) + " *" res4 = "* " + str(int((bool(logical_false) and bool(logical_false)))) + " *" print(inp_str + res4) print(delimiter * table_width) header = "* A *" + "* B *" + "* " + " A or B " + "*" # print (logical_A or logical_B) print("\n" + delimiter * table_width) print(header) print(delimiter * table_width) inp_str = "* " + str(logical_true) + " ** " + str(logical_true) + " *" res1 = "* " + str(int((bool(logical_true) or bool(logical_true)))) + " *" print(inp_str + res1) print(delimiter * table_width) inp_str = "* " + str(logical_true) + " ** " + str(logical_false) + " *" res2 = "* " + str(int((bool(logical_true) or bool(logical_false)))) + " *" print(inp_str + res2) print(delimiter * table_width) inp_str = "* " + str(logical_false) + " ** " + str(logical_true) + " *" res3 = "* " + str(int((bool(logical_false) or bool(logical_true)))) + " *" print(inp_str + res3) print(delimiter * table_width) inp_str = "* " + str(logical_false) + " ** " + str(logical_false) + " *" res4 = "* " + str(int((bool(logical_false) or bool(logical_false)))) + " *" print(inp_str + res4) print(delimiter * table_width) header = "* A *" + "* B *" + "* " + " A xor B " + "*" # print (logical_A xor logical_B) print("\n" + delimiter * table_width) print(header) print(delimiter * table_width) inp_str = "* " + str(logical_true) + " ** " + str(logical_true) + " *" res1 = "* " + str(int((bool(logical_true) ^ bool(logical_true)))) + " *" print(inp_str + res1) print(delimiter * table_width) inp_str = "* " + str(logical_true) + " ** " + str(logical_false) + " *" res2 = "* " + str(int((bool(logical_true) ^ bool(logical_false)))) + " *" print(inp_str + res2) print(delimiter * table_width) inp_str = "* " + str(logical_false) + " ** " + str(logical_true) + " *" res3 = "* " + str(int((bool(logical_false) ^ bool(logical_true)))) + " *" print(inp_str + res3) print(delimiter * table_width) inp_str = "* " + str(logical_false) + " ** " + str(logical_false) + " *" res4 = "* " + str(int((bool(logical_false) ^ bool(logical_false)))) + " *" print(inp_str + res4) print(delimiter * table_width) header = "* A *" + "* B *" + "* " + " A == B " + "*" # print (logical_A == logical_B) print("\n" + delimiter * table_width) print(header) print(delimiter * table_width) inp_str = "* " + str(logical_true) + " ** " + str(logical_true) + " *" res1 = "* " + str(int((bool(logical_true) is bool(logical_true)))) + " *" print(inp_str + res1) print(delimiter * table_width) inp_str = "* " + str(logical_true) + " ** " + str(logical_false) + " *" res2 = "* " + str(int((bool(logical_true) is bool(logical_false)))) + " *" print(inp_str + res2) print(delimiter * table_width) inp_str = "* " + str(logical_false) + " ** " + str(logical_true) + " *" res3 = "* " + str(int((bool(logical_false) is bool(logical_true)))) + " *" print(inp_str + res3) print(delimiter * table_width) inp_str = "* " + str(logical_false) + " ** " + str(logical_false) + " *" res4 = "* " + str(int((bool(logical_false) is bool(logical_false)))) + " *" print(inp_str + res4) print(delimiter * table_width)
T,R=int(input('Enter no. Test Cases: ')),[] while(T>0): P=[int(x) for x in input('Enter No. Cases,Sum: ').split()] A=sorted([int(x) for x in input('Enter Numbers(A): ').split()][:P[0]]) B=sorted([int(x) for x in input('Enter Numbers(B): ').split()][:P[0]]) for i in range(P[0]): if A[i]+B[-(i+1)]>P[1]: R.append('No') break elif i==P[0]-1: R.append('Yes') T-=1 for T in R: print('Output:',T)
# Copyright 2012 Justas Sadzevicius # Licensed under the MIT license: http://www.opensource.org/licenses/MIT # Notes library for Finch buzzer #("Middle C" is C4 ) frequencies = { 'C0': 16.35, 'C#0': 17.32, 'Db0': 17.32, 'D0': 18.35, 'D#0': 19.45, 'Eb0': 19.45, 'E0': 20.6, 'F0': 21.83, 'F#0': 23.12, 'Gb0': 23.12, 'G0': 24.5, 'G#0': 25.96, 'Ab0': 25.96, 'A0': 27.5, 'A#0': 29.14, 'Bb0': 29.14, 'B0': 30.87, 'C1': 32.7, 'C#1': 34.65, 'Db1': 34.65, 'D1': 36.71, 'D#1': 38.89, 'Eb1': 38.89, 'E1': 41.2, 'F1': 43.65, 'F#1': 46.25, 'Gb1': 46.25, 'G1': 49.0, 'G#1': 51.91, 'Ab1': 51.91, 'A1': 55.0, 'A#1': 58.27, 'Bb1': 58.27, 'B1': 61.74, 'C2': 65.41, 'C#2': 69.3, 'Db2': 69.3, 'D2': 73.42, 'D#2': 77.78, 'Eb2': 77.78, 'E2': 82.41, 'F2': 87.31, 'F#2': 92.5, 'Gb2': 92.5, 'G2': 98.0, 'G#2': 103.83, 'Ab2': 103.83, 'A2': 110.0, 'A#2': 116.54, 'Bb2': 116.54, 'B2': 123.47, 'C3': 130.81, 'C#3': 138.59, 'Db3': 138.59, 'D3': 146.83, 'D#3': 155.56, 'Eb3': 155.56, 'E3': 164.81, 'F3': 174.61, 'F#3': 185.0, 'Gb3': 185.0, 'G3': 196.0, 'G#3': 207.65, 'Ab3': 207.65, 'A3': 220.0, 'A#3': 233.08, 'Bb3': 233.08, 'B3': 246.94, 'C4': 261.63, 'C#4': 277.18, 'Db4': 277.18, 'D4': 293.66, 'D#4': 311.13, 'Eb4': 311.13, 'E4': 329.63, 'F4': 349.23, 'F#4': 369.99, 'Gb4': 369.99, 'G4': 392.0, 'G#4': 415.3, 'Ab4': 415.3, 'A4': 440.0, 'A#4': 466.16, 'Bb4': 466.16, 'B4': 493.88, 'C5': 523.25, 'C#5': 554.37, 'Db5': 554.37, 'D5': 587.33, 'D#5': 622.25, 'Eb5': 622.25, 'E5': 659.26, 'F5': 698.46, 'F#5': 739.99, 'Gb5': 739.99, 'G5': 783.99, 'G#5': 830.61, 'Ab5': 830.61, 'A5': 880.0, 'A#5': 932.33, 'Bb5': 932.33, 'B5': 987.77, 'C6': 1046.5, 'C#6': 1108.73, 'Db6': 1108.73, 'D6': 1174.66, 'D#6': 1244.51, 'Eb6': 1244.51, 'E6': 1318.51, 'F6': 1396.91, 'F#6': 1479.98, 'Gb6': 1479.98, 'G6': 1567.98, 'G#6': 1661.22, 'Ab6': 1661.22, 'A6': 1760.0, 'A#6': 1864.66, 'Bb6': 1864.66, 'B6': 1975.53, 'C7': 2093.0, 'C#7': 2217.46, 'Db7': 2217.46, 'D7': 2349.32, 'D#7': 2489.02, 'Eb7': 2489.02, 'E7': 2637.02, 'F7': 2793.83, 'F#7': 2959.96, 'Gb7': 2959.96, 'G7': 3135.96, 'G#7': 3322.44, 'Ab7': 3322.44, 'A7': 3520.0, 'A#7': 3729.31, 'Bb7': 3729.31, 'B7': 3951.07, 'C8': 4186.01, 'C#8': 4434.92, 'Db8': 4434.92, 'D8': 4698.64, 'D#8': 4978.03, 'Eb8': 4978.03, } class Command(object): octave = 4 note = '' duration = 0 sym = '' def reset(self): self.note = '' self.duration = 0 self.sym = '' def emit(self): if not self.note or not self.duration: return None if self.note == '-': return (0, self.duration) ref = self.note.upper()+self.sym+str(self.octave) frequency = frequencies.get(ref) if not frequency: return None return (frequency, self.duration) def parse(sheet, speed=0.25): """Parse a sheet of notes to a sequence of (duration, frequency) commands. speed is a duration of a "tick" in seconds. Each *symbol* in the sheet takes up one tick. Valid notes are C, D, E, F, G, A, B and - (which means silence). Sheet can also contain semitones: C#, Eb, etc. You can change active octave with numbers 0-8. Here are some examples: To play Do for four ticks and then Re for eight ticks, pass: 'C D ' To play Do for two ticks, then silence for two ticks, then Do again: 'C - C ' To play Do Re Mi, but octave higher: 'C5D E ' parse('C3E G E ', speed=0.25) will play C major chord over 2 seconds parse('C3 Eb G Eb ', speed=0.125) will play C minor chord over 2 seconds also """ sheet = list(sheet) commands = [] next = Command() while sheet: #pop off a token token = sheet.pop(0) #if next note is reached, append the current note onto the commands if (token in 'CDEFGAB-' and next.note): entry = next.emit() if entry: commands.append(entry) next.reset() #set the next note equal to the token next.note = token #special case for the first note if (token in 'CDEFGAB-' and not next.note): next.note = token #handle octaves elif token.isdigit(): next.octave = int(token) next.duration -= speed #handle flats and sharps elif ((token == '#' or token == 'b') and next.note): next.sym = token next.duration -= speed #rhythm next.duration += speed #append the last note into the commands entry = next.emit() if entry: commands.append(entry) next.reset() return commands def sing(finch, sheet, speed=0.05): """Sing a melody. sheet - a string of notes. For the format see parse method in notes.py speed - speed of a single tick in seconds. Example: sing('C D E F G A B C5', speed=0.1) """ music = parse(sheet, speed=speed) for freq, duration in music: if duration: finch.buzzer_with_delay(duration, int(freq))
class Solution: def findMaximumXOR(self, nums: List[int]) -> int: L = len(bin(max(nums))) - 2 nums = [[(num >> i) & 1 for i in range(L)][::-1] for num in nums] maxXor, trie = 0, {} for num in nums: currentNode, xorNode, currentXor = trie, trie, 0 for bit in num: currentNode = currentNode.setdefault(bit, {}) toggledBit = 1 - bit if toggledBit in xorNode: currentXor = (currentXor << 1) | 1 xorNode = xorNode[toggledBit] else: currentXor = currentXor << 1 xorNode = xorNode[bit] maxXor = max(maxXor, currentXor) return maxXor
""" Implementing DefaultErrorHandler. Object default_error_handler is used as global object to register a callbacks for exceptions in asynchronous operators, """ def _default_error_callback(exc_type, exc_value, exc_traceback): """ Default error callback is printing traceback of the exception """ raise exc_value.with_traceback(exc_traceback) class DefaultErrorHandler: """ DefaultErrorHandler object is a callable which is calling a registered callback and is used for handling exceptions when asynchronous operators receiving an exception during .emit(). The callback can be registered via the .set(callback) method. The default callback is _default_error_callback which is dumping the traceback of the exception. """ def __init__(self): self._error_callback = _default_error_callback def __call__(self, exc_type, exc_value, exc_traceback): """ When calling the call will be forwarded to the registered callback """ self._error_callback(exc_type, exc_value, exc_traceback) def set(self, error_callback): """ Register a new callback :param error_callback: the callback to be registered """ self._error_callback = error_callback def reset(self): """ Reset to the default callback (dumping traceback) """ self._error_callback = _default_error_callback default_error_handler = DefaultErrorHandler() # pylint: disable=invalid-name
''' 2969 6299 9629 ''' def prime(n): if n <= 2: return n == 2 elif n % 2 == 0: return False else: #vsa liha ostanejo d = 3 while d ** 2 <= n: if n % d == 0: return False d += 2 return True for x in range(1000, 10000-2*3330): if sorted(list(str(x))) == sorted(list(str(x + 3330))) == sorted(list(str(x + 2*3330))): if prime(x): if prime(x + 3330): if prime(x + 2*3330): print(f'{x}{x+3330}{x+2*3330}') ''' 148748178147 296962999629 '''
"""AyudaEnPython: https://www.facebook.com/groups/ayudapython 1. Escribe un programa que solicité al usuario ingresar cuatro números para luego mostrar el promedio de los tres. 2. Tres personas deciden invertir su dinero para fundar una empresa. Cada una de ellas invierte una cantidad distinta. Obtener el porcentaje que cada uno invierte con respecto a la cantidad total invertida. 3. Calcular el sueldo de un empleado, ingrese los siguientes datos: nombre, horas de trabajo y el salario por hora. Luego incrementar el sueldo en 15%. 4. Ingresar 2 números y luego escoger la operación que se quiere hacer con ellos (suma, resta, multiplicación, división) y reportar el resultado. 5. Diseñe un algoritmo que lea tres números y determine el número mayor. 6. Diseñe un algoritmo que determine si un número es par o impar. 7. Elabore un algoritmo que permita calcular el área de un triángulo. area = (base * altura) / 2 8. Diseñe un algoritmo que verifique si la cantidad de digitos ingresados de un DNI es correcta o no (el DNI tiene 8 dígitos). 9. Una tienda de música ha puesto a la venta DVD de diversos géneros con los precios que se describe en la siguiente tabla: +------------+-----------------+ | Marca | Precio Unitario | +------------+-----------------+ | 1 Salsa | S/. 56.00 | | 2 Rock | S/. 63.00 | | 3 Pop | S/. 87.00 | | 4 Folclore | S/. 120.50 | +------------+-----------------+ Como oferta la tienda ofrece un porcentaje de descuento sobre al importe de la compra en base a la cantidad de discos adquiridos de acuerdo con la siguiente tabla: NOTE: Ejercicio 9 esta incompleto, falta la tabla de descuentos. """ # ---------------------------------------------------------------- Ejercicio 1 x = int(input("Ingrese un número: ")) y = int(input("Ingrese un número: ")) z = int(input("Ingrese un número: ")) print(f"El promedio de los tres números es: {(x + y + z) / 3}") # ---------------------------------------------------------------- Ejercicio 2 x = int(input("Ingresar inversión: ")) y = int(input("Ingresar inversión: ")) z = int(input("Ingresar inversión: ")) print(f"Porcentaje invertido del primero: {x / (x + y + z) * 100}") print(f"Porcentaje invertido del segundo: {y / (x + y + z) * 100}") print(f"Porcentaje invertido del tercero: {z / (x + y + z) * 100}") # ---------------------------------------------------------------- Ejercicio 3 nombre = input("Ingrese su nombre: ") horas = int(input("Ingrese las horas trabajadas: ")) salario = int(input("Ingrese el salario por hora: ")) print(f"{nombre} gana {(salario * horas)}") print(f"Sueldo incrementado: {salario * horas * 1.15}") # ---------------------------------------------------------------- Ejercicio 4 x = int(input("Ingrese un número: ")) y = int(input("Ingrese un número: ")) operacion = input("Ingrese la operación que desea realizar: ") if operacion == "+": print(f"{x} + {y} = {x + y}") elif operacion == "-": print(f"{x} - {y} = {x - y}") elif operacion == "*": print(f"{x} * {y} = {x * y}") elif operacion == "/": if y == 0: print("No se puede dividir por 0") else: print(f"{x} / {y} = {x / y}") else: print("Operación inválida") # ---------------------------------------------------------------- Ejercicio 5 mayor = 0 x = int(input("Ingrese un número: ")) y = int(input("Ingrese un número: ")) z = int(input("Ingrese un número: ")) if x > mayor: mayor = x if y > mayor: mayor = y if z > mayor: mayor = z print(f"El número mayor es: {mayor}") # ---------------------------------------------------------------- Ejercicio 6 numero = int(input("Ingrese un número: ")) print("El número es par" if numero % 2 == 0 else "El número es impar") # ---------------------------------------------------------------- Ejercicio 7 base = int(input("Ingrese la base del triángulo: ")) altura = int(input("Ingrese la altura del triángulo: ")) print(f"El área del triángulo es: {(base * altura) / 2}") # ---------------------------------------------------------------- Ejercicio 8 dni = input("Ingrese su DNI: ") print("DNI correcto" if len(dni) == 8 else "DNI incorrecto")
class Rectangle: pass rect1 = Rectangle() rect2 = Rectangle() rect1.height = 30 rect1.width = 10 rect2.height = 5 rect2.width = 10 rect1.area = rect1.height * rect1.width rect2.area = rect2.height * rect2.width print(rect2.area)