blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
75dad43bfb2c5f96ba174b019b7b5da5274f84f7
zahlambo/Python-Code
/bfs_disconnected.py
3,314
4.125
4
#bfs is level order traversal for that we need enqueue import queue from collections import defaultdict class Graph: # A utility function to add an edge # in an undirected graph. def __init__(self): self.graph = defaultdict(list) #store graph def addEdge(self, u, v): self...
5d624507136c91d87637316a1216c48df1b9e388
RobertMoralesO/clases_python_BP_2021_1
/clase_uno.py
3,562
4.1875
4
print('hello world') a = 5 print(a) # OPERACIONES # Suma a = 5 b = 2 c = a + b print(c) # Resta a = 5 b = 2 c = a - b print(c) # Multiplicación a = 5 b = 2 c = a * b print(c) # División a = 5 b = 2 c = a / b print(c) # División parte entera a = 5 b = 2 c = a // b print(c) # Potencia a = 5 b = 2 c = a ** b print(...
133ea6118d1c342209d53be5108b3899f58fffad
lautarodelosheros/TDA_tp1
/Arreglo/permutacion.py
817
3.59375
4
def permutacion(lista): if len(lista) == 0: return [] if len(lista) == 1: return [lista] resultado = [] for i in range(len(lista)): dato = lista[i] lista_remanente = lista[ : i] + lista[ i + 1 : ] for elemento in permutacion(lista_remanente): ...
2f689e69e239e9553111cfa5fd7cd1b1748bec5c
lautarodelosheros/TDA_tp1
/Arreglo/mediana.py
339
3.640625
4
from merge_sort import merge_sort def mediana(lista): lista_ordenada = merge_sort(lista) medio = len(lista_ordenada) // 2 if len(lista_ordenada) % 2 == 0: numero1 = lista_ordenada[medio] numero2 = lista_ordenada[ medio - 1] return (numero1 + numero2) / 2 return list...
10f2cc427df1e657a26b91d9bea233114256494c
shubee17/Algorithms
/Array_Searching/check_pair_sum.py
346
3.90625
4
# Given an array Array[] and a number x,check for pair in Array[] with sum as x import sys def pair_sum(Array,x): for i in range(len(Array)-1): for j in range(i+1,len(Array)): if (Array[i] + Array[j]) == int(x): print Array[i],Array[j] else: pass Array = sys.argv[1] x = sys.argv[2] Array = map(int,...
33c05d544f56bec9699add58b0a26673d41e974a
shubee17/Algorithms
/Array_Searching/search_insert_delete_in_unsort_arr.py
1,239
4.21875
4
# Search,Insert and delete in an unsorted array import sys def srh_ins_del(Array,Ele): # Search flag = 0 for element in range(len(Array)): if Array[element] == int(Ele): flag = 1 print "Element Successfully Found at position =>",element + 1 break else: flag = 0 if flag == 0: print "Element Not F...
ba2f57feb91df96aeb9d13f13a8f17fa55ede439
shubee17/Algorithms
/Array_Searching/freq_greater_n_by_two.py
504
3.953125
4
# Find element in a sorted array whose frequency is greater then or equal to n/2 import sys def ele_freq(Array,n): cnt = 0 for i in range(len(Array)): if i == len(Array) - 1: cnt += 1 if (cnt == n or cnt > n): print Array[i] break else: break if Array[i] == Array[i+1]: cnt += 1 else: ...
e2372405fa6a6b53cc4eab2a939987269fb4489c
shubee17/Algorithms
/Array_Searching/bin_srch.py
681
3.75
4
# Binary search in sorted vector of pairs import sys def bin_srch(Array): k = str(raw_input("Enetr the key =>")) mid = len(Array) // 2 left = Array[:mid] right = Array[mid:] flag = 0 if left[-1][0] > k or left[-1][0] == k: for i in range(len(left)): if left[i][0] == k: print "Found" flag = 1 els...
b2d6d4f12893da3128b82f3fa10749be15035dec
shubee17/Algorithms
/Array_Searching/four_ele_sum_to_given_value.py
688
3.796875
4
# Find the four element that sum to a given value import sys def sum_value(Array,x,combos,n): if combos is None: combos = [] if len(Array) == n: if combos.count(Array) == 0: combos.append(Array) return combos else: for i in range(len(Array)): r_list = Array[:i] + Array[i+1:] combos = sum_value(r_l...
fa5596e22fb2e4ed723c6db4da5c7e2250d43953
shubee17/Algorithms
/Array_Searching/frst_repeating_ele.py
368
3.84375
4
# Find the first repeating element in an array of integer import sys def frst_rep(Array): for i in range(len(Array)): if Array[i] in Array[i+1:]: print "First Repeating Element =>",Array[i] flag = 1 break else: pass if flag == 0: print "No Repeating Element" else: pass Array = sys.argv[1] Arr...
4daf5c074e6b6969ba5b50d534db6a8cedf4a191
shubee17/Algorithms
/Array_Searching/lost_ele_dupli_arr.py
393
3.71875
4
# Find lost element from a duplicated array import sys def lost_ele(Array,Array1): flag = 0 for i in Array: if i not in Array1: print "Lost Element =>",i flag = 1 break else: pass if flag == 0: print "No Lost Element" else: pass Array = sys.argv[1] Array1 = sys.argv[2] Array = map(int, Array....
d46b4a8486b134de603e5b6c247e8030e6cacb77
shubee17/Algorithms
/Array_Searching/pair_sum_equal_rest_arr.py
754
3.875
4
# Check if there exists two elements in an array whose sum is equal to the sum of rest of the array import sys def Two_ele_rem_arr(Array,combos): index,list1,list2 = [],[],[] flag = 0 for i in range(len(Array)): for j in range(i+1,len(Array)): ind = [] ind.append(i) ind.append(j) index.append(ind) f...
35b91e330621a7d1a6f269a81a7ce7e1f423b902
Foxcat-boot/Python_ym
/Python_02/Password.py
403
3.59375
4
import os print("用户名:Temp") # os.system('cls' if os.name == 'nt' else 'clear') def a(): USA = "" while True: USB = input("密码:") if USB == USA: print("进入System...") break else: print("密码错误") # os.system('cls' if os.name == 'nt' else 'clear...
5aca9da4c1d5edc7ab40f828cdbf9cc81a79894d
Foxcat-boot/Python_ym
/python_01/py_11_字符串查找和替换.py
797
4.125
4
# 判断是否以某字符串开头 str1 = "str123 321" print(str1.startswith("str")) print(str1.startswith("Str")) """ ⬆此方法区分大小写 """ # 判断是否以某字符串结尾 str2 = "hu1 mao" print(str2.endswith("mao")) print(str2.endswith("Mao")) """ 同样区分大小写 """ # 查找字符串 str3 = "123humao321159 xhm" print(str3.find("159")) print(str3.find("1")) p...
9ab2e315097803b322a0c57f4e3f33ee165807c9
Olishevko/HomeWork1
/operators.py
466
4.53125
5
# Арифметические операторы # + - * / % ** // #print(2+5) #print(3-5) #print(5 / 2) #print(5 // 2) #print(6 % 3) #print(6 % 5) #print(5 ** 2) #number = 3 + 4 * 5 ** 2 +7 #print(number) # Операторы сравнения # == != > < >= <= #print(1 == 1) #print(1 == 2) #print('One' == 'ONE') #print('One' != 'ONE') # Операторы п...
966e0db72549798a13d6178d3d7f0cb56be82a24
HendersonLMateus/Python
/filtroDePalavroes.py
475
3.921875
4
#Digite o caminho do arquivo a ser pesquisado ler = open(r"C:\Users\PANDA CRAZ1\Desktop\Mateus\pythonUdacity\palavroes.txt") texto = ler.read() #print(texto) palavra = input ("Qual palavra você está procurando? ") while ("true"): if (palavra in texto): print ("A palavra está no Texto. Ela aparece...
18c09e7a0aa9008095a798a446036795a9097570
HendersonLMateus/Python
/acertarUmNumeroAleatorio.py
504
3.921875
4
import random chute = random.randint(1,10) while (True): a = int(input("Diz um numero: ")) b = int(input("Diz um numero: ")) if a == chute or b == chute: print("Você acertou, o valor é ", chute) break else: print("Errou") if a > chute: print("Dimi...
8a030978c36b8394aa8b25e24583b1a9f231a074
HendersonLMateus/Python
/dicionário.py
96
3.640625
4
dic = {"a":"alberto","m":"mateus","h":"henderson"} for chave in dic: print(dic[chave])
106e34daf8c2eb167d8a1c7379b8905ce055d36e
SoliDeoGloria31/study
/AID12 day01-16/day02/code/input2.py
214
3.78125
4
# input.py # 此示例示意input函数的用法 # 请输入一个整数,把这个整数乘以2后输出打印在终端上 s = input("请输入整数: ") x = int(s) # 转为整数 print("结果是:", x * 2)
b2a9e7d9c47eb54827ed00260ac3e0fd4616c121
SoliDeoGloria31/study
/AID12 day01-16/day02/exercise/abs_if_statement.py
354
4.0625
4
# 1. 写一个程序,输入一个数,用if语句计算这个数的绝对值,并打 # 印此绝对值 x = int(input("请输入一个数: ")) # 方法1 # if x < 0: # result = -x # 用result来记录结果 # else: # result = x # 方法2 result = x if result < 0: result = -result # 符号取反 print(x, '的绝对值是:', result)
c6f2dc37a1fdd0d3e93bb76e57b1b43765d18c92
SoliDeoGloria31/study
/AID12 day01-16/day05/exercise/get_char_count2.py
824
3.921875
4
# 练习: # 任意输入一段字符串 # 1) 计算出这个字符串中空格的个数,并打印这个个数 # (要求用for 语句,不允许使用S.count方法) # 2) 计算出字符串中全部英文字母(A-Z和a-z)的个数, # 并打印打印这个个数 # 完成上题后思考: # 能否用while语句实现上述功能 s = input("请输入一段字符串: ") blanks_count = 0 alpha_count = 0 i = 0 # i 代表字符串的索引 while i < len(s): # 索引不允许大于等于len(s) ch = s[i] # ch绑定每次遍...
d3678855cff4d6628b6e6b798ad4d7171f1e7338
SoliDeoGloria31/study
/AID12 day01-16/day06/code/deepcopy.py
165
3.546875
4
import copy # 导入考拷贝模块 L1 = [1, 2, [3.1, 3.2]] L2 = copy.deepcopy(L1) L2[2][0] = 3.14 print(L1) # [1, 2, [3.1, 3.2]] print(L2) # [1, 2, [3.14, 3.2]]
0bacac4830fb2e7fa4edef9892ac255a4eed721e
SoliDeoGloria31/study
/AID12 day01-16/day04/day03_exercise/delete_blank.py
283
4.1875
4
# 2. 输入一个字符串,把输入的字符串中的空格全部去掉,打印出处理 # 后的字符串的长度和字符串的内容 s = input("请输入字符串: ") s2 = s.replace(' ', '') print('替换后的长度是:', len(s2)) print('替换后的内容是:', s2)
567c6e083ddbe7de37c7fc2be8e2126062197326
SoliDeoGloria31/study
/AID12 day01-16/day08/exercise/print_even.py
351
4.125
4
# 练习2 # 写一个函数print_even,传入一个参数n代表终止的整数,打印 # 0 ~ n 之间所有的偶数 # 如: # def print_even(n): # ..... 此处自己完成 # print_even(10) # 打印: # 0 # 2 # 4 # 6 # 8 def print_even(n): for x in range(0, n+1, 2): print(x) print_even(10)
621505094d5093bb2cb1df2e21d3c1596f1c04f1
SoliDeoGloria31/study
/AID12 day01-16/day13/day12_exercise/clock2.py
352
3.59375
4
# 2. 写一个程序,以电子时钟格式打印时间: # 格式为: # HH:MM:SS def show_time(): import time while True: t = time.localtime() # print("%02d:%02d:%02d" % (t[3], t[4], t[5]), # end='\r') print("%02d:%02d:%02d" % t[3:6], end='\r') time.sleep(0.1) show_time()
c193dca10affb3232781a378dbfe2e5499d3df6b
SoliDeoGloria31/study
/AID12 day01-16/day08/day07_exercise/mydict.py
847
3.953125
4
# 2. 输入一些单词和解释,将单词作为键,将解释作为值,存入字典中 # 当输入单词或解释为空是停止输入,并打印这个字典 # 然后,输入查询的单词,给出单词的内容,如果单词不存在则提示: # 查无此词 mydict = {} # 创建一个空字典准备存储数据 while True: word = input("请输入单词: ") if not word: # 如果word空字符串,则退出 break trans = input("请输入解释: ") if not trans: break # 走到此处,说明word, ...
8213ca291772b51b791a39dabaa04f8821b8647d
SoliDeoGloria31/study
/AID12 day01-16/day09/exercise/mymax.py
990
4.03125
4
# 练习: # 已知内建函数max帮助文档为: # max(...) # max(iterable) -> value # max(arg1, arg2, *args) -> value # 仿造 max写一个mymax函数,功能与max完全相同 # (要求不允许调用max) # 测试程序如下: # print(mymax([6, 8, 3, 5])) # 8 # print(mymax(100, 200)) # 200 # print(mymax(1, 3, 5, 9, 7)) # 9 # def mymax(a, *args...
4e5c475470faac15e2316731db337048adb22a7b
SoliDeoGloria31/study
/MorvanPython/0_基础/tkinter_study6.py
763
3.5625
4
# -*- coding: utf-8 -*- import tkinter as tk window = tk.Tk() window.title('my window') window.geometry('200x200') l = tk.Label(window, bg='yellow', width=20, text='empty') l.pack() def print_selection(): if (var1.get()==1)&(var2.get()==0): l.config(text='I love only Python') elif (var1.get()==0)&(...
57f9244b7be7388361dcda8b71a8921773e36aec
SoliDeoGloria31/study
/AID12 day01-16/day16/exercise/myprint.py
765
4.03125
4
# 思考: # print() 函数是如何实现的? # 能否自己实现一个myprint函数与内建功能相同 # 如: # print(*args, sep=' ', end='\n', file=sys.stdout, # flush=False) import sys def myprint(*args, sep=' ', end='\n', file=sys.stdout, flush=False): flag = False # 当第一次循环时后,将此变量置为True for x in args: if flag: # ...
263c4455de71b08bfe1cdbcc1862beca2aa7af53
SoliDeoGloria31/study
/AID12 day01-16/day08/day07_exercise/list_remove.py
338
4
4
# 1. 思考下面的程序的执行结果是什么?为什么? #   L = list(range(10)) # for x in L: # L.remove(x) # print("L=", L) # 请问是空列表吗? L = list(range(10)) # for x in L: # print("+++++") # L.remove(x) while L: L.remove(L[0]) print("L=", L) # 请问是空列表吗?
0b03efeb39ed79bd6c36cba537cb74d319122b53
SoliDeoGloria31/study
/AID12 day01-16/day06/code/list_comprehesion.py
230
3.75
4
# 生成一个数值为1~9的整数的平方的列表,如: # L = [1, 4, 9, 16, 25, 36, 49, 64, 81] # 用循环语句: # L = [] # for x in range(1, 10): # L.append(x ** 2) L = [x ** 2 for x in range(1, 10)] print("L=", L)
cecaa8ff2d1ce042a9da127173ef3e292676a426
SoliDeoGloria31/study
/AID12 day01-16/day09/day08_exercise/student_info.py
1,393
4.125
4
# 3. 改写之前的学生信息管理程序: # 用两个函数来封装功能的代码块 # 函数1: input_student() # 返回学生信息字典的列表 # 函数2: output_student(L) # 打印学生信息的表格 def input_student(): L = [] # 创建一个列表,准备存放学生数据的字典 while True: n = input("请输入姓名: ") if not n: # 如果用户输入空字符串就结束输入 break a = int(input("请...
041b361776a99512e0ce6876f233feea3690d664
SoliDeoGloria31/study
/AID12 day01-16/day09/exercise/print_list.py
318
3.515625
4
# 练习: # 已知有列表: # L = [1, 2, True, None, 3.14] # 调用print函数,打印用'#'号分隔的文字信息到终端上 # print(....) # 打印 1#2#True#None#3.14 L = [1, 2, True, None, 3.14] print(*L, sep="#") # 打印 1#2#True#None#3.14 # 等同于print(1, 2, True, None, 3.14, sep='#')
553377ab396959c2d5f3e6f7c098be8b0f393d10
SoliDeoGloria31/study
/AID12 day01-16/day11/exercise/sorted_reverse_str.py
577
3.921875
4
# 练习: # names = ['Tom', 'Jerry', 'Spike', 'Tyke'] # 排序的依据为字符串的反序: # 'moT' 'yrreJ' 'skipS' 'ekyT' # 排序的结果为: # ['Spike', 'Tyke', 'Tom', 'Jerry'] # 请问如何用sorted进行排序 def reverse_str(s): '''s绑定需要排序的可迭代对象提供的元素''' r = s[::-1] # 把转原字符串 print("要排序的元素:", s, '排序的依据是:', r) return r nam...
3372de957ff0294127d8316eb6c6e96444e2b807
SoliDeoGloria31/study
/AID12 day01-16/day09/code/list_as_args.py
353
3.578125
4
# list_as_args.py # 此示例示意,当函数的实参为可变数据类型时,在函数内部可以改为 # 容器的内容 L = [1, 2, 3, 4] t = (1.1, 2.2, 3.3, 4.4) def append_5(x): # x.append(5) x += (5,) print('x=', x) # 1.1, 2.2, 3.3, 4.4, 5 append_5(L) print(L) # [1, 2, 3, 4, 5] append_5(t) print(t) # (1.1, 2.2, 3.3, 4.4)
7edc9e159095ac854a0eee1957efbc7956942756
SoliDeoGloria31/study
/AID12 day01-16/day05/exercise/reverse_string.py
431
3.984375
4
# 练习: # 输入一个字符串, 从尾向头输出这个字符串的字符 # 如: # 请输入: hello # 打印: # o # l # l # e # h s = input('请输入字符串: ') # s2 = s[::-1] # 反转字符串 # for c in s2: # print(c) # for c in s[::-1]: # print(c) # 用while循环实现 i = len(s)-1 # 代表索引 while i >= 0: print(s[i]) i -= 1 # 索引向前走一步
4f864584f6deb6a911972a6b9ec2ec6f3989cb9d
SoliDeoGloria31/study
/AID12 day01-16/day06/exercise/list_odd.py
291
3.671875
4
# 练习 : # 用列表推导式生成 1~100 内所有奇数组成的列表 # 结果是:[1, 3, 5, 7, ....., 99] # L = [x for x in range(1, 100, 2)] L = [x for x in range(1, 100) if x % 2 == 1] print(L) L = [] for x in range(1, 100): if x % 2 == 1: L.append(x) print("L=", L)
2f3c745b5f381fe09922092bb48cdbf4fdcaced5
SoliDeoGloria31/study
/AID12 day01-16/day03/exercise/rectangle2.py
496
3.875
4
# 练习: # 写一个程序,打印一个高度为4行的矩形方框 # 要求输入一个整数,此整数代码矩形的宽度,打印 # 相应宽度的矩形 # 如: # 请输入矩形宽度: 10 # 打印如下: # ########## # # # # # # # ########## w = int(input("请输入矩形的宽度: ")) print('#' * w) # 打印第一行 print('#', ' ' * (w-2), '#', sep='') # 第二行 print('#', ' ' * (w-2), '#',...
a67330c5dc0ad81a9fac382ec8fdcb5c310d5750
SoliDeoGloria31/study
/AID12 day01-16/day01/exercise/circle.py
376
4.25
4
# 练习: # 指定一个圆的半径为 r = 3 厘米 # 1) 计算此圆的周长是多少? # 2) 计算此圆的面积是多少? # 圆周率: 3.1415926 # 周长 = 圆周率 * 半径 * 2 # 面积 = 圆周率 * 半径 * 半径 r = 3 pi = 3.1415926 length = pi * r * 2 print("周长是:", length) area = pi * r * r # r ** 2 print("面积是:", area)
85c3dcc35ca37b4ef530a4643b47fd16e8f34e3e
betta-cyber/leetcode
/python/quick_sort.py
930
3.75
4
#!/usr/bin/env python # encoding: utf-8 def quick_sort(l, left, right): if left < right: i = partition(l, left, right) quick_sort(l, left, i - 1) quick_sort(l, i + 1, right) def partition(l, left, right): base = l[left] while left < right: while left < right and l[right] ...
b1ec062d544dfb65fbd8f09e67bb03dce65aeef6
betta-cyber/leetcode
/python/208-implement-trie-prefix-tree.py
784
4.125
4
#!/usr/bin/env python # encoding: utf-8 class Trie(object): def __init__(self): self.root = {} def insert(self, word): p = self.root for c in word: if c not in p: p[c] = {} p = p[c] p['#'] = True def search(self, word): nod...
2b77e3250c8b461e3c4b20244545e1f485812972
betta-cyber/leetcode
/python/152-maximum-product-subarray.py
810
3.84375
4
#!/usr/bin/env python # encoding: utf-8 class Solution(object): def maxProduct(self, nums): """ :type nums: List[int] :rtype: int """ if not nums: return 0 curv = maxv = minv = nums[0] res = [curv] for i in nums[1:]: curv = i ...
8139278bd32294e669e79e624c921a6549442f0b
betta-cyber/leetcode
/python/061-rotate-list.py
976
4
4
# -*- coding: utf-8 -*- # Definition for singly-linked list. class ListNode(object): def __init__(self, val=0, next=None): self.val = val self.next = next class Solution(object): def rotateRight(self, head, k): """ :type head: ListNode :type k: int :rtype: ListN...
d55493a507ff09a1ed2aade2085e9621e6760175
betta-cyber/leetcode
/python/215-kth-largest-element-in-an-array.py
919
3.6875
4
#!/usr/bin/env python # encoding: utf-8 # 可以说是最慢的Accepted了,需要优化 class Solution(object): def findKthLargest(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ topk = [] for n in nums: if len(topk) < k: topk = s...
a333cd57f20e1bef78add6b09bc804779ccc6a59
betta-cyber/leetcode
/python/113-path-sum-ii.py
905
3.734375
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None # dfs的思路,维护一个self.paths, 分别对子节点进行遍历 class Solution(object): def pathSum(self, root, sum): """ :type root: TreeNode :typ...
3e5baa8cea5b7a5f99e6b822d6acbe82415c8ae2
Clijmart/Python_Tasks
/Les5/pe5_5.py
101
3.953125
4
numbers = [5,7,2,5,8,1,5,2,3] for number in numbers: if (number % 2 == 0): print(number)
5178b6aa1a03661122b9f32a69314272deda22e9
Clijmart/Python_Tasks
/Les7/pe7_4.py
442
3.578125
4
def strftime(): import datetime vandaag = datetime.datetime.today() date = vandaag.strftime("%a %d %b %Y") return date hardlopers = open('hardlopers.txt', 'a') while True: name = input('Naam hardloper (Write "Exit" to exit): ') if name == 'Exit' or name == 'exit': hardlopers.close() ...
4b125a494e3a27bd8d8458a8a593750812073a29
Clijmart/Python_Tasks
/Les5/pe5_2.py
345
3.984375
4
leeftijd = int(input('Leeftijd: ')) paspoort = input('Heb je een Nederlands paspoort? (Ja/Nee) ').lower() if(leeftijd >= 18 and paspoort == 'ja'): print('Hieperdepiep, je mag stemmen!') elif(paspoort != 'ja'): print('Je moet een Nederlands paspoort hebben om te stemmen!') else: print('Je moet minimaal 18 j...
329090a8e85e0bafc9f3e4a3d3953a1424f23825
ahforoughi/map_coloring_csp
/map_coloring_csp.py
834
3.546875
4
colors = ['Red', 'Blue', 'Green'] states = ['A', 'B', 'C', 'D', 'E', 'F', 'G'] neighbors = {} neighbors['A'] = ['B', 'C'] neighbors['B'] = ['A', 'C', 'D'] neighbors['C'] = ['A', 'B', 'D', 'E', 'F'] neighbors['D'] = ['B', 'C', 'E'] neighbors['E'] = ['C', 'D','F'] neighbors['F'] = ['C', 'E'] neighbors['G'] = [''] colo...
da0caea4153d9574f7ec86bc595d28b42cb50fe2
AsadullahFarooqi/data_structures_and_algorithms_with_python
/09.2_Randomized_select_ith_smallest.py
827
3.6875
4
import random def partition(A, low, high): x = A[high] i = low - 1 for j in range(low, high): if A[j] <= x: i += 1 z = A[i] A[i] = A[j] A[j] = z y = A[i+1] A[i+1] = A[high] A[high] = y return i + 1 def randomized_partition(arr, start, end): i = random.randint(start, end) temp = arr[i] arr[i] =...
e1284b54167b575018ef343996ea429f652baa1a
AsadullahFarooqi/data_structures_and_algorithms_with_python
/07.3_Randomized_Quick_sort.py
679
3.8125
4
import random def partition(A, low, high): x = A[high] i = low - 1 for j in range(low, high): if A[j] <= x: i += 1 z = A[i] A[i] = A[j] A[j] = z y = A[i+1] A[i+1] = A[high] A[high] = y return i + 1 def randomized_partition(arr, start, end): i = random.randint(start, end) temp = arr[i] arr[i] =...
4c8c8bdc6facfd7953b001569346115cf1ebcd42
yangjiahao106/Data-structure-and-Algorithm-analysis-in-Python
/chain_talbe/single_chain_table.py
3,370
4.03125
4
#! python3 # __author__ = "YangJiaHao" # date: 2017/10/21 class Node(object): """a class about the element of the chain table""" def __init__(self, element, nex=None): self.element = element self.next = nex class SingleChainTable(object): """a class about single chain table :para...
3f99b38897fcab44f7b6e6501d7bad15055a33a7
yangjiahao106/Data-structure-and-Algorithm-analysis-in-Python
/tree/ADT.py
3,348
4
4
#! python3 # __author__ = "YangJiaHao" # date: 2018/3/20 from queue import Queue class Node(object): def __init__(self, val, parent=None): self.parent = parent self.val = val self.left = None self.right = None class BinarySearchTree(object): def __init__(self): self.r...
67f055682952637318298d1fe8cfed656cce3eef
NicoLep2005/Algos_racine_approche
/methode_dichotomie.py
787
3.53125
4
# -*- coding: utf-8 -*- """ Created on Mon Feb 15 18:16:19 2021 @author: PC Fixe Nicolas """ from math import * #definition d'une fonction g(x) def g(x): return log(x) + x**2 #algo dichotomique pour fonction continue et monotone, basée sur le corollaire du TVI def methode_dichotomie(a,b): ...
f91e9e8a3932a0ed15fb5dcc81a7777d9f0b698b
AlvaroMonserrat/app-comercial-kivy
/BasicThings/diccionarios.py
1,133
3.859375
4
#diccionarios: Tipo de lista no ordenada en la cual cada elemento está asociado a una llave """ LLave | Valor "a" | "Primero" "33" | "Segundo" 5 | "Tercero" (10,20)| "Cuarto" """ #Declarar diccionario """ dic1 = {} dic2 = dict() dic1["aaa"] = 1000 dic1["bbb"] = 2000 dic1["ccc"] =...
f553669a9599f1e72f5ed5fb65a7bb8d85d46902
sagarkarn/blog-blogpost2
/blog-post-2/python/Factorial.py
150
3.90625
4
number = int(input("Enter number: ")) factorial = 1 x = 0 for x in range(0,number): factorial *= x+1 print(number, "\b! = " , factorial) #((4))
166679a236b0c8d22e5240e71290fcec693d8a8d
QuinnSpearman/MovieRecommender
/MovieCorrelationsGenerator.py
5,214
3.828125
4
#!/usr/bin/env python # coding: utf-8 # In[1]: import pandas as pd import math print("Starting...") # Reads user ratings from a csv and stores in a dataframe ratings = pd.read_csv("MovieData/ratings.csv") # Drops the timestamp column ratings.drop('timestamp', axis = 1, inplace = True) # Reads movie data from a csv...
5c4fcbf797b3e1830417a8e3beeb4e5c17a2050c
llxxll12345/projects
/SSfiles/turdemo.py
994
3.9375
4
from turtle import * # draw a picture title("first drawing!") turtle = Turtle() def change(r): return ((r * 10) % 10)/10 #change the color r = 0.1 g = 0.1 b = 0.1 #initial color sc = Screen() sc.screensize(700,700) sc.bgcolor("green") sc.screensize(500.0,500.0) turtle.pencolor(r, g, b) leng =...
63e5e637862211d43db5aef7bd0764897204f6e5
juniorBM/Python-3-para-Iniciantes
/Curso Python/Entrada de Dados/EntradaDados.py
162
3.75
4
nome = input("Informe seu nome: ") print("Seu nome:", nome) idade = input("Informe a idade: ") print("Sua idade: ", idade) idade = int(input("Digite sua idade"))
8293d413eaed199707353a3d71991ad53a1c0c0a
juniorBM/Python-3-para-Iniciantes
/Curso Python/Funcoes Matematicas/FuncoesMatematicas.py
592
3.765625
4
import math #Retorna o maior e menor inteiro em relação ao número que passar print(math.ceil(3.14)) #Retorna o valor absoluto print(math.fabs(-5)) #Retorna o fatorial do número que passar no parametro print(math.factorial(5)) #Retonar o menor ou igual ao número que passar no parametro print(math.floor(3.14)) #Reto...
65e537543b8006819349a8b6746fb41924554768
juniorBM/Python-3-para-Iniciantes
/Curso Python/Operadores Logicos/OperadoresLogicos.py
238
3.671875
4
variavel = True print("Valor Incial", type(variavel), variavel) print("Valor Alterado", type(variavel), not variavel) p1 = True p2 = True r = p1 and p2 print("Resultado AND", r) v1 = False v2 = True t = v1 or v2 print("Resultado OR", t)
1acf9dbe86ad40b8f488beb4849abdda49680962
Archanciel/GradientDescent
/LinearRegression/my_multivar_linear_regr.py
1,882
3.609375
4
# This version matches exactly the results of the Coursera Octave version ! import numpy as np import pandas as pd verbose = False data = pd.read_csv('home.txt', names=['surface', 'rooms', 'price']) if verbose: print('data\n', data.head()) X = np.array(data.iloc[:,0:2]) X_before_norm = X if verbose: print(...
7f9128452215ca22a737f994a86a5e35d9e68c8a
garymale/python_learn
/Exercise/EX17.py
738
3.75
4
list_1 = [1,4,5,21,33,11,55,7,3,6,8,2,6,9] list_1 = set(list_1) print(list_1,type(list_1)) list_2 = set([2,4,5,6,11,44,55,66,77,3]) print(list_1,list_2) """交集""" list_too = list_1.intersection(list_2) print(list_too) print("------------") print(list_1 & list_2) """并集""" list_union = list_1.union(list_2) print(list_...
919a37ba58267ffe921c2485b317baca4d2f33d9
garymale/python_learn
/Learn/Learn04.py
1,096
4.3125
4
#创建数值列表 #使用函数 range()可以生成一系列数字,打印1-4 for value in range(1,5): print(value) #range()创建数字列表,使用函数list()将range()的结果直接转换为列表 numbers = list(range(1,6)) print(numbers) #使用函数range()时,还可指定步长,下列步长为2 enen_numbers = list(range(2,11,2)) print(enen_numbers) #例:创建一个列表,其中包含前 10个整数(即1~10)的平方,在Python中,两个星号(**)表示乘方运算 squares = []...
9f7a5977df4e57f7c7c5518e4e3bc42f517d1856
matthew-lu/School-Projects
/CountingQueue.py
1,823
4.125
4
# This program can be called on to create a queue that stores pairs (x, n) where x is # an element and n is the count of the number of occurences of x. # Included are methods to manipulate the Counting Queue. class CountingQueue(object): def __init__(self): self.queue = [] def __repr__(s...
3c4e770c0bd0ea9a33e708790a6572d8582d7fb3
hpache/nStates
/nStates.py
8,781
3.59375
4
''' Henry Pacheco Cachon Created: 01/15/2021 Last Modified: 01/18/2021 Creating a class that sets up our NState system and sets up the needed matrix equation to solve for the steady state ''' import numpy as np from sympy import * from sympy.physics.quantum import * import pandas as pd from sci...
0a0197ebbe447e8ec9bff7601b1f5f8b5195ce26
matthewgiles/NEA
/validator.py
3,178
4.1875
4
import re def validateEmail(string): """This function takes a string as its input and returns a string 'message' which determines whether or not the input is a valid email""" message = "" # Create a regular expression matching a valid email pattern = re.compile("^([a-zA-Z0-9]+(\.[a-zA-Z0-9]+)*@[a-...
90381dd685ebb1211b33bf6e964f9219bc06db08
qbboe/Learning-Python
/6_fiboInterpolation.py
1,677
3.640625
4
import sys def addNumber(sNum, lNum):# last and second last number sumNum = sNum + lNum return sumNum print("How much numbers in Fibonacci's sequence do yuo want?") list_lenght = sys.stdin.readline() list_lenght = int(list_lenght) fibo_list = [0,1] dim = len(fibo_list) lNum = fibo_list[dim-1] sNum = ...
d5ee19d31126ac73db9dff07e5132abd9ef1956e
jorgeaninoc/PythonDataStructures
/Stacks & Queues/InPosPreFix.py
932
3.671875
4
from DinamicArrayStack import DinamicArrayStack def infixToPosfix(string): operands = DinamicArrayStack() result = [] prec = {} prec["*"]=3 prec["/"]=3 prec["+"]=2 prec["-"]=2 prec["("]=1 tokens = string.split() for symbol in tokens: if symbol in "ABCDEFGHIJKLMNOPQRSTUVW...
9e5262368f8a7d8d708183a3d9c68dcd8c035415
jorgeaninoc/PythonDataStructures
/Algorithms/ShellSort.py
525
3.9375
4
def ShellSort(A): sublistcount = len(A)//2 while sublistcount > 0: for startposition in range(sublistcount): gap_insertion_sort(A,startposition,sublistcount) sublistcount = sublistcount//2 def gap_insertion_sort(A,start,gap): for i in range(start+gap,len(A),gap): currentv...
b572dfeb4af8b2f4850a461a3ea0653fea98476f
jorgeaninoc/PythonDataStructures
/Recursion/PathFinder.py
477
3.59375
4
def path_finder(Matrix,position,N): if position == (N-1,N-1): return [(N-1,N-1)] x,y = position if x+1 < N and Matrix[x+1][y] == 1: a = path_finder(Matrix,(x+1,y),N) if a != None: return [(x,y)]+a if y+1<N and Matrix[x][y+1]==1: b = path_finder(Matrix,(x,y+1),...
5a430c3c8070e3ae94da8845565900a2c4c6083a
jorgeaninoc/PythonDataStructures
/Graphs/BreathFirstSearch.py
755
3.5
4
from DinamicArrayQueue import DinamicArrayQueue def bfs(G,s): start = G.get_vertex(s) start.set_distance(0) start.set_previous(None) vertQueue = DinamicArrayQueue() vertQueue.enqueue(start) while not vertQueue.isEmptyQueue(): currentVert=vertQueue.dequeue() print(currentVert.get...
1101fdf9505ea8a2d692fecf5e77e1f0ba11c717
mediator03/quadratic
/fakeFastaGenerator.py
846
3.515625
4
#Takes five arguments, generate fake fasta files #Useage: python fakeFastaGenerator.py outputFasta.txt a b c #a:number of sequence to generate #b:minimum length of the sequence #c:maximum length of the sequence import sys import random as rd def rand_seq(a): import numpy from numpy import random nt = ["A","...
45dd59a42a3b5af886ad516a9fa1c4aaf67fb0bd
iotrusina/M-Eco-WP3-package
/xjerab13/blogs_download2/cmd_blog_download/bdllib/download.py
2,165
3.5625
4
import urllib2 from gzip import GzipFile from StringIO import StringIO import logging from base64 import encodestring from httplib import BadStatusLine log = logging.getLogger("blog_download") def getDataFrom(url, user, password, gzip=True): '''Download data from url. Can use siplme HTTP auth and gzip compres...
e4582dfbba1b6fe5d1705df9542d88f0b3c17e04
virigould/PythonFun
/DataBase.py
493
3.84375
4
import sqlite3 # database practice with python. connection = sqlite3.connect("users.db") cursor = connection.cursor() cursor.execute("""DROP TABLE user""") command = """ CREATE TABLE user ( uname VARCHAR(15), walletAmount INTEGER, joining DATE);""" cursor.execute(command) command = """INSERT IN...
82e02af1c7ad4f8d08018e1d770d60cd8152a18d
Dark-Knight-17/Analysis-of-Algorithms-Practicals
/Prac 8 eucledian gcd.py
437
3.578125
4
def gcdExtended(a, b, x, y): if a == 0 : x = 0 y = 1 return b x1 = 1 y1 = 1 # To store results of recursive call gcd = gcdExtended(b%a, a, x1, y1) x = y1 - (b/a) * x1 y = x1 return gcd x = 1 y = 1 a = 70 b = 58 g = gcdExtended(a, b, x, y...
62d102c6482d3152223ebf6e9d917b00174c19c9
ClydeChen/Openjudge
/PythonOpenJudge/f1011.py
3,793
3.90625
4
#描述 #George took sticks of the same length and cut them randomly until all parts became at most 50 units long. Now he wants to return sticks to the original state, but he forgot how many sticks he had originally and how long they were originally. Please help him and design a program which computes the smallest possible...
3682dedc05c9eb85fa0f5f1b6cde12ee87a1b5af
SinkLineP/Python-18.08.2021
/HomeWork/HM/dz.py
425
3.875
4
while True: b = input('Введите текст: ') z = (b.lower()) w = z.replace(" ", "") l = "".join(w for w in w if w not in ('!','.',':',',','?',';','-','_','|')) w = l s = w (list(s)) a = ("".join(s[::-1])) p = ('stop') if b == p: exit() if s == a: print("Ваш текст является полиндромом!") else: print("...
6f4afb9b790a494e3a32a862daf271b14ca1582f
os-utep-master/python-intro-JosephSWarren
/wordCount.py
763
3.625
4
import sys import re import os import subprocess if len(sys.argv) is not 3: print("Correct usage: wordCount.py <input text file> <output text file>") exit() textFname = sys.argv[1] if not os.path.exists(textFname): print("text file input %s doesn't exist! Exiting" %textFname) exit() allWords = [] wi...
7722ca6b833aee0776770a9b413e8e00b4cb7c00
NaiaraSantoss/Inteligencia-artificial-basico
/8_hebb_preceptron_console/3_hebb_rule/hebb.py
683
3.515625
4
# Inputs x1 = [-1, 1, -1, 1] x2 = [-1, -1, 1, 1] # Output target = [-1, -1, -1, 1] # inicialização dos pesos - deltas w1o = [] w2o = [] bo = [] ke = 0 for i in x1: w1o.append(i*target[ke]) ke = ke + 1 ke = 0 for i in x2: w2o.append(i * target[ke]) ke = ke + 1 # Pesos w1 = [] w2 = [] bo = [] w1.app...
f19d76cbdc49c23df69078fd7f7c39d1b9fc1e83
UnDeR-The-mAsK/lab3
/PyCharm/user.py
197
3.90625
4
name = input("What is your name?") old = input("How old are you?") place = input("Where are you live?") print('This is, ', name) print(' It is, ', old, 'years old') print('(S)he live in ', place)
61f1714cae0c2e20659b629977e880610da700c3
elklepo/pwn
/my_tasks/rubiks/game.py
2,732
3.65625
4
#!/usr/bin/python2 -u from sys import argv from time import time from datetime import timedelta from logic.cube2x2x2 import Cube2x2x2 from logic.cube3x3x3 import Cube3x3x3 def reset_console(): print '\033[H\033[2J' def print_ihelp(): reset_console() print '''Cube is represented as: U L...
c7bf94263b9c0326e96fac0a0147cd0da2835065
isis0517/realtime-moving-fish
/opencv-test.py
4,452
3.609375
4
import cv2 import numpy as np def rotate_angle(image, angle): # rotate the square image height, width = image.shape[0:2] # get the height and width of image if height != width: raise NameError("it is not square image!") rota_matrix = cv2.getRotationMatrix2D((height / 2, width / 2), angle, 1) ...
e1a799cf996ec3b32f171f41fce7db3f9bf9e611
GriffH/school-files
/project_1/hausken_griff_todays_date.py
151
3.984375
4
from datetime import date #importing date module todaydate = date.today() #gets the date print("Today's date is: ", todaydate) #displays date
8e1b308cefcc351ef321a2a6c00fdae59b1f75c7
GpsProjection/devop
/gpsprojection/percentilecheck.py
1,078
3.96875
4
# -*- coding: utf-8 -*- """ Created on Sat Mar 14 22:48:09 2015 @author: Administrator """ import math import numpy #import functools def percentile(N, percent, key=lambda x:x): """ Find the percentile of a list of values. @parameter N - is a list of values. Note N MUST BE already sorted....
4ecdbf4601a689c75cda2214ca9e4fdcf0688610
valiyakath/code
/strings/first_non_repeating_character.py
291
3.578125
4
# O(n) time | O(1) space def firstNonRepeatingCharacter(string): hashTable = {} for s in string: if s not in hashTable: hashTable[s] = 0 hashTable[s] += 1 for i, s in enumerate(string): if hashTable[s] == 1: return i return -1
b8d472f404bcfd2e2d1744dd38c028688ed895ac
valiyakath/code
/binary_search_trees/find_closest_value_in_bst.py
1,061
3.53125
4
# O(log(n)) time | O(log(n)) space def findClosestValue(tree, target, closestValue): if not tree: return closestValue if abs(tree.value - target) < minDiff: closestValue = tree.value if target < tree.value: return findClosestValue(tree.left, target, closestValue) else: re...
1500884019b8c8c568a3994b7fee907207c1ed6b
valiyakath/code
/arrays/spiral_traverse.py
2,696
3.546875
4
# O(n) time | O(n) space # Iterative solution 2 def spiralTraverse(array): result = [] startRow, endRow = 0, len(array) - 1 startCol, endCol = 0, len(array[0]) - 1 while startRow <= endRow and startCol <= endCol: for col in range(startCol, endCol + 1): result.append(array[startRow][...
af09d0b55c9ae18f18709d33d83b07d85b0ab984
valiyakath/code
/arrays/array_of_products.py
966
3.53125
4
# O(n) time | O(n) space def arrayOfProducts(array): arrayProduct = [] leftProduct = 1 for idx in range(len(array)): arrayProduct.append(leftProduct) leftProduct *= array[idx] rightProduct = 1 for idx in reversed(range(len(array))): arrayProduct[idx] *= rightProduct ...
c2afa5564336e0cdbb48aad6adaf1e9154837f24
valiyakath/code
/graphs/breadth_first_search.py
236
3.734375
4
# O(n) time | O(1) space def breadthFirstSearch(self, array): q = [self] while len(q) > 0: node = q.pop(0) array.append(node.name) for child in node.children: q.append(child) return array
421acdd0c0bd12526592bed9d95c9578552f188e
Daoud-Hussain/Python-Rock-Paper-Scissor-game
/game.py
1,112
4.28125
4
while True: print( "*****Rock Paper Scissor Game****") import random comp = random.randint(1,3) if comp == 1: computer = 'r' elif comp == 2: computer = 'p' else: computer = 's' player = input("Enter 'r' for rock, 's' for scissor, 'p' for paper: ") if player == 'r'...
c12f2cca13ec11d7432da36b0956cb6676aa7043
grvcmd/popular-github-projects-api-project
/python_repos.py
978
3.578125
4
import requests # Make an API call and store the response. url = 'https://api.github.com/search/repositories?q=language:python&sort=stars' headers = {'Accept': 'application/vnd.github.v3+json'} r = requests.get(url, headers=headers) print(f"Status code: {r.status_code}") # Store API response in a variable. response_d...
899c0e8ef140f479f5b4bfa6480a134299eb3f8f
Dennysro/Python_DROP
/9.1_List_Comprehension.py
735
3.859375
4
""" List Comprehension Nós podemos adicionar estruturas condicionais lógicas às nossas list comprehensions """ # Exemplos numeros = [1, 2, 3, 4, 5, 6] # 1 pares = [numero for numero in numeros if numero % 2 == 0] impares = [numero for numero in numeros if numero % 2 != 0] print(pares) print(impares) #...
8464016eb57ab1d72628555c417586a544038d0d
Dennysro/Python_DROP
/8.5_DocStrings.py
880
4.3125
4
""" Documentando funções com Docstrings - Serve para deixar o código mais claro para que for ler. - Podemos ter acesso à documentação de uma função em Python utilizando 2 formas: 1. __doc__ como no exemplo: print(diz_oi.__doc__) 2. print(help(diz_oi)) """ def diz_oi(): """Uma função s...
ffc78156602934d729fb3fc52125c8a95d51e730
Dennysro/Python_DROP
/8.4_Funcoes_com_Parametro_Padrao.py
3,328
4.3125
4
""" Funções com Parâmetro Padrão (Default Parametres) - Funções onde a passagem de parâmetro seja opcional; print('Drop the Beat') print() - Funções onde a passagem de parâmetro não é opcional; def quadrado(numero): return numero ** 2 print(quadrado(3)) print(quadrado()) # TypeError ...
c698040822bc3cdec690b166ad4a930bba3207bf
Dennysro/Python_DROP
/10.0_Utilizando_Lambdas.py
1,720
4.875
5
""" Utilizando Lambdas Conhecidas por expressões Lambdas ou simplesmente lambdas, são funções sem nome. Ou seja, anônimas. #Função em Python: def soma(a, b): return a+b def funcao(x): return 3 * x + 1 print(funcao(4)) """ # Expressão Lambda lambda x: 3 * x + 1 # E como utilizar ...
cc9f8a575d13450fd8af52a92efe1ef9be4e6e09
acheun1/05.MathDojo
/mathdojo.py
1,740
3.984375
4
#MathDojo #2018 09 19 #Cheung Anthony # HINT: To do this exercise, you will probably have to use 'return self'. If the method returns itself (an instance of itself), we can chain methods. # Create a Python class called MathDojo that has the methods add and subtract. Have these 2 functions take at least 1 parameter. ...
73ec06fd0d5e4476542014445b8fef3bfc16db11
gauthammk/zip-cracker
/zip_crack.py
668
3.953125
4
import zipfile wordlist = 'rockyou.txt' zip_file = 'secret.zip' # initialize the Zip File object zip_file = zipfile.ZipFile(zip_file) # count the number of words in this wordlist num_words = len(list(open(wordlist, "rb"))) # print the total number of passwords print "Total passwords to test: " + str(num_words) #try th...
7624c88d4b3bd420e26cefa91b8e4ae9c70cf474
ww334/python-functions-and-modules
/solutions/ex2_2_b.py
603
4.09375
4
def reverse_complement(sequence): """Write a function to return the reverse-complement of a nucleotide sequence. """ reverse_base = {'A': 'T', 'T': 'A', 'G': 'C', 'C': 'G'} sequence = sequence.upper() sequence = reversed(sequence) result = [] for base in sequence: # check if sequ...
0ee854f30eede880d73504a9445056d282052dc7
Gennaro1/Laboratory-of-bioinformatics-1-b-
/extract_seq.py
1,040
3.734375
4
# !/usr/bin/python import sys def get_ids(idfile): ids=open(idfile).read().rstrip().split("\n") return(ids) def print_seqs(ids,dbfile): with open(dbfile, "r") as fdb: #IDK the meaning of the sintaxt "with open..." for line in fdb: if line[0]==">": #pid=line.split("|")[1...