blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
542aaa5ad309ea0202940209291a0d88d830752c
BabuGumpu/PythonProject
/src/trust_fund_bad.py
250
3.859375
4
print( """ Please Enter the requested,monthly costs """ ) car = int(input("Enter Car -- ")) rent = input("Enter Rent -- " ) food = int(input("Enter Food -- ")) total = int(car) + int(rent) + int(food) print("\n Grand Total -->",long(float(total)))
be54ac7925ba7dfb2848a52b902c67fdc18b8bde
bonus-tm/euforia
/events/vizier.py
5,977
3.640625
4
# Визирь from event import Event class Vizier(Event): """ Визирь Армия: довольствие, дезертиры Население: рождаемость, смертность, недовольство, голод Урожай: засухи-наводнения, урожайность, крысы Визирь: украл золото и скрылся """ def __init__(self, data, say, ask): self.data = data self.say = say self.ask = ask # def start(self): """ Запуск события — пересчёт параметров и вывод результатов """ self.check_army() self.check_population() self.check_crop() self.check_rob_caravan() self.check_rob_church() self.check_vizier() if self.let_him_in(): self.report() # довольствие армии def check_army(self): # дезертиры self.data.deserters = 0 # денежное довольствие армии self.data.allowance = self.data.resources['soldier'] * 10 # считаем дезертировавших из-за невыплаты довольствия if self.data.allowance > self.data.money: shortage = self.data.allowance - self.data.money self.data.allowance = self.data.money self.data.deserters = min(round(shortage / 10 * self.ask.frand(0, 1.5)), self.data.resources['soldier']) self.data.money -= self.data.allowance self.data.resources['soldier'] -= self.data.deserters # население # настроения народа def check_population(self): # родилось self.data.births = 0 # померло от голода self.data.famishes = 0 # сбежало self.data.fugitives = 0 sldr = self.data.resources['soldier'] psnt = self.data.resources['peasant'] # считаем скольким хватило зерна на прокорм, а сколько рабочих померло с голодухи if psnt + sldr > self.data.corn_for_food: shortage = psnt + sldr - self.data.corn_for_food self.data.famishes = round(shortage * self.ask.frand(0.3, 1)) self.data.resources['peasant'] -= self.data.famishes # считаем рабочих, сбежавших от нехватки земли if psnt > min(self.data.corn_for_seed, self.data.resources['land']): shortage = psnt - min(self.data.corn_for_seed, self.data.resources['land']) self.data.fugitives = min(round(shortage * self.ask.frand(0, 1.2)), self.data.resources['peasant'],) self.data.resources['peasant'] -= self.data.fugitives # эпидемия чумы # остальные размножаются self.data.births = round(self.data.resources['peasant'] * self.ask.frand(0.05, 0.4)) self.data.resources['peasant'] += self.data.births # надо посчитать заговорщиков # урожай def check_crop(self): self.data.rats_eat = 0 # крысы пожрали зерно if self.ask.dice(50): self.data.rats_eat = round(self.data.resources['corn'] * self.ask.frand(0.1, 0.9)) # расчёт урожайности self.data.resources['corn'] += round(self.data.corn_for_seed * self.data.crop_rate) # стихийные бедствия - засухи, пожары, наводнения # визирь украл и скрылся def check_vizier(self): pass # ограблен храм # def report(self): self.say.clear_screen() self.say.line("Жалованье солдат: {:>10n} руб.\n".format(self.data.allowance)) self.say.line("-----------------------------------------------------------------------") self.debug("на еду {:n}, на посев {:n} × {:.3} = урожай {:n} тонн, итого {:n}" .format(self.data.corn_for_food, self.data.corn_for_seed, self.data.crop_rate, round(self.data.corn_for_seed * self.data.crop_rate), self.data.resources['corn'])) if self.data.rats_eat: self.say.line(" - Крысы сожрали {:>10n} тонн зерна.".format(self.data.rats_eat)) if self.data.deserters: self.say.line(" - Гвардия не получила денежного довольствия.\n" + " {:>10n} солдат покинули казармы и ушли за кордон.".format(self.data.deserters)) if self.data.fugitives: self.say.line(" - Рабочим не хватает земли. Сбежало {:>10n} человек.".format(self.data.fugitives)) if self.data.famishes: self.say.line(" - Вы заморили голодом {:>10n} ваших верноподданных!".format(self.data.famishes)) if self.data.births: self.say.line(" - В государстве родилось {:>10n} детей.".format(self.data.births)) # if self.data.: # self.say.line(" - {:>10n} \n".format(self.data.)) # self.say.line() # def let_him_in(self): return self.ask.yesno("Ваше высочество! Прибыл визирь, впустить?")
ffb145ebef92d4a9a1cf9c5ecb97129219d09391
ErisonSandro/Exercicios-Python
/exercicios/ex044Gerenciador de pagamentos.py
1,139
3.765625
4
print('=' * 10, 'Loja Nene', '=' * 10) preço = float(input('Preço das compras: R$ ')) print('Forma de pagamento:') print('[1] à vista dinheiro / cheque') print('[2] à vista no cartão') print('[3] 2x no cartão de credito') print('[4] 3x ou mais no cartão de credito') opção = int(input('Qual é a sua opção: ')) if opção == 1: d1 = preço - (preço*10/100) print('Sua compra de R${} vai custar R${} no final'.format(preço, d1)) elif opção == 2: d2 = preço - (preço*5/100) print('Sua compra de R${} vai custar R${} no final'.format(preço, d2)) elif opção == 3: parcela = int(input('Quantas parcelas: ')) print('Sua compra sera em {}x de {} sem juros!'.format(preço, preço / parcela)) print('Sua compra vai custar R${}'.format(preço)) elif opção == 4: parcelas = int(input('Quantas parcelas: ')) j1 = preço + (preço*20/100) juros = j1 / parcelas print('Sua compra sera parcelada em {}x de {} com juros'.format(parcelas, juros)) print('Sua compra foi de R${} vai custar R${} parcelando em 3x'.format(preço, j1)) else: print('OPÇÃO INVALIDA, TENTE NOVAMENTE!')
726072a543a2208b184e61c1284ec4ffd408f0d7
sivakurella/python-programming
/Python Scripts/Binary_tree.py
687
3.890625
4
class Node: def __init__(self, value=None): self.value = value self.left = None self.right = None class BinaryTree: def __init__(self, root=None): self.root = root # Add `insert` method here. def insert(self, value): if not self.root: self.root = Node(value) elif not self.root.left: self.root.left = Node(value) elif not self.root.right: self.root.right = Node(value) else: pass tree = BinaryTree(Node(value=1)) for value in [2,3,4]: tree.insert(value) root = tree.root.value left = tree.root.left.value right = tree.root.right.value
312ab3b07594f45eb9fa3b3c1ac67346fc9b9ef8
glayn2bukman/jermlib
/fuel.py
6,014
3.65625
4
''' this module calibrates a fuel tank for the fuel sensor the module then stores the tank details in a global jfms data library ''' false = False # just in case i forget I'm in Python and not C++ def read(pin=23, against=0): ''' read the height(or volume?) value on the RPi sensor if `against` is given, then generate random numbers ''' if against: return against - round(random.random(), 2) def calibrate(*args, **kwargs): ''' Read height(x-data) data from the tank to be calibrated plus * either height(y-data) in standard tank OR * volume(y-data) of liquid flowing out of the subject tank This function does not distinguish between the two posible target readings ie `height in standard tank` or `volume of liquid flowing out of the subject tank` This is distinction is left to the interpolating function! The only precaution made is determining if the y-data is from an overflow or not(this is particularly true for the second type of y-data when the standard tank is smaller than the subject tank so it has to be emptied whenever its full before the operation can continue) return value is a tuple(or list) of 2-item tuples PLUS data_count ie the entries in the data set ''' x_data_pin = kwargs.get('x-pin',10) y_data_pin = kwargs.get('y-pin',11) x_zero_tolerance = kwargs.get('x-zero-tolerance',0.5) # its hard to get the height to absolute 0 when draining the subject tank data_count = 0 x,y = 1,0 while (x-x_zero_tolerance)>0: x = read(x_data_pin) y = read(y_data_pin) data.append((x,y)) data_count += 1 return data, data_count def _interpolate(p0,p1,p2, target_pos=1): ''' p0,p1,p2: (x0,y0),(x1,y1),(x2,y2) target_pos is the index of the point with the unknown y-value, default is the middle point this function ASSUMES THAT ALL POINTS ARE FLOATS ''' target_pos = target_pos if 1<=target_pos<=3 else 1 if target_pos==0: return p1[1] + ((p1[1]-p2[1])/(p1[0]-p2[0]))*(p0[0]-p1[0]) elif target_pos==1: return p0[1] + ((p2[1]-p0[1])/(p2[0]-p0[0]))*(p1[0]-p0[0]) else: # target_index = 2 return p1[1] + ((p1[1]-p0[1])/(p1[0]-p0[0]))*(p2[0]-p1[0]) def get_actual_value(data, reading, data_count=0, tolerance=.001): ''' data: return value of `calibrate` reading: float data_count: number of readings in the data. if 0, will be calculated with len(data) providing it would imporove on this functions efficiency tolerance: since we are dealing with floats, we cant exactly compare values directly so we need a tolerance such that if x==y: ... becomes if abs(x-y)<=tolerance: ... function to use the calibrated data to interpolate a y-data value given an x-data reading(that may or may not be in the calibrated data table) Because we are not sure that the x-data(height of liquid in subject tank) is sure to decline in well-defined steps, pinpointing the x-data value to use for the interpolation is near impossible so a binary search was prefered as the only guarantee we have is that the x-data is sorted NB: the most fundumental principle here is that the x-data is in DECENDING order ''' if (abs(reading-data[0][0])<=tolerance) or (reading>data[0][0]): return data[0][1] if (abs(reading-data[-1][0])<=tolerance) or (reading<data[-1][0]): return data[-1][1] i = 1 # iterations to track out binary search. needed in debug mode data_count = data_count if data_count else len(data) pos, _pos = data_count/2, 0 prev_pos = 0 while 1: print "search={}, prev-pos={}, pos={}, vi={}".format(i,prev_pos,pos,data[pos][0]) # this is not impossible given the large sample set if abs(reading-data[pos][0])<=tolerance: return data[pos][1] if not pos: return _interpolate(data[pos+1],(reading,-1),data[pos]) elif pos==data_count-1: return _interpolate(data[pos],(reading,-1),data[pos-1]) _pos = pos if reading>data[pos][0]: # search to the left if abs(reading-data[pos-1][0])<=tolerance: return data[pos-1][1] if reading<data[pos-1][0]: return _interpolate(data[pos],(reading,-1),data[pos-1]) pos -= (pos-prev_pos)/2 if pos>prev_pos else (prev_pos-pos)/2 if pos==_pos: pos -= 1 else: # search to the right if abs(reading-data[pos+1][0])<=tolerance: return data[pos+1][1] if reading>data[pos+1][0]: return _interpolate(data[pos+1],(reading,-1),data[pos]) pos += (pos-prev_pos)/2 if pos>prev_pos else (prev_pos-pos)/2 if pos==_pos: pos += 1 i += 1 prev_pos = _pos if __name__=="__main__": import random, os data = ( #calibrate() (6.0, 0.0), (5.8, 3.56), (5.6, 5.29), (5.4, 7.18), (5.2, 8.49), (5.0, 9.04), (4.8, 9.65), (4.6, 10.0), (4.3, 10.5), (4.01, 11.23), (3.87, 12.04), (3.68, 12.5), (3.64, 12.53), (3.61, 12.59), (3.58, 12.69), (3.52, 12.81), (3.21, 13.06), (3.07, 14.23), (2.49, 16.14), (2.08, 16.91), (1.98, 17.52), ) def show_table(): os.system('clear') print "%8s%8s"%('X-data','Y-data') print ' --------------' for r in data: print '%8.3f%8.3f'%(r[0],r[1]) print while 1: show_table() n = input('x-value(-1 to exit): ') if n==-1: break print "\nx={}, y={}".format(n, get_actual_value(data,n,len(data))) raw_input('\npress enter to continue...')
7f9ec22771bc635ef95deb23d4a04ddb39177256
harman666666/Algorithms-Data-Structures-and-Design
/Algorithms and Data Structures Practice/LeetCode Questions/String/647. Palindromic Substrings.py
1,435
4.28125
4
''' 647. Palindromic Substrings Medium 1753 88 Favorite Share Given a string, your task is to count how many palindromic substrings in this string. The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters. Example 1: Input: "abc" Output: 3 Explanation: Three palindromic strings: "a", "b", "c". Example 2: Input: "aaa" Output: 6 Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa". Note: The input string length won't exceed 1000. ''' class Solution(object): def countSubstrings(self, s): # Find all even and odd substrings. ''' THis is also known as the expand around center solution. ''' i = 0 count = 0 for i in range(len(s)): left = i right = i # Count odd palins def extend(left, right, s): count = 0 while True: if left < 0 or right >= len(s) or s[left] != s[right]: break count += 1 left = left - 1 right = right + 1 return count count += extend(left, right, s) count += extend(left, right+1, s) return count
bd59f0322ba2268faa921e3a1c93ef86bc633d8d
zhuqiangLu/leetcode
/JumpGame.py
529
3.734375
4
from typing import List class Solution: def canJump(self, nums: List[int]) -> bool: n = len(nums) dist = 0 for i in range(n-1): if i <= dist: dist = max(i + nums[i], dist) print(dist) if dist >= n-1: return True else: return False if __name__ == "__main__": nums = [2,3,1,1,4] nums = [3,2,1,0,4] nums = [0, 2, 3] print(Solution().canJump(nums))
65ff86e12c9f6673be4e5b43d6bd40d7f593aa4a
dpebert7/TIdy
/TI.py
16,823
3.703125
4
# @title TI Class import re from defaults import DEFAULT_OUTDIR, DEFAULT_TAB def is_comment(line): """ Determine if a line is a comment """ strip = line.strip() if len(strip) > 0 and strip[0] == '#': return True return False def find_parentheses(s): """ Find and return the location of the matching parentheses pairs in s. Given a string, s, return a dictionary of start: end pairs giving the indexes of the matching parentheses in s. Suitable exceptions are raised if s contains unbalanced parentheses. """ # The indexes of the open parentheses are stored in a stack, implemented # as a list stack = [] parentheses_locs = {} for i, c in enumerate(s): if c == '(': stack.append(i) elif c == ')': try: parentheses_locs[stack.pop()] = i except IndexError: raise IndexError('Too many close parentheses at index {}' .format(i)) if stack: raise IndexError('No matching close parenthesis to open parenthesis ' 'at index {}'.format(stack.pop())) return parentheses_locs def is_blank(line): """ Determine if a line is a comment """ if line.strip() == '': return True return False def is_hash(line): """ Determine if a line is entirely hash. E.g. ############### Line must have at least one hash, but not no other characters :param line: :return: """ import re if '#' in line: if re.sub('#', '', line).strip() == '': return True return False def is_one_line_if_statement(line): """ Some if statements happen on one line. E.g. IF(nCondition = 1, ProcessBreak, 0); This should be split into 3 lines to prevent indentation issues """ if is_comment(line): return False else: # Assume line must start with IF, and entire IF() statement is in ONE line if line.lstrip().upper()[:2] == "IF": # Get only text inside IF parentheses paren_string = line[line.find("(") + 1:line.rfind(")")] # Remove inner parenthesis before counting commas while '(' in paren_string: paren_string = paren_string[:paren_string.find("(")] + paren_string[paren_string.rfind(")") + 1:] if paren_string.count(",") == 2: return True return False def line_is_intro_or_conclusion(lst, line_idx): """ Determine if a line comes before the prolog or after the epilog. """ for i in range(len(lst)): start_idx = None end_idx = None if lst[i].startswith('572,'): start_idx = i elif lst[i].startswith('575,'): end_idx = i + int(lst[i][4:]) if start_idx is None: return False elif line_idx < start_idx: return True elif end_idx is None: return False elif line_idx > end_idx: return True else: return False def char_is_in_string(lst, line_idx, char_idx): """ Determine if a given character (referenced by index) is part of a string. E E.g. logx = '\\s-grp-dbsvr6\sqlpackagedata$\TM1\Working\test.txt'; should return True for all \, but nResult = nNumerator \ nDenominator; should return False for \ Since strings can go over multiple lines, look back to previous semicolon (if exists?) for start of strings """ # Loop backward to find first semicolon idx = line_idx start_idx = 0 while idx > 0: if ";" in lst[idx]: # Assume ";" is the last character of previous line start_idx = idx idx = 0 elif idx == 1: start_idx = 0 idx = idx - 1 # Create single string from start_idx to line_idx, then append current line longstr = "".join(lst[start_idx:line_idx]) longstr += (lst[line_idx][:char_idx + 1]) # Count the number of occurrences of ' count = longstr.count("'") if count % 2 == 0: return False return True class TI(object): """ A python class for tidying up TM1 TurboIntegrator Processes """ text: object def __init__(self, text=None, infile="", tab=DEFAULT_TAB, outdir=DEFAULT_OUTDIR, outfile="out.ti"): """ Initialize TI object in python """ self.infile = infile self.text = text self.tab = tab self.outdir = outdir self.outfile = outfile self.isprofile = False if self.infile != "": with open(self.infile, 'r') as f: text_list = f.read().splitlines() self.text = text_list elif self.text != "": ### Note: In cases like nNumerator\nDenominator, a raw string must be passed here. # self.text = self.text.replace('\\', '\\ ') self.text = self.text.split('\n') if self.text is None: print("I think there's an error here. Make sure infile or text are populated...") if self.infile != "": self.outfile = self.infile.split('/')[-1] def set_tab(self, tab_str): self.tab = tab_str def set_outdir(self, outdir_str): self.outdir = outdir_str def set_outfile(self, outfile_str): self.outfile = outfile_str def capitalize_keywords(self): """ Capitalize 7 control keywords if found at the start of a line """ from defaults import KEYWORDS out = [] for line in self.text: if is_comment(line) is True: out.append(line) else: for keyword in KEYWORDS: idx = line.upper().find(keyword) if idx != -1: if line.strip().upper().find(keyword) == 0: line = line[:idx] + keyword + line[idx + len(keyword):] out.append(line) self.text = out def capitalize_functions(self): """ Capitalize ~150 reserved TI function names """ from defaults import FUNCTION_NAMES out = [] for line in self.text: if is_comment(line) is True: out.append(line) else: for keyword in FUNCTION_NAMES: idx = line.upper().find(keyword.upper()) # Keyword must be preceded by a space or '(' if not at start of line: if idx != -1 and (line[idx - 1] == ' ' or line[idx - 1] == '(' or idx == 0): # Keyword must also be followed by a space or '(' or ';' following_char = str(line + ' ')[idx + len(keyword)] if following_char == ' ' or following_char == '(' or following_char == ';': line = line[:idx] + keyword + line[idx + len(keyword):] # print(line, keyword, idx) # Else keyword must be followed closely by '(' elif idx == 0 and '(' in line[idx + len(keyword):idx + len(keyword) + 3]: line = keyword + line[idx + len(keyword):] elif idx != -1: # uncomment for testing # print(line, keyword, idx) pass out.append(line) self.text = out # # def separate_one_line_ifs(self): # """ # Some if statements happen on one line. E.g. IF(nCondition = 1, ProcessBreak, 0); # This should be split into 3 lines to prevent indentation issues # """ # out = [] # line_idx = -1 # for line in self.text: # line_idx += 1 # if is_comment(line) or line_is_intro_or_conclusion(self.text, line_idx): # out.append(line) # else: # # Assume line must start with IF, and entire IF() statement is in ONE line # if line.lstrip().upper()[:2] == "IF": # paren_string = line[line.find("(")+1:line.rfind(")")] # # Remove inner parenthesis before counting commas # #print('Hello', paren_string) # while '(' in paren_string: # paren_string = paren_string[:paren_string.find("(")] + paren_string[paren_string.rfind(")")+1:] # #print('Hello', paren_string) # if paren_string.count(",") == 2: # print(line, paren_string.split(',')) # splt = paren_string.split(',') # # # Append If statement # out.append("IF(" + splt[0] + ");") # # # Append condition if true # if str(splt[1]).split() == '0': # out.append(" ") # else: # out.append(splt[1] + ";") # # #Append Else and Endif # if str(splt[2]).strip() == '0': # out.append('ENDIF;') # else: # out.append('ELSE;') # out.append(splt[2] + ';') # out.append('ENDIF;') # else: # out.append(line) # else: # out.append(line) # self.text = out def indent(self): """ Add indentation """ level = 0 out = [] tab = self.tab for line in self.text: line = line.lstrip() if line.startswith('END') or line.startswith('ENDIF') or line.startswith('ELSE'): level -= 1 out.append(tab * level + line) if line.startswith('WHILE') or line.startswith('IF') or line.startswith('ELSEIF') or line.startswith( 'ELSE'): level += 1 # Rare exception for one line if statements if is_one_line_if_statement(line): level -= 1 self.text = out def remove_trailing_whitespace(self): self.text = [x.rstrip() for x in self.text] def space_operators(self): """ Add spacing around operators. E.g. n=n+1; --> n = n + 1; """ from defaults import OPERATORS out = [] previous_lines = [] line_idx = -1 for line in self.text: line_idx += 1 previous_lines.append(line) if is_comment(line) or line_is_intro_or_conclusion(self.text, line_idx): out.append(line) else: for op in OPERATORS: # Need to escape + and * when using regex if op == '+' or op == '*': reop = '\\' + op else: reop = op indices = [m.start() for m in re.finditer(reop, line)][::-1] for idx in indices: # Make sure operator doesn't occur in a string if char_is_in_string(previous_lines, len(previous_lines) - 1, idx) is False: # If previous or next character is another operator or '@', then skip this operator for this position if idx == 0 or line[idx - 1] not in OPERATORS + ['@']: if idx + len(op) == len(line) or line[idx + len(op)] not in OPERATORS + ['@']: # Apply spacing before operator if idx == 0: line = ' ' + op + line[idx + len(op):] elif line[idx - 1] != ' ': line = line[:idx] + ' ' + op + line[idx + len(op):] idx += 1 # Apply spacing after operator if idx + len(op) < len(line): if line[idx + len(op)] != ' ': line = line[:idx] + op + ' ' + line[idx + len(op):] else: line = line[:idx] + op + ' ' out.append(line) self.text = out def enforce_max_blank_lines(self): from defaults import MAX_CONSECUTIVE_BLANK_LINES out = [] consecutive_blanks = 0 for line in self.text: if is_blank(line): consecutive_blanks += 1 if consecutive_blanks <= MAX_CONSECUTIVE_BLANK_LINES: out.append(line) else: consecutive_blanks = 0 out.append(line) self.text = out def remove_hash_lines(self): # Only remove hash lines if there are more than one in a row. out = [] consec = 0 for line in self.text: if is_hash(line) is True: consec += 1 if consec < 2: out.append(line) else: consec = 0 out.append(line) self.text = out def space_back_slash(self): # Forward slashes cause issues in python, especially 12\n_months which creates a newline. out = [] previous_lines = [] line_idx = -1 for line in self.text: line_idx += 1 previous_lines.append(line) indices = [m.start() for m in re.finditer(r'\\', line)][::-1] for idx in indices: if line_is_intro_or_conclusion(previous_lines, len(previous_lines) - 1) is False: if char_is_in_string(previous_lines, len(previous_lines) - 1, idx) is False: if len(line) > idx: line = line[:idx] + " \\ " + line[idx + 1:] else: line = line[:idx] + " \\ " + line[idx + 1:] line = line.replace(" ", " ") out.append(line) self.text = out def remove_space_before_semicolon(self): out = [] for line in self.text: while " ;" in line: line = line.replace(" ;", ";") out.append(line) self.text = out def update_pmde_lengths(self): """ When working with a .pro file, the Prolog, metadata, data, and epilog tabs are preceded by <Code>,<Length of tab>. .pro files risk being invalid if this line is not updated. This process should not make any changes to TI code that is not in .pro format """ pmde_lengths = {'intro': 0, 'prolog': 0, 'metadata': 0, 'data': 0, 'epilog': 0, 'outro': 0} stage = 'intro' for i in range(len(self.text)): if self.text[i][:4] == '572,': stage = 'prolog' elif self.text[i][:4] == '573,': stage = 'metadata' elif self.text[i][:4] == '574,': stage = 'data' elif self.text[i][:4] == '575,': stage = 'epilog' elif self.text[i][:4] == '576,': stage = 'outro' pmde_lengths[stage] += 1 for i in range(len(self.text)): if self.text[i][:4] == '572,': self.text[i] = '572,' + str(pmde_lengths['prolog'] - 1) elif self.text[i][:4] == '573,': self.text[i] = '573,' + str(pmde_lengths['metadata'] - 1) elif self.text[i][:4] == '574,': self.text[i] = '574,' + str(pmde_lengths['data'] - 1) elif self.text[i][:4] == '575,': self.text[i] = '575,' + str(pmde_lengths['epilog'] - 1) pmde_lengths[stage] += 1 def tidy(self): """ Apply all TIdy processes """ self.space_back_slash() self.capitalize_keywords() self.capitalize_functions() self.remove_trailing_whitespace() self.space_operators() self.indent() self.enforce_max_blank_lines() self.remove_space_before_semicolon() self.remove_hash_lines() self.update_pmde_lengths() def write_output(self): """ Write text to outfile """ with open(self.outdir + '/' + self.outfile, 'w') as f: for line in self.text: f.write("%s\n" % line) def print_output(self): """ Print text """ for line in self.text: print(line)
15abd9b50900c9cf56e440a34b453527d507f19f
Skipper609/python
/Sample/class eg/lab questions/1A/5.py
162
3.8125
4
'''''' inp_num = input("Enter a number :") res = "" for i in inp_num: res += str((int(i) + 1) % 10) print(f"The resultent for the input {inp_num} is {res}")
422abad6882219cd3df3d100aba8c382b3e8b032
Pekmen/dailyprogrammer
/Easy/e.53.py
97
3.75
4
#!/usr/bin/env python3 lista = [1, 5, 7, 8] listb = [2, 3, 4, 7, 9] print sorted(lista + listb)
86537efbcae42a9638222088cd5255b553e185a4
vlad17/deeprl_project
/src/keyboard_pong.py
1,048
3.734375
4
""" This file lets you play pong with the keyboard. Simply run this file and then enter 0, 1, 2, 3, 4, or 5 on stdin to make an action. """ import argparse import random import tensorflow as tf import numpy as np import atari_env def _read_action_from_stdin(): allowable_actions = ["0", "1", "2", "3", "4", "5"] action = input() while action not in allowable_actions: print("Error: enter one of {}.".format(allowable_actions)) action = input() return int(action) def main(): """Plays pong with the keyboard.""" parser = argparse.ArgumentParser() parser.add_argument('--seed', type=int, default=0) args = parser.parse_args() seed = args.seed tf.set_random_seed(seed) np.random.seed(seed) random.seed(seed) env = atari_env.gen_pong_env(args.seed) _obs = env.reset() env.render() done = False while not done: act = _read_action_from_stdin() _obs, _reward, done, _info = env.step(act) env.render() if __name__ == "__main__": main()
820a9b5b77d2b353208cd495992dc0702de1c1bf
i1196689/GitPython
/python_exercise/day_11.py
746
3.609375
4
#敏感词文本文件 filtered_words.txt,里面的内容 和 0011题一样,当用户输入敏感词语,则用 星号 * 替换,例如当用户输入「北京是个好城市」,则变成「**是个好城市」。 import os s=input("intput:") filePath="D:\\test\\" fileName=os.listdir(filePath) with open(filePath+fileName[0],encoding="utf-8")as f: context=f.readlines() #去掉空格 def Rep(st): return st.replace("\n","") #代替*的数量 def Rep_num(num): a="" for ss in range(num): a+="*" return a context_new=list(map(Rep,context)) ss=s.replace("input:","") for i in range(len(context_new)) : sss=ss.replace(context_new[i-1],Rep_num(len(context_new[i-1]))) aims=sss ss=aims print(sss)
b092ee0df9f4c49676af20b90191cdfd3a331798
BenYanez/Yanez_Ben
/PYLESSON_03/RudeAI.py
845
4
4
name = input("What is your name?") print(name , "?!! Why would anyone name a baby that?") old = input("How old are you,Ben?") print(old , "Oooooo!!! 14 is getting up there.") fun = input("What do you do for fun, Ben?") print(fun , "? I thought only nerds like to play soccer?") music = input("What kind of music do you like?") print(music , "? Boooo!!! I wouldn't wish the sound of rap on my worst enemy.") siblings = input("How many siblings do you have?") print(siblings , "? Wow, I hope the rest of your family is better looking.") grow = input("What do you want to be when you grow up?") print(grow , "? I think you'd have to be stronger to be a Pro_Soccer_Player.") print("So Ben, you're 14... You like to play soccer and listen to Rap... Good luck becoming a Pro_Soccer_Player. I'm only kidding Ben.")
1413a0848d7548cf3e353307c6d1a562c86f44de
shivamnamdeo0101/Pyhton_OOPS
/OOP_8_Ques.py
314
3.78125
4
class Simple(): def __init__(self,value): self.value = value def add_to_value(self,amount): print("{} Added To Your Account".format(self.value)) self.value = self.value +amount myobj = Simple(300) myobj.value myobj.add_to_value(300) print("Your Current Balance Is : ",myobj.value) print(myobj.value)
5d2101c72d077a2ece51c28dd0fad958f2618c03
WinCanton/PYTHON_CODE
/SumSquareDifference/sum_square_diff.py
173
3.671875
4
# setup a list containing the first 100 natural numbers numbers = range(1,101,1) # calculate the difference diff = sum(numbers)**2 - sum([x*x for x in numbers]) print diff
875fd11b9edbcf975c9f18ffab2f60e98a7fdffb
jambran/elite_speak
/models/define.py
1,793
3.625
4
from PyDictionary import PyDictionary from models import words def generate_definitions(word_list, lemmatizer): """ Gets dictionary definitions for passed words. Only deals with nouns, verbs, adjectives, and adverbs as there aren't really any other types with "obscure" lexical items. Uses PyDictionary for lookup """ defs = {} # dict of words and their definitions (specific to part of speech) dictionary = PyDictionary() # Just gets the broad POS (i.e. we don't care if its a plural or singular noun) for word, pos in word_list: if pos.startswith('NN'): # Noun part = 'Noun' elif pos.startswith('VB'): # Verb part = 'Verb' elif pos.startswith('JJ'): # Adjective part = 'Adjective' elif pos.startswith('RB'): # Adverb part = 'Adverb' else: continue try: #Lemmatizes word to (hopefully) have better getting correct POS lemmatized_word = words.lemmatize(word, lemmatizer) definitions = dictionary.meaning(lemmatized_word) # given that POS_Tagger tags words, if the POS is not found for that word, grabs the first ("default") one if not part or part not in definitions: part = list(definitions.keys())[0] defs[lemmatized_word] = { 'pos': part, 'def': definitions[part][0] } except TypeError: continue return defs def parse_speakable_definitions(definitions): """ Formats the definitions to be handled by a TTS engine """ words = dict(definitions) definitions = [word + ": " + words[word]['pos'] + ": " + words[word]['def'] for word in words] return definitions
b00889eacd46136d3832062f93f5afc3900b5013
itscrisu/pythonPractice
/Ejercicios/listaDeEjercicios.py
2,608
4.125
4
# Multiplicar dos números sin usar el símbolo de multiplicación a = 2 b = 8 resultado = 0 for x in range(a): resultado += b print(resultado) # Ingresar un nombre y apellido e imprimelo al revés nombre = 'Cristian' apellido = 'Dominguez' ambos = nombre + ' ' + apellido print(ambos[::-1]) # Intercambiando valores: nombre = 'Crisu' apellido = 'Damins' nombre, apellido = apellido, nombre print(nombre) print(apellido) # Escribir una función que encuentre el elemento menor de una lista lista = [1, 4, 7, 13, 44, 24, -30] menor = 'inicial' for x in lista: if menor == 'inicial': menor = x else: menor = x if x < menor else menor print('El número menor es', menor) # Escribir una función que devuelva el volumen de una esfera por su radio # 4/3 * pi * r ** 3 def calculaVolumen(r): return 4/3 * 3.14 * r ** 3 resultado = calculaVolumen(6) print(resultado) # Escribir una función que indique si el usuario es mayor de edad def esMayor(usuario): return usuario.edad > 17 class Usuario: def __init__(self, edad): self.edad = edad usuario = Usuario(15) usuario2 = Usuario(21) usuario3 = Usuario(17) resultado1 = esMayor(usuario) resultado2 = esMayor(usuario2) resultado3 = esMayor(usuario3) print(resultado1, resultado2, resultado3) # Escribir una función que indique si el número ingresado es par o impar def esPar(n): return n % 2 == 0 resultado = esPar(10) resultado2 = esPar(3) resultado3 = esPar(11) resultado4 = esPar(14) print(resultado) print(resultado2) print(resultado3) print(resultado4) # Escribir una funcion que indique cuantas vocales tiene una palabra: palabra = 'Cristian' vocales = 0 for x in palabra: y = x.lower() vocales += 1 if x == 'a' or x == 'e' or x == 'i' or x == 'o' or x == 'u' else 0 print(vocales) # escribir una app que reciba una cantidad infinita de n° hasta decir basta, luego que # devuelva la suma de los n° ingresados lista = [] print('Ingrese numeros y para salir escriba "basta"') while True: valor = input('Ingrese un valor: ') if valor == 'basta': break else: try: valor = int(valor) lista.append(valor) except: print('Dato no válido') exit() resultado = 0 for x in lista: resultado += x print(resultado) # escriba una funcion que reciba un nombre y un apellido y los vaya agregando a un archivo def nameToFile(nombre, apellido): c = open('nombreCompleto.txt', 'a') c.write(nombre + ' ' + apellido + '\n') c.close() nameToFile('Cristian', 'Dominguez')
c5cf8a111f3e83fa96f1343bc8b3efa6836bcdb2
malayh/neural_network
/randomTest.py
103
3.78125
4
x=[3*a for a in range(0,10)] for c,i in reversed(list(enumerate(x))): print("{} {}".format(c,i))
fd4fc12f7cd9b3160191d174f55483d4553ffba0
jiangliu2u/PythonCoreLearn
/LearnDaemon.py
567
3.640625
4
import threading from time import ctime, sleep def loop1(): print('start loop1 func at:',ctime()) sleep(5) print('end loop1 hhhhh') def loop2(): print('star loop2 func at:',ctime()) sleep(2) print('end loop2') def main(): threads = [] t1 = threading.Thread(target=loop1) t1.setDaemon(True) threads.append(t1) t2 = threading.Thread(target=loop2) threads.append(t2) for i in range(2): threads[i].start() #for i in range(2):#等待所有线程结束,加了这个也会等待守护线程结束 # threads[i].join() if __name__=='__main__': main()
0e5b0ac41f8fb927a2fb999c6cb98ab5bc871cad
ranggamd/Simulasi-Dadu_Rangga-Mukti
/Dadu.py
709
3.78125
4
import random putaran= {} def putardadu(min, max): while True: print("Memutar Dadu.....") angka = random.randint(min, max) if angka in putaran: putaran[angka] +=1 else: putaran[angka] =1 print(f"Kamu Dapat Angka : {angka}") choice = input("Apakah anda ingin memutar dadu lagi (y/n)?") if choice.lower() == 'n' or choice.lower() == 'N': for angka in putaran: print("Angka", str(angka), "di dapat sebanyak", str(putaran[angka]), "kali.") if choice.lower() == 'y' or choice.lower() == 'Y': choice=False else: break putardadu(1,6)
d2aab00a704ac0ab7bd23e82331e9a8c9dc7ff23
mak131/Pandas
/3.csv/5.how to write in csv file in pandas (prefix) parameter v6.py
1,089
4.09375
4
import pandas as pd df = pd.read_csv("E:\\code\\Pandas\\3.csv\\Bill_details23.csv") print(df) print() # this method is used to change header using header parameter # if none header change to string header # so this method is used both parameter header and prefix but Header =None prefix_data = pd.read_csv("E:\\code\\Pandas\\3.csv\\Bill_details23.csv",header=None,prefix="Data") print(prefix_data) print() # this method is used to change header using header parameter # if none header change to string header # so this method is used both parameter header and prefix but Header =None prefix_col = pd.read_csv("E:\\code\\Pandas\\3.csv\\Bill_details23.csv",header=None,prefix="Columns") # this method all col name same print(prefix_col) print() # this method is used to change header using header parameter # if none header change to string header # so this method is used both parameter header and prefix but Header =None prefix_col = pd.read_csv("E:\\code\\Pandas\\3.csv\\Bill_details23.csv",header=None,prefix="Columns") # this method all col name same print(prefix_col) print()
6c76aeb69324ac2db3bd37c9c82c95cf5e6db9f0
SixuLi/Leetcode-Practice
/Second Session(By Frequency)/994. Rotting Oranges.py
926
3.671875
4
# Solution 1: BFS # Time Complexity: O(mn) # Space Complexity: O(mn) in the worst case from collections import deque class Solution: def orangesRotting(self, grid: List[List[int]]) -> int: queue = deque() m, n = len(grid), len(grid[0]) level = 0 for r in range(m): for c in range(n): if grid[r][c] == 2: queue.append((r, c, level)) directions = [[-1, 0], [1, 0], [0, -1], [0, 1]] while queue: r, c, level = queue.popleft() for d in directions: nr, nc = r + d[0], c + d[1] if 0 <= nr < m and 0 <= nc < n and grid[nr][nc] == 1: grid[nr][nc] = 2 queue.append((nr, nc, level + 1)) for i in range(m): for j in range(n): if grid[i][j] == 1: return -1 return level
9d79d51d832f0f97c03990c05b2ae62e9f57a6fc
carden-code/python
/stepik/old_problem.py
449
3.625
4
# There is 100 rubles. # How many bulls, cows and calves can be bought with all this money if the payment for # a bull is 10 rubles, for a cow - 5 rubles, for a calf - 0.5 rubles and you need to buy 100 head of cattle? # # Note. Use a nested for loop. bull = 10 cow = 5 calf = 0.5 for i in range(1, 100): for j in range(1, 100): for k in range(1, 100): if bull * i + cow * j + calf * k == 100: print(i, j, k)
4973420e7b132def09cfedfa6cdae3c4b5a971fe
macinspiresedu/python
/programs/rot13.py
328
4.03125
4
text = input("Please enter what you want me to translate: ") result = '' for c in text: if c >= 'a' and c <= 'z': result += chr(((ord(c) - ord('a') + 13) % 26) + ord('a')) elif c >= 'A' and c <= 'Z': result += chr(((ord(c) - ord('A') + 13) % 26) + ord('A')) else: result += c print (result)
8a4ea9ea9c8aaaca9de6c7ae32eff346f8144c22
kim-soohan/2018_PythonStudy
/PythonBasicAlgorithm/p03_3_1.py
753
3.703125
4
# -*- coding: utf-8 -*- #n명 중 두 명을 뽑아 짝을 짓는다고 할 때, #짝을 지을 수 있는 모든 조합을 출력하는 알고리즘을 만드시오 #예를 들어 "Tom", "Jerry", "Mike" 라면 Tom - Jerry / Tom - Mike / Jerry - Mike def bindPerson(a): n = len(a) for i in range(0, n-1): for j in range(i+1, n): if a[i] != a[j]: print(a[i],"-", a[j]) name = ["A", "B", "C", "D", "E", "F"] print(bindPerson(name)) # def bindPerson(a): # n = len(a) # result = set() # for i in range(0, n-1): # for j in range(i-1, n): # if a[i] != j[i]: # result.add(a[i],a[j]) # return result # # name = ["Tom", "Jerry", "Mike"] # print(bindPerson(name))
7aa73f4c3be5943ee43f5d8976882969deee1099
AnastasiiaPosulikhina/Python_course
/lab4/lab_04_07.py
5,817
3.65625
4
class Row: id = 1 # идентификатор строки def __init__(self, collection, value): self.id = Row.id Row.id += 1 self.collection = collection # список значений переменных для текущего значения функции self.value = value # значение функции def display(self): # вывод таблицы на экран line = "" for i in self.collection: line += str(i) + " " return str(self.id) + " " + line + "| " + str(self.value) class Table: def __init__(self, rowsNum): self.rowsNum = rowsNum # количество строк таблицы self.rows = list() # список объектов класса Row def addRow(self, row): # добавление строки (объект row класса Row) в список for i in self.rows: if i.id == row.id: print("Ошибка: в списке уже находится строка с таким же идентифиатором!") break self.rows.append(row) def setRow(self, row): # изменение строки (объект row класса Row) for i in range(0, len(self.rows)): if self.rows[i].id == row.id: self.rows[i] = row return else: print("Ошибка: в списке нет строки с таким же идентифиатором!") def getRow(self, rowId): # получение строки c идентификатором for i in range(0, len(self.rows)): if self.rows[i].id == rowId: return self.rows[i] def display(self): # вывод таблицы на экран line = "id x1 x2 x3 f(x1,x2,x3)\n" for i in range(0, len(self.rows)): line += str(self.rows[i].display()) + "\n" return line class LogicFunction: def __init__(self, variablesNum, table): self.variablesNum = variablesNum # количество переменных функции self.table = table # таблица истинности логической функции def getExpression(self): # вычислние и возвращение минимальной формулы логической функции. def minimal(mass): counter = [0] * (len(mass) - 1) # список, состоящий из количества различий между значениями переменных, при которых значение функции равно единице mass_index = [0] * (len(mass[0])) # список, состоящий из индексов переменных, значения которых в таблице истинности отличаются одной 1 или одним 0 for i in range(0, len(mass) - 1): # сравнение строк таблицы истинности, значение функции в которых равно 1 for j in range(len(mass[i])): if mass[i][j] != mass[i + 1][j]: counter[i] += 1 mass_index[i] = j for i in range(len(counter)): # удаление строки, отличающейся от других строк на одно значение if counter[i] == 1: del mass[i] for i in range(len(mass_index) - 1): if mass_index[i] == 0: mass_index.remove(mass_index[i]) if len(mass) < len(counter): counter.remove(counter[1]) for i in range(0, len(mass)): # '*' - обозначение элемента строки, который был отличен у двух строк for j in range(len(mass[i])): if j == mass_index[i] and counter[i] == 1: mass[i][j] = '*' return mass znach = list() for i in self.table.rows: # создание списка значений переменных, при которых значение функции равно единице if i.value == 1: znach.append(i.collection) print("Значения переменных, при которых значение функции равно единице: ", znach) k = minimal(znach) counter_k = [0] * (len(k) - 1) for i in range(0, len(k) - 1, 2): for j in range(len(k[i])): if k[i][j] != k[i + 1][j]: counter_k[i] += 1 for i in range(len(counter_k)): if counter_k[i] == 1: znach = minimal(k) res = "" # минимальная формула j = -1 for i in znach: # создание минимальной формулы if j != -1: res += "+" for j in range(0, len(i)): if i[j] != "*": if i[j] == 1: res += "x" + str(j + 1) else: res += '"x' + str(j + 1) return res def getTable(self): return self.table def printTable(self): print(str(self.table)) table = Table(8) table.addRow(Row([0, 0, 0], 1)) table.addRow(Row([0, 0, 1], 1)) table.addRow(Row([0, 1, 0], 0)) table.addRow(Row([0, 1, 1], 0)) table.addRow(Row([1, 0, 0], 1)) table.addRow(Row([1, 0, 1], 1)) table.addRow(Row([1, 1, 0], 0)) table.addRow(Row([1, 1, 1], 0)) print(table.display()) l = LogicFunction(3, table) print("Минимальная формула логической функции: ", l.getExpression())
78cd87c5b8cf572d54fcc7c451626aa800c8fffe
Deekshaesha/Python
/maths/factorial_python.py
85
3.828125
4
n = int(input("Enter a number")) s = 1 for i in range(1,n+1): s*=i print (s)
aee0990db5d58b8a412d602b02641a26ac57eef3
cmanny/expert-octo-garbanzo
/mathematics/fundamentals/find_point.py
223
3.578125
4
import sys def find_point(px, py, qx, qy): return (2*qx - px, 2*qy - py) if __name__ == "__main__": n = int(input()) for _ in range(n): print(" ".join(map(str, find_point(*map(int, input().split())))))
390841c12e02773b297f12f5beabc0cfdab274d9
Spartabariallali/Pythonprograms
/pythonSparta/Listsparta.py
724
4
4
#lists #manage data #access data #add, remove data # syntax variable = [] , () = tuple, dictionary {key:value} pairs #tuples are immutable # guestlist = ["Muhammed Ali","Mike Tyson", "Tyson Fury","Don King"] # print(guestlist[3]) # guestlist[3] = "Roy Jones jr" # replaced the data at index 3 with the new data # print(guestlist) # guestlist.append("Vasyl lomachenko") # guestlist.append("Don King") # print(guestlist) # guestlist.remove("Don King") # print(guestlist) # guestlist.pop() # print(guestlist) # guestlist.insert(4,"Vasyl Lomachenko") # print(guestlist) mix_type_string = [[1,2,3,], ["One","two","three"]] print(mix_type_string) string_list = ["One","two","three"] int_list = [1,2,3,] mixed_list = (string_list + int_list) print(mixed_list)
268e753e855e3df702576f318cd4c17a00cbec9f
charlesats/curso_python
/pythonExercicios/ex022.py
1,173
3.84375
4
# Elabore um programa que calcule o valor a ser pago por um produto, # considerando o seu preço normal e condição de pagamento: # # – à vista dinheiro/cheque: 10% de desconto # # – à vista no cartão: 5% de desconto # # – em até 2x no cartão: preço formal # # – 3x ou mais no cartão: 20% de juros# print('=-=' * 5, 'Lojas do Charlin', '=-=' * 5) valor = float(input('Valor das compras: ')) print('Forma de Pagamento\n[1] - À vista no dinheiro\n[2] - À vista no cartão\n[3] - 2 x no cartão\n[4] - 3 x no cartão') opcao = int(input('Digite uma opção: ')) if opcao == 1: total = valor - (valor * 0.1) print('O valor total a ser pago é: R${:.2f}'.format(total)) elif opcao == 2: total = valor - (valor * 0.05) print('O valor total a ser pago é: R${:.2f}'.format(total)) elif opcao == 3: parcela = valor / 2 print('O valor de R${:.2f} será pago em 2 x R${:.2f}'.format(valor,parcela)) elif opcao == 4: total = valor + (valor * 0.2) parcela = total / 3 print('O valor de R${:.2f}, com 20% de juros, será pago em 3 x R${:.2f}'.format(total, parcela)) else: print('Opção incorreta, tente novamente!') print('=-=' * 16)
58bcb93d45999ce3d86221e6acb7d2c49e80113a
thelmuth/cs110-spring-2019
/review_turtle.py
575
4
4
import turtle, math def main(): t = turtle.Turtle() t.fillcolor("coral") t.begin_fill() t.up() t.backward(150) t.down() height = math.sqrt(60 ** 2 - 30 ** 2) for _ in range(2): t.forward(300) t.left(90) t.forward(height) t.left(90) t.end_fill() t.left(60) t.fillcolor("blue") t.begin_fill() for _ in range(5): t.forward(60) t.right(120) t.forward(60) t.left(120) t.end_fill() turtle.mainloop() main()
fef6da3597d671e772702a7f5506dfeb61e125c5
Mauricio-Amr/TF_Faculdade
/LIST_PLP_01/05.py
639
4.03125
4
''' ----------------------------------------------------------------- UNIVERSIDADE PAULISTA - ENG COMPUTAÇÃO - BACELAR Nome: Mauricio Silva Amaral RA : D92EJG-0 Turma : CP6P01 Data: 09/10/2021 Lista: 01 - 05 Enunciado: 05 – Escreva um programa que calcule a soma de três variáveis e imprima o resultado na tela. ----------------------------------------------------------------- ''' var1 = float(input("Entre com o primeiro valor : ")) var2 = float(input("Entre com o segundo valor : ")) var3 = float(input("Entre com o teceiro valor : ")) soma = var1 + var2 + var3 print(f'A soma das variaveis é {soma: .1f}')
093383cec9e0d92911b52647584352b452cd5161
hartnetl/unitTest-lessons
/refactor-lesson/test_evens.py
995
4.03125
4
import unittest from evens import even_number_of_evens class TestEvens(unittest.TestCase): # Remember test names MUST start with the word test # Keep them related def test_throws_error_if_value_passed_in_is_not_list(self): # assertRaises is a method from TestCase and when ran will check if a # TypeError has been raised when the function is called with a value # of 4 self.assertRaises(TypeError, even_number_of_evens, 4) def test_values_in_list(self): # Returns false if empty list is passed in self.assertEqual(even_number_of_evens([]), False) # Returns true if even number of evens is sent self.assertEqual(even_number_of_evens([2, 4]), True) # Fails when one even number is sent self.assertEqual(even_number_of_evens([2]), False) # Fails when no even numbers are sent self.assertEqual(even_number_of_evens([1, 3, 5]), False) if __name__ == "__main__": unittest.main()
02c925ced562e543ce1dcd98ec15bd5884b134f4
ajmathews/Algorithms-Python
/LinkedListPalindrome.py
1,150
3.890625
4
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def isPalindrome(self, head): """ :type head: ListNode :rtype: bool """ fast = head slow = head while fast is not None and fast.next is not None: fast = fast.next.next slow = slow.next if fast is not None: slow = slow.next rever = self.reverse(slow) while rever is not None: if rever.val != head.val: return False rever = rever.next head = head.next return True def reverse(self, head): rev = None prev = None while head is not None: rev = ListNode(head.val) rev.next = prev prev = rev head = head.next return rev testSol = Solution() test = ListNode(1) test.next = ListNode(2) test.next.next = ListNode(3) test.next.next.next = ListNode(1) test.next.next.next.next = ListNode(1) print(testSol.isPalindrome(test))
4f5d9b68529998efef5e51b2f724735a81fe1237
sandrews98/400B_Andrews
/Homeworks/Homework5/CenterOfMass.py
14,462
3.5625
4
# Homework 4 # Center of Mass Position and Velocity # Samantha Andrews #2/9/20 ############################################################################### # Keep in mind this is just a template; you don't need to follow every step and feel free to change anything. # We also strongly encourage you to try to develop your own method to solve the homework. ############################################################################### # import modules import numpy as np import astropy.units as u from ReadFile import Read import math class CenterOfMass: # Class to define COM position and velocity properties of a given galaxy # and simulation snapshot def __init__(self, filename, ptype): # Initialize the instance of this Class with the following properties: # read data in the given file using Read self.time, self.total, self.data = Read(filename) #create an array to store indexes of particles of desired Ptype self.index = np.where(self.data['type'] == ptype) #print("Index = ", self.index) # store the mass, positions, velocities of only the particles of the given type # the following only gives the example of storing the mass self.m = self.data['m'][self.index] self.x = self.data['x'][self.index] #print("x[0-4]",self.x[0],self.x[1],self.x[2],self.x[3],self.x[4]) # print(self.x) # print("Length of x",len(self.x)) self.y = self.data['y'][self.index] self.z = self.data['z'][self.index] self.vx = self.data['vx'][self.index] self.vy = self.data['vy'][self.index] self.vz = self.data['vz'][self.index] #self refers to quantities that are common to the object #each function created must start with self as an input def comp_mag(self,x,y,z): #fucntion to compute magnitude given the coordinates (x,y,z) in kpc # from the center of the mass position # NONE OF THESE VALUES ARE GLOBAL FOR THE CLASS SO I AM NOT USING SELF IN FRONT OF THEM #initialize mag=0 #Compute mag mag=math.sqrt(x**2+y**2+z**2) #Returen the mag return mag def COMdefine(self,a,b,c,m): # Function to compute the center of mass position or velocity generically # input: array (a,b,c) of positions or velocities and the mass # returns: 3 floats (the center of mass coordinates) #values not global for the class so not using self in front of them # write your own code to compute the generic COM using Eq. 1 in the homework instructions # xcomponent Center of mass Acom = np.sum(np.multiply(a,m))/np.sum(m) # ycomponent Center of mass Bcom = np.sum(np.multiply(b,m))/np.sum(m) # zcomponent Center of mass Ccom = np.sum(np.multiply(c,m))/np.sum(m) #print("Acom", Acom, "Bcom", Bcom, "Ccom", Ccom) return Acom, Bcom, Ccom def COM_P(self, delta): # Function to specifically return the center of mass position and velocity # input: # particle type (1,2,3) # delta (tolerance) decides whether the COM position has converged # returns: One vector, with rows indicating: # 3D coordinates of the center of mass position (kpc) # Center of Mass Position ########################### # Try a first guess at the COM position by calling COMdefine #goal is to refine the COM position calc iteratively to make sure the position has converged XCOM, YCOM, ZCOM = self.COMdefine(self.x, self.y, self.z, self.m) # compute the magnitude of the COM position vector. #when referring to functions already defined in class use self.function RCOM = self.comp_mag(XCOM, YCOM, ZCOM) #print("First RCOM", RCOM) # iterative process to determine the center of mass # change reference frame to COM frame # compute the difference between particle coordinates # and the first guess at COM position # subtract first guess COM position from partivle position xNew = self.x - XCOM yNew = self.y - YCOM zNew = self.z - ZCOM #create an array to store the mag of the new position vecors of all # particles in the COM frame RNEW = np.sqrt(xNew**2 + yNew**2 + zNew**2) #sanity check # print("xNew", xNew) # print("yNew", yNew) # print("zNew", zNew) # print("first value", np.sqrt(xNew[0]**2 + yNew[0]**2 + zNew[0]**2)) # print("RNEW", RNEW) # find the max 3D distance of all particles from the guessed COM # will re-start at half that radius (reduced radius) RMAX = max(RNEW)/2.0 #print(f"RMax = {RMAX}") # pick an initial value for the change in COM position # between the first guess above and the new one computed from half that volume # it should be larger than the input tolerance (delta) initially CHANGE = 1000.0 #[kpc] # start iterative process to determine center of mass position # delta is the tolerance for the difference in the old COM and the new one. while (CHANGE > delta): #delta is the tolerance # select all particles within the reduced radius (starting from original x,y,z, m) #runs as long as the difference btw RCOM and a new COM position # is larger than some tolerance (delta) # write your own code below (hints, use np.where) index2 = np.where(RNEW < RMAX) """ #show that indexing is narrowing in sync print("New loop through while") print("RNew = ", RNEW) print("RMax = ", RMAX) print("index2 = ", index2) print("RNEW[0-4] = ", RNEW[index2][0], RNEW[index2][1], RNEW[index2][2], RNEW[index2][3], RNEW[index2][4]) """ x2 = self.x[index2] y2 = self.y[index2] z2 = self.z[index2] m2 = self.m[index2] #Check values are narrowing """ print("Len x2", len(x2)) print("x2[0-4]", x2[0], x2[1], x2[2], x2[3], x2[4]) print("y2[0-4]", y2[0], y2[1], y2[2], y2[3], y2[4]) print("z2[0-4]", z2[0], z2[1], z2[2], z2[3], z2[4]) print("m2[0-4]", m2[0], m2[1], m2[2], m2[3], m2[4]) """ # Refined COM position: # compute the center of mass position using # the particles in the reduced radius # write your own code below XCOM2, YCOM2, ZCOM2 = self.COMdefine(x2, y2, z2, m2) #print("Xcom2", XCOM2, "Ycom2", YCOM2, "Zcom2", ZCOM2) # compute the new 3D COM position # write your own code below RCOM2 = self.comp_mag(XCOM2, YCOM2, ZCOM2) #print(f"new COM magnitude = {RCOM2}") # determine the difference between the previous center of mass position # and the new one. CHANGE = np.abs(RCOM - RCOM2) # uncomment the following line if you wnat to check this #print ("CHANGE = ", CHANGE) # Before loop continues, reset : RMAX, particle separations and COM # reduce the volume by a factor of 2 again RMAX = RMAX/2.0 # check this. #print ("maxR", maxR) # Change the frame of reference to the newly computed COM. # subtract the new COM # write your own code below xNew = self.x - XCOM2 yNew = self.y - YCOM2 zNew = self.z - ZCOM2 RNEW = np.sqrt(xNew**2 + yNew**2 + zNew**2) #new array of magnitudes for new from of reference COM #print("RNEW", RNEW) #refine volume again #RMAX = RMAX/2. #print("RMAX", RMAX) # set the center of mass positions to the refined values XCOM = XCOM2 YCOM = YCOM2 ZCOM = ZCOM2 RCOM = RCOM2 # create a vector to store the COM position #COMP = [XCOM, YCOM, ZCOM] # set the correct units usint astropy and round all values # and then return the COM positon vector # write your own code below COMP = np.around([XCOM, YCOM, ZCOM], 2)*u.kpc return COMP def COM_V(self, COMX,COMY,COMZ): # Center of Mass velocity # input: X, Y, Z positions of the COM # returns 3D Vector of COM Velocities # the max distance from the center that we will use to determine the center of mass velocity RVMAX = 15.0*u.kpc # determine the position of all particles relative to the center of mass position # write your own code below xV = self.x - COMX yV = self.y - COMY zV = self.z - COMZ RV = np.sqrt(xV**2 + yV**2 + zV**2) # determine the index for those particles within the max radius # write your own code below indexV = np.where(RV < RVMAX.value) # determine the velocity and mass of those particles within the mas radius # write your own code below vxnew = self.vx[indexV] vynew = self.vy[indexV] vznew = self.vz[indexV] mnew = self.m[indexV] # compute the center of mass velocity using those particles # write your own code below VXCOM, VYCOM, VZCOM = self.COMdefine(vxnew, vynew, vznew, mnew) # create a vector to store the COM velocity # set the correct units usint astropy # round all values # write your own code below COMV = np.around([VXCOM, VYCOM, VZCOM], 2)*u.km/u.s # return the COM vector return COMV # ANSWERING QUESTIONS ####################### # Create a Center of mass object for the MW, M31 and M33 # below is an example of using the class for MW MWCOM = CenterOfMass("MW_000.txt", 2) # now write your own code to answer questions #QUESTION 1: # below gives you an example of calling the class's functions # MW: store the position and velocity COM MW_COMP = MWCOM.COM_P(0.1) print("MW_COMP", MW_COMP) MW_COMV = MWCOM.COM_V(MW_COMP[0].value,MW_COMP[1].value,MW_COMP[2].value) print("MW_COMV", MW_COMV) #for M31 M31COM = CenterOfMass("M31_000.txt", 2) M31_COMP = M31COM.COM_P(0.1) print("M31_COMP", M31_COMP) M31_COMV = M31COM.COM_V(M31_COMP[0].value, M31_COMP[1].value, M31_COMP[2].value) print("M31_COMV", M31_COMV) #for M33 M33COM = CenterOfMass("M33_000.txt", 2) M33_COMP = M33COM.COM_P(0.1) print("M33_COMP", M33_COMP) M33_COMV = M33COM.COM_V(M33_COMP[0].value, M33_COMP[1].value, M33_COMP[2].value) print("M33_COMV", M33_COMV) #QUESTION 2: #What is the mag of the current separation and velocity between MW and M31? sep = MW_COMP - M31_COMP mag_sep = np.sqrt(sep[0]**2 + sep[1]**2 + sep[2]**2) print(f"The magnitude fo the separation between MW and M31 is {mag_sep}") velocity = MW_COMV - M31_COMV mag_velocity = np.sqrt(velocity[0]**2 + velocity[1]**2 + velocity[2]**2) print(f"The magnitude of the velocity between MW and M31 9s {mag_velocity}") #QUESTION 3: #What is the magnitude of the current separation and velocity between M33 and M31? sep = M33_COMP - M31_COMP mag_sep = np.sqrt(sep[0]**2 + sep[1]**2 + sep[2]**2) print(f"The magnitude fo the separation between MW and M31 is {mag_sep}") velocity = M33_COMV - M31_COMV mag_velocity = np.sqrt(velocity[0]**2 + velocity[1]**2 + velocity[2]**2) print(f"The magnitude of the velocity between MW and M31 9s {mag_velocity}") #QUESTION 4: #It is important to use the iterative process for this system because # MW and M31 are about to collide so there will be a lot of changes # to the distribution of the mass. It is important to have the disk movements # since the halo will move around. We need to know the center of the stars, # and the iterative process allows us to do that.
db209d1295e7fd3279e1889876fdb533fdd39c9e
jguardado39/A-Kata-A-Day
/Python/find_short.py
854
4.375
4
def find_short(s): """ Simple, given a string of words, return the length of the shortest word(s). String will never be empty and you do not need to account for different data types. """ text_array = s.split() shortest_word = len(text_array[0]) for i in range(1,len(text_array)): if len(text_array[i]) < shortest_word: shortest_word = len(text_array[i]) return shortest_word print(find_short("bitcoin take over the world maybe who knows perhaps")) # 3 print(find_short("turns out random test cases are easier than writing out basic ones")) # 3 print(find_short("lets talk about javascript the best language")) # 3 print(find_short("i want to travel the world writing code one day")) # 1 print(find_short("Lets all go on holiday somewhere very cold")) # 2
e94e3658282b9f6b67a6773d2ae3efb0e98c3de0
sherlocklock666/shuzhifenxi_python
/第一章上机程序/chapter1_17_2.py
174
3.546875
4
j = 2 N = 10**2#从2到N S_N = 0 S_N_list = []#S_N的每次输出值列表 while j <= N: M = 1/(N**2-1) S_N = S_N + M S_N_list.append(S_N) N -= 1 else: print(S_N_list)
ec07d64f6b8f58db398e0149ac81b799ea7736f7
Kevin-Howlett/edabit-problems
/sum_dig_prod.py
482
4.125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Dec 28 19:16:54 2019 @author: kevinhowlett """ #Function that takes numbers as arguments, adds them together, and #returns the product of digits until the answer is only 1 digit long def sum_dig_prod(*argv): num = 0 for arg in argv: num += arg while len(str(num)) != 1: new_num = 1 for digit in str(num): new_num *= int(digit) num = new_num return num
2ca368fb3ab88a17a73b001f7e23c20fcf578d56
point800411/YZU_python
/Lesson03/Cass 03.py
297
4
4
# 函式(有回傳值) def add(x, y): sum = (x + y) * 1.03 return sum # 函式(無回傳值) def addAndPrint(x, y): sum = (x + y) * 1.03 print(sum) return print(((1 + 2) * 1.03)) print(((2 + 5) * 1.03)) print(add(1, 2)) print(add(2, 5)) addAndPrint(1, 2) addAndPrint(2, 5)
3388cc6602ea2e03f7014158903e9791c57bd4b2
ShashankRaturi/Python-Projects
/3_Hirst Painting/src/Other patterns/shapes.py
428
3.875
4
import turtle as t import random from color import random_color t.colormode(255) tur = t.Turtle() tur.shape('turtle') ################# different shapes ########### def shape(num_of_sides): angle = 360 / num_of_sides for i in range(num_of_sides): tur.forward(100) tur.right(angle) for i in range(3 , 11): tur.color(random_color()) shape(i) screen = t.Screen() screen.exitonclick()
77e1ca633a92d9a27c09a72dfa410c3acee5c4e4
Rauldsc/ExercisesPython
/basic1/ex68.py
202
3.90625
4
""" Write a Python program to calculate the sum of the digits in an integer. """ def digits(num): n = str(num) sum = 0 for i in n: sum += int(i) return sum print(digits(18145))
c44893d9901e49d83bc76e229de4ed79c226ee7c
Gabriel-Coutinho0/Lista-1
/EX 1.py
70
3.703125
4
a = int(input('Número: ')) b = int(input('Número: ')) print (a + b)
e7b526b28cac9b19848978082fe9ccf11c808514
pablogonz/programas-lorenzo
/FactorialIterativo/FactorialIterativo.py
236
4.28125
4
# Factorial forma iterativo n= int(input(" introduzca un numero que desea sacarle factorial ")) def Factorial(n): factor = 1 for i in range(factor, n + 1): factor = factor * i return factor print(Factorial(n))
5e78ed1cdcac1c2396702a6e5ddbcf11af7fff94
draganmoo/trypython
/Python_Basic/list/generator_4_multiconcurrent.py
3,128
3.765625
4
import time """ 通过生成器进行单线程下的并发 故事是这样的: 三个消费者一个生产者 生产者生产包子给三个消费者吃 """ def consumer(name): print('消费者%s准备吃包子啦~~'% name ) while True: baozi = yield print('消费者%s接收到包子编号%s'%(name,baozi)) """注意: 此时并没有调用consumer函数,虽然用consumer(),但其实是赋值给了一个变量 只有这个变量后面加小括号或者指令,才是真正调用这个函数""" c1 = consumer('consumer_1') c2 = consumer('consumer_2') c3 = consumer('consumer_3') """注意: 不要忘记给生成器的第一个值必须是是空值""" c1.__next__() c2.__next__() c3.__next__() for i in range(10): print('-----------------生产出了第%s批包子------------------'% i) c1.send(i) c2.send(i) c3.send(i) """ return: 消费者consumer_1准备吃包子啦~~ 消费者consumer_2准备吃包子啦~~ 消费者consumer_3准备吃包子啦~~ -----------------生产出了第0批包子------------------ 消费者consumer_1接收到包子编号0 消费者consumer_2接收到包子编号0 消费者consumer_3接收到包子编号0 -----------------生产出了第1批包子------------------ 消费者consumer_1接收到包子编号1 消费者consumer_2接收到包子编号1 消费者consumer_3接收到包子编号1 -----------------生产出了第2批包子------------------ 消费者consumer_1接收到包子编号2 消费者consumer_2接收到包子编号2 消费者consumer_3接收到包子编号2 -----------------生产出了第3批包子------------------ 消费者consumer_1接收到包子编号3 消费者consumer_2接收到包子编号3 消费者consumer_3接收到包子编号3 -----------------生产出了第4批包子------------------ 消费者consumer_1接收到包子编号4 消费者consumer_2接收到包子编号4 消费者consumer_3接收到包子编号4 -----------------生产出了第5批包子------------------ 消费者consumer_1接收到包子编号5 消费者consumer_2接收到包子编号5 消费者consumer_3接收到包子编号5 -----------------生产出了第6批包子------------------ 消费者consumer_1接收到包子编号6 消费者consumer_2接收到包子编号6 消费者consumer_3接收到包子编号6 -----------------生产出了第7批包子------------------ 消费者consumer_1接收到包子编号7 消费者consumer_2接收到包子编号7 消费者consumer_3接收到包子编号7 -----------------生产出了第8批包子------------------ 消费者consumer_1接收到包子编号8 消费者consumer_2接收到包子编号8 消费者consumer_3接收到包子编号8 -----------------生产出了第9批包子------------------ 消费者consumer_1接收到包子编号9 消费者consumer_2接收到包子编号9 消费者consumer_3接收到包子编号9 """
2a1801df465d749be78efd3978b199678429f211
bakunobu/exercise
/1400_basic_tasks/chap_5/5_87.py
283
3.796875
4
def find_nums(a: int) -> list: nums = [] for _ in range(3): num = a % 10 a //= 10 nums.append(num) return(nums) def count_nums(a:int=100, b:int=500) -> int: nums = [x for x in range(a, b+1) if sum(find_nums(x)) == 15] return(len(nums))
376e04dab7ff683d3d109da713f1732885be91a7
VanJoyce/Algorithms-Data-Structures-and-Basic-Programs
/Trie.py
11,959
4.09375
4
""" Vanessa Joyce Tan 30556864 Assignment 3 """ class Node: """ Node class for the Trie. """ def __init__(self): """ Creates a node with a list of links for every lowercase English alphabet character and a terminal character, and frequency. :time complexity: best case and worst case are both O(1) because no matter what, it takes the same amount of time to create a node. :space complexity: O(1) because space is fixed for every node :aux space complexity: O(1) """ self.link = [None] * 27 self.freq = 0 class Trie: """ Trie class to store strings. """ def __init__(self, text): """ Creates a Trie object containing the strings in text. :param text: a list of strings :pre-condition: the strings in text must only consist of lowercase English alphabet characters and there are no empty strings :post-condition: Trie object is created with the strings in text Assuming T is the total number of characters over all the strings in text, :time complexity: best case and worst case are both O(T) because each word is inserted into the Trie and the time complexity of __setitem__ depends on the number of characters in the word :space complexity: O(T) because a node exists for each character over all strings :aux space complexity: O(T) """ self.root = Node() for word in text: self.__setitem__(word) def __setitem__(self, key): """ Inserts a string into the Trie. :param key: the string to be inserted into the Trie. :return: - :pre-condition: key has to be in lowercase English alphabet characters :post-condition: key is stored in Trie Assuming N is the number of characters in key, :time complexity: best case and worst case are both O(N) because time complexity of setitem_aux() is O(N) :space complexity: O(N) because setitem_aux() has O(N) space complexity :aux space complexity: O(N) """ current = self.root current.freq += 1 self.setitem_aux(current, key) def setitem_aux(self, current, key, pos=0): """ Recursive function to insert a string into the Trie. Creates a node it if doesn't exist yet for each character in the string and one for the terminal character. If a node already exists, increase its frequency. :param current: the current Node :param key: the string to be inserted into the Trie :param pos: iterator for key to know which character is being inserted :return: - :pre-condition: key has to be in lowercase English alphabet characters :post-condition: if node exists for character in key, the frequency is updated. If it doesn't exist, a node is created Assuming N is the number of characters in key, :time complexity: best case and worst case are both O(N) because each recursive call is O(1) and this method is called for every character in key :space complexity: O(N) because each node takes O(1) space and this method is called for each character in key :aux space complexity: O(N) """ if pos >= len(key): # end of string index = 0 else: index = ord(key[pos]) - 96 if current.link[index] is None: current.link[index] = Node() current.link[index].freq += 1 if index == 0: # end recursion return else: self.setitem_aux(current.link[index], key, pos + 1) def string_freq(self, query_str): """ Checks how many times a given word occurs in the Trie. :param query_str: the word we are looking for :return: an integer representing how many times the word appears in the Trie :pre-condition: query_str consists of lowercase English alphabet letters only :post-condition: nothing is changed in Trie Assuming q is the number of characters in query_str, :time complexity: best case is O(1) when the first letter of query_str doesn't exist in Trie and worst case is O(q) when we check for nodes the characters in query_str is pointing to :space complexity: O(1) because we only look at one node at a time in search() :aux space complexity: O(1) """ word = self.search(query_str) if word is not None and word.link[0] is not None: return word.link[0].freq else: return 0 def prefix_freq(self, query_str): """ Checks how many words in the Trie has a given prefix. :param query_str: the prefix to look for in the Trie :return: an integer representing how many words have the the given prefix in Trie :pre-condition: query_str must only consist of lowercase English alphabet letters :post-condition: no changes made to Trie Assuming q is the number of characters in query_str, :time complexity: best case is O(1) when the first letter of query_str is not found in the Trie and worst case is O(q) where we look at the nodes each character in query_str is pointing to :space complexity: O(1) because we only look at one node at a time in search() :aux space complexity: O(1) """ prefix = self.search(query_str) if prefix is None: return 0 else: return prefix.freq def search(self, query_str): """ Searches for a string in the Trie and returns the node the last letter of the string is pointing to if it exists. :param query_str: the string we are searching for in the Trie :return: the node the last letter of query_str is pointing to if it exists, otherwise None :pre-condition: query_str must only consist of lowercase English alphabet characters :post-condition: nothing is changed in Trie Assuming q is the number of characters in query_str, :time complexity: best case is O(1) when the node the first letter points to doesn't exist and worst case is O(q) because we must check the nodes for each character in query_str :space complexity: O(1) because we only look at one node at a time :aux space complexity: O(1) """ current = self.root for letter in query_str: index = ord(letter) - 96 if current.link[index] is not None: current = current.link[index] else: return None return current def wildcard_prefix_freq(self, query_str): """ Checks for strings in the Trie that have a given prefix with a wildcard. :param query_str: the given prefix with a wildcard :return: a list of strings that have a prefix matching query_str :pre-condition: query_str must not be an empty string, wildcard character must be represented by the char '?', all other characters in query_str besides the wildcard must be in lowercase English alphabets :post-condition: the list returned contains strings that have prefixes that matches the query_str Assuming q is the number of characters in query_str, S is the number of characters in all the strings in the Trie which have the matching prefix, :time complexity: best case is O(1) if the first letter of query_str doesn't even exist in the Trie and worst case is O(q + S) when we call the auxiliary function recursively to get all the strings which have the matching prefix Assuming N is the length of the longest word in output and M is the size of output so far, :space complexity: O(N + M) because auxiliary function has this space complexity :aux space complexity: O(N + M) """ current = self.root output_str = "" for pos in range(len(query_str)): if current is None: # prefix doesn't even exist in Trie return [] if query_str[pos] == '?': return self.wildcard_prefix_freq_aux(current, query_str, pos, output_str, []) else: output_str += query_str[pos] current = current.link[ord(query_str[pos]) - 96] def wildcard_prefix_freq_aux(self, current, query_str, pos, output_str, output): """ Recursive function to check for strings in the Trie that have a given prefix with a wildcard. :param current: the node we are checking currently :param query_str: the given prefix with a wildcard :param pos: iterator for query_str to know which character in query_str we are looking at currently :param output_str: string which has the given prefix :param output: list of strings found in Trie which contain the given prefix :return: a list of strings that contain the given prefix :pre-condition: the wildcard must be represented by the character '?'. If query_str has any other characters besides the wildcard, they must be lowercase English alphabet characters. query_str cannot be an empty string :post-condition: output contains all the strings that have the given prefix so far in Trie Assuming q is the number of characters in query_str, S is the total number of characters in the strings that have the given prefix, :time complexity: best case is O(1) when the node the first letter is pointing to doesn't exist, and worst case is O(q + S) because we have to check through all the nodes where the characters in query_str and the other strings that have the matching prefix point to Assuming N is the length of the longest word in output and M is the size of output so far, :space complexity: O(N + M) because it depends on output list and how deep the recursion goes, and each recursive call only looks at one node which takes O(1) space and the recursion only goes as deep as the length of the longest word that contains the given prefix :aux space complexity: O(N) because output is passed as a parameter """ if current is None: return # doesn't exist, go back if pos < len(query_str): # prefix if query_str[pos] == '?': for i in range(1, len(current.link)): if current.link[i] is None: continue self.wildcard_prefix_freq_aux(current.link[i], query_str, pos+1, output_str + chr(i+96), output) else: i = ord(query_str[pos]) - 96 self.wildcard_prefix_freq_aux(current.link[i], query_str, pos+1, output_str + query_str[pos], output) else: # suffix if current.link[0] is not None: # output_str is a word that has the prefix for i in range(current.link[0].freq): # for duplicate strings output.append(output_str) for i in range(1, len(current.link)): if current.link[i] is None: continue self.wildcard_prefix_freq_aux(current.link[i], query_str, pos, output_str + chr(i+96), output) return output
1358e576ef240044c338df3be473d78745aa8d32
Aasthaengg/IBMdataset
/Python_codes/p03624/s532165923.py
212
3.84375
4
s_list = list(input()) result = None for s_uni in range(ord('a'), ord('z') + 1): if not chr(s_uni) in s_list: result = chr(s_uni) break if result: print(result) else: print('None')
2ea137ab340db7d78dcc252370f0b5b60639401d
ash6327/SQLite3beginner
/sql3.py
815
4.09375
4
import sqlite3 conn = sqlite3.connect('Movies.db') cur = conn.cursor() cur.execute('''CREATE TABLE IF NOT EXISTS movie (movie_name TEXT, movie_actor REXT,movie_actress TEXT, movie_year INTEGER,movie_director TEXT)''' ) movies = [ ('Mr robot','Rami Malek','Carly Chaikin','2015','Sam Ishmail'), ('Kuruti','Roshan Mathew','srindaa','2021','Anish Pallyall'), ('Nadodikkattu','Mohan Lal','Shobana','1987','Sathyan Anthikad'), ('Pattanapravesham','Sreenivasan','Shobana','1988','Sathyan Anthikad'), ('The social network','Jesse Eisenberg','Brenda Song','2010','David Fincher') ] cur.executemany("INSERT INTO movie VALUES (?,?,?,?,?)",movies) conn.commit() for row in cur.execute('''SELECT * FROM movie'''): print(row) a=input('Enter actor name:') cur.execute(f"SELECT * FROM movie WHERE movie_actor LIKE '{a}'") print(cur.fetchone()) conn.close()
d2151f2507379face1da3fc2267f36581ea36bfa
vsikarwar/Algorithms
/Graph/Graph.py
1,645
3.515625
4
''' Created on Mar 9, 2016 @author: sikarwar ''' class Graph: def __init__(self, nodes=0): self.n = set(range(nodes)) self.g = {} self.e = set() self.w = {} def add(self, a, b, weight): self.g.setdefault(a, []) self.g[a].append(b) edge = (a, b) self.e.add(edge) self.w.setdefault(edge, 0) self.w[edge] = weight def weight(self, f, t, order=True): if self.w[(f, t)] is not None: return self.w[(f, t)] if order is False: if self.w[(t, f)] is not None: return self.w[(t, f)] return 0 def addEdge(self, f, t, w=0, undirected=False): self.add(f, t, w) self.n.add(f) self.n.add(t) if undirected: self.add(t, f, w) def hasNode(self, idx): if idx in self.n: return True return False def hasEdge(self, frm, to, weight = 0, order=True): if order and (frm, to, weight) in self.e: return True if order is False and ((frm, to, weight) in self.e or (to, frm) in self.e): return True return False def print(self): print(self.g) def size(self): return len(self.n) def nodes(self): return self.n def edges(self): return self.e def edges_size(self): return len(self.e) def children(self, idx): if idx not in self.g: return [] return self.g[idx] def children_size(self, idx): return len(self.g[idx]) def graph(self): return self.g
90c529c6af8cf5dabca846a2c9f10def5e3b3798
teenageknight/Python-Beginner-Projects
/Random/Sydney/solution.py
188
4
4
number1 = int(input("What is the first number?\n")) number2 = int(input("What is the second number?\n")) sum = number1 + number2 print("The sum of", number1, "and", number2, "is", sum)
ecbb445f7610eecb78b7b9a8e48cf86f65e81225
shubham14/Coding_Contest_solutions
/DS-Algo/quicksort.py
603
3.921875
4
# -*- coding: utf-8 -*- """ Created on Sat Sep 8 14:27:20 2018 @author: Shubham """ import numpy as np def Quicksort(A, start, end): if (start < end): p = Partition(A, start, end) Quicksort(A, start, p-1) Quicksort(A, p+1, end) def Partition(A, start, end): i = start - 1 pivot = A[end] for j in range(start, end): if A[j] < pivot: i += 1 # swapping elements A[i], A[j] = A[j], A[i] A[end], A[i+1] = A[i+1], A[end] return (i+1) A = [1,5,3,8,9,6] Quicksort(A, 0, len(A)-1) print (A)
fb4925921f17f7c7b8bfa4ffd6f7198cc7a59e0a
JamesPiggott/Python-Software-Engineering-Interview
/Multithreading/Multithreading.py
786
4.0625
4
''' Multi-threading. This is the Python implementation of Multi-threading. Running time: ? Data movement: ? @author James Piggott. ''' import time import threading threads = [2] def printsomething(): print("Starting: ",threading.current_thread().getName()) time.sleep(2) print("Exiting: ", threading.current_thread().getName()) if __name__ == "__main__": try: print("Now Thread-1 will be created") threadone = threading.Thread(name="Thread-1", target=printsomething()) threads.append(threadone.start()) print("Now Thread-2 will be created") threadtwo = threading.Thread(name="Thread-2", target=printsomething()) threads.append(threadtwo.start()) except: print("Error: unable to start thread")
25c59fc2724d26b6f94da86d4b166b536568378a
JerryZhuzq/leetcode
/Tree/105. Construct Binary Tree from Preorder and Inorder.py
1,481
3.765625
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode: if not preorder: return None root = TreeNode(preorder[0]) store = {key: value for value, key in enumerate(inorder)} def helper(root, preorder, inorder): # print(root.val, preorder, inorder) if len(preorder) <= 1: return None t = store[preorder[0]] - store[inorder[0]] # print(t) if t == 0: root.left = None node = TreeNode(preorder[1]) root.right = node helper(node, preorder[1:], inorder[1:]) elif t == len(preorder) - 1: root.right = None node = TreeNode(preorder[1]) root.left = node helper(node, preorder[1:t + 1], inorder[:t + 1]) else: left_node = TreeNode(preorder[1]) root.left = left_node right_node = TreeNode(preorder[t + 1]) root.right = right_node helper(left_node, preorder[1:t + 1], inorder[:t]) helper(right_node, preorder[t + 1:], inorder[t + 1:]) helper(root, preorder, inorder) return root
8c98f464e41ab55ffbb6b88020d8f6806ea5695d
jdbr827/ProjectEuler
/ProjectEulerProblem56.py
375
3.703125
4
""" Project Euler Problem 56 Considering natural numbers of the form a^b, where a, b < 100, what is the maximal digit sum? """ def digit_sum(n): return sum([ord(i) - ord("0") for i in str(n)]) def solve(): best = 0 for a in range(1, 100): for b in range(1, 100): this = digit_sum(a**b) if best < this: best = this return best print solve()
389c53c753cea4596d97e5bfdfc983635be81a2c
cesarsst/PythonProjects
/PythonTeste/Aula09a.py
2,126
4.15625
4
# Manipulando Texto em Python frase = 'Curso em Video Python' # Fatiamento print(frase) print(frase[9]) # Pega a 9 letra da cadeia de caracteres da variavel frase print(frase[9:14]) # Pega do 9 até o 14 (mas vai até o 13, para de conta do 14) print(frase[9:21]) # Apesar de nao existir 21, ele pega só até o 20 print(frase[9:21:2]) # Pega do 9 ao 20 pulando de 2 em 2 espaços print(frase[:5]) # Pega do inicio até o valor 4 (5-1) print(frase[15:]) # Pega do 15 até o final print(frase[9::3]) # Pega do 9 até o final pulando de 3 em 3 # Análise print(len(frase)) # Mostra o comprimento da variavel print(frase.count('o')) # Conta quantas vezes a letra 'o' está presente print(frase.count('o',0,13)) # Contagem já com fatiamento entre o espaço 0 e 12 print(frase.find('deo')) # Mostra a posição em que começou a string que procura frase.find('Android') # Como não existe, retorna o valor -1 'Curso' in frase # Dentro da frase existe 'curso'? True or False # Transformação frase.replace('Python','Android') # Substitui x por y frase.upper() # Deixa tudo em maiusculo frase.lower() # Deixa em minusculo frase.capitalize() # Joga todos caracteres em minusculo, e só o primeiro fica em maiusculo frase.title() # Analisa qts palavras existem, e faz um capitalize em todos frase.strip() # Remove espaços inuteis no inicio e final da string frase.rstrip() # Remove espaços inuteis somente do lado direito frase.lstrip() # Remove espaços inuteis a esquerda # Divisao frase.split() # Onde tiver espaço, vai dividir em outras string recebendo uma nova indexação, gera uma nova lista # Junção '-'.join(frase) # Junta todas as frases,antes separadas, separados por -
f21e2a814f72493d12a75ffe06b81b590d9a5882
yhxddd/python
/阶乘.py
217
3.546875
4
def jiecheng(n): result= n for i in range(1,n): result *= i return result number = int (input("输入一个整数:")) rel = jiecheng(number) print("%d 的阶乘是:%d" %(number,rel))
03528ffb2adde11fbadee01ce1a9906f90f8a7e0
SinglePIXL/CSM10P
/Testing/8-26-19 Lecture/twoNames.py
252
4.28125
4
# We get two names from the user # Then we write them in alphabetical order name1 = input('Enter the first name: ') name2 = input('Enter the second name: ') if name1 < name2: print(name1) print(name2) else: print(name2) print(name1)
da98fdbce014d046498f48662c3ab0eca555f0e8
neasatang/CS3012
/test/directedAcyclicGraph.py
3,656
3.5
4
import sys class DAG(object): # prints graph #def print_graph(self, graph): # print(graph) # prints the nodes from a list from graph #def print_node_list(self,list): # print(list) # create empty set for nodes for the DAG def __init__(self): self.create_graph() # creates empty dict def create_graph(self): self.graph = {} # add node to set def add_node(self, node, graph=None): if not graph: graph = self.graph if node in graph: return False graph[node] = [] # add edge to set def add_edge(self, ind_node, dep_node, graph=None): if not graph: graph = self.graph # if both nodes exist in the graph if ind_node in graph and dep_node in graph: graph[ind_node].append(dep_node) else: raise KeyError("One or both nodes do not exist") # function that does DFS def DFS(self, node_list, graph, node): if not graph[node]: return True else: for child in graph[node]: if child not in node_list: node_list.append(child) #Add to list that stores the route if not self.DFS(node_list, graph, child): return False node_list.remove(child) else: return False return True # wrapper for DFS function def DFSWrapper(self, graph): result = True for node in graph: if not self.DFS([node], graph, node): result = False break return result # wrapper for calculating the LCA using DFS - similar to DFS() but modified code to get LCA to work def LCA_DFS_Wrapper(self, graph, nodeA, nodeB): global node_A_list node_A_list = [] global node_B_list node_B_list = [] #gets the node routes for each node and stores them into a list for node in graph: self.LCA_DFS([node], graph, node, 1, nodeA) self.LCA_DFS([node], graph, node, 2, nodeB) lowest_count = sys.maxsize for itemA in node_A_list: for itemB in node_B_list: count = 0 # count increments per route until node is found for index, node1 in enumerate(reversed(itemA)): count = index for node2 in reversed(itemB): if node1 == node2 and count < lowest_count: # LCA is the one with the lowest count LCANode = node2 lowest_count = count return LCANode count += 1 # calculates the DFS for an LCA node def LCA_DFS(self, node_list, graph, node, index, end_node): if node == end_node: # distinguish between the two routes using index if index == 1: node_A_list.append(node_list[:]) elif index == 2: node_B_list.append(node_list[:]) return True if not graph[node]: return True else: for child in graph[node]: if child not in node_list: node_list.append(child) # appends child node to correct node list using the index parameter if not self.LCA_DFS(node_list, graph, child, index, end_node): return False node_list.remove(child) else: return False return True
5dee320d1fd1a2d3215ae0d2594695be7e5639a6
bikramjitnarwal/CodingBat-Python-Solutions
/Logic-2.py
3,759
4.03125
4
# make_bricks: # We want to make a row of bricks that is goal inches long. We have a number of small bricks (1 inch each) and big # bricks (5 inches each). Return True if it is possible to make the goal by choosing from the given bricks. This is # a little harder than it looks and can be done without any loops. def make_bricks(small, big, goal): big_needed = min(big, goal // 5) return goal - (big_needed * 5) <= small # lone_sum: # Given 3 int values, a b c, return their sum. However, if one of the values is the same as another of the values, # it does not count towards the sum. def lone_sum(a, b, c): sum = a+b+c if a == b: if a == c: sum -= 3 * a else: sum -= 2 * a elif b == c: sum -= 2 * b elif a == c: sum -= 2 * a return sum # lucky_sum: # Given 3 int values, a b c, return their sum. However, if one of the values is 13 then it does not count towards the # sum and values to its right do not count. So for example, if b is 13, then both b and c do not count. def lucky_sum(a, b, c): array = [a, b, c] sum = 0 i = 0 while i < len(array) and array[i] != 13: sum += array[i] i += 1 return sum # no_teen_sum: # Given 3 int values, a b c, return their sum. However, if any of the values is a teen -- in the range 13..19 # inclusive -- then that value counts as 0, except 15 and 16 do not count as a teens. Write a separate helper # "def fix_teen(n):"that takes in an int value and returns that value fixed for the teen rule. In this way, you # avoid repeating the teen code 3 times (i.e. "decomposition"). Define the helper below and at the same indent level # as the main no_teen_sum(). def no_teen_sum(a, b, c): a = fix_teen(a) b = fix_teen(b) c = fix_teen(c) return a + b + c def fix_teen(n): # checks if n is a teen if 13 <= n <= 19: # checks if n is 15 or 16 but checking if it is found in the set # if True then leave n as it is if n in {15, 16}: n = n return n # if it fails then n = 0 else: n = 0 return n # if n is not in the teens return it as is return n # round_sum: # For this problem, we'll round an int value up to the next multiple of 10 if its rightmost digit is 5 or more, so 15 # rounds up to 20. Alternately, round down to the previous multiple of 10 if its rightmost digit is less than 5, so 12 # rounds down to 10. Given 3 ints, a b c, return the sum of their rounded values. To avoid code repetition, write a # separate helper "def round10(num):" and call it 3 times. Write the helper entirely below and at the same indent level # as round_sum(). def round_sum(a, b, c): return round10(a) + round10(b) + round10(c) def round10(num): n = num % 10 if (n >= 5): return (num - n + 10) else: return (num - n) # close_far: # Given three ints, a b c, return True if one of b or c is "close" (differing from a by at most 1), while the other # is "far", differing from both other values by 2 or more. Note: abs(num) computes the absolute value of a number. def close_far(a, b, c): return (is_close(a, b) and is_far(a, b, c)) or (is_close(a, c) and is_far(a, c, b)) def is_close(a, b): return abs(a - b) <= 1 def is_far(a, b, c): return abs(a - c) >= 2 and abs(b - c) >= 2 # make_chocolate: # We want make a package of goal kilos of chocolate. We have small bars (1 kilo each) and big bars (5 kilos each). # Return the number of small bars to use, assuming we always use big bars before small bars. Return -1 if it can't be # done. def make_chocolate(small, big, goal): maxBig = goal / 5 if big >= maxBig: if small >= (goal - maxBig * 5): return goal - maxBig * 5 if big < maxBig: if small >= (goal - big * 5): return goal - big * 5 return -1
552e90db821481db33782fbf212ba1911574660a
Hrocio/Python-Programs
/palindrome.py
851
4.40625
4
def word_palindrome(word): '''Function which return reverse of a string. It also works with numbers. any string containing just one letter is by default a palindrome. ''' if len(word) < 2: # Can be less than 2. return True if word[0] != word[-1]: # Comparing input string with the reverse string. return False return word_palindrome(word[1:-1]) def main(): '''This function determines whether the user's input is a palindrome. the string is taken as an input, reversed, and then tested. ''' user_input = (input("Enter a word: ")) # It ignores if its uppercase or lowercase. if word_palindrome(user_input.upper()) == 1: print(user_input, 'is a palindrome') else: print(user_input, 'is not a palindrome') if __name__ == '__main__': # Main. main()
43c6c043624d3f86127bcd0ab897ee7295dd9681
chelseashin/My-Algorithm
/daily_study/ProblemSolving/7490_0만들기.py
1,033
3.53125
4
# 자연수 N의 범위(3 <= N <= 9)가 매우 한정적이므로 완전탐색으로 문제 해결 # 수의 리스트와 연산자 리스트를 분리하여 모든 경우의 수를 계산(재귀함수 이용) # 파이썬의 eval() 함수를 이용하여 문자열 형태의 표현식을 계산할 수 있다. import copy def solve(arr, n): if len(arr) == n: # 가능한 모든 경우 연산자 리스트에 담기 opLSt.append(copy.deepcopy(arr)) return arr.append(' ') solve(arr, n) arr.pop() arr.append('+') solve(arr, n) arr.pop() arr.append('-') solve(arr, n) arr.pop() T = int(input()) for _ in range(T): N = int(input()) opLSt = [] solve([], N-1) numLst = [i for i in range(1, N + 1)] for op in opLSt: temp = "" for i in range(N-1): temp += str(numLst[i]) + op[i] temp += str(numLst[-1]) if eval(temp.replace(" ", "")) == 0: # 계산 결과가 0이라면 print(temp) print()
b832a8dbf51c93f41c244dcdcded6ce8e7c09542
abonybear/my-python-learning-journal
/a4/4-3.py
114
3.5
4
nums = [num for num in range(1, 21)] print(nums) nums = list(range(1, 1000000)) print(nums) print(sum(nums))
adc4cdc018101b7382d3c6ec6481c99800d126b5
AakSin/CS-Practical-FIle
/Reference/Lab Reference/list worksheet/Q5.py
1,115
3.953125
4
l=eval(input("Enter a list")) print("what do u want to do","Add=0","modify=1","delete=2","sort=3","display=4","exit=5",sep="\n") a=int(input()) while a!=5: if a==0: b=int(input("what do u want to add")) l.append(b) print(l) elif a==1: c=eval(input("what do u want to add")) d=int(input("where do u want to add")) l[d]=c print(l) elif a==2: e=int(input("what do u want to delete")) l.remove(e) print(l) elif a==3: print("in which order do u want to sort","ascending=1","descending=2",sep="\n") f=int(input()) if f==1: l.sort() print(l) elif f==2: l.sort(reverse=True) print(l) else: print("you can't follow simple instructions huh!!") elif a==4: print(l) elif a==5: break else: print("you can't follow simple instructions huh!!") print("what do u want to do","Add=0","modify=1","delete=2","sort=3","display=4","exit=5",sep="\n") a=int(input())
85907ce4488e8972e66a3619b3d4bc274eb4c2de
TalhaBhutto/Ciphers
/Network Security/RouteCipher.py
1,213
3.90625
4
def encrypt(Data,key): l=len(Data) l2=0 temp="" num=0 while((l/key)%1): l=l+1 Data=Data+"X" col=int(l/key) while(l2<l): temp=temp+Data[(l2%key)*col+num] l2=l2+1 if(l2%key==0): num=num+1 return temp def decrypt(Data,key): l=len(Data) l2=0 num=0 temp="" col=int(l/key) while(l2<l): temp=temp+Data[(l2%col)*key+num] l2=l2+1 if(l2%col==0): num=num+1 return temp def Encryption(): #data=input("Enter a message for encryption: ") #A=int(input("Enter the KEY : ")) data="WEARESTUDYINGANDTRYINGTOUNDERSTANDTRANSPOSITIONCIPHERS" A=4 print("The encrypted message is:\n"+encrypt(data,A)) def Decryption(): #data=input("Enter a message for decryption: ") #A=int(input("Enter the KEY : ")) data="WNRIEDSTATTIRRAOEYNNSIDCTNTIUGRPDTAHYONEIUSRNNPSGDOXAESX" A=4 print("The decrypted message is:\n"+decrypt(data,A)) print("Made by group # 4\nNoman Ahmed 42\nTalha Hussain 51") key=input("Press 1 for Encrypther and any other key for decryption : ") temp="" if(key=="1"): Encryption() else: Decryption()
69138ee2f67046683fcd2c347946f898fe7dd68e
avinash-rao/Python
/mean_median_mode.py
630
4.125
4
print("Enter the numbers: ") nums = [] n = 0 # to store the length of nums while True: num = input() if num == '': break nums.append(int(num)) n += 1 nums.sort() # Find out mean mean = sum(nums)/n # Find out median if n % 2 == 0: #If total number of elements is even median = (nums[(n//2)-1] + nums[n//2])/2 else: #If total number of elements is odd median = nums[n//2] # Find out mode tupleNums = tuple(nums) mode = tupleNums[0] for i in tupleNums: if nums.count(i) > mode: mode = i # Display M3 print(mean) print(median) print(mode)
767af29611bf05af512b6ff16abf582d2a96605d
DebasishMohanta/turtle
/practice/Georgias_Spiral_trial.py
442
4
4
import turtle wn=turtle.Screen() wn.bgcolor("black") tina=turtle.Turtle() tina.shape("turtle") tina.pensize(2) def draw_circle(x): for i in range(60,120,x): tina.speed(0) tina.circle(i) def draw_special(x): for _ in range(10): draw_circle(x) tina.rt(36) colors=["white","yellow","blue","orange","pink"] x=10 for color in colors: tina.color(color) draw_special(x) x+=3 turtle.mainloop()
1fa7a74cb60d2df344c9b163342659fc67cee298
patkennedy79/picture_video_file_organizer
/PictureVideoFileOrganizer/DirectoryWithDateSubfolders.py
3,548
4.34375
4
from os import listdir, mkdir, chdir from os.path import isfile, join, isdir from shutil import copy2 from string import replace from Directory import Directory from File import File """ Purpose: This class defines a directory that contains any number of directories that are named by date that will be copied from this directory to a destination directory. For example, this would be the structure of the directory: - digital_camera_files -- 2015_01_01 -- 2015_01_02 -- 2015_01_03 -- 2015_01_07 ... Attributes: directory_path: path of this directory destination_directory: directory where the file will be attempted to be copied to without the trailing '/' files: list of Files that are contained in this directory Note: - The directories that are passed into the Constructor can either have a trailing '/' or not. Within the Constructor, there is a check to ensure that a trailing '/' is included in the directory string. """ class DirectoryWithDateSubfolders(object): # Constructor def __init__(self, directory_path, picture_destination_directory, movie_destination_directory): self.directory_path = File.check_directory_name(directory_path) self.picture_destination_directory = File.check_directory_name(picture_destination_directory) self.movie_destination_directory = File.check_directory_name(movie_destination_directory) self.directories = [ folder for folder in listdir(self.directory_path) if isdir(join(self.directory_path,folder)) ] self.directories.sort() self.file_count = 0 self.files_copied = 0 self.files_not_copied = 0 self.files_with_date_found = 0 self.files_without_date_found = 0 def print_details(self): print " Directory details:" print " Directory path: %s" % self.directory_path print " Picture Destination directory: %s" % self.picture_destination_directory print " Movie Destination directory: %s" % self.movie_destination_directory print " Number of directories in directory: %s" % len(self.directories) print " Number of files in directory: %s" % self.file_count print " Files copied: %d, Files not copied: %d (sum: %d)" % (self.files_copied, self.files_not_copied, (self.files_copied + self.files_not_copied)) print " Files with date found: %d, Files without date found: %d (sum: %d)" % (self.files_with_date_found, self.files_without_date_found, (self.files_with_date_found + self.files_without_date_found)) def copy_files_to_destination_directory(self): for current_folder_original in self.directories: if current_folder_original.lower().startswith('20'): current_dir = Directory((self.directory_path + current_folder_original), self.picture_destination_directory, self.movie_destination_directory) current_dir.copy_files_to_destination_directory() current_dir.print_details self.file_count += len(current_dir.files) self.files_copied += current_dir.files_copied self.files_not_copied += current_dir.files_not_copied self.files_with_date_found += current_dir.files_with_date_found self.files_without_date_found += current_dir.files_without_date_found
ceeb4cbb0fe375017ad2ef6ed5908bc4b636be8e
rashmiiiiii/python-ws
/REGULAR EXPRESSION/re6.py
151
3.8125
4
import re data = "Learning- Python, is fun. Python_programming is, easy" data= re.sub(r"-|_|,|\s+"," ",data) data ==re.sub(r"\s+"," ",data) print(data)
4efccf79d7fc734d0e2e58aa6f9097eb69c46985
HAMDONGHO/USMS_Senior
/python3/python_Practice/rockScissorPaper.py
494
3.859375
4
import time, random print('play rock/scissor/paper') play = True while play: player = input('select : ') while (player != 'rock' and player != 'scissor' and player != 'paper'): player = input('select : ') computer = random.choice(['rock', 'scissor', 'paper']) time.sleep(1) if(player==computer): print('same') else: print(player) print(computer) userInput=input('retry? : ') if userInput=='n' : play=False
34d66e23792573a25fbe48906985d92c9a45ee17
xielongzhiying/python_test100
/61-80/69.py
362
3.828125
4
# -*- coding: UTF-8 -*- #有n个整数,使其前面各数顺序向后移m个位置,最后m个数变成最前面的m个数 n = int(input("n个数")) m = int(input("后移m位")) list = [] for i in range(n): list.append(input("data:")) print(list) for i in range(m): for j in range(n-m+1): list[i],list[i+j] = list[i+j],list[i] print(list)
86b242bcb4b4e3fb5e91fb76bb85cf1be2b314a7
jaylenw/helioseismology
/omegas/main.py
2,414
3.578125
4
from gamma1 import omegaP #importing omegaP fxn from gamma1 file from gamma1 import omegaGsquared # ' ' from gamma1 import omegaG # ' ' from plotting import plotomegaP #importing plotomegaP fxn from plotting file from plotting import plotomegaGsqrd # ' ' from plotting import plotomegaG # ' ' """ If using my mental model from quantum correctly and applying it to finding p and g modes of radial oscillations, 'n' is the energy mode (energy level). 'l' is the angular degree. The rotation splitting modes and angular degrees all depend on 'n'. """ #Below asking user for input on angular degree n = raw_input( "Please enter a number for the radial order: ") n = int(n) """In python 2.7, it is recommended to take user input using raw_input and then I'm converting the string into an int""" print "Energy mode is",n,"." #initializing lists for angular and splitting modes m_list = [] #splitting modes l_list = [] #angular modes omegaP_list = [] #omega for p modes omegaGsqrd_list = [] #omega squared for g modes omegaG_list = [] #omega for g modes #below we are building the angular energy mode for number in xrange(0, (n+1)): l_list.append(number) #adding numbers to list print "Angular degrees are...", "\n", l_list #below we are building the rotation splitting modes, 'm' , known as m for number in xrange((-1*n), (n+1)): m_list.append(number) #adding numbers to list print "Rotation splitting modes are...", "\n", m_list for number in xrange(0, (n+1)): #going to capture answer for omega l = l_list[number] #specific angular mode in the angular mode list omegaP_list.append(omegaP(n, l)) #building the omegaP_list omegaGsqrd_list.append(omegaGsquared(n, l)) #building the omegaGsquared_list omegaG_list.append(omegaG(omegaGsquared(n, l))) #building the omegaG list print "Omegas for a given 'n' that are p modes are...", "\n", omegaP_list print "Omega squared for a given 'n' that are g modes are...","\n", omegaGsqrd_list print "Omegas for a given 'n' that are g modes are...", "\n", omegaG_list """below using the plot functions in plotting.py to plot the angular degree list and the omega lists""" plotomegaP(l_list, omegaP_list) plotomegaGsqrd(l_list, omegaGsqrd_list) plotomegaG(l_list, omegaG_list)
5640b1a265006bffd381c46428859bf0c2dee58b
cyclades1/Python-Programs
/p8.py
86
3.828125
4
'''input 13 ''' n = int(input()) if(n%2==0): print("EVEN") else: print("ODD")
b1b9167d445bc301fd534a795c1aec1b3efe9c2f
ramyamango123/test
/python/python/src/python_problems/other_python_prob/regex_special_characters.py
487
3.703125
4
import re p = 'Python is a #scripting language edited new I am learning to? test it!' #x = 'Python is a #scripting language edited new\n', 'I am learning to? test it!' #pattern = re.search("(\w+)\s+(\w+)", p) #pattern = re.search("(.*)", p) pattern = re.search("(\w+.*)\#(\w+)\s+(.*)\?(\s+\w+\s+\w+)\!", p) result = pattern.group(1)+ pattern.group(2)+ " " + pattern.group(3) + pattern.group(4) print result #print pattern.group(1) + pattern.group(2) + pattern.group(3)
4638a95633b9dc9f06fcf18986efc796b06b3672
oreHGA/HomicideAnalysis
/sort_by_rel.py
1,549
3.796875
4
''' File name: homicide_year_sort.py @author: James Boyden Date created: 4/30/2017 Date last modified: 5/8/2017 Sorts the list by relation, and finds the most common relationship between the victim and perpatrator. ''' def sort_by_rel(homicide_array, outputLoc): myfile = open(outputLoc, "a") # list of relationship types relationshipList = ['Acquaintance', 'Unknown', 'Wife', 'Stranger', 'Girlfriend', 'Ex-Husband', 'Brother', 'Stepdaughter', 'Husband', 'Sister', 'Friend', 'Family', 'Neighbor', 'Father', 'In-Law', 'Son', 'Ex-Wife', 'Boyfriend', 'Mother', 'Common-Law Husband', 'Common-Law Wife', 'Stepfather', 'Stepmother', 'Daughter', 'Boyfriend/Girlfriend', 'Employer', 'Employee'] # create an array to track the number of times each relationship occurs relationship = [[x, 0] for x in relationshipList] # two for each loops to increase the count for each occurance of a specific relationship for homicide in homicide_array: for relations in relationship: if homicide.relationship == relations[0]: relations[1] += 1 # sort the list by the count variable relationship.sort(key=lambda x: x[1], reverse=True) # print the top five relationships for the perpatrator myfile.write("Top 5 relationships between the victim and perpatrator\n") for x in range(5): myfile.write(str(relationship[x])+"\n") myfile.close()
ceb40a98b541f4c4d4f57e4dc8f0b55fddbe1e77
JKThanassi/2016_Brookhaven
/matplotLibTest/scatter_plot.py
716
4.1875
4
#import matplotlib.pyplot as plt def scatter_plt(plt): """ This function gathers input and creates a scatterplot and adds it to a pyplot object :param plt: the pyplot object passed through :return: Void """ #list init x = [] y = [] #get list length list_length = int(input("How many data sets would you like to enter")) #get input for i in range(0, list_length): x.append(int(input("enter x var for dataset " + str(i)))) y.append(int(input("enter y var for dataset " + str(i)))) print() #create scatterplot plt.scatter(x, y, marker='*') plt.xlabel("x") plt.ylabel("y") plt.title("Test scatter plt") #plt.show(
8ad72e2a9edb6bdb75d24ad0199f2faa0c43d1aa
ponmanimanoharan/practice_files
/python-prac_till_functions/practice.py
8,743
4.28125
4
# Modify this program to greet you instead of the World! print("Hello, Ponmani Manoharan!") # Modify this program to print Humpty Dumpty riddle correctly print("\n") print("Humpty Dumpty sat on a wall,") print("Humpty Dumpty had a great fall.") print("All the king's horses and all the king's men") print("Couldn't put Humpty together again.") # Greet 3 of your classmates with this program, in three separate lines print("\n") print("Hello, Esther!") print("Hello, Mary!") print("Hello, Joe!") # Write a program that prints a few details to the terminal window about you print("\n") my_detials = ["Ponmani Manoharan", 23, 1.73] for x in my_detials: print(x) # Create a program that prints a few operations on two numbers: 22 and 13 print("\n") # Print the result of 13 added to 22 print(13+22) # Print the result of 13 substracted from 22 print(22-13) # Print the result of 22 multiplied by 13 print(22*3) # Print the result of 22 divided by 13 (as a decimal fraction) print(22/13) # Print the integer part of 22 divided by 13 print(22//13) # Print the remainder of 22 divided by 13 print(22 % 13) print("\n") # An average Green Fox attendee codes 6 hours daily # The semester is 17 weeks long # # Print how many hours is spent with coding in a semester by an attendee, # if the attendee only codes on workdays. # 5 workdays in one week work_days = 5 hours_spent = 6 weeks_of_work = 17 total_working_hours_workdays = work_days*hours_spent*weeks_of_work """print(total_working_hours_workdays) print(17*5)""" # 85 week days in 17 weeks # 1 days = 24 hours # working hours = 6 # 85*6 """print(85*6) print("if the attendee only codes on workdays and have spent 6 hours everyday for 17 weeks: Number of hours attended are 510 hours and Number of days 21.25")""" # Print the percentage of the coding hours in the semester if the average # work hours weekly is 52 average_work_hour = 17*52 percentage_of_coding_hrs_average = round(100*(total_working_hours_workdays/average_work_hour)) print(total_working_hours_workdays) print(percentage_of_coding_hrs_average) """print(5*6*17) print(17*52) print((510/884)*100)""" print("\n") fav_number = 8 print("my favourite number is : " + str(fav_number)) print("\n") a = 123 b = 526 print("original values : " + str(a),str(b)) temp = a a = b b = temp print("swapped values : " + str(a), str(b)) print("\n") print("Body Mass Index") massinkg = 81.2 heightinm = 1.78 BMI = massinkg/heightinm print("the Body mass index is : " + str(BMI)) # print body mass index based on these values print("\n") # Define several things as a variable then print their values name = "Ponmani Manoharan" # Your name as a string age = 23 # Your age as an integer height = 1.73 # Your height in meters as a float Married = False # Whether you are married or not as a boolean print(name,age,height,Married) print("\n") a = 3 a += 10 # make the "a" variable's value bigger by 10 print(a) b = 100 b -= 7 # make b smaller by 7 print(b) c = 44 c *= c # please double c's value print(c) d = 12 d /= 5 # please divide by 5 d's value print(d) e = 8 e = e**3 # please cube of e's value print(e) f1 = 123 f2 = 345 # tell if f1 is bigger than f2 (pras a boolean) print(f1>f2) g1 = 350 g2 = 200 print((g2*2) > g1) # tell if the double of g2 is bigger than g1 (pras a boolean) h = 1357988018575474 # tell if 11 is a divisor of h (pras a boolean) print(h%11 == 0) i1 = 10 i2 = 3 # tell if i1 is higher than i2 squared and smaller than i2 cubed (pras a boolean) print(i1 > (i2**2) < (i2**3)) j = 1521 # tell if j is divisible by 3 or 5 (pras a boolean) print(j%3 == 0 or j%5 == 0) print("\n") # Write a program that stores 3 sides of a cuboid as variables (float) # The program should write the surface area and volume of the cuboid like: # # Surface Area: 600 # Volume: 1000 l = 10.0 b = 10.0 h = 10.0 volume_of_cuboid = (l*b*h) Surface_area= 2 * (l*b+b*h+l*h) print("Volume : "+ str(volume_of_cuboid), "Surface Area : "+ str(Surface_area)) print("\n") current_hours = 14; current_minutes = 34; current_seconds = 42; # Write a program that prints the remaining seconds (as an integer) from a # day if the current time is represented by the variable total_seconds = 24*3600 past_seconds = (current_hours * 3600) + (current_minutes * 60) + current_seconds remaining_seconds = total_seconds - past_seconds print("The remaining seconds :" + str(remaining_seconds)) print("\n") # Modify this program to greet the user instead of the World! # The program should ask for the name of the user """user = input("Please enter your name : ") print("Hello, " + user + "!") print("\n") # miles to kilometer converter distance_in_miles = input("please enter distance in miles: ") convert_miles_to_kilometers = int(distance_in_miles) * 1.609344 print("The kilometer : " + str(convert_miles_to_kilometers)) print("\n") # Write a program that asks for two integers # The first represents the number of chickens the farmer has # The second represents the number of pigs owned by the farmer # It should print how many legs all the animals have chicken_owned = int(input("Enter the number of chickens owned : ")) pigs_owned = int(input("Enter the number of pigs owned : ")) if chicken_owned != 0: chicken_owned *= 2 print(chicken_owned) if pigs_owned != 0: pigs_owned *=4 print(pigs_owned)""" print("\n") # Write a program that asks for 5 integers in a row, # then it should print the sum and the average of these numbers like: # # Sum: 22, Average: 4.4 """five_int = [] for i in range(5): five_value = input("enter the five numbers : ") five_int.append(int(five_value)) print(five_int) sum_five = sum(five_int)/len(five_int) print(sum(five_int)) print(sum_five) """ print("\n") # Write a program that reads a number from the standard input, # Then prints "Odd" if the number is odd, or "Even" if it is even. """check_number = int(input("enter the number : ")) if check_number%2 == 0: print("even") else: print("odd")""" # Write a program that reads a number form the standard input, # If the number is zero or smaller it should print: Not enough # If the number is one it should print: One # If the number is two it should print: Two # If the number is more than two it should print: A lot """check_number = int(input("enter the number : ")) if check_number == 0 or check_number <= 0 : print("not enough") elif check_number == 1: print("One") elif check_number == 2: print("Two") else: print("A lot")""" # Write a program that asks for two numbers and prints the bigger one """num_one = int(input("enter number one : ")) num_two = int(input("enter number two : ")) if num_one > num_two : print("Number one is bigger ") elif num_one < num_two: print("Number two is bigger ") else: print("wrong input")""" # Write a program that asks for two numbers # The first number represents the number of girls that comes to a party, the # second the boys # It should print: The party is exellent! # If the the number of girls and boys are equal and there are more people coming than 20 # # It should print: Quite cool party! # It there are more than 20 people coming but the girl - boy ratio is not 1-1 # # It should print: Average party... # If there are less people coming than 20 # # It should print: Sausage party # If no girls are coming, regardless the count of the people """number_of_girls = int(input("enter the number of girls : ")) number_of_boys = int(input("enter the number of boys : ")) total_number_of_people = number_of_boys + number_of_girls if number_of_girls == number_of_boys: print("The party is exellent!") elif number_of_girls == 0: print("Sausage party") elif total_number_of_people > 20 and number_of_girls != number_of_boys: print("Quite cool party!") elif total_number_of_people < 20: print("Average party...")""" a = 24 out = 0 # if a is even increment out by one if a % 2 == 0: out += 1 print(out) b = 87 out2 = "" # if b is between 10 and 20 set out2 to "Sweet!" # if less than 10 set out2 to "Less!", # if more than 20 set out2 to "More!" if 10<b<20: out2 += "Sweet!" elif b<10: out2 += "Less!" elif b> 20: out2 += "More!" print(out2) c = 123 credits = 100 is_bonus = False # if credits are at least 50, # and is_bonus is false decrement c by 2 # if credits are smaller than 50, # and is_bonus is false decrement c by 1 # if is_bonus is true c should remain the same if credits >=50 and is_bonus == False: c -= 2 elif credits <50 and is_bonus == False: c -=1 elif is_bonus == True: c =c print(c) d = 8 time = 120 out3 = "" # if d is dividable by 4 # and time is not more than 200 # set out3 to "check" # if time is more than 200 # set out3 to "Time out" # otherwise set out3 to "Run Forest Run!" #print(out3)
b69a8a83e9088dc8bc14641ae5ef822831a2f044
CelsoAntunesNogueira/Phyton3
/ex032 - Ano bissexto.py
300
3.875
4
from datetime import date a = int(input('Digite um ano e falarei se é um ano bissexto ou não!E para analisar o ano atual digite 0:')) if a ==0: a = date.today().year if a % 4 == 0 and a %100 != 0 or a % 400 == 0: print('esse ano é bissexto!!') else: print('Não é um ano bissexto!')
2da91076cb9b04d12fc5c8b36e07b7435ab35d00
naresh14404666/guvi
/greater_number.py
165
3.921875
4
a=eval(input()) b=eval(input()) print("enter the numbers:") if(a>b): print(a,"is largest") elif(a==b): print("invalid") else: print(b,"is largest")
2889f294aece486287e2dda1272ab4d40eb359f4
bedekelly/crawler
/tests/test_parsing.py
998
3.515625
4
""" test_parsing.py: Test the functionality of the `parsing.py` module. These tests should be small and self-contained. """ import unittest from crawler.parsing import on_same_domain class TestParsing(unittest.TestCase): """ Test functionality inside the parsing module. """ def test_on_same_domain(self): """ Test the functionality of the `on_same_domain` function. It should return True if the URLs given are on the same domain, or False if they aren't. """ self.assertTrue(on_same_domain( "https://google.com/a/b", "http://sub-domain.google.com?time=0400" )) def test_not_on_same_domain(self): """ Test the `on_same_domain` function returns false for two URLs which happen to be on different domains. """ self.assertFalse(on_same_domain( "https://google.com", "https://google.goggle.com/google.com/google" ))
588638e325affa108972eff42dfaf689b348f3fc
grimario-andre/Python
/exercicios/desafio26.py
548
4.0625
4
print('================== Contador de Letras ===================') nome = str(input('Informe o nome completo ')).strip().upper() #contador de letras 'a'. print('A letra aparece tantas {} vezes na fraze '.format(nome.count('A'))) #exibir em qual posição aparece a letra pela primeira vez. #print(letra[:].count('a')) print('A primeira letra A foi encontrada na posição {} '.format(nome.find('A') + 1)) #exibir em qual posição aparece a letra pela ultima vez. print('A ultima letra A foi encontrada na posição {} '.format(nome.rfind('A')))
c0e8a3cc295fad4d96bcf6933e1d5619c2a54b10
pureplayN/LeetCode
/leetcode/tests/_010.py
2,342
3.53125
4
import unittest from leetcode.solutions._010_regular_expression_matching import Solution class RegularExpressionTest(unittest.TestCase): def setUp(self): self.solution = Solution() def testPureStringNotMatch(self): s = 'aabbccdd' p = 'aabbcdd' self.assertFalse(self.solution.isMatch(s, p)) def testStringShoterThanPattern(self): s = 'aabbcc' p = 'aabbccddee' self.assertFalse(self.solution.isMatch(s, p)) def testPureStringMatch(self): s = 'aa' p = 'a' self.assertFalse(self.solution.isMatch(s, p)) def testEmptyMatch(self): s = '' p = '' self.assertTrue(self.solution.isMatch(s, p)) s = '' p = 'a*' self.assertTrue(self.solution.isMatch(s, p)) s = 'dsds' p = '' self.assertFalse(self.solution.isMatch(s, p)) def testStartWithAnySubStringMatch(self): s = 'kmfkdlkdkijdskdsidskdskijdskds' p = '.*ijdskds' self.assertTrue(self.solution.isMatch(s, p)) def testStartWithAnySubStringNotMatch(self): s = 'kmfkdlkdkijdskdsidskdskijdskds' p = '.*jdskdsj' self.assertFalse(self.solution.isMatch(s, p)) def testSingleCharRepeatingMatch(self): s = 'iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii' p = 'i*iiii' self.assertTrue(self.solution.isMatch(s, p)) s = 'iiii' p = 'i*iiii' self.assertTrue(self.solution.isMatch(s, p)) def testSingleCharNotMatch(self): s = 'iii' p = 'i*iiii' self.assertFalse(self.solution.isMatch(s, p)) def testSample(self): s = 'ac' p = '..c*b*ac*.bc*bb*' self.assertFalse(self.solution.isMatch(s, p)) s = "bbaaccbaaccaccac" p = ".*..c*b*ac*.bc*bb*" self.assertFalse(self.solution.isMatch(s, p)) s = "" p = "c*c*" self.assertTrue(self.solution.isMatch(s, p)) s ="aaa" p ="ab*a*c*a" self.assertTrue(self.solution.isMatch(s, p)) s = "mississippi" p = "mis*is*ip*." self.assertTrue(self.solution.isMatch(s, p)) s = "aab" p = "c*a*b" self.assertTrue(self.solution.isMatch(s, p)) s = 'aa' p = 'a*' self.assertTrue(self.solution.isMatch(s, p))
0c0c2cc3abba32531c23322dce5e71be9b90c7c3
AlexanderHughSmith/BasicWordSeach
/ws.py
1,455
3.78125
4
def horizontal(ans,puzzle): for x in range (0,len(puzzle)): temp = "".join(map(str,puzzle[x])) if temp.find(ans) > -1: print("Right to Left: ("+str(temp.find(ans)+1)+","+str(x+1)+")") return True if temp.find(ans[::-1]) > -1: print("Left to Right (Backwards): ("+str(temp.find(ans[::-1])+1)+","+str(x+1)+")") return True return False def vertical(ans, puzzle): for x in range(0, len(puzzle[0])): temp = [] for j in range(0, len(puzzle)): temp.append(puzzle[j][x]) temp = "".join(map(str,temp)) if temp.find(ans) > -1: print("Top to Bottom: ("+str(x+1)+","+str(temp.find(ans)+1)+")") return True if temp.find(ans[::-1]) > -1: print("Bottom to Top: ("+str(x+1)+","+str(temp.find(ans[::-1])+len(ans))+")") return True return False def solve(ans,puzzle): Found = False while not Found: if horizontal(ans,puzzle): break if vertical(ans,puzzle): break else: print("Not found in puzzle") break l1 = "csmfsnow" l2 = "ocbrcsmh" l3 = "aaqoobvk" l4 = "treslfei" l5 = "wfotdqsz" l6 = "lwkyqice" l7 = "vqwigloo" l8 = "hwintern" puzzle = [1,2,3,4,5,6,7,8] puzzle[0] = list(l1) puzzle[1] = list(l2) puzzle[2] = list(l3) puzzle[3] = list(l4) puzzle[4] = list(l5) puzzle[5] = list(l6) puzzle[6] = list(l7) puzzle[7] = list(l8) def print_puzzle(puz): for x in range (0,len(puz)): print(puz[x]) print_puzzle(puzzle) while True: word = input("What word are you looking for: ") solve(word,puzzle)
7d370a043cf5135c952b9f0557cdef8f451ace20
dexter2206/flask-pytkrk4
/examples/example_10_json.py
860
3.71875
4
# Example 10: using json with flask from flask import Flask, request, jsonify app = Flask(__name__) @app.route("/incoming-json", methods=["POST"]) def post_json(): # If content type of the request is application/json, Flask can # automatically decode json object for you. # Remember, this will only work if the correct content type is set in the request. # Alternatively, you can forcefuly interpret incoming data as json by passing # force=True to request.get_json() return "\n".join(f"{key}: {value}" for key, value in request.get_json(force=True).items()) @app.route("/outgoing-json", methods=["GET"]) def get_json(): # jsonify works like a json.dumps function. but wraps the encoded # json in a response object response = jsonify({"foo": 2, "bar": 3}) return response if __name__ == '__main__': app.run()
064d1ca8676e042147a562493c4342b23bf99e4d
SHPStudio/LearnPython
/batteriesincluded/internal.py
1,335
3.65625
4
# 内置模块 # 时间 # 时间模块 datetime # 导入时间类 datetime # from datetime import datetime # 获取当前时间 # now = datetime.now() # print(now) # 设置一个时间 # dt = datetime(2017,6,30,12,14,30) # print(dt) # 转换为时间戳 # print(dt.timestamp()) # 从时间戳转换为datetime时间对象 是本地时间也就是北京时间 时区为utc+8:00 # dtimestamp = 1429417200.0 # print(datetime.fromtimestamp(dtimestamp)) # utc时间 utc时间是带时区的默认是标准时区 # print(datetime.utcfromtimestamp(dtimestamp)) # str转换为datetime对象 # cday = datetime.strptime('2017-04-20 18:16:30','%Y-%m-%d %H:%M:%S') # print(cday) # 同样的可以把datetime转换为字符串 # dstr = now.strftime('%Y-%m-%d %H:%M:%S') # print(dstr) # 对时间的加减 # from datetime import datetime,timedelta # 对时间的增减需要导入timedelta 通过加减timedelta对象来实现 # 加10个小时 也就是对应的年月日等等都可以加减 # now = datetime.now() # addtenh = now + timedelta(hours=10,) # print(addtenh) # 时区 # 需要导入timezone 可以对时间进行时区的转换 from datetime import datetime,timedelta,timezone # 设置时区为utc +8 tz_zh = timezone(timedelta(hours=8)) now = datetime.now() print(now) # 设置时区 dt = now.replace(tzinfo=tz_zh) print(dt)
5119ac3568bca8b348a326bb745a38ada32bee2b
LCfP-basictrack/basictrack-2020-2021-2b
/how_to_think/chapter_3/third_set/exercise_3_4_4_12_c_variant.py
237
3.625
4
n = -123456789.0 original_n = n count = 0 if n < 0: count += 1 # should the minus sign count as a digit? n *= -1 while n != 0: if n % 2 == 0: count += 1 n = n // 10 print(original_n, "has", count, "digits")
6090c25a7ece3b92c6ad37a7f67ec34b55dec39f
menliang99/CodingPractice
/StringMult.py
608
3.625
4
## Carry Save Combinational Multiplier Architecture in VLSI def StrMult(num1, num2): num1 = num1[::-1] num2 = num2[::-1] print num1 print num2 arr =[0 for i in range(len(num1) + len(num2))] for i in range(len(num1)): for j in range(len(num2)): arr[i + j] += int(num1[i]) * int(num2[j]) ans = [] print arr for i in range(len(arr)): digit = arr[i] % 10 carry = arr[i] / 10 if i < len(arr) - 1: arr[i + 1] += carry ans.insert(0, str(digit)) while ans[0] == '0' and len(ans) > 1: del ans[0] print ans return ''.join(ans) num1 = "98" num2 = "97" print StrMult(num1, num2)
c01833c48d68e665ae9656f03f5933c1c5fea35b
cynergist/holbertonschool-higher_level_programming
/0x11-python-network_1/3-error_code.py
716
3.6875
4
#!/usr/bin/python3 import urllib.request import urllib.parse import sys ''' Script that takes in a URL, sends a request to the URL and, displays the body of the response, decoded in utf-8 ''' if __name__ == "__main__": try: with urllib.request.urlopen(sys.argv[1]) as response: ''' The returned response object gives us access to all headers ''' print(response.read().decode('utf-8')) except urllib.error.HTTPError as error: print("Error code: {}".format(error.code)) ''' Returns: $ ./3-error_code.py http://0.0.0.0:5000 Index $ ./3-error_code.py http://0.0.0.0:5000/status_401 Error code: 401 $ ./3-error_code.py http://0.0.0.0:5000/doesnt_exist Error code: 404 '''
9c8ebf5f81bea0c404d9d48aa57f63f8728c44de
YeasirArafatRatul/Python
/SortingAlgorithms/SelectionSort.py
1,412
4.21875
4
#Selection sort #step 1: i = 0 #step 2: if i >= n-1 go to step 11 (for counting the iterations) #step 3: minimum no of the list is i = index_min #step 4: j = i+1 #step 5: if j <= n go to step 9 #step 6: if list[j] < list[index_min] # go to step 7 # else go to step 8 #step 7: index_min = j (set the next value) i could be written as i+1 since j = i+1 #step 8: j = j+1 ( compare with the next one and go on) #step 9: if i != index_min then swap list[i] & list[index_min] #step 10: i = i+1 and go to step 2 #step 11: the list is sorted def selection_sort(a_list): n = len(a_list) #finding the lowest value of the list for i in range(0,n-1): index_min = i for j in range(i+1,n): if a_list[j] < a_list[index_min]: index_min = j #comparing the lowest value with the value of a_list[i] which is changing with each iterations if index_min != i: a_list[i],a_list[index_min] = a_list[index_min],a_list[i] #swapping if __name__ == "__main__": data_list = [] # number of elemetns as input n = int(input("Enter number of elemens:")) # iterating till the range for i in range(0, n): element = int(input()) data_list.append(element) print("list before sorting:",data_list) selection_sort(data_list) print("list after sorting:",data_list)
7b3fe01966efd44425e6b8a62e1fb524221ce8fa
oijmark7/python_
/문제300/5차/5차 2급 6_initial_code.py
745
3.703125
4
def solution(korean, english): answer = 0 math = 210 - (korean + english)#최소 점수의 수학을 구하는 방법 수학= 평귵xn-(다른 과목들의 점수의 합)이다 if math > 100:#만약 수학점수가 100점보다 크다면 answer = -1#답은없다 else:#아니면 answer = math#답을 수학으로 지정 return answer#답반환 #아래는 테스트케이스 출력을 해보기 위한 코드입니다. 아래에는 잘못된 부분이 없으니 위의 코드만 수정하세요. korean = 70#한국어 70점 english = 60#영어 60점 ret = solution(korean, english) #[실행] 버튼을 누르면 출력 값을 볼 수 있습니다. print("solution 함수의 반환 값은", ret, "입니다.")
5aa1ca39f9358d0874dbf220f69c9b31f5b87f20
iaslyk/sort_visualizer
/merge_s.py
864
4.0625
4
def swap(A, i, j): A[i], A[j] = A[j], A[i] def merge_sort(nums, left, right): if(right <= left): return elif(left < right): mid = (left + right)//2 yield from merge_sort(nums, left, mid) yield from merge_sort(nums, mid+1, right) yield from merge(nums, left, mid, right) yield nums def merge(nums, left, mid, right): new = [] i = left j = mid+1 while(i <= mid and j <= right): if(nums[i] < nums[j]): new.append(nums[i]) i += 1 else: new.append(nums[j]) j += 1 if(i > mid): while(j <= right): new.append(nums[j]) j += 1 else: while(i <= mid): new.append(nums[i]) i += 1 for i, val in enumerate(new): nums[left+i] = val yield nums
2f315c2d0eebe2e191bf4a08fb7db73182c48f71
Localde/scripts-python
/ex10-conversor-de-moedas.py
117
3.59375
4
dinheiro = float(input("Quanto dinheiro você tem?")) input("Você pode comprar {} dolares.".format(dinheiro / 3.27))
609844503c00a9dd82d39fd20185e8e4ef6615ae
Vissureddy2b7/must-do-coding-questions
/strings/6_check_if_string_is_rotated_by_two_places.py
492
3.8125
4
# Input: # 2 # amazon # azonam # geeksforgeeks # geeksgeeksfor # # Output: # 1 # 0 t = int(input()) for _ in range(t): str1 = input() str2 = input() n1, n2 = len(str1), len(str2) if n1 != n2 or (n1 < 3 and str1 != str2): print(0) continue if (str1[n1-2] == str2[0] and str1[n1-1] == str2[1] and str1[:n1-2] == str2[2:]) or \ (str1[0] == str2[n2-2] and str1[1] == str2[n2-1] and str1[2:] == str2[:n2-2]): print(1) else: print(0)
660849f30452cbd5a614b65b658167ddc9bda9bd
graceknickrehm21/open-cv-
/bitwise.py
1,864
4.1875
4
#bitwise operations: AND, OR, XOR, and NOT #represented as grayscale images #pixel is turned off if it has a value of zero and on if it has a value greater than zero #binary operations #AND: A bitwise AND is true if and only if both pixels are greater than zero. #OR: A bitwise OR is true if either of the two pixels are greater than zero. #XOR: A bitwise XOR is true if and only if either of the two pixels are greater than zero, but not both. #NOT: A bitwise NOT inverts the “on” and “off” pixels in an image. import numpy as np #importing the packages needed import cv2 rectangle = np.zeros((300, 300), dtype = "uint8") #initializes rectangle image as a 300 by 300 numpy array cv2.rectangle(rectangle, (25, 25), (275, 275), 255, -1) #drawing a 250 x 250 white rectangle at the image center cv2.imshow("Rectangle", rectangle) circle = np.zeros((300, 300), dtype = "uint8") #initalize an image to contain a circle cv2.circle(circle, (150, 150), 150, 255, -1) #circle is centered at the center of the image with a radius of 150 pixels cv2.imshow("Circle", circle) bitwiseAnd = cv2.bitwise_and(rectangle, circle)#applying AND to the rectangle and circle images --> rectangle doesn't cover as large an area as the circle so both pixels should be off cv2.imshow("AND", bitwiseAnd) cv2.waitKey(0) bitwiseOr = cv2.bitwise_or(rectangle, circle) #applying OR to the shapes cv2.imshow("OR", bitwiseOr) cv2.waitKey(0) bitwiseXor = cv2.bitwise_xor(rectangle, circle) #applying XOR function to the shapes --> center of square is removed because XOR operation cannot have both pixels greater than zero cv2.imshow("XOR", bitwiseXor) cv2.waitKey(0) bitwiseNot = cv2.bitwise_not(circle) #applying the NOT function to flip pixel values --> pixels greater than zero are set to zero and pixels set to zero are set to 255 cv2.imshow("NOT", bitwiseNot) cv2.waitKey(0)
8ba42e8ddfa0cb9a569b3e8661317a4ad46080a1
shahamran/intro2cs-2015
/ex6/balanced_brackets.py
3,607
4
4
#Constants for the brackets strings OPEN_STR = "(" CLOSED_STR = ")" def is_balanced(s): '''Gets a string varibale [s] and checks if it contains balanced brackets. return True if so, and False otherwise. ''' length = len(s) opened = 0 #checks every character in the string. If it's a closed bracket and #there were no open ones, it returns False for i in range(length): if s[i] == OPEN_STR: opened += 1 elif s[i] == CLOSED_STR: opened -= 1 if opened < 0: return False #If after checking every char the number of opened brackets isn't #the same as the closed ones, it returns False. if opened == 0: return True else: return False def violated_balanced(s): '''Gets a string variable [s] and checks if it is balanced. If not it returns the index of the char which breaks the balance. If the balance can be restored by adding closed brackets, it returns the string's length. If the string is balanced, returns '-1' ''' #first checks if the string is balanced if is_balanced(s): return -1 #The recursive funciton. gets an unbalanced string and an index and #checks every sub-string (from the start to the index) to find the last #index in which it was balanced and if it can be rebalanced def check_index(s, index): #if the index is greater than the length of the string, the string #can be balanced and the function returns the length of the string if index >= len(s): return len(s) #if the sub-string is balanced, check the next one. if is_balanced(s[:index + 1]): return check_index(s, index + 1) else: #if the string isn't balanced, checks if there is any number #of closed brackets that can be added in order to balance it #if not, then a closed bracket broke our balance and the function #returns it's index. for i in range(1, index + 2): if is_balanced(s[:index + 1] + (CLOSED_STR * i)): return check_index(s, index + 1) return index #calls the recursive function with the index '0', to start the search. return check_index(s, 0) def match_brackets(s): '''Gets a string variable [s] and returns a list in the size of the string that specify the location of a bracket set by a set of numbers which indicate the distance from the index in the list to the matching bracket. if the string is unbalanced, returns [] ''' def get_list(s, index, result=[0] * len(s)): '''the recursive function. assuming it's initial input string is balanced, checks every char to find an open bracket. when found, goes over every next substring to check where its matching closer is found. then sets the list in those indexes to the correct values according to this info. NOTE: Gets a non-empty string ''' if s[index] == OPEN_STR: #uses another function to check where the matching bracket is j = violated_balanced(s[index + 1:]) result[index] = j + 1 result[index + j + 1] -= j + 1 #stops when it reaches the end of the string (index > len(s)) if index < len(s) - 1: result = get_list(s, index + 1, result) return result out_list = [] # initial output list is empty if is_balanced(s) and len(s) != 0: out_list = get_list(s, 0) # calls the recursive function return out_list
2c978f5e33ce3157c3a23aba6484fe0726964c01
vivek2319/mercy
/playnumpy.py
1,847
3.890625
4
import numpy as np #create an array of 10 zero's np.zeros(10) #Create an array of 10 one's np.ones(10) #Create an array of 10 five's #First method np.ones(10) * 5 #Second method np.zeros(10) + 5 #Create an array of intergers from 10 to 50 np.arange(10,51) #Create an array of all the even integers frm 10 to 50 np.arange(10,51,2) #Creata 3X3 matrx with values ranging from 0 to 8 np.arange(9).reshape(3,3) #Create a 3X3 identiy matrix np.eye(3) #Use numpy to generate a random number between 0 and 1 np.random.rand(1) #Use numpy to generate an array of 25 random numbers sampled from a standard normla distribution np.random.rand(25) #Create a matrix from 0.01 to 1.00, 2-D array, step size 0.01 all the way to 1 #first method np.arange(1,101).reshape(10,10)/100 #Create an array of 20 linearly spaced points between 0 and 1 np.linspace(0,1,20) #Numpy Indexing and solution #Now you will be given a few matrices, and be asked to replicate the resulting matrix outputs mat = np.arange(1,26).reshape(5,5) mat ''' array([[ 1, 2, 3, 4, 5], [ 6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25]]) >>> ''' #Write code to generate foll matix ''' array([[12, 13, 14, 15], [17, 18, 19, 20], [22, 23, 24, 25]]) >>> ''' mat[2:,1:] #Just grab 20 from mat mat[3,4] #Now grab following matrix ''' array([[ 2], [ 7], [12]]]) ''' mat[:3,1:2] #Write a code to display array([21,22,23,24,25]) mat[-1] #Other way mat[4,:] #Write a code to display following output #array([16,17,18,19,20], # [21,22,23,24,25]]) mat[3:5,:] #Get the sum of the values in mat np.sum(mat) #Other way mat.sum() #Get the standard deviation of the values in mat np.std(mat) #Other way mat.std() #Get the sum of all columns in mat mat.sum(axis=0)
acf9fbbd39a6f038c03a68b976f0ce96b6d0e507
chirateep/algorithm-coursera-course1
/week5_dynamic_programming1/1_money_change_again/change_dp.py
524
3.5
4
# Uses python3 import sys def get_change(m): # write your code here coins = [1, 3, 4] min_num_coin = [m + 1] * (m + 1) min_num_coin[0] = 0 for i in range(1, m + 1): for coin in coins: if i >= coin: num_coins = min_num_coin[i - coin] + 1 if num_coins < min_num_coin[i]: min_num_coin[i] = num_coins # print(min_num_coin) return min_num_coin[m] if __name__ == '__main__': m = int(sys.stdin.read()) print(get_change(m))
96231fe7aaeabfe5d35585baa3a2c522a023c88a
jardelhokage/python
/python/reviProva/Python-master/23_TriâguloSimOuNao.py
387
4.125
4
print('Informe os valores para os lados do triângulo!') lado1 = int(input('Qual o valor do lado 1? ')) lado2 = int(input('Qual o valor do lado 2? ')) lado3 = int(input('Qual o valor do lado 3? ')) if lado1 >= lado2 + lado3 \ or lado2 >= lado1 + lado3 \ or lado3 >= lado2 + lado1: print('Os lados NÃO formam um trângulo.') else: print('Os lados FORMAM um triângulo.')
d2ea19b141730c3cd34422cc8e2048bd24e49faf
neerajp99/algorithms
/problems/leetcode/lt-104.py
702
3.875
4
# 104. Maximum Depth of Binary Tree """ Given the root of a binary tree, return its maximum depth. A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. """ # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def maxDepth(self, root: Optional[TreeNode]) -> int: def helper(value): if not value: return 0 else: return 1 + (max(helper(value.left), helper(value.right))) return helper(root)
47969230cf60d9c9925917f04557e7a16a04d679
tarsqi/ttk
/deprecated/get_lexes.py
1,738
3.53125
4
""" Standalone utility script to extract all the tokens from a file and print them space separated using one sentence per line. Files are XML files that need to contain <s> and <lex> tags. USAGE: % python get_lexes.py INFILE OUTFILE % python get_lexes.py INDIR OUTDIR Note that in the first case INFILE has to exist and outfile not. In the second case, INDIR and OUTDIR have to be directories, existing files in OUTDIR may be overwritten. """ from __future__ import absolute_import from __future__ import print_function import sys, os from xml.dom.minidom import parse from io import open def getText(nodelist): rc = [] for node in nodelist: if node.nodeType == node.TEXT_NODE: rc.append(node.data) return ''.join(rc) def get_lexes(infile, outfile): try: dom = parse(infile) except: "Warning in XML parsing, skipping %s" % infile return fh = open(outfile, 'w') sentences = dom.getElementsByTagName("s") for sentence in sentences: tokens = [] lexes = sentence.getElementsByTagName("lex") for lex in lexes: tokens.append(getText(lex.childNodes)) fh.write(' '.join(tokens).encode('utf-8') + "\n") if __name__ == '__main__': IN = sys.argv[1] OUT = sys.argv[2] if os.path.isfile(IN) and not os.path.exists(OUT): get_lexes(IN, OUT) elif os.path.isdir(IN) and os.path.isdir(OUT): for filename in os.listdir(IN): infile = IN + os.sep + filename outfile = OUT + os.sep + filename if outfile[-3:] == 'xml': outfile = outfile[:-3] + 'txt' print(outfile) get_lexes(infile, outfile)
d1515ce3cb5bf5fd9993873ac848cbc0a4d17499
kasai05/mashup_py
/kadai1/cost.py
311
3.859375
4
import time, random sum = 0 # ブランクを空ける before = time.clock() # インデントの数を調整する for i in range( 1000000 ) : sum = sum + random.randint(1 , 100) # geptimeの単語の間に'_'をいれる gap_time = time.clock() - before print "dummy:", sum print "gaptime:", gaptime