blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
86973ee3bc1be500ebbf678c64b1d1f07333daef
drop-table-lol/Fartcraft
/Animations/Animation.py
1,149
3.5
4
"""animation.py contains different animations with timelines we wish to play, similar to sprites, though, we're using sprites as still images rather than sprite sheets, hence this file.""" import pygame from Displays import Display import Sprites class Animation: def __init__(self, x,y, type, gridObj): self.x = x self.y = y self.counter = 0 self.type = type self.isActive = True gridObj.receiveAnim(self) self.rect = pygame.Rect(self.x, self.y, Display.TILE_SIZE, Display.TILE_SIZE) if self.type is "slash": self.sprite = Sprites.spr_slash elif self.type is "arrows": self.sprite = Sprites.spr_arrows elif self.type is "corpse": self.sprite = Sprites.spr_corpse elif self.type is "rubble": self.sprite = Sprites.spr_rubble else: self.sprite = Sprites.spr_corpse def draw(self): self.counter += 1 if self.counter < 30: self.updateRect() Display.CANVAS.blit(self.sprite, self.rect) elif self.counter > 30: self.isActive = False def updateRect(self): self.rect = pygame.Rect(self.x*Display.TILE_SIZE, self.y*Display.TILE_SIZE, Display.TILE_SIZE, Display.TILE_SIZE)
8b639fa0be4883c266bb27c4bc64d903bfbcfc91
mtinet/microbit
/before/charger(green).py
1,014
3.5625
4
# 차저 # flash: green 점점 밝게, stop: red 점점밝게 import radio from random import randint from microbit import * import neopixel # Create the "flash" animation frames. Can you work out how it's done? flash = [Image().invert()*(i/9) for i in range(9, -1, -1)] # The radio won't work unless it's switched on. radio.on() np = neopixel.NeoPixel(pin0, 16) # Event loop. while True: # Read any incoming messages. incoming = radio.receive() if incoming == 'flash': red = 0 green = 0 blue = 0 #점점 밝게 for num in range(0, 255): for pixel_id in range(0, len(np)): np[pixel_id] = (0, num, 0) np.show() if incoming == 'stop': red = 0 green = 0 blue = 0 #점점 밝게 for num in range(0, 200): for pixel_id in range(0, len(np)): np[pixel_id] = (0, 199-num, 0) np.show()
416f02c2863f52b48b7f7afcbb99cd29bd491ba1
jain1dit/entity-extraction
/Atoms/Atom_from_number_to_number.py
23,767
4.21875
4
""" EXTRACT A PREDEFINED PATTERN FROM TEXT Returnes a list of unique values that follows the passed regex pattern and found in the text. In case where no etitites were extracted, an empty list is returned. Parameters: 1. entity_name -> name of the entity to be parsed. 2. definite_extraction_regex -> regular expression pattern to be searched in the text, for full numbers to numbers 3. exclusion_offset -> number of characters to be ignored after an appereance of an exclusion_list item. 4. exclusion_list -> textual items that precedes characters that should be ignored while searching. 5. inclusion_offset -> number of characters to be included after an appereance of an inclusion_list item. 6. exclusion_list -> textual items that precedes characters that should be searched for. 7. indicator -> True if only a True/False indication of an entity existence in the doc should be returned, False if the actual entity is to be returned. 8. integer_indicator -> True if only integer number to be extracted. 9. unique_indicator -> if True and more than 1 entity found returns an empty list. 10. length_limit -> maximum number of characters in each entity 11. default_value -> default value - PYTHON COMMAND - when no entities are found or more than 1 is found where unique_indicator is set to true 12. remove_char -> ONE charcter to be removed from the extracted entity 13. upper_case -> True if all charters should be in upper case 14. replace_char -> list with 2 entries - char to be replaced and a replaceable char """ import re import string class FromNumberToNumber: def __init__(self, #entity_name_1 = 'From_Number', #entity_name_2 = 'To_Number', entity_name = 'From_Number_To_Number', extraction_regex = "((?<=\D)|(?<=\b)|(?<=^))0\d{3}-\d{7}(?=\D)\s*\n*to\s*\n*0\d{3}-\d{7}(?=\D|$)|(((?<=\D)|(?<=\b)|(?<=^))0?\d{2,}\s*\n*\d*\s*\n*\d*(?=\D)\s*\n*to\s*\n*0?\d{2,}\s*\n*\d*\s*\n*\d*(?=(\D|$)))|(((?<=\D)|(?<=\b)|(?<=^))0?\d{2,}\s*\n*\d*\s*\n*\d*(?=\D)\s*\n*-\s*\n*0?\d{2,}\s*\n*\d*\s*\n*\d*(?=(\D|$)))|(((?<=\D)|(?<=\b)|(?<=^))0?\d{2}\s*\n*\d{4}\s*\n*\d{4}(?=(\D|$)))", definite_to_extraction_regex = "((?<=\D)|(?<=\b)|(?<=^))0?\d{2}\s*\n*\d{4}\s*\n*\d{4}(?=\D)\s*\n*(to|-)\s*\n*0?\d{2}\s*\n*\d{4}\s*\n*\d{4}(?=(\D|$))|((?<=\D)|(?<=\b)|(?<=^))0\d{3}(?:-)\d{7}(?=\D)\s*\n*to\s*\n*0\d{3}(?:-)\d{7}(?=\D|$)", partial_extraction_regex = "", just_one_extraction_regex = "((?<=\D)|(?<=^))\d{10,11}(?=\D|$)|((?<=\D)|(?<=^))0\d{3}-\d{7}(?=\D|$)", first_extraction_regex = "", second_extraction_regex = "", exclusion_offset=40, exclusion_list = [], inclusion_offset = 40, inclusion_list = [], indicator = False, integer_indicator = False, unique_indicator = False, length_limit = 1000, default_value = [], remove_char = "", upper_case = False, replace_char = ["",""] ): #self.entity_name_1 = entity_name_1 #self.entity_name_2 = entity_name_2 self.entity_name = entity_name #print("extraction_regex = ",extraction_regex) self.extraction_regex = extraction_regex self.search_pattern = re.compile(self.extraction_regex, re.MULTILINE|re.IGNORECASE) #print("search_pattern = ",self.search_pattern) self.definite_to_extraction_regex = definite_to_extraction_regex self.definite_to_search_pattern = re.compile(self.definite_to_extraction_regex, re.MULTILINE|re.IGNORECASE) self.partial_extraction_regex = partial_extraction_regex self.partial_search_pattern = re.compile(self.partial_extraction_regex, re.MULTILINE|re.IGNORECASE) self.just_one_extraction_regex = just_one_extraction_regex self.just_one_search_pattern = re.compile(self.just_one_extraction_regex, re.MULTILINE|re.IGNORECASE) self.exclusion_offset=exclusion_offset self.exclusion_list=exclusion_list self.inclusion_offset=inclusion_offset self.inclusion_list=inclusion_list self.indicator=indicator self.integer_indicator=integer_indicator self.unique_indicator=unique_indicator self.length_limit=length_limit self.remove_char = remove_char self.upper_case = upper_case self.replace_char = replace_char self.exclusion_pats = [] for exc in self.exclusion_list: self.exclusion_pats.append(re.compile(exc, re.IGNORECASE)) self.inclusion_pats = [] for exc in self.inclusion_list: self.inclusion_pats.append(re.compile(exc, re.IGNORECASE)) self.default_value = default_value ''' try: if self.integer_indicator: self.default_value = [int(eval(default_value))] else: self.default_value = [eval(default_value)] except: self.default_value = [] ''' def create_dict_from_two_lists(self,From_Number_List,To_Number_List,length_list): ''' Input: two lists: From_Number,To_Number,length of the lists Returns: one list of [From_Number_List1-To_Number_List1, From_Number_List2-To_Number_List2, From_Number_List3-To_Number_List3,...] ''' List_to_Return = [] #print("From_Number_List = ",From_Number_List) #print("To_Number_List = ",To_Number_List) #print("length_list = ",length_list) #print("len(From_Number_List) = ",len(From_Number_List)) #print("len(To_Number_List) = ",len(To_Number_List)) if not len(From_Number_List)==len(To_Number_List): dict = {self.entity_name:List_to_Return} return dict for index,number in enumerate(From_Number_List): #print("From_Number_List[index]=",From_Number_List[index]) #print("(To_Number_List[index]).strip()=",type((To_Number_List[index]).strip())) #print("int(To_Number_List[index]).strip()=",int((To_Number_List[index]).strip())) #List_to_Return[index] = str((From_Number_List[index]).strip()+" - "+(To_Number_List[index]).strip()) from_num_add = str(int((From_Number_List[index]).strip())).zfill(length_list[index]) to_num_add = str(int((To_Number_List[index]).strip())).zfill(length_list[index]) List_to_Return.append(str(from_num_add+" - "+to_num_add)) #print("List_to_Return = ",List_to_Return) return List_to_Return def is_in_list(self,number_to_check,From_numbers,To_numbers): ''' Input: number_to_check - string containing a number, list of From_numbers and list of To_numbers Returns: True if the number is already in one of the lists, False if it isn't ''' #print("number_to_check = ",number_to_check,type(number_to_check)) #print("From_numbers = ",From_numbers) #print("To_numbers = ",To_numbers) if int(number_to_check) in [int(i) for i in From_numbers]: #print("num in from_list",number_to_check) return True if int(number_to_check) in [int(i) for i in To_numbers]: #print("num in to_list",number_to_check) return True #print("num not in lists") return False def get_matches(self, doc): ''' Input: doc - string containing description text Returns: list of strings, each one is a valid phone number ''' doc = doc["text"] res = [] From_Number = [] To_Number = [] default_value = [] length_list = [] found_in_res = False regex_first_extraction = "((?<=\D)|(?<=\b)|(?<=^))0?\d{9,10}(?=\D)\s*\n*(?=(to|-))|((?<=\D)|(?<=\b)|(?<=^))0\d{3}-\d{7}(?=\D)\s*\n*(?=to)" pattern_first_extraction = re.compile(regex_first_extraction, re.MULTILINE|re.IGNORECASE) regex_second_extraction = "((?<=to)|(?<=-))\s*\n*0?\d{9,10}(?=(\D|$))|(?<=to)\s*\n*0\d{3}-\d{7}(?=(\D|$))" pattern_second_extraction = re.compile(regex_second_extraction, re.MULTILINE|re.IGNORECASE) partial_to_search_regex = "(((?<=\D)|(?<=\b)|(?<=^))0?\d{2,8}\s*\n*to\s*\n*0?\d{9,10}(?=(\D|$|\n)))|(((?<=\D)|(?<=\b)|(?<=^))0?\d{2,8}\s*\n*-\s*\n*0?\d{9,10}(?=(\D|$|\n)))|(((?<=\D)|(?<=\b)|(?<=^))0?\d{9,10}\s*\n*to\s*\n*0?\d{2,8}(?=(\D|$|\n)))|(((?<=\D)|(?<=\b)|(?<=^))0?\d{9,10}\s*\n*-\s*\n*0?\d{2,8}(?=(\D|$|\n)))" pattern_partial_to_search = re.compile(partial_to_search_regex, re.MULTILINE|re.IGNORECASE) partial_first_in_partial_regex = "((?<=\D)|(?<=\b)|(?<=^))0?\d{2,10}\s*\n*(?=to)|((?<=\D)|(?<=\b)|(?<=^))0?\d{2,10}\s*\n*(?=-)" pattern_first_in_partial_extraction = re.compile(partial_first_in_partial_regex, re.MULTILINE|re.IGNORECASE) partial_second_in_partial_regex = "(?<=to)\s*\n*0?\d{2,10}(?=(\D|$|\n))|(?<=-)\s*\n*0?\d{2,10}(?=(\D|$|\n))" pattern_second_in_partial_extraction = re.compile(partial_second_in_partial_regex, re.MULTILINE|re.IGNORECASE) ''' try: if self.integer_indicator: default_value = [int(eval(self.default_value))] else: default_value = [eval(self.default_value)] except: default_value = [] ''' for p in self.search_pattern.finditer(doc): #print("p = ",p) found_exc = False found_inc = False start_pos, end_pos = p.span() this_expr = False #Seacrh through all exclusion list items and tag True if found in at least one of them for exc_pat in self.exclusion_pats: if exc_pat.search(doc[max(start_pos-self.exclusion_offset,0):start_pos]): found_exc = True #Seacrh through all inclusion list items and tag True if found in at least one of them if not self.inclusion_list: found_inc = True else: for inc_pat in self.inclusion_pats: if inc_pat.search(doc[max(start_pos-self.inclusion_offset,0):start_pos]): found_inc = True #print("found_inc = ",found_inc) #If not found in any of the exclusion list items and found in the inclusion list items than append to extraction list if (not found_exc) and found_inc: res.append(re.sub(self.replace_char[0],self.replace_char[1],re.sub(self.remove_char,"",p.group()))) #print("res = ",res) for p0 in self.definite_to_search_pattern.finditer(p.group()): #print("p0.group = ",p0.group()) first_num = re.search(pattern_first_extraction, p0.group()).group().replace("-","") second_num = re.search(pattern_second_extraction, p0.group()).group().replace("-","") #print("first_num,second_num = ",first_num,",",second_num) first_as_str = str(int(first_num)) len_first = (len(first_num.strip())) len_sec = (len(second_num.strip())) #print("len_first,len_sec = ",len_first,",",len_sec) #Equal lengths of from and to, this is a definite expression of 10 or 11 digits if (len_first == len_sec) and (len_first==10) or (len_first==11): #print("equal") if not self.is_in_list(str(first_num.strip().zfill(len_first)),From_Number,To_Number): From_Number.append(str(first_num.strip().zfill(len_first))) #print("From_Number after adding = ",From_Number) length_list.append(len_first) found_in_res = True this_expr = True if not self.is_in_list(str(second_num.strip().zfill(len_sec)),From_Number,To_Number): To_Number.append(str(second_num.strip().zfill(len_sec))) #print("To_Number after adding = ",To_Number) #elif - this is a partial expression (pp - p partial) if not this_expr: #print("partial expression") for pp in pattern_partial_to_search.finditer(p.group()): #print("Partial Pattern") first_in_partial = re.search(pattern_first_in_partial_extraction, pp.group()).group().replace("-","") second_in_partial = re.search(pattern_second_in_partial_extraction, pp.group()).group().replace("-","") len_first = (len(first_in_partial.strip())) len_sec = (len(second_in_partial.strip())) #print("len_first,len_sec = ",len_first,",",len_sec) first_as_str = str(int(first_in_partial)).zfill(len_first) second_as_str = str(int(second_in_partial)).zfill(len_sec) #first num > 9 meaning that the first one is the full one if (not found_in_res) and ((len_first==10) or (len_first==11)): #print("the first one is the full one") sec_partial_as_str = str(int(second_in_partial)) sec_full_as_str = "" #print("sec_full_as_str = ",sec_full_as_str) for i in range(0,len_first-1): if (i<len_first-len_sec): sec_full_as_str = sec_full_as_str + first_as_str[i] #print("first_as_str[i],i, sec_full_as_str",first_as_str[i],",",i,",",sec_full_as_str) sec_full_as_str = sec_full_as_str + sec_partial_as_str found_in_res = True #print("sec_full_as_str",sec_full_as_str) second_as_str = sec_full_as_str #first num < 10 meaning that the second is the full one else: #print("the second one is the full one") first_partial_as_str = str(int(first_in_partial)) first_full_as_str = "" for i in range(0,len_sec-1): #print("i = ",i) if (i<len_sec-len_first): first_full_as_str = first_full_as_str + second_as_str[i] first_full_as_str = first_full_as_str + first_partial_as_str found_in_res = True #print("first_full_as_str",first_full_as_str) first_as_str = first_full_as_str #for partial sets, after filled, add to the From-To lists #print("first_as_str, sec_full_as_str",first_as_str.strip().zfill(len_first),",",second_as_str.strip().zfill(len_sec)) #print("From_Number = ",From_Number) #print("To_Number = ",To_Number) if not self.is_in_list(first_as_str.strip().zfill(len_first),From_Number,To_Number): From_Number.append(str(first_as_str.strip().zfill(len_first))) #print("From_Number after adding 2= ",From_Number) length_list.append(max(len_first,len_sec)) found_in_res = True if not self.is_in_list(second_as_str.strip().zfill(len_sec),From_Number,To_Number): To_Number.append(str(second_as_str.strip().zfill(len_sec))) #print("To_Number after adding 2= ",To_Number) #print("p1.group = ",p1.group()) #print("length_list = ",length_list) #to_num_add = (re.search(pattern_to_in_to, p1.group()).group()).replace('-','') #print("To_Number = ",To_Number) #start_pos_p1, end_pos_p1 = p1.span() #text_after_definite = p1.group() #text_after_definite = text_after_definite[0:start_pos_p1]+text_after_definite[end_pos_p1:] #print("text_after_definite = ",text_after_definite[end_pos_p1:]) #print("From_Number 3 = ",From_Number) #print("To_Number 3 = ",To_Number) #print("found_in_res = ",found_in_res) if (not found_in_res) or (not From_Number): #print("here") for p1 in self.just_one_search_pattern.finditer(p.group()): #print("p1 = ",p1) num = p1.group().strip().replace('-','') #print("p2.group = ",type(p2.group())) if self.is_in_list(str(int(num)),From_Number,To_Number): #print("is in list already:",p2.group()) continue length_list.append(len(num)) From_Number.append(str(num)) To_Number.append(str(num)) #print("To_Number = ",To_Number) ''' if self.integer_indicator: int_value = int(re.sub("[^0-9]", "",p.group())) if len(str(int_value))<=self.length_limit: res.append(int_value) else: #res.append(p.group().replace(self.remove_char,"")) if self.upper_case: res.append(re.sub(self.replace_char[0],self.replace_char[1],re.sub(self.remove_char,"",p.group().upper()))) else: res.append(re.sub(self.replace_char[0],self.replace_char[1],re.sub(self.remove_char,"",p.group()))) ''' #Filter to only unique entities in the extraction list #print("res = ",res) #res_uniq = list(set(res)) #print("res_uniq = ",res_uniq) #print("From_Number_final = ",From_Number) #print("To_Number_final = ",To_Number) #Return Default value (empty list) if no number or more than one range when we need only one if (len(From_Number)<1) or (self.unique_indicator and len(From_Number)>1): dict = {self.entity_name:default_value} #print("dict0") return dict #only one number in the ticket if (len(From_Number)==1): #print("From_Number1 = ",From_Number) #print("To_Number1 = ",To_Number) dict = {self.entity_name:self.create_dict_from_two_lists(From_Number,To_Number,length_list)} #print("dict1") return dict #True if only a True/False indication of an entity existence in the doc should be returned, False if the actual entity is to be returned if self.indicator: dict = {self.entity_name:len(From_Number)>0} #print("dict2") return dict dict = {self.entity_name:self.create_dict_from_two_lists(From_Number,To_Number,length_list)} #From_Number = {self.entity_name_1:from_num} #To_Number = {self.entity_name_2:to_num} #print("dict3") return dict #Script Tester def main(argv): line = argv[0] extractor = FromNumberToNumber( #entity_name_1 = 'From_Number', #entity_name_2 = 'To_Number', entity_name = 'From_Number_To_Number', #inclusion_list=["soc_cd","SOC_CD"], #,indicator = True #integer_indicator = True, #length_limit = 2, #unique_indicator = True, #default_value = "datetime.datetime.now().strftime('%d')" #remove_char = " ", #upper_case = True, #replace_char = [":"," "] ) From_Number_To_Number = extractor.get_matches(line) print(From_Number_To_Number) if __name__== "__main__": #sample = "02042961000 to 02042961099" #sample = "Need to be release of PRI serise 05224261800 to 05224261849" #sample = "Hi Team Please release below PRI series in NMS 02249093500 to \n\n02249093699 (200 nos) 02240083500 to 02240083699 (200 nos) 02240483500 to \n\n02240483699 (200 nos)" #sample = "NMS : Nubmer release form Aging to available did range : 04045453550 \n\nto 04045453599\n\n04045453599" #- uneven number of numbers #sample = "04045453550 to 04045453599 MSU Change : 4045453540 to 4045453589" #sample = "04045111111 to \n\n\n 04045222222" #- #sample = "PRI series release urgent - 07940211000 to 07940211099" #sample = "the range is 01149292100-01149292199" #sample = "release nms 0124-4601776 to 0124-4601778" #sample = "01149292100-99" #(INC000002072777) the range is 01149292100-01149292199 #sample = "01244785860 to 4785899" # (INC000002072778):the range is 01244785860 to 01244785899 (same first 4 digits to be completed automatically) #sample = "Pls PRI series release 07292426200 to 249" #sample = "123 to 04444444444" #sample = "123 to 1444444445" #sample = "01244785860 to 4785899, 123 to 04444444444" #sample = "release nms 0124-4601777" #{'From_Number_To_Number': ['0124-4601777']} #sample = "Hardware/ Software related support please relese number from NMS\n\n8822222220\n\n8822222220" #sample = "please relese number from NMS 7042607800" # (INC000002129883): Send same number in both parameters #sample = "Number Is To Be Release In NMS 7880979768" # (INC000002073503) what should be extracted? [Anirudha – 7880979768 is to be extracted in both parameters] #sample = "Number IS To be Release IN NMS 7390090621" #sample = "Hi Team\nPls release the number in NMS \n7081006123\n9081006116\n\n8081006125\n6081006118" sample = "01204130808\n01204165050\n01294144600\n01204135589\n01204130808\n01204165050\n01294144600\n01204135589" #sample = "01204130808\n01204130808" #sample = "" #sample = "" doc = {"text":sample} main([doc])
6f9d936c0c46889fd07ca508aa030a41c918966d
K-Stumbaugh/GitProjects
/PythonAgain/rangeByTwos.py
233
3.96875
4
#range by 1 print('addition by 1') for i in range(12,16): print(i) #range by twos print('addition by 2') for i in range (0, 11, 2): print(i) #range subtraction print('subtraction') for i in range(5, -1, -1): print(i)
26f2d3651294e73420ff40ed603baf1ac2abb269
Rohitjoshiii/bank1
/read example.py
439
4.21875
4
# STEP1-OPEN THE FILE file=open("abc.txt","r") #STEP2-READ THE FILE #result=file.read(2) # read(2) means ir reads teo characters only #result=file.readline() #readline() it print one line only #result=file.readlines() #readlines() print all lines into list line=file.readlines() # for loop used when we dont want our text into list form for result in line: print(result) #STEP3-CLOSE THE FILE file.close()
c16ef9027338bdacfcd075303ee5a84be17c03f4
juannico007/laberinto-logica-proposicional
/maze.py
5,362
3.734375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import numpy as np import random #Crea un laberinto de dimensiones n * m conectado, con 2 casillas que nunca tendran un muro en ella. Recibe: #Dimensiones del tablero, f = filas, c = columnas como enteros, tamaño por defecto 7x7 #Caisllas de inicio y final como tuplas def create_maze(start, end, c = 7, f = 7): sets = [] board = np.zeros((f,c)) keep = [] for y in range(f): muros = [] n_muros = random.randint(c//3, c//2) #Coloco los muros en la fila respectiva j = 0 it = 0 while j < n_muros and it < 30: x = random.randint(0, c - 1) if (y, x) != start and (y, x) != end and board[y, x] != -1 and (y,x) not in keep: muros.append(x) board[y, x] = -1 j += 1 it += 1 muros.sort() #Junto las casillas adyacentes de la fila sin muro en un set set_c = [] for i in range(len(muros)): if i == 0: set_c.append({(y, x) for x in range(muros[i])}) if i == len(muros) - 1: set_c.append({(y, x) for x in range(muros[i] + 1, c)}) else: set_c.append({(y, x) for x in range(muros[i] + 1, muros[i + 1])}) set_c = [x for x in set_c if x] #Establezco las casillas que se extienden hacia abajo if y < f - 1: keep = [] for s in set_c: nxt = set() stuck = True while stuck: for cas in s: down = random.randint(1, len(s)) if down == 1: keep.append((y + 1, cas[1])) nxt.add((y + 1, cas[1])) stuck = False if(len(nxt) >= len(s) / 2): break s.update(nxt) #print(set_c) #Coloco los primeros conjuntos en el arreglo if y == 0: sets.append(set_c) #Junto las casillas adyacentes en un solo conjunto #Verticalmente if y > 0: #Junto lo que no este aun en el conjunto while len(set_c) > 0: s = set_c.pop(0) found = False for i in sets[0]: for (a,b) in s: if (a,b) in i or (a - 1, b) in i: found = True temp = s.union(i) sets[0].remove(i) sets[0].append(temp) break if not found: sets[0].append(s) #Reviso en el conjunto temp = sets[0][:] sets[0] = [] stack = [] notdisj = False while len(temp) > 0: if not notdisj: stack.append(temp.pop(0)) notdisj = False for i in temp: if not stack[0].isdisjoint(i): notdisj = True stack.append(i) for i in stack: if i in temp: temp.remove(i) if notdisj: temp2 = set() for i in stack: temp2 = temp2.union(i) stack = [temp2] if len(temp) == 0: notdisj = False sets[0].append(stack.pop()) else: sets[0].append(stack.pop()) if y == f - 1: ll = [] for s in sets[0]: for ca in s: if ca[0] == y: ll.append(ca[1]) ll.sort() mini = ll[0] maxi = ll[-1] set_c = set() for x in range(mini, maxi + 1): board[y, x] = 0 set_c.add((y, x)) sets[0].append(set_c) #Reviso en el conjunto temp = sets[0][:] sets[0] = [] stack = [] notdisj = False while len(temp) > 0: if not notdisj: stack.append(temp.pop(0)) notdisj = False for i in temp: if not stack[0].isdisjoint(i): notdisj = True stack.append(i) for i in stack: if i in temp: temp.remove(i) if notdisj: temp2 = set() for i in stack: temp2 = temp2.union(i) stack = [temp2] if len(temp) == 0: notdisj = False sets[0].append(stack.pop()) else: sets[0].append(stack.pop()) walls = [] for i in range(f): for j in range(c): if (i,j) not in sets[0][0]: walls.append((i, j)) return walls
7dd022b7ea2b91c640ff2e3a2d661faca179a22e
rscircus/advent_of_code_2019
/06.py
2,642
3.90625
4
from collections import defaultdict # The task today is # input: map of local orbits # things orbit each other except the CenterOfMass # if BBB orbits AAA it is written like `AAA)BBB` # to verify maps, orbit count checksums are used: the total no of direct orbits and indirect orbits # # direct orbits: an object O orbiting directly another one A # indirect orbits: an object O orbiting all the stuff A is orbiting # #lines = open('./6test.txt').read().splitlines() lines = open('./6.txt').read().splitlines() # create orbit pairs orbit_pairs = [s.split(')') for s in lines] # TODO: There is an efficient function for this: from operator import methodcaller. # # Debug: # print(orbit_pairs) def create_adjacency_list(orbit_pairs): """Returns a graph from orbit pairs based on the root COM.""" tree = defaultdict(list) for pair in orbit_pairs: tree[pair[0]].append(pair[1]) return tree data = create_adjacency_list(orbit_pairs) #print(data) def get_parent(tree, node): """returns the parent of a given node or False.""" for parent, children in tree.items(): if node in children: return parent return False def count_orbits(tree): """Counts direct and indirect orbits.""" direct = 0 indirect = 0 # get all direct orbits for _, children in tree.items(): direct += len(children) # get all indirect orbits for child in children: parent = get_parent(tree, _) while parent: indirect += 1 parent = get_parent(tree, parent) return direct + indirect # Debug # adj_list = create_adjacency_list(orbit_pairs) # print(count_orbits(adj_list)) def count_orbits_jumps(tree): """Count the number of orbit jumps needed to reach Santa.""" # get all direct orbits for _, children in tree.items(): # create my list of ancestors if 'YOU' in children: you_parents = [] parent = get_parent(tree, _) while parent: you_parents.append(parent) parent = get_parent(tree, parent) # create santas list of ancestors elif 'SAN' in children: san_parents = [] parent = get_parent(tree, _) while parent: san_parents.append(parent) parent = get_parent(tree, parent) # find lowest common ancestor for i, p in enumerate(you_parents): if p in san_parents: return i + san_parents.index(p) + 2 # add two extra orbits # part 1 print(count_orbits(data)) # part 2 print(count_orbits_jumps(data))
6673a47fee3138ba14d20bc97b6a3674328a7a70
IceIce1ce/Pacman-AI-Project-HCMUS
/setup_map.py
6,772
3.578125
4
from util import * from setting import * import pygame from copy import deepcopy class Map: # init for map def __init__(self, width, height): self.width = width # width of map self.height = height # height of map self.InitMap = initGame() loading_map = [] # create an empty list for loading map self.data = [[loading_map for y in range(height)] for x in range(width)] # coordinate x define for width of map, coordinate y define for height of map, store data height and width for each map self.visitedMap = [[0 for y in range(height)] for x in range(width)] # set all cell in map as not visited (0), if pacman visited, mark that cell as visited (1) self.screen = pygame.display.set_mode((WIDTH, HEIGHT)) # screen of pygame self.cell_width = MAZE_WIDTH // COLS self.cell_height = MAZE_HEIGHT // ROWS # update new location for agent (pacman, monster) in map after each step moving def update(self, current_location, new_location, characterMap): # current_location: current position of agents (pacman, monsters) # new_location: new position of agents (pacman, monsters) after moving # characterMap: 3: monster, 4: pacman x_pos, y_pos = current_location[0], current_location[1] # coordinate for agent's current location new_x_pos, new_y_pos = new_location[0], new_location[1] # coordinate for agent's new location try: self.data[y_pos][x_pos].remove(characterMap) # remove agent from current location # if initial state (current location) == None if len(self.data[y_pos][x_pos]) == 0: self.data[y_pos][x_pos] = deepcopy([]) # return empty position if initial state is empty except ValueError: pass # update agent new location newState = deepcopy(self.data[new_y_pos][new_x_pos]) # take coordinate of new position newState.append(characterMap) # add characterMap to new location after removing that characterMap from old location self.data[new_y_pos][new_x_pos] = deepcopy(newState) # update info of new location # helper function def __getitem__(self, item): return self.data[item] def __setitem__(self, key, value): self.data[key] = value def copy(self): g = Map(self.width, self.height) g.data = [x[:] for x in self.data] return g def shallowCopy(self): g = Map(self.width, self.height) g.data = self.data return g def deepCopy(self): return self.copy() def __eq__(self, other): # allows two states to be compared if other == None: return False return self.data == other.data def __ne__(self, other): return not self.__eq__(other) def __hash__(self): # allows states to be keys of dictionaries return hash(self.data) def __str__(self): return str(self.data) # helper function # draw map def start_draw(self): # draw background background = pygame.image.load("image/theme.gif") # load image self.screen.blit(background, (0, 0)) # draw in buffer for y in range(self.height): for x in range(self.width): # if character pacman in initmap = 4 same to mapData, draw pacman if self.InitMap.pacman in self.data[y][x]: # pygame.draw.circle(self.screen, PLAYER_COLOR, (int(x * self.cell_width) + self.cell_width // 2 + TOP_BOTTOM_BUFFER // 2, int(y * self.cell_height) + self.cell_height // 2 + TOP_BOTTOM_BUFFER // 2), int(self.cell_width // 5.5)) pacmanImg = pygame.image.load("image/pacman_right.gif") self.screen.blit(pacmanImg, (int(x * self.cell_width) + self.cell_width // 2.5 + TOP_BOTTOM_BUFFER // 2.5, int(y * self.cell_height) + self.cell_height // 3 + TOP_BOTTOM_BUFFER // 3)) # if character wall in initmap = 1 same to mapData, draw wall elif self.InitMap.wall in self.data[y][x]: # draw grid # pygame.draw.line(self.screen, (52, 82, 235), (x * self.cell_width + TOP_BOTTOM_BUFFER // 2, 0), (x * self.cell_width + TOP_BOTTOM_BUFFER // 2, HEIGHT)) # pygame.draw.line(self.screen, (52, 82, 235), (0, x * self.cell_height + TOP_BOTTOM_BUFFER // 2), (WIDTH, x * self.cell_height + TOP_BOTTOM_BUFFER // 2)) # draw wall pygame.draw.rect(self.screen, (52, 82, 235), (x * self.cell_width + TOP_BOTTOM_BUFFER // 2, y * self.cell_height + TOP_BOTTOM_BUFFER // 2, self.cell_width, self.cell_height)) # if character food in initmap = 2 same to mapData, draw food elif self.InitMap.food in self.data[y][x]: pygame.draw.circle(self.screen, WHITE, (int(x * self.cell_width) + self.cell_width // 2 + TOP_BOTTOM_BUFFER // 2, int(y * self.cell_height) + self.cell_height // 2 + TOP_BOTTOM_BUFFER // 2), 5) # if character monster in initmap = 3 same to mapData, draw monster elif self.InitMap.monster in self.data[y][x]: # pygame.draw.circle(self.screen, GREEN, (int(x * self.cell_width) + self.cell_width // 2 + TOP_BOTTOM_BUFFER // 2, int(y * self.cell_height) + self.cell_height // 2 + TOP_BOTTOM_BUFFER // 2), int(self.cell_width // 5.5)) monsterImg = pygame.image.load("image/monster.gif") self.screen.blit(monsterImg, (int(x * self.cell_width) + self.cell_width // 2.5 + TOP_BOTTOM_BUFFER // 2.5, int(y * self.cell_height) + self.cell_height // 3 + TOP_BOTTOM_BUFFER // 3)) pygame.display.update() # pygame.time.delay(200) # change this value for suitable speed of game # get resolution of map for pacman because we want pacman to learn and get full view map during scanning def getResolutionMap(self): return [self.width, self.height] # add fixed index of foods into map def getFood(self, foods): for idx in foods: self.update(idx, idx, self.InitMap.food) # add fixed index of walls into map def getWall(self, walls): for idx in walls: self.update(idx, idx, self.InitMap.wall) # add agents(pacman, monsters) into map def getAgent(self, agents): for agent in agents: self.update(agent.location, agent.location, agent.myInitMap) # self.myInitMap.pacman or self.myInitMap.monster # remove food at index which pacman ate from map def destroyFood(self, food_index): x_food, y_food = food_index[0], food_index[1] # get fixed index of food try: self.data[y_food][x_food].remove(self.InitMap.food) # remove from map after pacman eating except ValueError: pass
cefd70520471331df28cce805b8041f465f8d24a
Pasha-Ignatyuk/python_tasks
/task_5_7.py
912
4.15625
4
"""Дана целочисленная квадратная матрица. Найти в каждой строке наибольший элемент и поменять его местами с элементом главной диагонали.[02-4.2-ML22]""" import random n = 4 m = 4 matrix = [[random.randrange(0, 10) for y in range(m)] for x in range(n)] print(matrix) def print_matrix(matrix): for i in range(len(matrix)): for j in range(len(matrix[i])): print("{:4d}".format(matrix[i][j]), end="") print() print_matrix(matrix) print("") # для разделения матриц, чтобы не сливались в глазах for i in range(len(matrix)): for j in range(len(matrix[0])): max_elem = max(matrix[i]) if i != j: continue else: matrix[i][j] = matrix[i][j] * 0 + max_elem print_matrix(matrix)
1b3f5a6ae3442857926e1f0eeb7594566769929e
Pasha-Ignatyuk/python_tasks
/converter.py
3,744
4.09375
4
while True: enter = int(input('Введите 1 для выбора конвертера дюймов в сантиметры, 2 - для выбора конвертера сантиметров в дюймы,\n ' '3 - миль в километры, 4 - километров в мили, 5 - фунтов в килограммы, 6 - килограммов в фунты,\n ' '7 - унций в граммы, 8 - граммов в унции, 9 - галлонов в литры, 10 - литров в галлоны,\n ' '11 - пинт в литры, 12 - литров в пинты. Для выходв из программы введите 0')) if enter == 1: def inch(): enter = float(input("Введите дюймы для перевода в санитметры")) centimeter = enter * 2.54 print(centimeter) return centimeter inch() elif enter == 2: def cent(): enter = float(input("Введите сантиметры для перевода в дюймы")) inch = enter * 0.393701 print(inch) return inch cent() elif enter == 3: def mile(): enter = float(input("Введите мили для перевода в километры")) mile = enter * 1.60934 print(mile) return mile mile() elif enter == 4: def km(): enter = float(input("Введите километры для перевода в мили")) km = enter * 0.621371 print(km) return km km() elif enter == 5: def pound(): enter = float(input("Введите фунты для перевода в кг")) pound = enter * 0.453592 print(pound) return pound pound() elif enter == 6: def kg(): enter = float(input("Введите кг для перевода в фунты")) kg = enter * 2.20462 print(kg) return kg kg() elif enter == 7: def ounce(): enter = float(input("Введите унции для перевода в граммы")) ounce = enter * 28.3495 print(ounce) return ounce ounce() elif enter == 8: def gram(): enter = float(input("Введите граммы для перевода в унции")) gram = enter * 0.035274 print(gram) return gram gram() elif enter == 9: def gallon(): enter = float(input("Введите галлоны для перевода в литры")) gallon = enter * 4.54609 print(gallon) return gallon gallon() elif enter == 10: def liter(): enter = float(input("Введите литры для перевода в галлоны")) liter = enter * 0.264172 print(liter) return liter liter() elif enter == 11: def pint(): enter = float(input("Введите пинты для перевода в литры")) pint = enter * 0.473176 print(pint) return pint pint() elif enter == 12: def lit(): enter = float(input("Введите литры для перевода в пинты")) lit = enter * 2.11338 print(lit) return lit lit() elif enter == 0: break
b1fb588e178f59630573ba9af3629810832f5978
Pasha-Ignatyuk/python_tasks
/task_4_4.py
410
3.9375
4
lst = [1, 2, 3, 4, 5] lst_2_1 = [] # для цикла с while lst_2_2 = [] # для цикла с for first_item = lst.pop(0) length = len(lst) temporary = 0 while length > 0: item = lst[temporary] lst_2_1.append(item) temporary += 1 length -= 1 else: lst_2_1.append(first_item) print(lst_2_1) for i in lst: lst_2_2.append(i) else: lst_2_2.append(first_item) print(lst_2_2)
c20fb5d6dbd82dbbc090f8c85612dcce1da98f41
Pasha-Ignatyuk/python_tasks
/task_11_1.py
5,927
4
4
class Computer: def __init__(self, brand, type, price): self.__brand = brand self.__type = type self.__price = price def set_brand(self, brand): if len(brand) in range(1, 10): self.__brand = brand else: print('Брэнд не определен') def set_type(self, type): if len(type) in range(1, 15): self.__type = type else: print('Тип не определен') def set_price(self, price): if price in range(150, 5001): self.__price = price else: print('Цена не верна') def get_brand(self): return self.__brand def get_type(self): return self.__type def get_price(self): return self.__price def display_info(self): print("Брэнд:", self.__brand, "\tТип:", self.__type, '\tЦена:', self.__price) def capital(self): print(self.__brand.upper()) comp = Computer("Lenovo", "transformer", 1000) comp.set_price(6000) comp.display_info() comp.capital() class Car: def __init__(self, mark, model, year): self.__mark = mark self.__model = model self.__year = year @property def mark(self): return self.__mark @mark.setter def mark(self, mark): if len(mark) in range(1, 20): self.__mark = mark else: print('Марка неопределена') @property def model(self): return self.__model @model.setter def model(self, model): if len(model) in range(1, 20): self.__model = model else: print('Мoдель неопределена') @property def year(self): return self.__year @year.setter def year(self, year): if year in range(1900, 2021): self.__year = year else: print('Неверный год') def display_info(self): print("Марка:", self.__mark, "\tМодель:", self.__model, '\tГод выпуска:', self.__year) def capital(self): print(self.__mark.upper()) car = Car('bmw', '3', 2016) car.year = 2025 car.display_info() car.capital() class House: def __init__(self, flors, square, rooms): self.__flors = flors self.__square = square self.__rooms = rooms @property def flors(self): return self.__flors @flors.setter def flors(self, flors): if flors in range(1, 3): self.__flors = flors else: print('Дом многоквартирный') @property def square(self): return self.__square @square.setter def square(self, square): if square in range(1, 500): self.__square = square else: print('Вилла') @property def rooms(self): return self.__rooms @rooms.setter def rooms(self, rooms): if rooms / self.__flors > 1: self.__rooms = rooms else: print('Неверное число комнат') def display_info(self): print("Число этажей:", self.__flors, "\tПлощадь:", self.__square, '\tКоличество комнат:', self.__rooms) hs = House(1, 200, 5) hs.rooms = 0 hs.display_info() class Trafic: def __init__(self, mark, model, year): self.__mark = mark self.__model = model self.__year = year self.__speed = 0 def set_mark(self, mark): if len(mark) in range(1, 20): self.__mark = mark else: print('Марка неопределена') def set_model(self, model): if len(model) in range(1, 20): self.__model = model else: print('Мoдель неопределена') def set_year(self, year): if year in range(1900, 2021): self.__year = year else: print('Неверный год') def set_speed(self, speed): self.__speed += speed print(self.__speed) def get_mark(self): return self.__mark def get_model(self): return self.__model def get_year(self): return self.__year def get_speed(self): return self.__speed def display_speed(self): print("Текущая скорость:", self.__speed) def display_info(self): print("Марка:", self.__mark, "\tМодель:", self.__model, '\tГод выпуска:', self.__year) c = Trafic('bmw', '3', 2016) c.set_speed(5) c.set_speed(5) c.display_info() c.display_speed() class Univer: def __init__(self, stud, facult, rate): self.__stud = stud self.__facult = facult self.__rate = rate @property def stud(self): return self.__stud @stud.setter def stud(self, stud): if stud in range(1, 25000): self.__stud = stud else: print('Введите число студентов') @property def facult(self): return self.__facult @facult.setter def facult(self, facult): if facult in range(1, 100): self.__facult = facult else: print('Введите число факультетов') @property def rate(self): return self.__rate @rate.setter def rate(self, rate): if rate in range(1, 10): self.__rate = rate else: print('Установите рейтинг от 1 до 10') def display_info(self): print("Число студентов:", self.__stud, "\tЧисло факультетов:", self.__facult, '\tРейтинг:', self.__rate) def capital(self): print(self.__mark.upper()) univ = Univer(15000, 50, 10) univ.stud = 16000 univ.display_info()
f23c3ebe2bfdd14b6735cd455bfc136bae291bb0
Pasha-Ignatyuk/python_tasks
/task_13_01/func.py
669
3.875
4
class Func: def __init__(self, arg1, arg2, operator): self.arg1 = arg1 self.arg2 = arg2 self.operator = operator def process(self): if self.operator == '+': return self.add() elif self.operator == '-': return self.subtract() elif self.operator == '*': return self.mult() elif self.operator == '/': return self.divide() def add(self): return self.arg1 + self.arg2 def subtract(self): return self.arg1 - self.arg2 def mult(self): return self.arg1 * self.arg2 def divide(self): return self.arg1 / self.arg2
186a78291be415955402729980afcf4b0829cf8b
AK-1121/code_extraction
/python/python_21522.py
108
3.6875
4
# Count number of matches between two strings python &gt;&gt;&gt; sum(a==b for a, b in zip('bob', 'boa')) 2
664ee2fddd0a90da5d197063cb14d604f2a6f65b
AK-1121/code_extraction
/python/python_14803.py
92
3.65625
4
# Remove repeated item in list in python d = ['a', 'man', 'and', 'a', 'woman'] list(set(d))
e0587e98a14e5a3abb63dcc2627c513d6358dd1d
AK-1121/code_extraction
/python/python_84.py
166
4.15625
4
# How do I reverse a list using recursion in Python? mylist = [1, 2, 3, 4, 5] backwards = lambda l: (backwards (l[1:]) + l[:1] if l else []) print backwards (mylist)
3c9b4f1bec33cbfb0f33a7f4b04085c309e30401
AK-1121/code_extraction
/python/python_18589.py
204
3.5625
4
# combine list of lists in python (similar to string.join but as a list comprehension?) &gt;&gt;&gt; lis = [['A',1,2],['B',3,4]] &gt;&gt;&gt; [', '.join(map(str, x)) for x in lis ] ['A, 1, 2', 'B, 3, 4']
cd82d5d786108a30e1d00ad8276247f92c35d253
AK-1121/code_extraction
/python/python_16612.py
206
3.59375
4
# Create a word replacement dictionary from list of tuples &gt;&gt;&gt; word_dict = {'et': ['horse','dog'], 'ft': ['horses','dogs']} &gt;&gt;&gt; dict(word_dict.values()) {'horses': 'dogs', 'horse': 'dog'}
161eabeb2ea6587543ccbd302402462e7eaf0d66
AK-1121/code_extraction
/python/python_26845.py
155
3.734375
4
# Unit conversion using Python amount, unit = input('Enter amount with units: ').split()[:2] converted_data = int(amount) * {'in': 2.54, 'cm': 0.39}[unit]
985e9ff7f03b3c670b006d4ac8470239c57c38f0
AK-1121/code_extraction
/python/python_22004.py
97
3.921875
4
# Python regex matching 1 or 2 but not 3 of a character matches = (1 &lt;= s.count('-') &lt;= 2)
159cba82e824d397baf00cb6ee566c6ee0da656b
AK-1121/code_extraction
/python/python_17125.py
224
3.609375
4
# How to get the values in split python? &gt;&gt;&gt; l = ['column1:abc,def', 'column2:hij,klm', 'column3:xyz,pqr'] &gt;&gt;&gt; [item.split(":")[1].split(',') for item in l] [['abc', 'def'], ['hij', 'klm'], ['xyz', 'pqr']]
0def15b25817edc28742c3564faad7cc0c568730
AK-1121/code_extraction
/python/python_3728.py
147
3.71875
4
# Python's example for "iter" function gives me TypeError with open("mydata.txt") as fp: for line in iter(fp.readline, ''): print line
d5ad4b6867f72609ca64432551487a678c807b2c
AK-1121/code_extraction
/python/python_13685.py
151
3.875
4
# Returning index of list with greatest value def thing(list_): temp = enumerate(max(x) - min(x) for x in list_) return max(x[::-1] for x in temp)
d2fc09c1de840c70fa1b458934b55d987b4af08c
AK-1121/code_extraction
/python/python_14368.py
183
3.734375
4
# How to add clickable links to open a folder/file in output of a print statement? (Python desktop application) print('&lt;a href="http://www.example.com"&gt;example text&lt;/a&gt;')
d10c73852b5753ff7adbcf450d8f760d9c45fd62
AK-1121/code_extraction
/python/python_29140.py
293
3.8125
4
# How to get a value and its key from a dictionary &gt;&gt;&gt; d = {'0003': ['Mike', 'Restrepo', 'mtrepot', '87654321'], '0001': ['John', 'Jelenski', 'jelensohn', 'snf23jn4'], '0002': ['Clyde', 'Owen', 'clonew', 'dummy2015']} &gt;&gt;&gt; [k for k, v in d.items() if 'mtrepot' in v] ['0003']
f81d1b37817d00eba34b59a5e5efc9bef35dbb7e
AK-1121/code_extraction
/python/python_26620.py
126
3.609375
4
# Format a string with a space between every two digits s = "534349511" print ' '.join([s[i:i+2] for i in range(0,len(s),2)])
513d44b97f28b60667481bbd25bbc92f6439e2a7
AK-1121/code_extraction
/python/python_379.py
148
3.578125
4
# python create slice object from string slice(*[{True: lambda n: None, False: int}[x == ''](x) for x in (mystring.split(':') + ['', '', ''])[:3]])
cc6dc009a3c4c690fe92d36054e9455632222d2b
AK-1121/code_extraction
/python/python_26084.py
160
3.5
4
# How to default to the default argument in Python kwargs = dict((k, getattr(self, k)) for k in ('c', 'd') if getattr(self, k)) print_something(a, b, **kwargs)
5c0d57b426ec49b9c376327b2aaa3394f8e8312c
AK-1121/code_extraction
/python/python_1795.py
109
3.609375
4
# Multiple value checks using 'in' operator (Python) if any(s in line for s in ('string1', 'string2', ...)):
76c2d851e6a53874393a2a3f6c2e2c3c8a51e786
AK-1121/code_extraction
/python/python_15413.py
180
3.578125
4
# How can I change name of arbitrary columns in pandas df using lambda function? os_list = ['osxx', 'centos', 'windowsx'] df.rename(columns=lambda x: x+'x' if x in os_list else x)
f64650e0b9921c56f05721bde940299447e9329f
AK-1121/code_extraction
/python/python_11742.py
157
3.796875
4
# Sort entries of dictionary in decreasing order and print first n entries print sorted(mydictionary.items(), key=operator.itemgetter(1), reverse=True)[:10]
ea2e2de0294b53d70c00f689d08b742824d9388b
AK-1121/code_extraction
/python/python_11632.py
119
4.6875
5
# Replacing specific words in a string (Python) str = "What $noun$ is $verb$?" print str.replace("$noun$", "the heck")
8cc11edbf4514684f0ccebeb30a0086a8925dce2
AK-1121/code_extraction
/python/python_21649.py
148
3.734375
4
# How to use regular expressions to only capture a word by itself rather than in another word? import re print re.subn('Co$','',"Company &amp; Co")
9b18c33f304505db454d8de39d5f161bf11c9d0a
AK-1121/code_extraction
/python/python_10731.py
124
3.640625
4
# Is there a way to check a number against all numbers in a list? if any(n % x == 0 for x in mylist): print "Not Prime"
172e6672d7988b20147ea16cd5d76ae1b10d9d46
AK-1121/code_extraction
/python/python_27058.py
217
3.75
4
# How to use a 'for' loop to iterate nested-list index items in Python 2.7? for i in range(1,len(nList)): for distance in nList[i]: outputLlist.append('{} metres, {} metres, {} seconds'.format(*distance))
822db626d13358d4c9ec052aa640bef672a6ca98
AK-1121/code_extraction
/python/python_8674.py
86
4
4
# Print the concatenation of the digits of two numbers in Python print(str(2)+str(1))
a82f237a5fe2dc5ea77f54c863243879eabd99df
AK-1121/code_extraction
/python/python_26683.py
198
3.640625
4
# python sort list of lists based on inner element AND ignore case &gt;&gt;&gt; sorted([[1, 'C'], [2, 'D'], [3, 'a'], [4, 'b']], key=lambda x: x[1].lower()) [[3, 'a'], [4, 'b'], [1, 'C'], [2, 'D']]
40ba81aa3c5f61275d9a869a51f33566433e71de
AK-1121/code_extraction
/python/python_26885.py
121
3.53125
4
# Python - "Joining" list of lists of different types new_list=[''.join(str(y) for x in z for y in x) for z in my_list]
a241bad2e4d14e44775f10c7924b10fb4e1696a0
AK-1121/code_extraction
/python/python_862.py
125
3.578125
4
# Python string interpolation using dictionary and strings mystr = "path: %s curr: %s prev: %s" % (mydict[path], curr, prev)
7f07ababf1f59da566aeb8a9048c83bdd2d27e4e
AK-1121/code_extraction
/python/python_23678.py
168
3.6875
4
# replacing line in a document with Python import fileinput for line in fileinput.input(filename, inplace=True): print(line.replace(string_to_replace, new_string))
0e62422a2e6de1ac67e68e712db81101c53f4ed2
AK-1121/code_extraction
/python/python_7107.py
99
3.625
4
# multiple actions in list comprehension python for i in list: print('bla1') print('bla2')
420c0e931a427be69461d7c2b09f90869ef9917c
AK-1121/code_extraction
/python/python_12455.py
200
3.96875
4
# Python 2.7 creating a multidimensional list &gt;&gt;&gt; y = [[[] for i in range(n)] for i in range(n)] &gt;&gt;&gt; print y [[[], [], [], []], [[], [], [], []], [[], [], [], []], [[], [], [], []]]
ac980d809ac2346ffa42f0fa1e4aa713b53c1e70
AK-1121/code_extraction
/python/python_26532.py
90
3.671875
4
# Python - Finding string frequencies of list of strings in text file words=f.readlines()
091355dfbbf02ae6dc7f47c1f60ff5ab6d90c40c
AK-1121/code_extraction
/python/python_4596.py
191
3.71875
4
# How do I convert characters like "&#58;" to ":" in python? &gt;&gt;&gt; import re &gt;&gt;&gt; re.sub("&amp;#(\d+);",lambda x:unichr(int(x.group(1),10)),"&amp;#58; or &amp;#46;") u': or .'
771dbeaa855367594e04ac9bb29435943595e86b
AK-1121/code_extraction
/python/python_24461.py
249
3.96875
4
# Sorting a list depending on every other element in python ls = ["Milan", 6, 2, "Inter", 3, 2, "Juventus", 5, 2] &gt;&gt;&gt; sorted([ls[i:i+3] for i in range(0,len(ls),3)], key=lambda x:x[1]) [['Inter', 3, 2], ['Juventus', 5, 2], ['Milan', 6, 2]]
abfa14b3ebae20849cfceacd4447d364a673ca8d
AK-1121/code_extraction
/python/python_3435.py
114
3.609375
4
# Converting string to tuple and adding to tuple x = "(1,2,3)" t = tuple(int(v) for v in re.findall("[0-9]+", x))
15b7cd0bdbcfb5931a79b39e99bd4bbd95205303
AK-1121/code_extraction
/python/python_19914.py
128
3.578125
4
# Recursive sequence $x_n = \sqrt{2}$, $x_{n+1} = \sqrt{2x_n}$ X = [sqrt(2)] for i in range(1,10): X.append(sqrt(2*X[i-1]))
85eccc15475416a821627aaf5f09451349d0459f
AK-1121/code_extraction
/python/python_15569.py
94
3.546875
4
# Create dictionary from list python myDic = {} for list in lists: myDic[list[0]] = list[:]
0649e2f5883095155b37721144037fddae45754e
AK-1121/code_extraction
/python/python_24238.py
189
3.9375
4
# Python collections.Counter How to print element and number of counts with open(output_file, 'w') as f: for word, count in word_list: f.write("{0}\t{1}\n".format(word, count))
81f5986603b0a969596fa8e984f3b992145fad86
AK-1121/code_extraction
/python/python_9674.py
123
3.5625
4
# How does a Python genius iterate over a single value in a Python tuple? [ x[2] for x in score.keys() if x[0:2] == (0,1)]
576197e58d7b315fc8d043a91dfdccabce925e94
AK-1121/code_extraction
/python/python_9896.py
101
4
4
# Accessing the last element in the list in python &gt;&gt;&gt; myl = [1,2,3] &gt;&gt;&gt; myl[-1] 3
952f6ffbeb56a84f348d546a13a115cc0b4d3da0
AK-1121/code_extraction
/python/python_13197.py
88
3.625
4
# accessing python 2D array a = [[1, 2, 3], [2, 3, 4]] result = zip(*a)[0] print result
a15bad952e9b61639ce81901c7ac605ebf21e711
AK-1121/code_extraction
/python/python_414.py
215
3.578125
4
# Is there a way to get all the directories but not files in a directory in Python? def listfiles(directory): return [f for f in os.listdir(directory) if os.path.isdir(os.path.join(directory, f))]
27c4732134fab6705968554a043b9736a1b36775
AK-1121/code_extraction
/python/python_27291.py
110
3.53125
4
# How to print out a numbered list in Python 3 for a, b in enumerate(blob, 1): print '{} {}'.format(a, b)
2791403dd2286573878045df2b10709866fd2a6d
AK-1121/code_extraction
/python/python_10702.py
123
3.8125
4
# Python function for capping a string to a maximum length def cap(s, l): return s if len(s)&lt;=l else s[0:l-3]+'...'
311d176550126ab0ab9f3ab8549392471267d3a4
AK-1121/code_extraction
/python/python_27093.py
144
3.5625
4
# How to find the length of a leading sequence in a string? &gt;&gt;&gt; F = lambda x:len(x)-len(x.lstrip(' ')) &gt;&gt;&gt; F(' ' * 5 + 'a') 5
7e12ac9f808acfa9da4170d8ca46ffc6929c5769
AK-1121/code_extraction
/python/python_12696.py
73
3.578125
4
# recursion function in python fibonacci(number-1) + fibonacci(number-2)
6154ce1ce57efce3293bf4dd7a3e515eae87d012
AK-1121/code_extraction
/python/python_21497.py
109
3.640625
4
# re.sub (python) substitute part of the matched string re.sub(r'&lt;p&gt;(?=[A-Z]{2,})','&lt;i&gt;',MyText)
448e128ebcf213152408882b6921ade7c297a2e8
AK-1121/code_extraction
/python/python_8840.py
108
3.53125
4
# how to find the excel value from row, col names in python? d = ws.cell(row = 4, column = 2) print d.value
95814d2e7ce29e94e8d18d4e21226397cdb20017
AK-1121/code_extraction
/python/python_6317.py
81
4.09375
4
# How to convert string to lowercase in Python? s = "Kilometer" print(s.lower())
d8245029fd64484f4893bd5692565eb1ffef007c
AK-1121/code_extraction
/python/python_7543.py
155
4.09375
4
# How to search strings with certain number of occurence using Regular Expression? Str1 = '"HHHHLLLHHHHHLLLLL"' if Str1.count("H") &gt;= 8 : print "match"
5951c39dd4cdc3a7b1018e8c43da7dc3dfd42a75
AK-1121/code_extraction
/python/python_21301.py
111
3.703125
4
# Python: For loop in a for loop? for d in students: print d["name"],d["homework"],d["quizzes"],d["tests"]
db3c248cd270dad58a6386c4c9b6dc67e6ae4fab
AK-1121/code_extraction
/python/python_20317.py
208
4.1875
4
# Why mutable not working when expression is changed in python ? y += [1,3] # Means append to y list [1,3], object stays same y = y+[1,3] # Means create new list equals y + [1,3] and write link to it in y
20f6d2739125548325648dd8194e52dfbaa62821
AK-1121/code_extraction
/python/python_24743.py
240
3.875
4
# Comparing Lists and Printing the Common things = set(['Apple', 'Orange', 'Cherry','banana','dog','door','Chair']) otherThings = set(['Apple', 'Orange','TV' ,'Cherry','banana','Cat','Pen','Computer','Book']) print things &amp; otherThings
cac07e3a272b7c9a27bde3f4a7c1afa19d039d21
AK-1121/code_extraction
/python/python_14221.py
106
3.75
4
# Searching List of Tuples by nth element in Python [t for t in list_of_tuples if t[1] == n or t[2] == n]
84285c6d355abb457b69a48fc62b23ff774678a6
AK-1121/code_extraction
/python/python_24729.py
170
3.75
4
# Pandas framework: determining the count of a column data counter = df["ItemID"].value_counts() #df is your dataframe print counter[1] #prints how many times 1 occurred
4c805d46e5a5a1d541516b95e492076d126d632d
AK-1121/code_extraction
/python/python_13293.py
149
3.59375
4
# Format string with all elements of a list &gt;&gt;&gt; statement = "%s you are so %s at %s" % tuple(words) 'John you are so nice at skateboarding'
267919fe7bb7c9137a2d5fadb9c5125857421c7f
AK-1121/code_extraction
/python/python_3817.py
106
3.640625
4
# Sort list of strings by integer suffix in python sorted(the_list, key = lambda x: int(x.split("_")[1]))
6c394abfea8781eae288b12287fc75099dcff03f
AK-1121/code_extraction
/python/python_3087.py
200
3.578125
4
# Image bit manipulation in Python r, g, b = im.split() # split the image into separate color planes im = Image.merge("RGB", (g, g, g)) # merge them back, using the green plane for each
7275c985231bb504bdb85d4cb8f88c8369bee1b3
AK-1121/code_extraction
/python/python_9255.py
166
3.546875
4
# Python Regular Expressions: Capture lookahead value (capturing text without consuming it) re.findall("([%]+)([^%]+)(?=([%]+))".replace("%", "".join(VOWELS)), word)
ac89ff06bf3ce8e6d71819481091160983ebfd3b
AK-1121/code_extraction
/python/python_8529.py
242
3.75
4
# How do I format text from a file in Python? def print_table(lines, col_num, col_width): for line_ix in range(0, len(lines), col_num): print ' -- '.join([line.strip().ljust(col_width) for line in lines[line_ix:line_ix+col_num]])
af072c303c1672dbe0dda1994fb6bdaf67a6c1ff
AK-1121/code_extraction
/python/python_234.py
123
3.515625
4
# Deleting multiple elements from a list indices = 0, 2 somelist = [i for j, i in enumerate(somelist) if j not in indices]
ed27b44628db1b53914555d9e875c6d064d18e52
AK-1121/code_extraction
/python/python_5693.py
210
3.609375
4
# Regex Python - Find every keyword instance, extract keyword and proceeding characters Input text: DODOD987654321 First match: DODOD987654321 Second match: DOD987654321 # Not found by re.finditer()
d8edfb9fbebf0510af3aa451c01403797a710e2b
AK-1121/code_extraction
/python/python_15459.py
118
3.609375
4
# Python - Most effective way to implement two's complement? x=int(a,2) num_bits = 10 print x - (1 &lt;&lt; num_bits)
2539312375a1568d8046330ed9660e0c7eb2d79e
AK-1121/code_extraction
/python/python_6924.py
130
3.625
4
# Query Python dictionary to get value from tuple &gt;&gt;&gt; D = {"Key1": (1,2,3), "Key2": (4,5,6)} &gt;&gt;&gt; D["Key2"][2] 6
4afc089e167a801c419df83e6ca748a2e78e4156
AK-1121/code_extraction
/python/python_15965.py
219
3.96875
4
# Can I return a list of ALL min tuples, using Python's Min function? listo = [('a','1'),('b','0'),('c','2'),('d','0')] minValue = min(listo, key=lambda x: x[1])[1] minValueList = [x for x in listo if x[1] == minValue]
fb640fc148d60aa1a1f66f13a0052f77c1542b01
AK-1121/code_extraction
/python/python_78.py
110
4.03125
4
# How to check if a string in Python is in ASCII? def is_ascii(s): return all(ord(c) &lt; 128 for c in s)
609e93c9cdbcbf5833e1e740f6e4b6186107e21e
AK-1121/code_extraction
/python/python_9240.py
137
3.59375
4
# Smallest way to expand a list by n &gt;&gt;&gt; l = [1,2,3,4] &gt;&gt;&gt; [it for it in l for _ in range(2)] [1, 1, 2, 2, 3, 3, 4, 4]
1e2e00ebac409aae87e026b011e410511b3435b8
AK-1121/code_extraction
/python/python_14135.py
129
3.65625
4
# invert a tuple array python array = [(126,150),(124,154),(123,145),(123,149)] inversed = [(item[1],item[0]) for item in array]
a0c0614800285c1c323ca4fd807b5aedb3f139e8
AK-1121/code_extraction
/python/python_15393.py
198
3.59375
4
# Python: Modified sorting order for a list &gt;&gt;&gt; items = ['24/2', '24/3', '25/2', '6'] &gt;&gt;&gt; sorted(items, key=lambda s: [int(n) for n in s.split('/')]) ['6', '24/2', '24/3', '25/2']
a29ff60c305f8d9bf7c7e537fc2cffed934cedd3
AK-1121/code_extraction
/python/python_1715.py
97
3.640625
4
# How to input an integer tuple from user? tuple(int(x.strip()) for x in raw_input().split(','))
3db6a0aea7728ac61e77fbc25756adf1e467d3ea
AK-1121/code_extraction
/python/python_22304.py
269
3.515625
4
# NumPy convert 8-bit to 16/32-bit image i = cv2.imread(imgNameIn, cv2.CV_LOAD_IMAGE_COLOR) # Need to be sure to have a 8-bit input img = np.array(i, dtype=np.uint16) # This line only change the type, not values img *= 256 # Now we get the good values in 16 bit format
a0d03d175e5732aa674a3369aeae2200a593d006
AK-1121/code_extraction
/python/python_24297.py
160
3.984375
4
# Iterating through the same key in different items python dictionary for key1 in dict: for key2 in dict[key1]: dict[key1][key2]['time'] = 'newTime'
442a1825bbe5b1e7d9a2462c90d2e6514ad5d807
AK-1121/code_extraction
/python/python_11438.py
173
3.5625
4
# How can I split a string in Python? my_str="123456781234567812345678" splits=[my_str[x:x+8] for x in range(0,len(my_str),8)] //splits = ["12345678","12345678","12345678"]
2f06e68c18f3678f38e13b15f4cc33cd6b61b45a
AK-1121/code_extraction
/python/python_15357.py
159
3.625
4
# Convert a number enclosed in parentheses (string) to a negative integer (or float) using Python? my_str = "(4,301)" num = -int(my_str.translate(None,"(),"))
21435912ae2bb268ec90d4f5e903a4a7428cad28
AK-1121/code_extraction
/python/python_18681.py
90
3.859375
4
# Sum up all the integers in range() res = sum(x for x in range(100, 2001) if x % 3 == 0)
e16d5d2398c8fb9089a4191971767561bb71f827
AK-1121/code_extraction
/python/python_4752.py
143
3.609375
4
# Writing data from python list? assert len(A) == len(B) == len(C) for a, b, c in zip(A, B, C): print a, b, c # replace with file write
576cc6138dd0ca91d403479303a71da31dc00dd9
AK-1121/code_extraction
/python/python_17002.py
121
3.53125
4
# Checking for multiple strings in python in a dictionary location = location + sum(mot[x][1] for x in mot if x in str2)
040c8f196de94e2c59d9e9e73bf7fdf4616c9504
AK-1121/code_extraction
/python/python_16918.py
103
3.515625
4
# Simplifying Python string regex/pattern matching MyString = MyString.strip(", ").replace(", , ", "")
3225e1591c18b6a5f05b1ddbb4fd4da42bcd628a
AK-1121/code_extraction
/python/python_18057.py
179
3.75
4
# Python: "Distributing" strings from two lists into one list &gt;&gt;&gt; print(list(itertools.product(['a', 'b'], ['c', 'd']))) [('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd')]
a6075e5910e620751a33078e54e2f556c06bc2fe
AK-1121/code_extraction
/python/python_3697.py
192
3.828125
4
# Python and character normalization How to detect if the values in array are in a certain range and return a binary array in Python? Y=X[0,:]+X[1,:] D = ((1&lt;Y) &amp; (Y&lt;2)).astype(int)
768c0b4ff8462e908f1a2a6187e5eaa2d6e94423
AK-1121/code_extraction
/python/python_7357.py
164
3.625
4
# How to unpack 6 bytes as single integer using struct in Python def unpack48(x): x1, x2, x3 = struct.unpack('&lt;HHI', x) return x1, x2 | (x3 &lt;&lt; 16)
529d5340d46bba259674e33f25b6c1adedc291ea
AK-1121/code_extraction
/python/python_28175.py
252
3.75
4
# Using .find to search a string inside a list &gt;&gt;&gt; list_of_strings = ['Hello!, my name is Carl', 'Hello!, my name is Steve', 'Hello!, my name is Betty', 'My Name is Josh'] &gt;&gt;&gt; [s.find('Hello!') for s in list_of_strings] [0, 0, 0, -1]
15839f452377dcc38908ac3dc51490c62f216c94
AK-1121/code_extraction
/python/python_20396.py
239
4.09375
4
# replaces multiple occurances of a character (except for first and last) in a python string str1 = '$2a$10$.XfjKl/,abcd, 1, ##, s, for free,2-3-4' parts = str1.split(',') str2 = '{},{},{}'.format(parts[0],'_'.join(parts[1:-1]),parts[-1])
09cf1dbfa8916742afabfe3bfe8a12cc69d39779
AK-1121/code_extraction
/python/python_5432.py
138
3.84375
4
# Referencing the ith element of each list in a 2d list i = 1 data = [[1,10],[2,20],[3,30]] result = [d[i] for d in data] # [10, 20, 30]
5b68be99f1426969b5ec0ba86e1a14c7fe530d15
AK-1121/code_extraction
/python/python_1113.py
186
4.09375
4
# Is there a way to split a string by every nth separator in Python? span = 2 words = "this-is-a-string".split("-") print ["-".join(words[i:i+span]) for i in range(0, len(words), span)]
92874a6a6da9162b9a862680fc9d652523167571
AK-1121/code_extraction
/python/python_23762.py
130
4.03125
4
# How to print the date and time in Python from string? &gt;&gt; dt = time.strftime('%d-%b-%Y', dt) &gt;&gt; print dt 11-Aug-2014
c193ac400d6c591bb3268f3b7e32d52c0d9b1475
AK-1121/code_extraction
/python/python_7056.py
98
3.5
4
# Reading Space separated input in python the_string = raw_input() name, age = the_string.split()
d7308cbef556b8cae091b39c756e06274fd842ec
AK-1121/code_extraction
/python/python_27038.py
92
3.8125
4
# How to add commas to digits in Python 3? print("Your income tax is ${:,}".format(income))
2a92daaf819f922f79b7c5fd2729533a6ea3fc50
AK-1121/code_extraction
/python/python_79.py
153
4
4
# I'm looking for a pythonic way to insert a space before capital letters &gt;&gt;&gt; re.sub(r"(\w)([A-Z])", r"\1 \2", "WordWordWord") 'Word Word Word'