blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
9ef6772a19ba0c1aa6c66b3902a7628dd095aba6
Inatigerdream/CTEW
/zMisc_Code/DATA_VISUALIZATION/doublebarplot.py
1,782
3.546875
4
import numpy as np import matplotlib.pyplot as plt def doublebarplot(list1, list2, n=20, title='', label1='l1', label2='l2', xlabel=[], color1='turquoise', color2='dodgerblue', save='', barval=True): """ Plot a double barplot of two lists. specify length with n """ if len(xlabel) == 0: xlabel = list1.index barwidth = 0.3 n = 50 r1 = np.arange(len(list1[:n])) r2 = [x + barwidth for x in r1] fig, ax = plt.subplots() rects1 = ax.bar(r1, list1[:n], barwidth, color=color1, alpha=1, zorder=3, label=label1) rects2 = ax.bar(r2, list2[:n], barwidth, color=color2, alpha=.8, zorder=3, label=label2) # add labels ax.set_ylabel('Counts', fontsize=14, fontweight='bold') ax.set_title(title, fontsize=14, fontweight='bold') ax.set_xticks(r1) ax.set_xticklabels(xlabel[:n+1], rotation='vertical', fontweight='bold') ax.set_facecolor('.98') ax.grid(color='.9', zorder=0) ax.legend() plt.ylim(0, 300) # auto label def autolabel(rects, xpos='center'): """ attach a text label above each bar displaying its height """ xpos = xpos.lower() ha = {'center': 'center', 'right': 'left', 'left': 'right'} offset = {'center': 0.5, 'right': 0.57, 'left': 0.43} for rect in rects: height = rect.get_height() ax.text(rect.get_x() + rect.get_width()*offset[xpos], 1.01*height, '{}'.format(int(height)), ha=ha[xpos], va='bottom') if barval==True: autolabel(rects1, "center") autolabel(rects2, "center") # plt.ylim((0,25)) fig.set_size_inches(15, 7) if save == '': plt.show() else: plt.savefig(save, dpi=500, quality=95, format='jpg', orientation='landscape')
363f9856c42906fdf8850d02c7ac7c0752f4184a
noanner/PBC_group92
/table_V1.py
862
3.609375
4
from tkinter import * from tkinter import ttk root = Tk() # 初始框的声明 columns = ("品項", "成本", "售價") treeview = ttk.Treeview(root, height = 18, show = "headings", columns = columns) # 表格 treeview.column("品項", width = 200, anchor = 'center', ) treeview.column("成本", width = 100, anchor = 'center') treeview.column("售價", width = 100, anchor = 'center') treeview.heading("品項", text = "品項") # 显示表头 treeview.heading("成本", text = "成本") treeview.heading("售價", text = "售價") treeview.pack(side = LEFT, fill = BOTH) name = ['牛肉漢堡', '豬肉漢堡', '雞肉漢堡', '生菜堡', '生酮堡'] cost = ['10', '9', '9', '6', '16'] price = cost * 2 for i in range(len(name)): # 写入数据 treeview.insert('', i, values = (name[i], cost[i], price[i])) root.mainloop() # 进入消息循环
8f3d41c81ad3c0e92b1e4f2bac6e9d1f873dfc17
ZhukovOleksandr/HW
/HW2/practic_task2.py
125
3.765625
4
for number in range(0, 1001, 1): if (number % 2 != 0) and (number % 3 == 0) and (number % 5 == 0): print(number)
266bda9d905488860f9123256ecbc3ab8048e475
helq/optimization-aspirants-locations
/greedy.py
5,442
3.5625
4
#!/usr/env/python3 from math import sqrt # Evaluating average distance (between aspirants and locations) # type :: ( [[float]], [int] ) -> float def averageDistance(M, assignment): return sum([ M[i][ assignment[i] ] for i in range(len(assignment)) ]) / len(assignment) # Defining distance between two points in space # type :: (float, float) -> float def d(a, b): x1, y1 = a x2, y2 = b return sqrt( (x1-x2)*(x1-x2) + (y1-y2)*(y1-y2) ) # given a matrix with the distances and the capacity of the locations return # an assignment (using a greedy algorithm) # type :: ( [[float]], [int] ) -> [int] def greedyAssignment(M, cs): n_locs = len(cs) n_ants = len(M) cpcties = cs[:] # copying capacities snd = lambda xs: xs[1] # second field of a tuple (actually, anything that has the __getitem__ attibute # aspirants sorted by their closeness to their closest presentation location # type :: [ (int, [ (int, float) ]) ] closestLoc = sorted( [ (i, sorted( [(j, M[i][j]) for j in range(n_locs)] , key=snd)) for i in range(len(M)) ] , key=lambda a: snd(a[1]) ) # creating assingment list # type :: [int] assignment = [-1 for i in range(n_ants)] # assigning locations to each aspirant, first those who live the closest # to their closest presentantion locations for aspirant, locations in closestLoc: for l,_ in locations: if cpcties[l] > 0: assignment[aspirant] = l cpcties[l] -= 1 break return assignment # Random assignment respecting capacities # type :: ( [[float]], [int] ) -> [int] def randomAssignment(M, cs): from random import randint n_locs = len(cs) n_ants = len(M) cpcties = cs[:] # copying capacities assignment = [-1 for i in range(n_ants)] for aspirant in range(n_ants): # getting random location with capacity loc = randint(0, n_locs-1) while cpcties[loc] == 0: loc = randint(0, n_locs-1) # assigning location assignment[aspirant] = loc cpcties[loc] -= 1 return assignment # Saving assignment to file # type :: ([int], string) -> None def saveAssignment(locs_ids, ants_ids, assignment, file_name): n_ants = len(assignment) f = open(file_name, 'w') for i in range(n_ants): f.write( "{:s};{:s}\n".format(ants_ids[i], locs_ids[assignment[i]]) ) f.close() # Testing the code # type :: string -> None def main(input_lines = None): if input_lines == None: from random import randint, random n_locs = 30 # number of locations n_ants = 40000 # number of aspirants locs_ids = ["{:02d}".format(i) for i in range(n_locs)] ants_ids = ["{:05d}".format(i) for i in range(n_ants)] # Creating random capacities cpcties = [randint(20, 1700) for i in range(n_locs)] while sum(cpcties) < n_ants: cpcties = [c+10 for c in cpcties] # Creating random (x,y) coordinates for Locations and aspirants locations = [(random(), random()) for i in range(n_locs)] aspirants = [(random(), random()) for i in range(n_ants)] else: n_locs, n_ants = input_lines[0].split(";") n_locs, n_ants = int(n_locs), int(n_ants) locs_ids = [ loc.split(";")[0] for loc in input_lines[1:n_locs+1] ] ants_ids = [ asp.split(";")[0] for asp in input_lines[n_locs+1:] ] cpcties = [ int(loc.split(";")[1]) for loc in input_lines[1:n_locs+1] ] # line to coordinates # type :: [string] -> (float, float) toCoord = lambda l: (float(l[0]), float(l[1])) locations = [ toCoord(loc.split(";")[2:]) for loc in input_lines[1:n_locs+1] ] aspirants = [ toCoord(asp.split(";")[1:]) for asp in input_lines[n_locs+1:] ] # Creating matrix with distances from aspirants to locations M = [ [d(locations[l], a) for l in range(n_locs)] for a in map(lambda i: aspirants[i], range(n_ants)) ] assignment = greedyAssignment(M, cpcties) assignment2 = randomAssignment(M, cpcties) distance = averageDistance(M, assignment) distance2 = averageDistance(M, assignment2) print( "Capacities:", cpcties ) print( " == Mean distance == ") print( "Assignment (greedy): {:f}".format(distance) ) print( "Assignment (random): {:f}".format(distance2) ) print( "Saving (greedy) assignment" ) saveAssignment(locs_ids, ants_ids, assignment, "greedy_assignment.csv") def mode_of_use(): print("Mode of use: python3 {:s} [-i|--input inputfile.txt]\n".format( argv[0] ) ) print(" Input file format: \n"+ " line | content \n"+ " ----- | -------------------------------------------------\n"+ " 1 | number_of_locations; number_of_aspirants \n"+ " n+1 | location_n_capacity; location_n_x_coord; y_coord \n"+ " | ... \n"+ " n+m+1 | aspirant_m_id; aspirant_m_x_coord; y_coord") exit(1) if __name__ == "__main__": from sys import argv if len(argv) == 1: main() elif len(argv) == 3 and argv[1] in ['-i', '--input']: main( open(argv[2], 'r').readlines() ) else: mode_of_use()
05e24f84b681d556bb1953f866957b67322421c3
ootz0rz/tinkering-and-hacking
/2021/LeetCode/FB/linked-lists/merge two sorted lists.py
2,655
3.65625
4
from listnode import ListNode from typing import * debug = False class Solution: # O(nm) def mergeTwoLists(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]: global debug a = l1 b = l2 if debug: print(f'\n------\nmergeTwoLists l1<{l1}> l2<{l2}>') # choose head o = None if a is not None: if b is not None: if a.val > b.val: o = b b = b.next else: o = a a = a.next else: o = a a = a.next else: o = b b = b.next if b is not None else None first = o if debug: print(f'# a<{a}> b<{b}> == o<{o}> || first<{first}>') while (o is not None) and ((a is not None) or (b is not None)): if debug: print(f'\t -> a<{a}> b<{b}> == o<{o}> || first<{first}>') if a is None: if debug: print('\t\t -> a == null', end='') if b is None: # a == null, b == null if debug: print(' b == null') break else: # a == null, b != null if debug: print(' b != null') o.next = b b = b.next else: if debug: print('\t\t -> a != null', end='') if b is None: # a != null, b == null if debug: print(' b == null') o.next = a a = a.next else: # a != null, b != null if debug: print(' b != null') if a.val < b.val: if debug: print(f'\t\t\t => a[{a.val}] < b[{b.val}]') o.next = a a = a.next else: if debug: print(f'\t\t\t => b[{b.val}] < a[{a.val}]') o.next = b b = b.next if o.next is not None: o = o.next return first if __name__ == '__main__': debug = True s = Solution() lng = ListNode.genFromList # assert str(s.mergeTwoLists(lng([]), lng([]))) == str(lng([])) # assert str(s.mergeTwoLists(lng([0]), lng([]))) == str(lng([0])) # assert str(s.mergeTwoLists(lng([]), lng([0]))) == str(lng([0])) # assert str(s.mergeTwoLists(lng([0]), lng([0]))) == str(lng([0,0])) assert str(s.mergeTwoLists(lng([1,2,4]), lng([1,3,4]))) == str(lng([1,1,2,3,4,4]))
0f95d1044cec1f3b8510db23c823cf9758b5b2e6
benjaminleon/EulerProject
/04_Largest_palindrome_product.py
572
3.78125
4
largest_palindrome = 0 for i in range(100,1000): for j in range(i,1000): # Don't try 2*3 and 3*2 number = str(i * j) failure = False for idx in range(3): if number[idx] != number[-(idx+1)]: failure = True break if not failure and int(number) > largest_palindrome: largest_palindrome = int(number) print "updating", int(number) print largest_palindrome """ 1 1 1 1 1 1 2 3 4 5 2 2 2 2 2 2 3 4 5 3 3 3 3 3 3 4 5 """
eb0432a8b10147af1950b177b9fb5bad4c93e3a1
pyElena21/FileManipulationTools
/FileUnzipping.py
628
3.5
4
''' Created on 14 Dec 2017 @author: Elena Koumpli See more in https://stackoverflow.com/questions/30887979/i-want-to-create-a-script-for-unzip-tar-gz-file-via-python ''' import tarfile import os def unzip_tarfiles(path_to_tarfiles, unzip_where_folder): ''' Fast unzipper for csv.tar.gz files ''' files = [f for f in os.listdir(path_to_tarfiles) if f.endswith('.csv.tar.gz')] print(files) for fname in files: tar = tarfile.open(path_to_tarfiles+fname, "r:gz") tar.extractall(unzip_where_folder) tar.close()
a8bff6ad3880f48dee989afc77066d48787a4b35
topherCantrell/computerarcheology
/holdAndDelete/cpu/cpu_common.py
7,979
3.59375
4
''' p - memory address (one byte) q - memory address (one byte) used for opcodes with multiple Ps t - memory address (two bytes) b - constant (one byte) w - constant (two byte) r - memory branch relative offset (one byte) s - memory branch relative offset (two byte) The "bus" field shows how a memory address (p, q, t, r, s) is used: - "" mnemonic does not contain a memory address - "r" memory address is read - "w" memory address is written - "rw" memory address is read and written - "x" memory address is code (jump destination) * 6809 specific y - indexed form (6809) z - two register set (6809) x - push register set S (6809) y - pull register set S (6809) u - push register set U (6809) v - pull register set U (6809) * 8051 specific z - bit address (one byte) y - 11-bit address (one byte -- 3 bits in the opcode) ''' class CPU: def __init__(self, opcodes): self._opcodes = opcodes self._make_data_map() self._make_frags() def _is_space_needed(self, text, pos): if text[pos] != ' ': return True if (text[pos - 1].isalpha() or text[pos - 1].isdigit()) and (text[pos + 1].isalpha() or text[pos + 1].isdigit()): return True return False def _remove_unneeded_whitespace(self, text): match = text while True: g = match.replace(' ', ' ') if g == match: break match = g nmatch = '' for i in range(len(match)): c = match[i] if self._is_space_needed(match, i): nmatch = nmatch + c return nmatch def _make_data_map(self): self._data_map = {} for op in self._opcodes: g = op['code'][:2] if g in self._data_map: self._data_map[g].append(op) else: self._data_map[g] = [op] def _make_frags(self): for op in self._opcodes: txt = op['mnem'] txt = self._remove_unneeded_whitespace(txt) op['frags'] = [''] for i in range(len(txt)): c = txt[i] if c.islower(): op['frags'].append(c) if i < (len(txt) - 1): op['frags'].append('') else: op['frags'][-1] = op['frags'][-1] + c def _does_op_fit(self, g, t): if len(g) != len(t): return False for i in range(len(g)): if t[i].islower(): continue if g[i] != t[i]: return False return True def make_word(self, value): # Little endian in the base class (I had to pick one or the other) return (value & 0xFF, value >> 8) def pick_opcode_from_aliases(self, mnem, opcodes): for op in opcodes: if op['mnem'].startswith(mnem[0]): return op return None def is_bus_x(self, op): return 'x' in op['bus'] def is_bus_r(self, op): return 'r' in op['bus'] def is_bus_w(self, op): return 'w' in op['bus'] def is_bus_rw(self, op): return self.is_bus_r(op) and self.is_bus_w(op) def is_memory_reference(self, op): s = op['code'] if 'p' in s or 's' in s or 't' in s or 'r' in s: return True return False def get_opcode_from_data(self, data): ret = [] g = '' for d in data: g = g + '{:02X}'.format(d) if not g[:2] in self._data_map: return [] for op in self._data_map[g[:2]]: if self._does_op_fit(g, op['code']): ret.append(op) return ret def process_fill_term(self, address, op, fill, decode): if not decode: return [] if decode[0] == 'r': # Typical relative offset. Override this method if your CPU does # something different address = address + int(len(op) / 2) fill = fill - address if fill > 127 or fill < -128: raise Exception('Relative jump out of byte range') if fill < 0: fill = fill + 256 ret = [] if len(decode) == 2: if fill > 255: print(address) raise Exception('Bigger than a byte: {:04X}'.format(fill)) ret.append(fill) else: if decode[1] == 'm': ret.append(fill >> 8) ret.append(fill & 0xFF) else: ret.append(fill & 0xFF) ret.append(fill >> 8) return ret def fill_in_opcode(self, asm, address, op, pass_number): opcode = op[0] fill = op[1] if pass_number == 0: return [0] * int(len(opcode['code']) / 2) else: ret = [] code = op[0]['code'] fill = op[1] dec = '' for i in range(0, len(code), 2): if code[i].islower(): dec = dec + code[i:i + 2] if dec: fill = asm.parse_numeric(fill) fill = self.process_fill_term(address, code, fill, dec) p = 0 for i in range(0, len(code), 2): if code[i].islower(): ret.append(fill[p]) p += 1 else: ret.append(int(code[i:i + 2], 16)) return ret def find_opcode(self, text, assembler): if '>' in text: size_override = 2 text = text.replace('>', '') elif '<' in text: size_override = 1 text = text.replace('<', '') else: size_override = 0 nmatch = self._remove_unneeded_whitespace(text) ret = [] for op in self._opcodes: frags = op['frags'] if len(frags) == 1: if frags[0] == nmatch.upper(): ret.append([op, None]) elif len(frags) == 2: if nmatch.upper().startswith(frags[0]) and len(nmatch) > len(frags[0]): ret.append([op, nmatch[len(frags[0]):]]) elif len(frags) == 3: if nmatch.upper().startswith(frags[0]) and nmatch.upper().endswith(frags[2]): ret.append([op, nmatch[len(frags[0]):-len(frags[2])]]) if not ret: return [] if len(ret) == 1: return ret[0] num_small = 1000 num_large = 0 for r in ret: x = len(r[0]['frags']) if x < num_small: num_small = x if x > num_large: num_large = x # if num_small is 1, it means we have an exact match -- use that # otherwise use the match with the largest fragments if num_small == 1: num_large = num_small for x in range(len(ret) - 1, -1, -1): if len(ret[x][0]['frags']) != num_large: del ret[x] if len(ret) == 1: return ret[0] if len(ret) == 2 and ret[0][0]['frags'][0] == ret[1][0]['frags'][0]: if size_override == 0: try: val = assembler.parse_numeric(ret[0][1]) except: val = 256 if val < 256: size_override = 1 else: size_override = 2 if size_override == 1: if len(ret[0][0]['code']) < len(ret[1][0]['code']): return ret[0] else: return ret[1] elif size_override == 2: if len(ret[0][0]['code']) > len(ret[1][0]['code']): return ret[0] else: return ret[1] return []
cd7c24b137ddbbed76f50c2db5e6e0895e071e75
TekNoir08/weather
/Weather.py
2,178
3.6875
4
''' Created on 21 Nov 2012 @author: Michael Kemp ''' import urllib2 import os from bs4 import BeautifulSoup page = urllib2.urlopen("http://www.metoffice.gov.uk/weather/uk/observations/") soup = BeautifulSoup(page) ## This need to be changed to allow the print and write to be separate. Too much duplication here def get_data(name): print 'Met Office: UK: Latest observations for ' + name + "\n" forest = soup.find(text=name).findPrevious('tr') print "Weather " + forest.img['title'] +"\n" write_data("Weather", forest.img['title'] +"\n") print "Degrees C\n" + forest('td')[2].text + "\n" write_data("Degrees>C", forest('td')[2].text + "\n") print "Wind direction\n" + forest('td')[4].text + "\n" write_data("Wind>direction", forest('td')[4].text + "\n") print "Wind speed (Mph)\n" + forest('td')[5].text + "\n" write_data("Wind>speed>(Mph)", forest('td')[5].text + "\n") print "Gust speed (Mph)\n" + forest('td')[7].text + "\n" write_data("Gust>speed>(Mph)", forest('td')[7].text + "\n") print "Visability (Kilometers)\n" + forest('td')[9].text + "\n" write_data("Visability", forest('td')[9].text + "\n") print "Pressure \n" + forest('td')[11].text write_data("Pressure", forest('td')[11].text.replace(u'\xa0', u' ')) print "Files have been sent to " + os.getcwd() def write_data(name, value): output = open(name +".txt", "w") output.write(name + "\n" + value) output.close() ##file.write(soup.title.string + ' for Ballypatrick Forest\n') ##file.write('\n') ## ##file.write("Degrees C\n" + forest('td')[2].text + "\n") ##file.write('\n') ##file.write("Wind direction\n" + forest('td')[4].text + "\n") ##file.write('\n') ##file.write("Wind speed (Mph)\n" + forest('td')[5].text + "\n") ##file.write('\n') ##file.write("Gust speed (Mph)\n" + forest('td')[7].text + "\n") ##file.write('\n') ##file.write("Visability (Kilometers)\n" + forest('td')[9].text + "\n") ##file.write('\n') ##file.write("Pressure\n" + forest('td')[11].text.replace(u'\xa0', u' ')) ##file.write('\n') ##file.close() get_data('Ballypatrick Forest')
a74b3e1b5130042204a5bb7d9a1735302be91b63
taghavi/EricssonTestTask
/Server/server6.py
592
3.5625
4
from pynput import keyboard from pynput.keyboard import Key def on_press(key): if isinstance(key ,Key): if key == keyboard.Key.esc: # Stop listener and exit keyboard.Listener.stop return False elif Key.space == key: print(" ",end="",flush=True) elif Key.enter == key: print("\n",end="",flush=True) else: print(key.char,end="",flush=True) print("hi") with keyboard.Listener(on_press=on_press) as listener: listener.join()
cdb14277df766adf58610782eb588fba65c2a2bc
FelixZFB/Python_advanced_learning
/02_Python_advanced_grammar_supplement/004_设计模式/001_工厂模式.py
1,082
3.859375
4
# -*- coding:utf-8 -*- # project_xxx\venv\Scripts python ''' Author: Felix Email: xiashubai@gmail.com Blog: https://blog.csdn.net/u011318077 Date: 2019/12/9 12:21 Desc: ''' # 工厂模式是一个在软件开发中用来创建对象的设计模式。 # 当程序运行输入一个“类型”的时候,需要创建于此相应的对象。 # 这就用到了工厂模式。在如此情形中,实现代码基于工厂模式, # 可以达到可扩展,可维护的代码。 # 当增加一个新的类型,不在需要修改已存在的类,只增加能够产生新类型的子类。 # 使用工厂模式应用场景: # 不知道用户想要创建什么样的对象 class Car(object): def run(self): print('so~so~de') def stop(self): print('ci~~~~') class BMW(Car): pass class Benz(Car): pass class CarFactory(object): def make_car(self, name): if name == 'BMW': return BMW() if name == 'Benz': return Benz() factory = CarFactory() car = factory.make_car('BMW') print(type(car)) # <class '__main__.BMW'>
7cc60a6dbfcd2bf8818d3bf11983039ef0b87b7c
sunjoopark/python-algorithm
/python_exercise/ex_037.py
350
3.796875
4
N = 12 def combi(n, r): p = 1 for i in range(1,r) : p = p*(n - i + 1) // i return p if __name__ == "__main__": for n in range(N+1) : t = 0 while t < (N - n) * 3 : print(" ",end="") t = t + 1 for r in range(n + 1) : print("%3d "%(combi(n,r)), end="") print()
3c0a9d6571c80782071beccff76827ea4e07b1a6
Rkhwong/RHK_PYTHON_LEARNING
/PythonExercices/Semana_Python_Ocean_Marco_2021-main/Exercicios_Python_PauloSalvatore/Exercicio_13.py
1,195
4.25
4
""" Exercício 13 Nome: Convertendo Celsius/Farenheit Objetivo: Escrever duas funções de conversão, uma de graus celsius em farenheit e a outra que faça o contrário. Dificuldade: Principiante 1 - Crie um aplicativo de conversão entre as temperaturas Celsius e Farenheit. 2 - Primeiro o usuário deve escolher se vai entrar com a temperatura em Célsius ou Farenheit, depois a conversão escolhida é realizada. 3 - Se C é a temperatura em Celsius e F em farenheit, as fórmulas de conversão são: C = 5 * (F - 32) / 9 F = (9 * C / 5) + 32 """ def converterCF(c): f = (( 9 * c )/ 5 ) + 32 print("Valor Convertido em Fº {:.2f}".format(f)) def converterFC(f): c = 5 * ( f - 32) / 9 print("Valor Convertido em Cº {:.2f}".format(c)) def dadosUsuario(): escolha = int(input("Escolha o Tipo de Temperatura\n [1]Celcius\n [2]Farenheit\nEscolha :")) if escolha == 1: valorCelsius = float(input("Valor da temperatura Cº :")) converterCF(valorCelsius) elif escolha == 2: valorFarenheit = float(input("Valor da temperatura Fº :")) converterFC(valorFarenheit) else: print("Escolha Invalida!") #Main dadosUsuario()
76d2b48fa2a1fc5ede96030f2c34a8508f3830f6
SanyaBoroda4/Hillel_Homeworks
/LESSON_06(LISTS, TUPLES)/Lesson 06_10.py
144
3.625
4
"""Expression comprehension""" list = [1, 3, 5, 8, 12] my_expr = sum(i for i in list if i % 2 == 0) # only works for 1 TIME!!! print(my_expr)
091626ca8cf2c7002c5d265b2f795bbcaa06bf21
timemaster5/BodyPos
/MediaPipe/HandPos/hands01DisplayHandLandmarks.py
1,819
3.546875
4
# this is a full tutorial # how to detect and display hands using live camera # first pip install media pipe #https://google.github.io/mediapipe/getting_started/install.html import mediapipe as mp import cv2 mp_drawing = mp.solutions.drawing_utils #helps to render the landmarks mp_hands = mp.solutions.hands cap = cv2.VideoCapture(0) # You can setup your camera settings cap.set(3,1920) cap.set(4,1080) with mp_hands.Hands(min_detection_confidence=0.5 , min_tracking_confidence=0.5) as hands: while cap.isOpened(): re, frame = cap.read() # start the detection # =================== # convert the image to RGB image = cv2.cvtColor(frame,cv2.COLOR_BGR2RGB) # flip the image image = cv2.flip(image,1) image.flags.writeable = False # this is the main process results = hands.process(image) image.flags.writeable = True # print the results #print(results.multi_hand_landmarks) if results.multi_hand_landmarks: #for num, hand in enumerate(results.multi_hand_landmarks): # mp_drawing.draw_landmarks(image,hand,mp_hands.HAND_CONNECTIONS) # lets change the colors and the dots and joits for num, hand in enumerate(results.multi_hand_landmarks): mp_drawing.draw_landmarks(image,hand,mp_hands.HAND_CONNECTIONS, mp_drawing.DrawingSpec(color=(255,0,0),thickness=2 , circle_radius=4), mp_drawing.DrawingSpec(color=(0,255,255),thickness=2 , circle_radius=2)) # recolor back the image to BGR image = cv2.cvtColor(image,cv2.COLOR_RGB2BGR) cv2.imshow('image',image) if cv2.waitKey(10) & 0xff == ord('q'): break cap.release() cv2.destroyAllWindows()
f8fb1fe5d5ea5bfc13ae45785ff5056f62ef11be
g-yuqing/leetcode
/110_BalancedBinaryTree.py
900
3.890625
4
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def isBalanced(self, root): """ :type root: TreeNode :rtype: bool """ if root: if root.right and root.left: return self.isBalanced(root.right) and self.isBalanced(root.left) elif root.right and (not root.left): if root.right.right or root.right.left: return False else: return True elif root.left and (not root.right): if root.left.right or root.left.left: return False else: return True else: return True else: return True
d297ebdd6b0bd0cff9f655f14e8de4e3ebc5eb73
gagm04/Resolver-los-prerequisitos
/Laboratorio5/online_retail.py
1,431
3.609375
4
#import necessary libraries import pandas as pd import numpy as np import sklearn as skl import matplotlib as plt # Read in iris data set iris = pd.read_csv("/home/sheynnie/Escritorio/online_retail_price1") # Add column names, features as indepent variables iris.columns = ['Quantity','Price','StockCode'] # Split data into # features and target a = iris.iloc[:, 0:2]# first four columns of data frame with all rows b = iris.iloc[:, 2:] # last column of data frame (species) with all rows #import libraries from sklearn.model_selection import cross_validate from sklearn.model_selection import train_test_split # Train, test split, a is X as matrix, b as y the vector a_train, a_test, b_train, b_test = train_test_split(a,b, test_size=0.20, random_state=0) #from sklearn.svm import LinearSVC from sklearn.svm import SVC # Build Linear Support Vector Classifier #fit method to train the algorithm on the training data passed as parameter #clf = LinearSVC() clf = SVC(kernel='rbf') clf.fit(a_train, b_train.values.ravel()) # Make predictions on test set predictions = clf.predict(a_test) from sklearn.metrics import accuracy_score # Assess model accuracy result = accuracy_score(b_test, predictions, normalize=True) #evaluating the algorithm from sklearn.metrics import classification_report #confusion_matrix #print(confusion_matrix(b_test, predictions)) print(classification_report(b_test, predictions)) print(result)
af364441be52f06890e21fa6f84a5a1d8a41b66b
mola1129/atcoder
/contest/abc142/D.py
593
3.671875
4
import math import fractions a, b = map(int, input().split()) def make_divisors(n): divisors = [] for i in range(1, int(n ** 0.5) + 1): if n % i == 0: divisors.append(i) if i != n // i: divisors.append(n // i) divisors.sort() return divisors def is_prime(n): if n == 1: return False for k in range(2, int(math.sqrt(n)) + 1): if n % k == 0: return False return True ans = 1 divs = make_divisors(fractions.gcd(a, b)) for num in divs: if is_prime(num): ans += 1 print(ans)
f7e7a34ea40111b0b26dd16720d36377cac96c93
fallerd/CS2050
/Assignment04.py
7,716
3.640625
4
from __future__ import print_function from sys import stdin import unittest ''' Description: Assignment 04 - Family Tree Author: David Faller Version: 02 Help received from: Help provided to: ''' class FamilyTree(object): def __init__(self, name, parent=None): self.name = name self.left = self.right = None self.parent = parent def __iter__(self): if self.left: for node in self.left: yield node yield self.name if self.right: for node in self.right: yield node def __str__(self): return ','.join(str(node) for node in self) def add_below(self, parent, child): ''' Add a child below a parent. Only two children per parent allowed. Names form a set.''' if not self.find(child): where = self.find(parent) if not where: raise ValueError('could not find ' + parent) if not where.left: where.left = FamilyTree(child, where) elif not where.right: where.right = FamilyTree(child, where) else: raise ValueError(self + 'already has the allotted two children') def find(self, name): '''Return node with given name''' if self.name == name: return self if self.left: left = self.left.find(name) if left: return left if self.right: right = self.right.find(name) if right: return right return None def Parent(self, name): '''Return name of parent''' if self.find(name): if self.find(name).parent: return self.find(name).parent.name else: return None def grandparent(self, name): '''Return name of grandparent''' if self.find(name): parent = self.Parent(name) if self.find(parent).parent: return self.find(parent).parent.name else: return None def generations(self, new_root=None): ''' Return a list of lists, where each sub-list is a generation. ''' if new_root: this_level = [self.find(new_root)] if this_level == [None]: return None else: this_level = [self] next_level = [] result = [] names = [] while this_level: names.append(this_level[0].name) if this_level[0].left: next_level.append(this_level[0].left) if this_level[0].right: next_level.append(this_level[0].right) this_level.pop(0) if not this_level: result.append(names) names = [] this_level = next_level next_level = [] return result def inorder(self, list=None): ''' Return a list of the in-order traversal of the tree. ''' if None == list: list = [] if self.left: self.left.inorder(list) list.append(self.name) if self.right: self.right.inorder(list) return list list.append(self.name) return list list.append(self.name) return list def preorder(self, list=None): ''' Return a list of the pre-order traversal of the tree. ''' if None == list: list = [] list.append(self.name) if self.left: self.left.preorder(list) if self.right: self.right.preorder(list) return list return list return list def postorder(self, list=None): ''' Return a list of the post-order traversal of the tree. ''' if None == list: list = [] if self.left: self.left.postorder(list) if self.right: self.right.postorder(list) list.append(self.name) return list list.append(self.name) return list list.append(self.name) return list class CLevelTests(unittest.TestCase): def test_empty(self): self.assertEquals(str(FamilyTree(None)), 'None') def setUp(self): self.tree = FamilyTree("Grandpa") self.tree.add_below("Grandpa", "Homer") self.tree.add_below("Grandpa", "Herb") self.tree.add_below("Homer", "Bart") self.tree.add_below("Homer", "Lisa") def test_str(self): self.assertEquals(str(self.tree), "Bart,Homer,Lisa,Grandpa,Herb") def test_inorder(self): self.assertEquals(self.tree.inorder(), ["Bart", "Homer", "Lisa", "Grandpa", "Herb"]) def test_preorder(self): self.assertEquals(self.tree.preorder(), ["Grandpa", "Homer", "Bart", "Lisa", "Herb"]) def test_postorder(self): self.assertEquals(self.tree.postorder(), ["Bart", "Lisa", "Homer", "Herb", "Grandpa"]) class BLevelTests(unittest.TestCase): def setUp(self): self.tree = FamilyTree("Grandpa") self.tree.add_below("Grandpa", "Homer") self.tree.add_below("Grandpa", "Herb") self.tree.add_below("Homer", "Bart") self.tree.add_below("Homer", "Lisa") def testparent(self): self.assertEquals(self.tree.Parent("Lisa"), "Homer") self.assertEquals(self.tree.Parent("Marge"), None) def test_grandparent(self): self.assertEquals(self.tree.grandparent("Lisa"), "Grandpa") def test_no_grandparent(self): self.assertEquals(self.tree.grandparent("Homer"), None) self.assertEquals(self.tree.grandparent("Marge"), None) class ALevelTests(unittest.TestCase): def setUp(self): self.tree = FamilyTree("Grandpa") self.tree.add_below("Grandpa", "Homer") self.tree.add_below("Grandpa", "Herb") self.tree.add_below("Homer", "Bart") self.tree.add_below("Homer", "Lisa") self.tree.add_below("Lisa", "Zia") self.tree.add_below("Bart", "Kirk") self.tree.add_below("Bart", "Picard") def test_generations(self): self.assertEquals(self.tree.generations(), \ [["Grandpa"], ["Homer", "Herb"], ["Bart", "Lisa"], ["Kirk", "Picard", "Zia"]]) ''' Write some more tests, especially for your generations method. ''' def test_generations_additive(self): tree1 = FamilyTree(None) self.assertEquals(tree1.generations(), [[None]]) tree1.add_below(None, "Homer") tree1.add_below(None, "Herb") self.assertEquals(tree1.generations(), [[None], ["Homer", "Herb"]]) tree1.add_below("Homer", None) self.assertEquals(tree1.generations(), [[None], ["Homer", "Herb"]]) def test_generations_from(self): self.assertEquals(self.tree.generations("Homer"), [["Homer"], ["Bart", "Lisa"], ["Kirk", "Picard", "Zia"]]) self.assertEquals(self.tree.generations("Bart"), [["Bart"], ["Kirk", "Picard"]]) self.assertEquals(self.tree.generations("Marge"), None) if '__main__' == __name__: ''' Read from standard input a list of relatives. The first line must be the ultimate ancestor (the root). The following lines are in the form: parent child.''' for line in stdin: a = line.strip().split(" ") if len(a) == 1: ft = FamilyTree(a[0]) else: ft.add_below(a[0], a[1]) print(ft.generations())
d85c53775aa0a720b7b8099063ad24267b34ae5d
Davidxswang/leetcode
/easy/1446-Consecutive Characters.py
1,098
3.859375
4
""" https://leetcode.com/problems/consecutive-characters/ Given a string s, the power of the string is the maximum length of a non-empty substring that contains only one unique character. Return the power of the string. Example 1: Input: s = "leetcode" Output: 2 Explanation: The substring "ee" is of length 2 with the character 'e' only. Example 2: Input: s = "abbcccddddeeeeedcba" Output: 5 Explanation: The substring "eeeee" is of length 5 with the character 'e' only. Example 3: Input: s = "triplepillooooow" Output: 5 Example 4: Input: s = "hooraaaaaaaaaaay" Output: 11 Example 5: Input: s = "tourist" Output: 1 Constraints: 1 <= s.length <= 500 s contains only lowercase English letters. """ # time complexity: O(n), space complexity: O(1) class Solution: def maxPower(self, s: str) -> int: current = s[0] count = 1 maxi = 1 for i in range(1, len(s)): if s[i] == current: count += 1 else: current = s[i] count = 1 maxi = max(maxi, count) return maxi
f66d64323f7d63191373e1e7af264000112c8a69
namratarane20/MachineLearning
/ML Basics/Create module in python for reusability.py
968
3.78125
4
#!/usr/bin/env python # coding: utf-8 # In[5]: def function(): print('welcome to jypyter notebook') # In[6]: def add(): num1 = int(input('Enter the first number ')) num2 = int(input('Enter the second number')) print('addition of an Entered numbers is ', num1 +num2) # In[7]: def sub(): num1 = int(input('Enter the first number ')) num2 = int(input('Enter the second number')) print('addition of an Entered numbers is ', num1 - num2) # In[12]: def mul(): num1 = int(input('Enter the first number ')) num2 = int(input('Enter the second number')) num3 = num1* num2 return num3 # In[ ]: # We can save our all function in one py file add our py file in Scripts folder in python. # and then if we want to access the perticular function from this file we need to import our file name and # then we can use or oun fuction anywhere. # just condtion is that we should not call any function in py file.
cbfb595f2e2ac70e40c00eba08f7ac719816bf5f
harisahmed11/FintechPy
/playground/python_lang_playground.py
183
3.65625
4
list_of_tuples = [ (1, 'Adnan', 39.6), (2, 'Naveen', 35.5), (3, 'Sabah', 13.1), ] for index, (id, name, age) in enumerate(list_of_tuples): print(index, id, name, age)
cd7a934dcc2bfb05ab400866cfccebd0efd60888
sppenna/cs415a1
/Sieve.py
377
3.84375
4
''' Finds Prime Numbers 2 - n and stores them in a list ''' def sievePrimes(n, count): """ """ count = 0 primeList = [] for h in range(1, n): primeList.append(h) for i in range(2, n): for j in range(i, n): count+=1 k = i * j if k in primeList: primeList.remove(k) return count
017212ac196114317e88f0a42b60c51e5a2d72a0
ffabut/kreap1
/4/ukol2.py
520
3.890625
4
def multipleHello(jmeno, x=1): pozdrav = "Hello " + jmeno + "!" # pozdrav vytvorime zde, at to pocitac nemusi vypocitavat pri kazdem novem pozdravu while x > 0: print(pozdrav) x = x - 1 # po pozdraveni zmensime x o 1 a cyklus se pote zepta, zda je cislo stale vetsi nez 0, tj. jestli mame jeste jednou opakovat # navratova hodnota neni treba # test zda to funguje: multipleHello("Eve", 9) multipleHello("George") # pokud nebudeme specifikovat druhy parametr, pouzije se jeho vychozi hodnota
7731c443ecc49348fe5c962a3e5af7a0196f58c0
sivakrishnarajarapu/code_signal-challenges
/Desktop/Desktop/Code_signals_challenge/test_28.py
200
3.578125
4
# m=chr(ord("s")+1) # print(m) def fun(s): n='' for i in s: if i=='z': n+='a' else: k=chr(ord(i)+1) n+=k return n print(fun("crazy"))
9b6fc3d43d5c790807825a2d29f9fd5cdcccc76e
hao310rui140326/my_verilog
/PCIE-TLP-DEMO/tb/test.py
752
3.765625
4
#def foo(): # print("starting...") # while True: # res = yield 4 # print("res:",res) # #g = foo() #print(next(g)) #print("*"*20) #print(next(g)) #def fun_inner(): # i = 0 # while True: # i = yield i # #def fun_outer(): # a = 0 # b = 1 # inner = fun_inner() # inner.send(None) # while True: # a = inner.send(b) # b = yield a # #if __name__ == '__main__': # outer = fun_outer() # outer.send(None) # for i in range(5): # print(outer.send(i)) def fun_inner(): i = 0 while True: i = yield i def fun_outer(): yield from fun_inner() if __name__ == '__main__': outer = fun_outer() outer.send(None) for i in range(5): print(outer.send(i))
164d072f1edcb96e208e8c6193e1ccec6afef610
USTH-Coders-Club/API-training
/callapi.py
527
3.8125
4
#import the library to make http request import requests #URL of the API URL = "https://ssd-api.jpl.nasa.gov/cad.api" distmax = input("set the maximum distance: ") vinfmax = input("set the maximum speed: ") #Params param = { 'dist-max': distmax, 'v-inf-max': vinfmax } #Make an API request and store date to r r = requests.get(url= URL, params = param) #Json data data = r.json() #extract count from data n = data['count'] print(f"The number of asteroids approaching earth within {distmax} at {vinfmax} is {n}")
4eae8f0722c2b3deadc57599dddbe26e7cc15f0e
Cecilia520/algorithmic-learning-leetcode
/cecilia-python/others/CalMaxPathNum.py
2,287
3.53125
4
#!/usr/bin/env python # -*- encoding: utf-8 -*- """ @File : CalMaxPathNum.py @Contact : 70904372cecilia@gmail.com @License : (C)Copyright 2019-2020 @Modify Time @Author @Version @Desciption ------------ ------- -------- ----------- 2020/9/15 18:59 cecilia 1.0 米兔吃胡萝卜,计算最大胡萝卜数目 """ from typing import List class Solution: def calMaxNum(self, matrix: List[List[int]], m: int, n: int) -> int: """ 统计胡萝卜的最大数目 :param matrix: 输入矩阵 :param m 矩阵的行数 :param n 矩阵的列数 :return: """ if not m and not n: return 0 dp = [[0 for _ in range(n)] for _ in range(m)] dp[0][0] = matrix[0][0] for j in range(1, n): dp[0][j] = dp[0][j - 1] + matrix[0][j] for i in range(1, m): dp[i][0] = dp[i - 1][0] + matrix[i][0] for i in range(1, m): for j in range(1, n): dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]) + matrix[i][j] return dp[-1][-1] def calMaxNum2(self, matrix: List[List[int]], m: int, n: int) -> int: """ 统计胡萝卜的最大数目(空间优化) :param matrix: 输入矩阵 :param m 矩阵的行数 :param n 矩阵的列数 :return: """ if not m and not n: return 0 for i in range(m): for j in range(n): if i == j == 0: continue elif i == 0: matrix[i][j] = matrix[i][j - 1] + matrix[i][j] elif j == 0: matrix[i][j] = matrix[i-1][j] + matrix[i][j] else: matrix[i][j] = max(matrix[i-1][j], matrix[i][j-1]) + matrix[i][j] return matrix[-1][-1] if __name__ == '__main__': s = Solution() input_list = input().strip().split() m, n = int(input_list[0]), int(input_list[1]) matrix = [] for i in range(m): tmp_list = list(map(int, input().strip().split())) matrix.append(tmp_list) print("matrix:{}".format(matrix)) print(s.calMaxNum(matrix, m, n)) print("-----------2------------") print(s.calMaxNum2(matrix, m, n))
9064fb62cc947b47b05a1809c99cd37ea3a74cd9
Oussema3/OneMonth
/formatters.py
698
3.578125
4
#!/usr/bin/python3 #strings are texts surronded by quotes singles '' or double "" or triple """ kanye_quote = "My greatest pain in life is that i will never be able to see my self perform live" print(kanye_quote) print() print("Now splited") print() kanye_splited_quote = """My greatest pain in life is that i will never be able to see my self perform live """ print(kanye_splited_quote) hamilton_quote = "well , the word got arround, they said, \"this kid is insane\"" print() print(hamilton_quote) name = "Mathan Griffel" orphan_fee = 200 teddy_bear_fee = 121.087525 total = orphan_fee + teddy_bear_fee #print(name, "the total will be: ", total) print() print(f"{name} the total will be {total:.2f}")
22f0790136f45572012603570cd1bb2d69ae8afa
rscorrea1/youtube
/python_from_scratch/13_dictionaries/dictionaries.py
712
4.5625
5
############################################# # Let's learn about Dictionaries in Python! # ############################################# ## how to initialize a dictionary menu = {} ## how to add element to a dictionary menu["Cappuccino"] = 2.5 menu["Tea"] = 1.5 menu["Water"] = 1.0 menu["Juice"] = 2.0 # print(menu) ## dictionary length # print(len(menu)) ## how to retrieve data from a dictionary element # tea_price = menu["Tea"] # water_price = menu["Water"] # # print(tea_price,water_price) # if "Orange" in menu: # print(menu["Orange"]) # else: # print("key not valid") ## how to reassign data menu["Tea"] = 1.8 print(menu) ## how to remove a dictionary element del menu["Water"] print(menu)
95ad0d6eff5f4bdbd20ac5e7b4b5e01ec32ed0a4
tgfbikes/python
/CS-1410/Drills/drill18.py
799
3.71875
4
import random class MathProblem: def __init__(self): self.num1 = random.randrange(1, 10) self.num2 = random.randrange(1, 10) def get_first_operand(self): return self.num1 def get_second_operand(self): return self.num2 def get_answer(self): return None def set_new_values(self): self.num1 = random.randrange(1, 10) self.num2 = random.randrange(1, 10) class AdditionProblem(MathProblem): def get_answer(self): num1 = self.get_first_operand() num2 = self.get_second_operand() return num1 + num2 class MultiplicationProblem(MathProblem): def get_answer(self): num1 = self.get_first_operand() num2 = self.get_second_operand() return num1 * num2
10f8a06fd1f918ccbb3bb89dbbf108b1a424437e
shailchokshi/ClientServer
/client.py
1,601
3.96875
4
from socket import * import sys import urllib.request #The socket module forms the basis of all network communication #Firstline specifies the address of the server. it can be an IP or servername. #e.g. "128.138.32.126" or "yourserver.eng.uci.edu" #second line shows which port your server will be working on(usually we use high number) clientSocket = socket(AF_INET, SOCK_STREAM) #this line creats a socket called clientSocket. #AF_INET specifies address family which is IPv4 #SOCK_STREAM shows the protocol for the socket which is TCP here. clientSocket.connect((sys.argv[1], sys.argv[2])) #initiates the TCP connection between the server and client. 3way handshake is established. clientSocket.send(sys.argv[3]) #this linse sends the sentence through the client's socket into TCP connection. #here we dont have to specify the address explicitly like UDP. #Instead we simply drop the packet to established TCP connection. modifiedSentence = clientSocket.recv(10000) #now when a message is recieved from internet to the client socket we will get it here. #then we will put the message in modifiedMessage. #2048 here is the size of the buffer for receiving data print ('From Server:', modifiedSentence.decode()) outputdata = urllib.request.urlopen(sys.argv[3]).read() for i in range(0, len(outputdata)): print(outputdata[i:i+1]); clientSocket.close() #IMPORTANT TO RUN THIS CODE #this code has to be run with arg parameters passed into through the command line # client.py server_host server_port filename #filename is the path to the file hosted on the server (e.g www.test.com/sam.html)
44bfdc6ed86805cefef1c88b86f283571e0db5a4
WilliamslifeWayne/python_practice
/python_new/collatz.py
3,550
4.15625
4
#例题: """ 考拉兹猜想(Collatz Conjecture),也叫奇偶归一猜想、3n + 1猜想、冰雹猜想、角骨猜想、哈塞猜想、乌拉姆猜想、叙拉古猜想 算法介绍: 1.对于每一个正整数,如果他是奇数,就对他乘以3,再加1,如果是偶数则对他除以2,最终都能得到1. """ # def collatz_conjecture(number): # while number != 1: # if number % 2 == 0: # # 偶数 # number /= 2 # print(number) # elif number % 2 == 1: # # 奇数 # number = number * 3 + 1 # print(number) # collatz_conjecture(6) # 习题2: 打印九九乘法表 # for i in range(1, 10): # for j in range(1, 10): # print("{} x {} = {:<2d}".format(i, j, i * j), end=' ') # print(f"{i} x {j} = {i * j}", end='') # print("{0}x{1}={2:0>2}".format(i,j,i*j),end="\t") # print() # 99乘法表的别的三角形写法 # for i in range(1,10): # j = 1 # while j <= i: # print("{}x{}={:2d}".format(j, i, i*j), end=" ") # j +=1 # print() # 习题3:鸡兔同笼问题:鸡兔同笼是古代我们数学名题之一,大约在1500年前,《孙子算经》中记载:今有雉兔同笼,上有三十五头,下有九十四足,雉兔各几何? #鸡兔共35只,用穷举法 # for rabbit in range(0, 35): # for chicken in range(0, 35): # if (rabbit + chicken) == 35 and (rabbit * 4 + chicken * 2 == 94): # print(f"鸡有{chicken}只,兔子有{rabbit}只") #以下是个死循环 # while True: # for x in range(6): # y = 2 * x + 1 # print(y) # if y > 9: # break # import math # # 二分法求平方根 # def square_root(num): # low = 0 # high = num # guess = (high + low ) / 2 # while abs(guess ** 2 - num) > 1e-6: # if guess ** 2 > num: # high = guess # else: # low = guess # guess = (low + high) / 2 # print(guess) # square_root(3) # 习题4: 从1开始,数 50 个素数 # count = 0 # num = 2 # while count <= 50: # for i in range(2, num): # if num % i == 0: # break # else: # print(num, end=" ") # count += 1 # num += 1 # 习题5:判断一个数字是不是回文数 例如 13431就是个回文数 # def is_repeat_num(num): # if num / 10 < 1: # # 说明是个 个位数 # print("{}是一个回文数".format(num)) # elif num / 100 < 1: # # 说明是个两位数 # shi = num // 10 # ge = num % 10 # if shi == ge: # print(f"{num}是一个回文数") # elif num / 1000 < 1: # # 说明是个 三位数 # bai = num // 100 # shi = num // 10 % 10 # ge = num % 10 # print(bai) # print(shi) # print(ge) # if bai == ge: # print("{0}是个回文三位数".format(num)) # else: # print("{0}不是个回文三位数".format(num)) # is_repeat_num(886) # 习题五 视频解法 # def judge_repeat_num(num): # num_t = num # num_p = 0 # while num != 0: # print(f"{num_p} num_p") # print(f"{num_t} num_t") # print(f"{num} num") # num_p = num_p * 10 + num % 10 # num = num // 10 # if num_t == num_p: # print(f"{num_t}是一个回文数") # else: # print("{}不是一个回文数".format(num_t)) # judge_repeat_num(888)
d3c34edd9cd84056bd5469d6bd3676e3cd0009ec
dmitrie43/PythonLabs
/Lab3-6/functions/Helper.py
3,001
3.53125
4
import os import csv class Helper: """ Класс для требований к программе. Лаб 3 Дополнительный функционал """ @staticmethod def get_count_in_dir(path) -> list: """ Возвращает кол-во файлов в директории :param str path: :return list: """ return os.listdir(path) @staticmethod def get_csv_data(path_to_csv) -> dict: """ Возвращает данные из csv файла :param str path_to_csv: :except OSError: :return dict: """ data = dict() try: with open(path_to_csv, "r") as file_obj: reader = csv.reader(file_obj) for index, row in enumerate(reader): data[index] = row except OSError: print('Ошибка работы с файлом') return data @staticmethod def record_in_csv(path_to_csv, csv_data): """ Запись данных в csv файл :param str path_to_csv: :param list csv_data: :except Exception: :return void: """ try: with open(path_to_csv, "a", newline='') as file_obj: writer = csv.writer(file_obj, delimiter=',') for line in csv_data: writer.writerow(line) except Exception: print('Ошибка работы с файлом') """Пусть дана некоторая директория (папка). Посчитайте количество файлов в данной директории (папке) и выведите на экран""" path_to_dir = os.getcwd() # print(Helper.get_count_in_dir(path_to_dir)) """Считайте информацию из файла в соответствующую структуру (словарь)""" path_to_file = 'D:\PythonWorks\Labs\Lab3-6\\files\data.csv' # print(Helper.get_csv_data(path_to_file)) """Выведите информацию об объектах, отсортировав их по одному полю (строковому)""" print(sorted(Helper.get_csv_data(path_to_file).items(), key=lambda item: item[1])) """Выведите информацию об объектах, отсортировав их по одному полю (числовому)""" print(sorted(Helper.get_csv_data(path_to_file).items())) """Выведите информацию, соответствующую какому-либо критерию""" print(Helper.get_csv_data(path_to_file)) data = Helper.get_csv_data(path_to_file).items() res3 = {k: v for k, v in data if 'leff' in v} print(res3) """Добавьте к программе возможность сохранения новых данных обратно в файл.""" # data = ['tv,skyline3,20,22000'.split(',')] # Helper.record_in_csv(path_to_file, data)
1920acc95446b7a068217a998ed9233435e67517
Aasthaengg/IBMdataset
/Python_codes/p02400/s581321955.py
81
3.65625
4
import math r = float(input()) print("%.10f %.10f"%(r**2*math.pi,2.0*math.pi*r))
be77e30a49b7c5d371f78a524e7eac1f25f3c742
greyhere/data-structures-and-algorithms-in-python
/ch04/R-4.3.py
886
4.0625
4
''' R-4.3 Draw the recursion trace for the computation of power(2,18), using the repeated squaring algorithm, as implemented in Code Fragment 4.12. ''' def power(x, n): '''Compute the value x**n for integer n.''' if n == 0: return 1 else: partial = power(x, n // 2) result = partial * partial if n % 2 == 1: result *= x return result print(power(2, 18)) ''' The recursion trace for the computation of power(2, 18) is, return 512 * 512 = 262144 power(2, 18) return 16 * 16 * 2 = 512 power(2, 9) return 4 * 4 = 16 power(2, 4) return 2 * 2 = 4 power(2, 2) return 1 * 1 * 2 = 2 power(2, 1) return 1 power(2, 0) '''
4643d368a020f067358e6dfa6919eb6f0031e05b
luisnarvaez19/Proyectos_Python
/edu/cursoLN/funciones/funciones4.py
960
4.25
4
''' Created on Agosto 18, 2019 Imprime un rango de valores y *args como argumento @author: luis. ''' print(list(range(3, 6))) # normal call with separate arguments args = [3, 6] print(list(range(*args))) # call with arguments unpacked from a list var_global = "cualquiera" # Hacer multiplicacion de multiples numeros def multiplicar(*args): resultado=1 for i in args: resultado *= i return resultado print(multiplicar(5,15,2,1)) # Python program to illustrate # *args for variable number of arguments def myFun(*argv): for arg in argv: print(arg) print(myFun('Hello', 'Welcome', 'to', 'GeeksforGeeks')) # Python program to illustrate # *kargs for variable number of keyword arguments def myFun(**kwargs): for key, value in kwargs.items(): #print("%s == %s" % (key, value)) print(f"{key} == {value}") # Driver code print(myFun(first='Geeks', mid='for', last='Geeks'))
413b5fdcc7874962a7ecd2b53e8454bcb6b0be5e
JZY11/mypro01
/myoop13.py
435
3.671875
4
# 测试 mro() 方法(查看类的目录结构) class A: pass class B(A): pass class C(B): pass print(C.mro()) # 重写 object的 __str__() class Person: def __init__(self,name): self.name = name def __str__(self): return "名字是:{0}".format(self.name) p = Person("小二") # print(p) # 不重写object的 __str__()时打印结果:<__main__.Person object at 0x002FAF30> print(p)
c9ad96870251f452c54ce5746f789137899b6998
shaikshareef99/Email-Spam-Filter
/classifier.py
978
3.984375
4
from collections import defaultdict #Classifier object declaration class classifier(object): """Classifier feature initialization""" def __init__(self): self.label_word_count = defaultdict(int) self.feature_count = defaultdict(lambda: defaultdict(int)) self.total_word_count = 0 self.total_email_count = 0 self.label_email_count = defaultdict(int) """Train function used to train the classifier based on the given features""" def train(self,features,label): for feature in features: self.feature_count[label][feature] = self.feature_count[label][feature]+1 self.label_word_count[label] = self.label_word_count[label]+1 self.total_word_count = self.total_word_count+1 self.label_email_count[label] = self.label_email_count[label]+1 self.total_email_count = self.total_email_count+1
b54da8ff96609263451631f3d326a39ee53dc63d
DOCgould/MessagePassing
/Shafi/Calibrated_Control.py
2,358
3.578125
4
import pygame import numpy as np def set_thruster_value(input_matrix): ''' Parameters: Matrix of xbox inputs Returns: the dot product of the xbox input along with this mathematically predetermined map by me, not by Christian at all. Why do you ask? ''' thruster_matrix = np.matrix(\ '1 0 0 0 0 0 1 0; \ 0 -1 0 0 0 -1 0 0; \ 0 0 0 -1 0 0 0 -1; \ 0 0 1 0 1 0 0 0; \ 0 1 0 0 0 1 0 0; \ 0 0 0 1 0 0 0 1') #print(np.dot(input_matrix, thruster_matrix)) return np.dot(input_matrix, thruster_matrix) def Calibrate(event): ''' Parameters: Xbox event Returns: Dot product of xbox values corresponding to the correct thruster ''' if event.type == pygame.JOYAXISMOTION: if event.axis == 1: return set_thruster_value(np.array([(-1 *event.value), 0, 0, 0, 0, 0])) #up down on left joystick, inverted elif event.axis == 2: #xbox trigger initial state is set to 1. this will cause the motors to continue spinning if trigger is released return set_thruster_value(np.array([0, 0, ((event.value + 1)/2), 0, 0, 0])) #left trigger elif event.axis == 4: return set_thruster_value(np.array([0, 0, 0, (-1 *event.value), 0, 0])) #up/down on right joystick elif event.axis == 5: #same reason as the left trigger return set_thruster_value(np.array([0, 0, 0, 0, 0, ((event.value + 1)/2)])) #right trigger else: return set_thruster_value(np.array([0,0,0,0,0,0])) elif event.type == pygame.JOYBUTTONDOWN: if event.button == 4: return set_thruster_value(np.array([0, 1, 0, 0, 0, 0])) #left bumper elif event.button == 5: return set_thruster_value(np.array([0, 0, 0, 0, 1, 0])) #right bumper elif event.button == 1: return "SWAP" else: return set_thruster_value(np.array([0,0,0,0,0,0])) elif event.type == pygame.JOYBUTTONUP: return set_thruster_value(np.array([0,0,0,0,0,0])) def main(): clock = pygame.time.Clock() pygame.init() pygame.joystick.init() joystick = pygame.joystick.Joystick(0) joystick.init() while True: for event in pygame.event.get(): print(Calibrate(event)) clock.tick(15) if __name__ == '__main__': main()
3def7b80a5a0f048754372f9ff9de5f40ced665e
rfm110/Tower_of_Hanoi
/recursive_tower_of_hanoi.py
1,844
4.15625
4
def recursive_tower_of_hanoi(pin_1=[4,3,2,1], pin_2=[], pin_3=[], number_of_disks=4): # change parameter names so they are more general? like source, target, and intermediate if pin_3 == [4, 3, 2, 1]: print "Game Completed" return pin_1, pin_2, pin_3 # let pin_1 be the source, pin_2 be the intermediate, and pin_3 be the destination # instead of using while loop, make function call itself print "Current Game State:", pin_1, pin_2, pin_3 print # if pin_3 != [4,3,2,1]: if number_of_disks != 0: # move disk from source to intermediate so pin_2 is the new target print "Moving disk from source to intermediate" print "recursion a" recursive_tower_of_hanoi(pin_1, pin_3, pin_2, number_of_disks-1) print "number of disks a", number_of_disks print "source", pin_1 print "intermediate", pin_3 print "target", pin_2 print # when source is not empty, move disk from source to target (pin_1 to pin_3) if pin_1 != []: # pin_3.append(pin_1[len(pin_1)-1]) print "Source is non-empty, moving disk from pin1(source) to pin3(target)" pin_3.append(pin_1.pop()) print "source", pin_1 print "intermediate", pin_2 print "target", pin_3 print # step 3 is moving disk from intermediate to target, from pin_2 to pin_3 print "Moving disk from intermediate to target" print "recursion b" recursive_tower_of_hanoi(pin_2, pin_1, pin_3, number_of_disks-1) print "number of disks b", number_of_disks print pin_2, pin_1, pin_3 print "source", pin_2 print "intermediate", pin_1 print "target", pin_3 print if __name__ == "__main__": recursive_tower_of_hanoi()
e83ae221fd2ffee37cc5ee7842f8766a26c2c9ae
sling1678/python
/hacker_rank/src/day1_prob.py
1,221
3.65625
4
import math N_int = int(input().strip()) if not (10 <= N_int <= 2500): raise AssertionError (" N must be integer between 10 <= N <= 2500 ") x = list(map(int, input().split())) # check right number of data points if not(N_int == len(x)): raise ValueError (" Number of elements of x mus t equal N") for num in x: if not (0 <= num <= 10**5): raise AssertionError (" All xi must be integer between 0 <= num <= 10**5") def find_mean(x): sum = 0 for num in x: sum += num mean = sum / len(x) return mean def find_median (x): idx_mid = len(x)//2 y = sorted(x) if len(x)%2 == 0: median = (y[idx_mid] + y[idx_mid - 1])/2 else: median = y[idx_mid] return median def find_mode(x): y = {} for i in range(len(x)): k = x[i] if k not in y: y[k] = 1 else: y[k] = y[k] + 1 max = 0 z = math.inf for k in y: v = y.get(k) if v >= max: max = v for k in y: v = y.get(k) if max == v and z > k: z = k return z ## main program print("mean = %f" %find_mean(x)) print("median = %f" %find_median(x)) print("mode = %f" %find_mode(x))
f8ffea9374c11fe71f9dcd945efaf1bb28f35c2f
Ye0l/python
/inputTest.py
122
3.53125
4
a = input("a 값을 입력하세요.") b = input("b 값을 입력하세요.") c = int(a) + int(b) print(a, "+", b, "=", c)
bbac88a7a57f3445153d1df85ecddc235e53c4f7
denis-trofimov/challenges
/leetcode/contest 156/Unique Number of Occurrences.py
461
3.5
4
from collections import Counter class Solution: def uniqueOccurrences(self, arr) -> bool: c = Counter(arr) l = list(c.values()) c2 = Counter(l) for i in c2.values(): if i > 1: return False return True if __name__ == "__main__": sol = Solution() case_input = [1,2] answer = sol.uniqueOccurrences(case_input) print(answer) expected = False assert expected == answer
31acd0b2f7c52ed3ef971048e9e28634341300e6
IsraelCavalcante58/Python
/Aprendendo Python/exercicios/ex012.py
301
3.59375
4
#Faça um algoritmo que leia o preço de um produto e mostre seu novo preço com 5% de desconto. preco = int(input('Qual o valor do produto?')) novo = preco - (preco * 5 / 100) print(f'O preço do produto sem desconto é: R${preco:.2f}') print(f'O valor com os 5% de desconto ficará: R${novo:.2f}')
da933451e22bea77b47d37ae16980b0385e5de03
DUanalytics/pyAnalytics
/88-TS/88B2_dt_intro2.py
1,432
3.71875
4
#Date Time - Operations & Arithmetic #----------------------------- #% from datetime import datetime as dt #to date from integer values new_date = dt(2019,7,4) new_date equinoxDate = dt(2019,6,23) equinoxDate #%% d1 = dt(2010,6,10) d2 = dt(2019,7,28) d2 + d1 #error diff=d2 - d1 #number of days diff diff/365 #this yrs #%% d3 = dt(2019, 7, 4, 15, 30, 59, 10) d3 d3.hour #hour d3.minute #minute d3.second #second d3.microsecond #microsecond d3.tzinfo #no info store in environment #time instance datetime.time.min datetime.time.max datetime.time.resolution #Date parts today = datetime.date.today() today today.ctime() today.timetuple() today.toordinal() today.year today.month today.day #time import time time.time() time.localtime() #time from datetime import time # time(hour = 0, minute = 0, second = 0) a = time() print("a =", a) # time(hour, minute and second) b = time(11, 34, 56) print("b =", b) # time(hour, minute and second) c = time(hour = 11, minute = 34, second = 56) print("c =", c) # time(hour, minute, second, microsecond) d = time(11, 34, 56, 234566) print("d =", d) #Replace a portion of date d = dt(2019, 7, 4,15,30) d d1=d.replace(day=28, year=2011) d1 #tuple : date time value d.timetuple() d.weekday() d.isoweekday() d.isocalendar() d.ctime() d.isoformat() #From 0 date d3 = dt.fromordinal(730920) # 730920th day after 1. 1. 0001 d3 #https://www.programiz.com/python-programming/datetime
c51026745e1c90a494d97e176d12b7037aa62dc8
djrgit/coursework
/udemy/python-video-workbook/my_progress/086.py
259
3.515625
4
# Exercise 86 - Data Checker checklist = ["Portugal", "Germany", "Munster", "Spain"] with open('countries_clean.txt', 'r') as f: countries = [l.strip('\n') for l in f.readlines()] filtered = [c for c in checklist if c in countries] print(sorted(filtered))
2c7c0243cfb250654e578ff575bbb68053d0f7be
DimejiAre/code-challenges
/python/equalize_array.py
311
3.703125
4
""" https://www.hackerrank.com/challenges/equality-in-a-array/problem """ def equalizeArray(arr): count = {} largest = 0 for i in arr: if i in count: count[i] += 1 else: count[i] = 1 largest = max(count[i], largest) return (len(arr) - largest)
f511e32735963d72e1a2bec216f8c8333afd3a2c
bartkowiaktomasz/algorithmic-challenges
/LeetCode - Top Interview Questions/BinaryTreeLevelOrderTraversal.py
1,067
3.921875
4
from collections import deque from typing import List # 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 levelOrder(self, root: TreeNode) -> List[List[int]]: res = [] queue = deque([root]) direction = 1 while len(queue) > 0: single_res = [] temp_queue = deque() while queue: node = queue.pop() if node is not None: single_res.append(node.val) if direction == 1: temp_queue.appendleft(node.left) temp_queue.appendleft(node.right) else: temp_queue.appendleft(node.right) temp_queue.appendleft(node.left) direction *= -1 queue = temp_queue if single_res: res.append(single_res) return res
fa4751dca2d7f80cdbea0f586c408e5bb6011265
mbermudez00/Tutorials
/Python/examples.py
488
3.890625
4
#x = "ejemplo" kilometer = [39.2, 36.5, 37.3, 37.8] try: #x = "Caballo" if x=="ejemplol" else x #feet = [3280.8399*x for x in kilometer] feet = map(lambda x: float(3280.8399)*x, kilometer) print(list(feet)) except: print("esto paso el try") # num = input("ingresa el numero maximo menor a 200: ") # try: # num = int(num) # print(2) # for i in range(3,(num+1)): # if i%2==1: print(i) # except ValueError: # print("only number allowed!")
f6342d6bd0db6fa911141a7dc0b4343a03ba6540
benjazor/leetcode
/Solutions/sortedArrayToBST.py
825
3.6875
4
# NAME : Convert Sorted Array to Binary Search Tree # LINK : https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/ # DATE : 29/04/2021 # 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 sortedArrayToBST(self, nums: List[int]) -> TreeNode: def recursion(i: int, j: int) -> TreeNode: if i == j: return TreeNode(nums[i]) if i > j: return None return TreeNode( nums[i + (j - i) // 2], recursion(i, i + (j - i) // 2 - 1), recursion(i + (j - i) // 2 + 1, j) ) return recursion(0, len(nums) - 1)
9bd373b912c9b2cc41c51627afded4e22655830c
manuelemacchia/algorithms
/data/stack.py
920
3.9375
4
class Stack: def __init__(self, n): self.n = n # maximum length of stack self.pos = -1 # current position inside stack (-1 is empty) self.stack = [None] * n def __repr__(self): return str(self.stack[:self.pos+1]) def _stack_empty(self): if self.pos == -1: return True return False def push(self, elem): if self.pos == self.n-1: raise IndexError("Stack overflow") self.pos += 1 self.stack[self.pos] = elem def pop(self): if self._stack_empty(): raise IndexError("Stack underflow") self.pos -= 1 return self.stack[self.pos+1] # Example my_stack = Stack(3) print(my_stack) my_stack.push(5) my_stack.push(7) my_stack.push(9) print(my_stack) print(my_stack.pop()) print(my_stack.pop()) print(my_stack) print(my_stack.pop())
eea8f453814c55a0854005e8f8a2b1afefec891a
nils-frank/moodle_fragen_importer
/jquiz_import.py
2,601
3.65625
4
#!/usr/local/bin/python import csv from sys import argv def read_csv(filename, fms): with open(filename, 'rb') as csvfile: csv_file = csv.reader(csvfile, delimiter=',', quotechar='|') next(csv_file, None) for row in csv_file: each_q = format_to_xml(fms, row) write_to_file(each_q) def write_to_file(q): xml_file = argv[2] jquiz_file = open(xml_file, 'r') line = jquiz_file.readlines() jquiz_file.close() line.insert(27, q) jquiz_file = open(xml_file, "w") content = "".join(line) jquiz_file.write(content) jquiz_file.close() def get_empty_template(): return """ <question-record> <question>{}</question> <clue></clue> <category></category> <weighting>100</weighting> <fixed>0</fixed> <question-type>{}</question-type> <answers> <answer> <text>{}</text> <feedback></feedback> <correct>{}</correct> <percent-correct>0</percent-correct> <include-in-mc-options>1</include-in-mc-options> </answer> <answer> <text>{}</text> <feedback></feedback> <correct>{}</correct> <percent-correct>100</percent-correct> <include-in-mc-options>1</include-in-mc-options> </answer> <answer> <text>{}</text> <feedback></feedback> <correct>{}</correct> <percent-correct>0</percent-correct> <include-in-mc-options>1</include-in-mc-options> </answer> <answer> <text>{}</text> <feedback></feedback> <correct>{}</correct> <percent-correct>0</percent-correct> <include-in-mc-options>1</include-in-mc-options> </answer> </answers> </question-record> """ def format_to_xml(fms, entry): return fms.format(entry[0], entry[1], entry[2], entry[3], entry[4], entry[5], entry[6], entry[7], entry[8], entry[9]) def main(): fms = get_empty_template() read_csv(argv[1], fms) if __name__ == '__main__': main()
130b479f29c854dee0f2848c8fe2f4e30fec509a
sellenth/algorithms
/stack.py
765
3.71875
4
import ll as linked class Stack: top = None; cap = 0; def __init__(self, v): if v == None: self.top = linked.ll(None); else: self.top = linked.ll([v]); self.cap = 1; def peek(self, v): return self.top.root.get_val(); def is_empty(self): if self.top.root == None: return True; return False; def pop(self): if self.is_empty(): print("Can't pop, stack is empty"); return None; self.cap -= 1; return self.top.remove_link(); def push(self, v): self.cap += 1; self.top.add_link(v); def print_all(self): while not self.is_empty(): print((self.pop()).get_val())
136b60238aec5c8f20f424b2e303a129a6196f3a
hensingh/FinalProject_SI206
/spotify_csv.py
1,244
3.796875
4
import os import sys import json from json.decoder import JSONDecodeError import sqlite3 import csv def spotify_csv(): print("Beginning process") conn = sqlite3.connect('spotify.sqlite') cur = conn.cursor() cur.execute("SELECT album, AVG(Popularity) FROM Spotify_Top_Songs GROUP BY album ORDER BY album") album_name = {} data = [] for row in cur: try: data.append(row) except: print('encoding error') for tup in data: album = tup [0] popularity = tup[1] if album not in album_name.keys(): album_name[album] = [popularity] else: album_name[album].append(popularity) for item in album_name.items(): average = sum(item[1])/len(item[1]) album_name[item[0]] = int(average) sorted_list_1 = sorted(album_name.items(), key=lambda x: x[0]) with open('spotify__albums.csv', 'w', newline='') as csvFile: writer = csv.writer(csvFile) writer.writerows(sorted_list_1) csvFile.close() print("Process ended") print("") print("Creating Spotify Album Data.") if __name__ == "__main__": spotify_csv()
b251fdf99671f78bf1aa7c652e93730601ee1188
RobAkopov/IntroToPython
/Week5/Practical/Problem2.py
136
3.53125
4
l1 = [1,2,3,4,5,6,7,8,10,11,45,68,61,18] def even_func(l1): e = [i for i in l1 if i % 2 == 0] return e print(len(even_func(l1)))
332c27b5bacacdb21d9867ec0685ca4dd7b6759b
radhikari54/FirstAlgorithmsThenCode
/chapter_03_the_tournament/tournament.py
1,502
3.9375
4
# Program TOURNAMENT in Python # Figure 3.4 from the book "Computational Thinking: First Algorithms, Then Code" # Authors: Paolo Ferragina and Fabrizio Luccio # Published by Springer # loads mathematical functions import math def tournament(set): """ Search the maximum in a table with n = 2^k partecipants. :param set: set of integers in which to search for the maximum """ n = len(set) # n is the number of elements of set k = int(math.log(n, 2)) # level of the leaves p = list() for i in range(0, n): # copy the set in p p.append(set[i]) h = k # h is the current level while h >= 1: # runs the matches at level h, from k to 1 i = 0 v = list() # x**y is the python expression for x^y while i <= 2**h - 2: # load in v the winners if p[i] > p[i + 1]: # p[i] is the winner v.append(p[i]) else: # p[i+1] is the winner v.append(p[i + 1]) i = i + 2 for i in range(0, 2**(h-1)): # copies in p the winners p[i] = v[i] h = h - 1 # moves to the level above print "the maximum is %d" % p[0] def main(): set = [24, 15, 7, 9, 20, 49, 33, 35, 22, 40, 52, 12, 62, 30, 8, 43] tournament(set) if __name__ == "__main__": main()
921733801eb645d39f781e301a8a89cca66051ac
Timothy-S-Fang/bookShelf
/Book.py
657
3.546875
4
class Book(): def __init__(self, title, author, rating, num_ratings): self.title = title self.author = author self.rating = rating # bookFinder.getRating() self.num_ratings = num_ratings # self.cover = cover # bookFinder.getBookCover(title) def __lt__(self, other): return self.rating < other.rating def get_title(self): return self.title def get_author(self): return self.author def get_rating(self): return self.rating def get_num_ratings(self): return self.num_ratings def print_book(self): print(self.title + " by " + self.author)
f711d7daae458d64992372c3be42dfcb87adbda4
JonSeijo/project-euler
/problems 30-39/problem_38.py
1,342
4.34375
4
# Pandigital multiples # Problem 38 """ Take the number 192 and multiply it by each of 1, 2, and 3: 192 * 1 = 192 192 * 2 = 384 192 * 3 = 576 By concatenating each product we get the 1 to 9 pandigital, 192384576. We will call 192384576 the concatenated product of 192 and (1,2,3) The same can be achieved by starting with 9 and multiplying by 1, 2, 3, 4, and 5, giving the pandigital, 918273645, which is the concatenated product of 9 and (1,2,3,4,5). What is the largest 1 to 9 pandigital 9-digit number that can be formed as the concatenated product of an integer with (1,2, ... , n) where n > 1? """ def isPandigital(number, maxDigits): num = str(number) if len(num) != maxDigits: return False if '0' in num: return False for digit in range(1, maxDigits+1): if str(digit) not in num: return False return True def main(): maxConcatenated = 0 # Limit is biggest 5 digit number for number in range(1, 100000): concaten = "" n = 1 while len(concaten) < 9: concaten += str(number * n) n += 1 if isPandigital(concaten, 9): if concaten > maxConcatenated: maxConcatenated = concaten print "answer: " + str(maxConcatenated) if __name__ == "__main__": main()
7f398f65810e21dd3290a18af7ef270156af4282
swingninja/AlgoPython
/check_palindrome_number.py
540
3.96875
4
def check_palindrome(num): if num is None: return False # Single digit is a palindrome if num/10 == 0: return True # Extract digits and push onto stack stack = [] num_copy = num while num_copy != 0: stack.append(num_copy % 10) num_copy = num_copy / 10 # while stack is not empty while stack: if stack.pop() == num % 10: num = num / 10 else: return False return True print check_palindrome(123) print check_palindrome(121)
d9b00aa406e5337fab1627b225e6ae9bdd09bddf
AnumaThakuri/pythonassignment
/assignment 6/question 7.py
159
4.0625
4
string=input("Enter your string :") def length(string): if string=='': return 0 else: return 1+length(string[1:]) print(length(string))
2292cae2865f29f0237aa4338c5e33df1069246e
600tomatos/exponea_challenge
/src/interfaces/validator.py
996
3.703125
4
from abc import ABC, abstractmethod class ValidatorInf(ABC): """Base class for validators""" @classmethod def check(cls, value): """Helper method that takes out the logic of creating a validator outside view. It is understood that validation begins with the perform_validate method. """ return cls().perform_validate(value) @abstractmethod def perform_validate(self, *args, **kwargs): """Any additional logic that can break validation into smaller logical parts""" pass def validate(self, *args, **kwargs): """ The main validation method. Pass value thorough all validators. """ available_validators = [func for func in dir(self) if func.startswith('validate_')] for validator in available_validators: current_validator = getattr(self, validator) error = current_validator(*args, **kwargs) if error: return error
45dbce74f0570b98078a6df52a499898cc227c8c
rohitkyadav/Codechef
/BOOKCHEF.py
2,217
3.546875
4
""" Chef Watson uses a social network called ChefBook, which has a new feed consisting of posts by his friends. Each post can be characterized by f - the identifier of the friend who created the post, p - the popularity of the post(which is pre-calculated by ChefBook platform using some machine learning algorithm) and s - the contents of the post which is a string of lower and uppercase English alphabets. Also, Chef has some friends, which he has marked as special. The algorithm used by ChefBook for determining the order of posts in news feed is as follows: Posts of special friends should be shown first, irrespective of popularity. Among all such posts the popular ones should be shown earlier. Among all other posts, popular posts should be shown earlier. Given, a list of identifiers of Chef's special friends and a list of posts, you have to implement this algorithm for engineers of ChefBook and output the correct ordering of posts in the new feed. Input First line contains N, number of special friends of Chef and M, the number of posts. Next line contains N integers A1, A2, ..., AN denoting the identifiers of special friends of Chef. Each of the next M lines contains a pair of integers and a string denoting f, p and s, identifier of the friend who created the post, the popularity of the post and the contents of the post, respectively. It is guaranteed that no two posts have same popularity. Output Output correct ordering of posts in news feed in M lines. Output only the contents of a post. Example Input: 2 4 1 2 1 1 WhoDoesntLoveChefBook 2 2 WinterIsComing 3 10 TheseViolentDelightsHaveViolentEnds 4 3 ComeAtTheKingBestNotMiss Output: WinterIsComing WhoDoesntLoveChefBook TheseViolentDelightsHaveViolentEnds ComeAtTheKingBestNotMiss """ #program N, M = map(int, input().split()) identifier = input().split() #can't input as intergers bcoz needs to be compared in if statement special = [] normal = [] for x in range(0, M): f, p, s = input().split() if f in identifier: special.append((int(p),s)) else : normal.append((int(p),s)) special.sort(key=lambda x: x[0], reverse = True) normal.sort(reverse = True) for p,s in special: print(s) for p,s in normal: print(s)
67496daf3685cb7908806e9cea0ec7d1287d2829
kaushik2000/python_programs
/ex_14/json1.py
347
3.59375
4
# Using json library in python import json data = '''{ "name" : "Kaushik", "phone" : { "type" : "int1", "number" : "+1 234 567 890" }, "email" : { "hide" : "yes" } }''' info = json.loads(data) print("Name:", info["name"]) print("Phone:", info["phone"]["number"]) print("Hide:", info["email"]["hide"])
b25edd005fb0985d224d12c39d9a972e39bc9901
weiranfu/cs61a
/functions/Exception/safe_newton_method.py
3,107
4.4375
4
""" Now we need to get the zero point of the objective function: f(x) = 2*x^2 + sqrt(x) using Newton method. """ from math import sqrt def objective_f(x): return 2*x*x + sqrt(x) def objective_df(x): return 4*x + 1/(2*sqrt(x)) ############### Something changes: def find_zero(f, df): def near_zero(x): # To determine that is the anwser we want. return approx_eq(f(x), 0) return improve(newton_update(f, df), near_zero) def improve(update, close_to, guess=1.0): while not close_to(guess): guess = update(guess) return guess #get the final answer def newton_update(f, df): #to compose the update function def h(x): return x - f(x) / df(x) return h def approx_eq(a, b, tolerance=1e-5): return abs(a - b) < tolerance #return True if a == b """ We can try to run it: >>> find_zero(objective_f,objective_df) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "safe_newton_method.py", line 59, in find_zero return improve(newton_update(f, df), near_zero) File "safe_newton_method.py", line 62, in improve while not close_to(guess): File "safe_newton_method.py", line 58, in near_zero return approx_eq(f(x), 0) File "safe_newton_method.py", line 51, in objective_f return 2*x*x + sqrt(x) ValueError: math domain error There's a ValueError, which means we culculate a root of negative number. Now we need to improve this function with considering x < 0 situation. In other word, if we imput x which is less than 0, will raise ValueError, however it will return the last guess value. """ """First, we define a new class that inherits from Exception.""" class IterImproveError(Exception): def __init__(self, last_guess): self.last_guess = last_guess def __str__(self): return 'Error when iterating' """ Next we define a version of improve, which handles ValueError by raising an IterImproveError.""" def improve(update, close_to, guess=1.0): try: while not close_to(guess): guess = update(guess) return guess except ValueError: raise IterImproveError(guess) # Pass mostly recent guess value to IterImproveError. """ Finally, we define safe_find_zero, which can handle an IterImproveError by returning its last guess.""" def safe_find_zero(f, df): """ To get the zero point of f function with considering ValueError situation in which it will return the most lastly guess value. >>> safe_find_zero(objective_f,objective_df) IterImproveError: Error when iterating -0.030214676328644885 """ def near_zero(x): return approx_eq(f(x), 0) try: return improve(newton_update(f, df), near_zero) except IterImproveError as e: print('IterImproveError: ',str(e)) return e.last_guess """Although this approximation is still far from the correct answer of 0, some applications would prefer this coarse approximation to a ValueError."""
400e3324e945cbd3e5b3bdf56494de1c97f77fe4
Rasgacode/codecool_tasks
/unit_task/4/test_poker_hand.py
681
3.59375
4
import unittest import poker_hand class poker_hand_test(unittest.TestCase): def test_poker_hand(self): self.assertEqual(poker_hand.hand_score([1, 1, 1, 1, 1]), "five") self.assertEqual(poker_hand.hand_score([1, 1, 1, 1, 2]), "four") self.assertEqual(poker_hand.hand_score([1, 1, 1, 2, 3]), "three") self.assertEqual(poker_hand.hand_score([1, 1, 4, 2, 3]), "pair") self.assertEqual(poker_hand.hand_score([1, 1, 2, 2, 3]), "twopair") self.assertEqual(poker_hand.hand_score([1, 1, 1, 2, 2]), "fullhouse") self.assertEqual(poker_hand.hand_score([1, 3, 2, 5, 4]), "nothing") if __name__ == "__main__": unittest.main()
f7d3b1bd374558bba5ac8e4a56bd42d2985b2eac
shivam-singh-au17/morning_boostup
/may05/my.py
978
3.78125
4
# 1 N = 5 for i in range(1, N + 1): res = ""; for j in range(1, i+1): res += "*" + " " print(res) print() # 2 N = 5 for i in range(1, N + 1): res = "" for j in range(1, N + 1): if (i == 1 or i == N or j == N): res += "*" + " " else: res += " " print(res) print() # 3 N = 5 for i in range(1, N + 1): res = ""; for j in range(1, N + 1): if (i == N or j == N): res += "* " else: res += " " print(res) # 4 N = 5 for i in range(1, N + 1): result = ""; for j in range(1, N + 1 - i): result += " " for k in range(1, i + 1): result += "*" + " " print(result) # print() # 5 N = 5 for i in range(1, N + 1): result = ""; for j in range(1, N + 1 - i): result += " " for k in range(1, i + 1): result += "*" + " " print(result)
dc2ad886a925e85a395a092284dfbcb194dff53a
javierdiaz13/CS-115
/hw6.py
5,058
3.921875
4
''' Created on: October 17, 2018 @author: Javier Diaz Pledge: "I pledge my honor that I have abided by the Stevens Honor System" CS115 - Hw 6 Got help from CS115 tutor! ''' # Number of bits for data in the run-length encoding format. # The assignment refers to this as k. COMPRESSED_BLOCK_SIZE = 5 # Number of bits for data in the original format. MAX_RUN_LENGTH = 2 ** COMPRESSED_BLOCK_SIZE - 1 # Do not change the variables above. # Write your functions here. You may use those variables in your code. def isOdd(n): '''Returns whether or not the integer argument is odd.''' if n % 2 == 0: return False return True def numToBinary(n): '''Precondition: integer argument is non-negative. Returns the string with the binary representation of non-negative integer n. If n is 0, the empty string is returned.''' if n == 0: return '' elif isOdd(n): return numToBinary(n // 2) + '1' return numToBinary(n // 2) + '0' def binaryToNum(s): '''Precondition: s is a string of 0s and 1s. Returns the integer corresponding to the binary representation in s. Note: the empty string represents 0.''' if s == '': return 0 elif int(s[-1]) == 1: return 1 + (2 * binaryToNum(s[:-1])) return 2 * binaryToNum(s[:-1]) t = 0 def compress(s): '''This function takes a binary string of length 64 and returns a binary string that represents the amount of consecutive 0s and 1s that are in the sequence. The output is also alternating between amount 0s and 1s ''' global t if s == '' or s == []: t = 0 return '' elif t == 0: t += 1 s = compress_helper(s) return compress(s) elif s[0] >= MAX_RUN_LENGTH + 1: s[0] = s[0] - (MAX_RUN_LENGTH) t += 1 return str(numToBinary(MAX_RUN_LENGTH)) + '0' * COMPRESSED_BLOCK_SIZE + compress(s) else: t += 1 return bin_to_bits(str(numToBinary(s[0]))) + compress(s[1:]) def bin_to_bits(S): '''This function takes in the string from compress(S) and outputs the zeros remaining to finish the (COMPRESSED_BLOCK_SIZE - 1) bit size of 5''' if len(S) != (COMPRESSED_BLOCK_SIZE): return '0' * ((COMPRESSED_BLOCK_SIZE) -len(S)) + S return S i = 0 def compress_helper(S): '''This function takes in a string from compress(S) and outputs a list of the amount of zeros and ones consecutively''' global i if S == '': i = 0 return [] else: if isOdd(i) == 0: i += 1 return [find_zero(S)] + compress_helper(next_one(S)) else: i += 1 return [find_one(S)] + compress_helper(next_zero(S)) def find_zero(S): '''This function takes in a string which counts how many zeros there are starting from the left up until the first encounter of a one and outputs the result''' if S == '': return 0 elif S[0] == '0': return 1 + find_zero(S[1:]) return 0 def find_one(S): '''This function takes in a string S which counts how many ones there are starting from the last zero up until the next zero and outputs the result''' if S == '': return 0 elif S[0] == '1': return 1 + find_one(S[1:]) return 0 def next_zero(S): '''This function takes in a string S which outputs the next consecutive zeros ''' if S == '': return '' elif S[0] == '1': return next_zero(S[1:]) return S def next_one(S): '''This function takes in a string S which outputs the next consecutive ones''' if S == '': return '' elif S[0] == '0': return next_one(S[1:]) return S def uncompress(S): '''This function takes in compressed string S and outputs the uncompressed string back to its original state''' outer_loop = False global t if t == 0: outer_loop = True t = 1 if S == '': t = 0 return [] else: S = [binaryToNum(S[0:COMPRESSED_BLOCK_SIZE])] + uncompress(S[COMPRESSED_BLOCK_SIZE:]) if(not outer_loop): return S if outer_loop: return uncompress_helper(S) def uncompress_helper(L): '''This function takes in a list L from the function uncompress and outputs the final string of binary numbers to its original uncompressed state.''' global i if L == []: i = 0 return '' elif isOdd(i) == 0: i += 1 return '0' * L[0] + uncompress_helper(L[1:]) else: i += 1 return '1' * L[0] + uncompress_helper(L[1:]) def compression(S): '''This function takes in a string S and outputs the ratio of the length of the compressed string to the original string''' return len(compress(S)) / len(S)
4b6eca3b1599f8e722c0e45ff2bcd761a58061a3
cce-bigdataintro-1160/winter2020-code
/3-python-notebook/9-functions.py
696
3.671875
4
#!/usr/bin/env python3 import os def pretty_print(a): return f"My value is: {a}" def sum_one(a): return a + 1 def sum(a, b): return a + b def prefix_string_with(prefix, string): return f'{prefix}{string}' def check(prefix, string): return f'{prefix}{string}' def reverse(s): return s[::-1] def is_palindrome(s): if s == reverse(s): return True else: return False def print_file(file_path): if os.path.isfile(file_path): print(f'{file_path} is valid, printing file') for l in open(file_path).readlines(): print(l) else: print(f'cannot print file, {file_path} doesn\'t have a valid file')
c982d69679ac842fe9c1f02450c268d2a2aab4a9
Pumacens/Competitive-Programming-Solutions
/CodeWars-excercises/Python/7_kyu/files/1. Remove duplicate words.py
287
3.734375
4
from collections import OrderedDict def remove_duplicate_words(s): return ' '.join(OrderedDict.fromkeys(s.split()).keys()) # Funciona a partir de python 3.6 porque los diccionaros ahora son ordenados # def remove_duplicate_words(s): # return ' '.join(dict.fromkeys(s.split()))
699f0685c3e12389225ef7ec9a60d8683e69c99b
SaleemShahdi/Extended-Project
/quadrat/get_user_input.py
998
3.546875
4
from re import fullmatch class Input: @staticmethod def read_double(text): try: x = input(text) x = float(x) return x except ValueError: return Input.read_double("That is not a number. Enter again: ") @staticmethod def get_decision(text): x = input(text) if fullmatch("([Yy](es)?)|(YES)", x): '''had to debug <search> and <match> vs <fullmatch>. search and match would incorrectly return "Ye" and "ye" as True. fullmatch correctly returned them as False. Must have something to do with the way search and match are defined, but I don't have a proper explanation. Here is a link to the documentation: https://docs.python.org/3/library/re.html''' return True elif fullmatch("([Nn]o?)|(NO)", x): return False else: return Input.get_decision("Enter yes or no: ")
e4afc36b9d8363092d8ef00c0a786c7e4480ffb9
s1092877/ipfit5
/Inladenimage.py
4,296
3.53125
4
# Importeer TKinter voor GUI import tkinter as tk from tkinter import * from tkinter import filedialog opdracht1 = "IP-adressen" opdracht2 = "Mailadressen" opdracht3 = "Entiteiten" root = tk.Tk() def main(): global var var = IntVar() # Toon welkom bericht welkomLabel = tk.Label(root, text = "Welkom bij de applicatie Groep7. Selecteer wat u wilt doen en klik op Volgende") welkomLabel.pack() # Radiobuttons aanmaken voor keuze te maken R1 = Radiobutton(root, text = opdracht1,variable = var, value = 1) R1.pack(anchor = W) R2 = Radiobutton(root, text = opdracht2, variable = var, value = 2) R2.pack(anchor = W) R3 = Radiobutton(root, text = opdracht3, variable = var, value = 3) R3.pack(anchor = W) # Button aanmken om keuze te bevestigen B1 = Button (root, text = "Volgende", command = lambda : keuze()) B1.pack(anchor = E) global L1 root.mainloop() def keuzePrint(opdracht): L1 = tk.Label(root, text="U heeft gekozen voor: " + opdracht) L1.pack() def get_output_filename(input_file_name): """ replace the suffix of the file with .rst """ return input_file_name.rpartition(".")[0] def gui(): def button_go_callback(): """ what to do when the "Go" button is pressed """ input_file = entry.get() if input_file.rsplit(".")[-1] != "E01": statusText.set("Filename must end in `.E01'") message.configure(fg="red") return else: table_contents = read_E01(input_file) if table_contents is None: statusText.set("Error reading file `{}'".format(input_file)) message.configure(fg="red") return output_file = get_output_filename(input_file) if write_table(output_file, table_contents): statusText.set("Output is in {}".format(output_file)) message.configure(fg="black") else: statusText.set("Writing file " "`{}' did not succeed".format(output_file)) message.configure(fg="red") def button_browse_callback(): """ What to do when the Browse button is pressed """ filename = filedialog.askopenfilename() entry.delete(0, END) entry.insert(0, filename) root = Tk() frame = Frame(root) frame.pack() statusText = StringVar(root) statusText.set("Press Browse button or enter E01 filename, " "then press the Go button") label = Label(root, text="E01: ") label.pack() entry = Entry(root, width=50) entry.pack() separator = Frame(root, height=2, bd=1, relief=SUNKEN) separator.pack(fill=X, padx=5, pady=5) button_go = Button(root, text="Go", command=button_go_callback) button_browse = Button(root, text="Browse", command=button_browse_callback) button_exit = Button(root, text="Exit", command=sys.exit) button_go.pack() button_browse.pack() button_exit.pack() separator = Frame(root, height=2, bd=1, relief=SUNKEN) separator.pack(fill=X, padx=5, pady=5) message = Label(root, textvariable=statusText) message.pack() def keuze(): global selectie selectie = var.get() if selectie == 1: keuzePrint(opdracht1) gui() button_browse = Button(root, text="Browse", command=button_browse_callback) elif selectie == 2: keuzePrint(opdracht2) gui() button_browse = Button(root, text="Browse", command=button_browse_callback) elif selectie == 3: keuzePrint(opdracht3) gui() button_browse = Button(root, text="Browse", command=button_browse_callback) else: print("Geen keuze") if __name__ == '__main__': main()
0cf72584ef95a40fa94fbd43b53552c23f8a0d3d
chybot/crawler
/CommonLib/DataParse.py
1,508
4.0625
4
# -*- coding: utf-8 -*- import string def listToCoupleList(lst): """ change list to a list with couple element in a touple such as [1,2,3,4]=>[(1,2),(3,4)] :param lst: :return: """ return zip(lst[::2],lst[1::2]) def listToDict(lst): return dict(zip(lst[::2],lst[1::2])) def doubleListToDict(lst1,lst2): return dict(zip(lst1,lst2)) def doubleListToDictLong(lst1,lst2): pass def removeEmptyItemInList(value_list): """ remove the empty item in a list :param value_list: :return: processed list """ # while '' in value_list: # value_list.remove('') # return value_list return filter(lambda x:x, value_list) def removeEmptyInListItem(value_list): """ remove empty and other useless characters of an item in the list :param value_list: :return: list with useless characters removed """ list=[] for item in value_list: list.append(item.strip()) return list def removeEmptyInListItemMap(value_list): """ remove empty and other useless characters of an item in the list :param value_list: :return: list with useless characters removed """ return map(string.strip, value_list) def removeUselessChar(str): """ used to process some special string if strip() is not work :param str: :return: """ return "".join(str.split()).replace("\t","") if __name__ =="__main__": ll = ["axx "," b"] removeEmptyInListItemMap(ll) print ll
69cb8d5089dfd07e0965d81dd5057e928b4b6607
Jeronimo-MZ/Math-And-PEMDAS
/MathGame.py
527
3.734375
4
from MyPythonClass import MathGame from time import sleep print('='*50) print("Arithmetics game".center(50)) print("="*50) starter = MathGame() starter.Iniciar() while True: question = input("Do you want to see your Score?[Y/N]").upper() if question == "Y": starter.show_score() break elif question == "N": break else: print('Invalid Value! please insert "Y" or "N":') input("Press Any Key To Finish....") print('='*50) print("Finished!!!".center(50)) print("="*50) sleep(2)
f9f12d683fb245fac62d6c98cf1c6502ad930c89
hihello-jy/portfolio
/2034연습문제8-운동에너지.py
257
3.765625
4
mass=float(input("물체의 무게를 입력하시오(킬로그램): ")) velocity=float(input("물체의 속도를 입력하시오(미터/초): ")) energy= 0.5*mass*velocity**2 print("물체는 "+str(energy)+"(줄)의 에너지를 가지고 있다.")
c47a62b1a08e261370975c60ae95c45406d30aaf
victorbrossa/curso_python
/exercicios2/exer2.py
271
4
4
'''Escreva um programa que abra um arquivo digitado pelo usuário e imprima seu conteúdo na tela. ''' nome = input('Digite o nome do arquivo que voce deseja abrir: ') arquivo = open(nome) linhas = arquivo.readlines() for linha in linhas: print (linha.strip())
b759ace487a7b4c417c661f504d9ec41b79bf006
eserebry/holbertonschool-higher_level_programming
/0x0B-python-input_output/14-pascal_triangle.py
458
3.9375
4
#!/usr/bin/python3 def pascal_triangle(n): """returns a list of lists of integers representing the Pascal’s triangle of n Args: n - size of triangle """ outer = [] for i in range(n): inner = [] for j in range(i + 1): if j == 0 or j == i: inner.append(1) else: inner.append(outer[i-1][j-1] + outer[i-1][j]) outer.append(inner) return outer
7faa8b7639db9efc93bae988ad6bad83f60bec02
varsha131/assignment1
/6.py
391
3.625
4
Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:20:19) [MSC v.1925 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> #stars num=int(input("enter the rows")) for i in range(1,num+1): for j in range(1,i+1): print("*",end=" ") print()
9f825661d8ea4317d8b13faa5596b23edd1b7497
Cristinamulas/algorithms-for-big-data
/Quick_sort.py
2,039
3.78125
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Thu Apr 18 16:52:35 2019 @author: cristinamulas """ import numpy as np import random import time def create_array (x,y): randon_sample = random.sample(range(x), y)# creat an list of ramdon mumbers array = np.array(randon_sample) # convert a list into an array return array arr_20 = create_array(21,20) #call the function to creat an array of 20 elements arr_100 = create_array(101,100) ##call the function to creat an array of 100 elements arr_200 = create_array(201,200)#call the function to creat an array of 20 elements #print(arr_20) #print(arr_100) print(arr_200) time_start = time.time() # calulate time #Iplementation of quick_sort function def quick_sort(arr): quick_sort2(arr, 0, len(arr)) #recursive call of quick_sort2 return arr def quick_sort2(arr, beg, end): if end - beg > 1: #chaning if its more that 1 elemets to be sorted par = partition(arr, beg, end) # recusive called of partition function quick_sort2(arr, beg, par) # recirsive called of quicksort2 functionright part of the array quick_sort2(arr, par + 1, end) # recirsive called of quicksort2 functionrsort left part of the array def partition(arr, beg, end): piv = arr[beg] # initialize pivot value i = beg + 1 # Initialiase beg value j = end - 1 # Initialiase end value while True: # iterate over the array while (i <= j and arr[i] <= piv): # comparing each element to the piv i += 1 # add 1 while (i <= j and arr[j] >= piv): j -= 1 # substract one if i <= j: #comparation elemets arr[i], arr[j] = arr[j], arr[i] #swap it values else: arr[beg], arr[j] = arr[j], arr[beg] #swap it values return j print(quick_sort(arr_200))#calling the selection_sort function time_end = time.time() # calculate time cal_time = time_end - time_start formate_caltime = format(cal_time, "e") # format to scientifict notation print(formate_caltime)
69a2005b0c91b87016f4b285e497cd334bec7bf0
PilarPinto/holbertonschool-machine_learning
/math/0x00-linear_algebra/101-the_whole_barn.py
1,308
3.609375
4
#!/usr/bin/env python3 '''Adds two matrices''' def matrix_shape(matrix): '''Matrix shape function''' shape_m = [] shape_m.append(len(matrix)) if type(matrix[0]) == list: while type(matrix[0]) != int: shape_m.append(len(matrix[0])) matrix = matrix[0] return shape_m def add_matrices(mat1, mat2): '''Adding matrices function''' if(type(mat1[0]) == int) and (len(mat1) == len(mat2)): return [mat1[i] + mat2[i] for i in range(len(mat1))] if(matrix_shape(mat1) == matrix_shape(mat2)): if len(matrix_shape(mat1)) == 4: return([[[[mat1[i][j][k][l] + mat2[i][j][k][l] for l in range(len(mat1[i][j][k]))] for k in range(len(mat1[i][j]))] for j in range(len(mat1[i]))] for i in range(len(mat1))]) elif len(matrix_shape(mat1)) == 3: return([[[mat1[i][j][k] + mat2[i][j][k] for k in range(len(mat1[i][j]))] for j in range(len(mat1[i]))] for i in range(len(mat1))]) elif(len(matrix_shape(mat1)) == 2): return([[mat1[i][j] + mat2[i][j] for j in range(len(mat1[i]))] for i in range(len(mat1))])
de326a7b4f8959e50f39b9cc5278b00854d3529f
korowood/algorithm-and-data-structures
/1 - Сортировки и O-нотация/D. Количество инверсий.py
775
3.578125
4
""" input: 4 1 2 4 5 output: 0 """ def merge_list(left, right): ans = list() i, j = 0, 0 count = 0 while i < len(left) and j < len(right): if left[i] <= right[j]: ans.append(left[i]) i += 1 else: ans.append(right[j]) j += 1 count += (len(left) - i) ans += left[i:] ans += right[j:] return ans, count def merge_sort(arr): if len(arr) <= 1: return arr, 0 middle = len(arr) // 2 left, l_count = merge_sort(arr[:middle]) right, r_count = merge_sort(arr[middle:]) merged, count = merge_list(left, right) count += (l_count + r_count) return merged, count t = int(input()) ml = list(map(int, input().split())) print(merge_sort(ml)[1])
fec491fb51394beba56a1729ba21e7961f49b2fd
lorranapereira/exer_python
/exercicios/exercicio7.py
2,316
3.78125
4
#import datetime #def func(year,month,day,aux): # x = datetime.datetime(year,month,day) # if aux==1: # print(x.strftime('%Y')+','+x.strftime('%d')+' of '+x.strftime('%B')) # if aux==2: # print(x.strftime('%d')+'/'+x.strftime('%m')+'/'+x.strftime('%Y')) #func(2000,9,8,1) #func(2000,9,8,2) #--------- #from datetime import datetime #def func(nome,dt,vet): # dt = dt.split("/") # date = datetime(int(dt[2]),int(dt[1]),int(dt[0])) # vet = vet.split(';') # d = dict() # d = {"nome": nome, "dataNascimento":date, "telefone":vet } # print(d["telefone"][0]) #nome = input("Dígite seu nome: ") #dt = input("Dígite sua Data de aniversario no formato dia/mes/ano: ") #vet = input("Dígite seu número de telefone, sem pontos ou traços. Caso tenha mais de um número, os separe com ;: ") #teste = func(nome,dt,vet) #class Pessoa: # def __init__(self,nome): # self._nome = nome # def _get_nome(self): # return self._nome # def _set_nome(self, nome): # self._nome = nome # nome = property(_get_nome, _set_nome) # p = Pessoa('Julio') # print(p.nome) #9) Em Python, para a geração de um número aleatório usamos o pacote random. Escreva um programa #(jogo) que gere um número entre 0 e 1000 e peça para o usuário adivinhar o número. A cada tentativa o #programa informa se o número informado pelo usuário é maior ou menor que o número a ser #descoberto. Ao final o programa deve informar quantas tentativas foram feitas até a descoberta do #número. import random number = random.randint(0, 1000) def c(number): x = int(input("Qual é o número ")) while x!=number: if x < number: print("O número é maior") if x > number: print("O número é menor") x = int(input("Qual é o número ")) print("Você acertou o número é : "+str(number)) #10) Faça uma função para cada situação: #a) Gere a matriz transposta; #b) Some duas matrizes; #c) Faça a multiplicação de duas matrizes. def matriz_transposta(vet): cont=0 vet2 = [] for x in vet: vet2[0][1] = vet1[1][0] cont+=1 print(cont) matriz_transposta([[0,1,2],[3,4,5]) [0][3] - > [0,3] [1][4] [2][5]
77df4581317d5f632678eccb52ab312005e79de3
MrHamdulay/csc3-capstone
/examples/data/Assignment_7/vgyric001/question1.py
605
3.921875
4
# Assignment 7 # Question 1 # Richard van Gysen # 29 April 2014 # Enter strings strings = input("Enter strings (end with DONE):\n") lis = [] # Add strings if strings!='DONE': lis.append(strings) # Terminate list when DONE is entered while strings!='DONE': strings = input() if strings =='DONE': break else: lis.append(strings) new_lis = [] for i in range(len(lis)): if not lis[i] in new_lis: new_lis.append(lis[i]) else: pass #print unique list print() print("Unique list:") for item in new_lis: print(item)
02afec53e27d3309dfce37ad347222c216c7339b
Graziele-Rodrigues/100-exercicios-resolvidos-em-python
/62_ProgressaoV2.py
551
3.890625
4
# Leia o primeiro termo e a razão de uma PA e mostre os 1 termos usando a estrutura while # print('Gerador de PA') print('-='*10) primeiro = int(input('Primeiro termo: ' )) razao = int(input('Razão da PA: ')) termo = primeiro n = 1 total = 0 mais = 10 while mais != 0: total = total + mais while n <= total: print('{} -> '.format(termo+(n-1)*razao), end = '') n+=1 print('PAUSA') mais = int(input('Quantos termos você quer contar a mais? ')) print('Progressão aritmética finalizada com {} termos'.format(total))
fa0e7b118ab45e6aaa1cb00c91aa1ac8edd9af5d
richa92/Jenkin_Regression_Testing
/robo4.2/fusion/FusionLibrary/libs/utils/keyword.py
356
3.640625
4
import types def convert_bool(s): if isinstance(s, types.BooleanType): return s elif isinstance(s, types.StringType) or isinstance(s, types.UnicodeType): if s.lower() == 'true': return True elif s.lower() == 'false': return False raise Exception('Invalid value for boolean conversion: %s' % s)
d733b9facac06947a7f996532fc16083eea20bfb
Khushi2324/Python
/linked_list/merge_two_sorted_list.py
665
4.03125
4
class Node: def __init__(self,data,next): self.data=data self.next=next def merge(L1,L2): L3=Node(None,None) #Create Empty List prev=L3 while (L1!=None and L2!=None): if L1.data<L2.data: prev.next=L1 L1=L1.next else: prev.next=L2 L2=L2.next prev=prev.next if L1 is None: prev.next=L2 else: prev.next=L1 return L3 n3=Node(10,None) n2=Node(3,n3) n1=Node(2,n2) L1=n1 n6=Node(8,None) n5=Node(7,n6) n4=Node(4,n5) L2=n4 merged=merge(L1,L2) while merged!=None: print(merged.data) merged=merged.next print("None")
1b6fdf7141a4ed6ab1fef1a1787a707776c5c878
msaio/pythonstuff
/get_ExchangeRate.py
783
3.71875
4
import requests def get_currency_rates(): # Where USD is the base currency you want to use url = 'https://api.exchangerate-api.com/v4/latest/USD' # Making our request response = requests.get(url) data = response.json() # Your JSON object f = open("ExchangeRate.txt", "w") # print(type(data['rates'])) # print(data['rates']) # f.write(data['rates']) for i, j in data['rates'].items(): print(i, j) f.write(str(i) + ' : ' + str(j) + "\n") f.close() # print(type(data)) return data['rates'] def get_currency_rates2(): return requests.get('https://api.exchangerate-api.com/v4/latest/USD').json()['rates'] if __name__ == "__main__": dict = get_currency_rates2() print(dict)
698fe0d59bb083a6cad4454d44a1e12d0fe27877
Microstrong0305/coding_interviews
/33.二叉搜索树的后序遍历序列/33.二叉搜索树的后序遍历序列.py
596
3.6875
4
# -*- coding:utf-8 -*- class Solution: def VerifySquenceOfBST(self, sequence): # write code here if len(sequence) == 0: return False return self.check(sequence,0,len(sequence)-1) def check(self,arr,start,end): if start>=end: return True root = arr[end] end = end - 1 while(end >=0 and arr[end]>root): end -= 1 mid = end + 1 for i in range(start,mid): if arr[i] > root: return False return self.check(arr,start,mid-1) and self.check(arr,mid,end)
faff568661729dd13bdb94e1da75950cb78d364a
dhjnvytyjub/SpecialistPython2_v2
/Module9/examples/02_collections_deque.py
1,566
4.0625
4
import collections queue = collections.deque() print(queue) # deque([]) - пустая очередь queue.append("read book") # Добавляет элмент в очередь queue.append("sleep") # Добавляет элмент в очередь print(queue) # deque(['read book', 'sleep']) queue.popleft() # Удаляет первый(левый) элемент очереди print(queue) # deque(['sleep']) # Методы очереди: # append(x) - добавляет x в конец. # # appendleft(x) - добавляет x в начало. # # clear() - очищает очередь. # # count(x) - количество элементов, равных x. # # extend(iterable) - добавляет в конец все элементы iterable. # # extendleft(iterable) - добавляет в начало все элементы iterable (начиная с последнего элемента iterable). # # pop() - удаляет и возвращает последний элемент очереди. # # popleft() - удаляет и возвращает первый элемент очереди. # # remove(value) - удаляет первое вхождение value. # # reverse() - разворачивает очередь. # # rotate(n) - последовательно переносит n элементов из начала в конец (если n отрицательно, то с конца в начало). # Подробнее тут: https://docs.python.org/3/library/collections.html#collections.deque
171f5c54fa923b55a9503e3af471d026685119e0
Caimingzhu/Managing_Your_Biological_Data_with_Python_3
/11-classes/11.4.3_subclasses.py
769
3.84375
4
''' Classes can inherit from other classes and extend their functionality. ----------------------------------------------------------- (c) 2013 Allegra Via and Kristian Rother Licensed under the conditions of the Python License This code appears in section 11.4.3 of the book "Managing Biological Data with Python". ----------------------------------------------------------- ''' from pea import Pea class CommentedPea(Pea): def __init__(self, genotype, comment): Pea.__init__(self, genotype) self.comment = comment def __repr__(self): return '%s [%s] (%s)' % (self.get_phenotype(), self.genotype, self.comment) yellow1 = CommentedPea('GG', 'homozygote') yellow2 = CommentedPea('Gg', 'heterozygote') print(yellow1) print(yellow2)
ba908d07e25a6492ffa7e7641e0126e3f5ffcb4d
tundecmd/holbertonschool-interview
/0x1C-island_perimeter/0-island_perimeter.py
561
3.78125
4
#!/usr/bin/python3 """Module perimeter""" def island_perimeter(grid): """length of the perimeter""" i = 0 for y, row in enumerate(grid): for x, cell in enumerate(row): if cell == 1: if y == 0 or grid[y - 1][x] == 0: i += 1 if y == len(grid) - 1 or grid[y + 1][x] == 0: i += 1 if x == 0 or grid[y][x - 1] == 0: i += 1 if x == len(row) - 1 or grid[y][x + 1] == 0: i += 1 return i
5a554a8257b8a24d6f5958cad8a4ca18eb4852f2
devender15/CoronaVirus_Updates_Checker
/main.py
3,592
3.515625
4
from bs4 import BeautifulSoup import requests from discord_webhooks import DiscordWebhooks import datetime def get_website(url): r = requests.get(url) return r.text def updates(): my_data = get_website("https://www.worldometers.info/coronavirus/") # creating soup instance for extracting data soup = BeautifulSoup(my_data, "html.parser") # creating an empty dictionary to store all the values msg = {} for data in soup.find_all("div", class_="maincounter-number")[0].find_all("span"): latest_cases = data.get_text() msg['Total Cases'] = latest_cases for data in soup.find_all("div", class_="maincounter-number")[1].find_all("span"): latest_deaths = data.get_text() msg['Total Deaths'] = latest_deaths for data in soup.find_all("div", class_="maincounter-number")[2].find_all("span"): recovered = data.get_text() msg['Total Recovered'] = recovered return msg def custom_countries_updates(country_name): new_data = get_website("https://www.worldometers.info/coronavirus/#countries") soup = BeautifulSoup(new_data, "html.parser") # making this empty list for appending all the available countries on the website countries_available = [] for data in soup.find_all("a", class_="mt_a"): all_countries = data.get_text() countries_available.append(all_countries) # getting our heading row thead = soup.find("thead").find("tr").find_all("th") # appendind all headings into a list heading_list = [] for w in thead: heading_list.append(w.get_text()) # empty list for append all the values of countries stats values_list = [] if (country_name in countries_available): # finding the parent tag using the value a_string = soup.find(string=country_name) parent_string = a_string.find_parent("a") grand_parent_string = parent_string.find_parent("td") for item in grand_parent_string.find_parent("tr").find_all("td"): values_list.append(item.get_text()) else: print("Country Not Found!") # converting our two lists into a dictionary using zip function res = dict(zip(heading_list, values_list)) return res def send_msg_discord(msg, cases, deaths, recovered): webhook_url = "" # add your discord webhook url here WEBHOOK_URL = webhook_url webhook = DiscordWebhooks(WEBHOOK_URL) current_time = datetime.datetime.now().strftime("%d-%m-%Y %H:%M:%S") webhook.set_footer(text=f"Last Updated: {current_time}") webhook.set_content(title="CoronaVirus Latest Update", description=msg) webhook.add_field(name="Cases", value=cases, inline=True) webhook.add_field(name="Deaths", value=deaths, inline=True) webhook.add_field(name="Recovered", value=recovered, inline=True) webhook.send() if __name__ == '__main__': user_choice = int(input("Which data you want to see?\n1. World\t2. Custom Country\n")) if(user_choice==1): print("Searching....") world_data = updates() for item in world_data: print(f"{item}: {world_data[item]}\n") elif(user_choice==2): user_input = input("Enter the Country Name, whose data you want to see\n") print("Searching....") custom_data = custom_countries_updates(user_input) for item in custom_data: print(f"{item}: {custom_data[item]}\n") else: print("Your input is invalid!") # if you want to send updates to your Discord Server then, uncomment the following code and please make sure that you have entered your Discord Webhook Url in it's Function # dictm = updates() # getting values from the key of dictionary # c = dictm['Total Cases'] # d = dictm['Total Deaths'] # r = dictm['Total Recovered'] # send_msg_discord("Check the list", c, d, r)
9fb1c08f046b7ae13d2fe420f299df1060fd4d91
cooldoggy/Python-Projects
/BookExamples/Is it dark.py
210
4.03125
4
is_dark = input('Is it dark outside? (y/n)') if is_dark == 'y': print("O.K.! Goodnight! Zzzzzzzzzzzzzzzz......") elif is_dark == 'n': print("O.K! Staying On!") else: print("Invalid Input, please try again.")
b15a3693699d361eea8a7b2b782e61e2b9071772
therochaexperience/coursera-algorithmic-toolbox
/max_pairwise_product.py
2,250
4.03125
4
# Maximum pairwise prodcut # Python 3.4.3 # Date: 11/5/2016 # Author: harryjrocha@gmail.com # Finds two integers in a sequence that will give the largest product # Assumes all integers are positive import random def maximum_pairwise_product(a): # Goes through every possible pair of integers in a list; Naive solution O(n^2) result = 0 for x in range(len(a)): for y in range(x + 1, len(a)): if a[x] * a[y] > result: result = a[x] * a[y] return result def maximum_pairwise_product_fast(a): # Finds the two largest integers in a list max_index1 = -1 # why are we initializing the index with -1? for i in range(len(a)): if((max_index1 == -1) or (a[i] > a[max_index1])): max_index1 = i max_index2 = -1 for j in range(len(a)): if((j != max_index1) and ((max_index2 == -1) or (a[j] > a[max_index2]))): max_index2 = j return a[max_index1] * a[max_index2] def user_input(): # Gets list of integers from user size = int(input()) numbers = [int(n) for n in input().split()] return numbers def random_input(): # Generates random list of integers max_list_size = 5 max_val = 10 n = random.randint(2, max_list_size) numbers = [random.randint(0, max_val) for i in range(n)] return numbers def stress_test(): # Tests algorithm with a randomly generated list of integers while (True): a = random_input() print(len(a)) print(a) if(run_test(a)): break return def manual_test(): # Tests algorithm with a user generated list of integers while(True): a = user_input() if(run_test(a)): break return def run_test(a): # Runs both MPP algorithms and determines whether they both give equal results result1 = maximum_pairwise_product(a) result2 = maximum_pairwise_product_fast(a) if(result1 != result2): print("Wrong answer: " + str(result1) + ' ' + str(result2)) return True else: print("OK") return False # Select the type of test you'd like to run #stress_test() #manual_test()
bdaa0e5c68b8408c729c9da8181defbc89fefa4c
mistryharsh28/A-December-of-Algorithms-2019
/December-06/python_mistryharsh28_fibonacciPrimeNumberGeneration.py
530
3.90625
4
def fibonacci_prime_numbers(n): result = [] second_prev = 0 prev = 1 i = 0 while(i<n): next_fibo = prev + second_prev # check if next_fibo is prime for j in range(2, next_fibo//2): if next_fibo % j == 0: break else: if(next_fibo != 1): result.append(next_fibo) i = i + 1 second_prev = prev prev = next_fibo return result result = fibonacci_prime_numbers(5) print(result)
e2abc9a3b5f54cd6699b37968bd9ebd06907ff56
siuols/Python-Basics
/strings.py
2,216
4.21875
4
def init(): input_string = input("Enter a string: ") count = 0 upper_string(input_string) lower_string(input_string) count_string(input_string) convertion_to_list(input_string) indexing(input_string) count_string(input_string) reverse(input_string) slicing(input_string) start_end(input_string) split(input_string) def upper_string(input_string): upper = input_string.upper() print("String {} is uppered case.".format(upper)) def lower_string(input_string): lower = input_string.lower() print("String {} is lowered case.".format(lower)) def count_string(input_string): print("the total length of {} is : {}".format(input_string, len(input_string))) def convertion_to_list(input_string): string_list = list(input_string) print(string_list) def indexing(input_string): #this method only recognizes the first 'o'. print("number of 'o' is {} is: {}".format(input_string, input_string.index("o"))) def count_string(input_string): #this method counts the all 'l or L' in the string print("number of 'l' is {} is: {}".format(input_string,input_string.count("l"))) def reverse(input_string): reverse_word = "" i = len(input_string)-1 while(i != -1): reverse_word += input_string[i] i-=1 print("The reverse string of {} is {}".format(input_string, reverse_word)) def slicing(input_string): #This prints the characters of string from 3 to 7 skipping one character. This is extended slice syntax. The general form is [start:stop:step]. print("string from 3 to 7 skipping one character is: " + input_string[3:7:1]) def start_end(input_string): #This is used to determine whether the string starts with something or ends with something, respectively. The first one will print True, print("if the inputted string starts with 'hello' it will return to : {}".format(input_string.startswith("Hello"))) print("if the inputted string starts with 'hello' it will return to : {}".format(input_string.endswith("world"))) def split(input_string): #This splits the string into a bunch of strings grouped together in a list. word = input_string.split(" ") print(word) init()
126dd15cb721a5d913d3ee02f98214276c7e539d
ebby-s/ALevelCS
/Python Challenges/ebbyA206.py
2,456
3.8125
4
import random class Card: suits = ["Clubs", "Diamonds", "Hearts", "Spades"] ranks = ["","Ace","2","3","4","5","6","7","8","9","10","Jack","Queen","King"] def __init__(self, suit=0, rank=0): self.suit = suit self.rank = rank def __str__(self): return (self.ranks[self.rank] + " of " + self.suits[self.suit]) def cmp(self, other): if self.suit > other.suit: return 1 if self.suit < other.suit: return -1 if self.rank > other.rank: return 1 if self.rank < other.rank: return -1 return 0 def __eq__(self, other): return self.cmp(other) == 0 def __le__(self, other): return self.cmp(other) <= 0 def __ge__(self, other): return self.cmp(other) >= 0 def __gt__(self, other): return self.cmp(other) > 0 def __lt__(self, other): return self.cmp(other) < 0 def __ne__(self, other): return self.cmp(other) != 0 class Deck: # Collection of card objects def __init__(self): self.cards = [] for suit in range(4): for rank in range(1, 14): self.cards.append(Card(suit, rank)) def print_deck(self): for card in self.cards: print(card) def __str__(self): s = "" for i in range(len(self.cards)): s = s + " " * i + str(self.cards[i]) + "\n" return s def shuffle(self): random.shuffle(self.cards) def remove(self,card): if card in self.cards: self.cards.remove(card) return True else: return False def pop(self): return self.cards.pop() def is_empty(self): return self.cards == [] def multadd (x, y, z): # Polymorphism, works on any data type that can be multiplied or added return x * y + z class Hand(Deck): # Inheritance, Hand is a modified Deck object def __init__(self, name=""): self.cards = [] self.name = name def deal(self, hands, num_cards=999): num_hands = len(hands) for i in range(num_cards): if self.is_empty(): break card = self.pop() hand = hands[i % num_hands] hand.add(card) def __str__(self): s = "Hand " + self.name if self.is_empty(): s += " is empty\n" else: s += " contains\n" return s + Deck.__str__(self)
851e9dfde3ec8fb771a90e9f87e4b77a292c7972
aironm13/Python_Project_git
/Modules_learn/functools_Modules/functools_total_ordering.py
349
3.65625
4
from functools import total_ordering @total_ordering class Person: def __init__(self, name, age): self.name = name self.age = age def __eq__(self, other): return self.age == other.age def __gt__(self, other): return self.age > other.age def __lt__(self, other): return self.age < other.age
4e39eb65f44e423d9695653291c6c15b95920df2
rocket7/python
/S8_udemy_Sets.py
695
4.1875
4
############### # SETS - UNORDERED AND CONTAINS NO DUPLICATES ############### # MUST BE IMMUTABLE # CAN USE UNION AND INTERSECTION OPERATIONS # CAN BE USED TO CLEAN UP DATA animals = {"dog", "cat", "lion", "elephant", "tiger", "kangaroo"} print(animals) birds = set(["eagle", "falcon", "pigeon", "bluejay", "flamingo"]) print(birds) for animal in birds: print(animal) birds.add("woodpecker") animals.add("woodpecker") print(animals) print(birds) # In the exercise below, use the given lists to print out a set containing all the participants from event A which did not attend event B. a = ["Jake", "John", "Eric"] b = ["John", "Jill"] A = set(a) B = set(b) print(A.difference(B))
fcffc923213aecbe1ae7e9873f0f3739fe0dfe68
manikandanmass-007/manikandanmass
/Python Programs/program to find a num is prime number or not.py
276
4.21875
4
#program to find a num is prime number or not i=2 num=(int(input("enter the number..."))) while (i<=num-1): if(num%i==0): print("the given number is not a prime number") break i=i+1 if(i==num): print("the given number is a prime number")