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
8a06c27f394720bbf0d9a95dc5a2ed844c5b01ca
natetostlebe/bonnie
/app.py
417
3.53125
4
from tkinter import * # create window object app = Tk() # Part part_text = StringVar() part_label = Label(app, text='How can i help you?', font=('bold', 14), pady=20) part_label.grid(row=0, column=0, sticky=W) part_entry = Entry(app, textvariable=part_text) part_entry.grid(row=0, column=1) # Buttons add_btn = Button...
b0484809be78a6e377085d56cff114f335c556ac
brianwang/gftop
/mySuanming/src/csvReader.py
257
3.5625
4
#coding=utf-8 import csv myfile=open('mobile_num_jixiong.db','r') reader=csv.reader(myfile) myfile.close for row in reader: #print row #无法显示中文 #print type(row) #list for item in row: print item #print len(row)
898b3be3b7d57db361182bd69801a950b1fd5a27
Sj0berg/GitTest
/pizza.py
730
3.875
4
#Det fantastiska pizzaprogrammet print("*** Hej och välkommen till Pizzamakaren ***") print("1. Skriv in ditt val av topping\n" + "2. Skriv ut ditt val av topping\n" + "3. Skicka Beställning\n" +"4. Avsluta") topping = "" meny = 0 while meny != 4: try: meny = int(input("Gör ett val från menyn: ")) exce...
a0147918ee99933f2f2b5587b49335091412c35e
Tanych/CodeTracking
/208-Implement-Trie-(Prefix-Tree)/solution.py
2,026
4.0625
4
class TrieNode(object): def __init__(self): """ Initialize your data structure here. """ self.childlist=[0 for _ in xrange(26)] # the node value self.val=None # end flag to determin whether it's prefix self.isend=False class Trie(object): ...
8d94c83799264695e9354a53e41829bfbcb8c2c7
Tanych/CodeTracking
/88-Merge-Sorted-Array/solution.py
709
3.640625
4
class Solution(object): def merge(self, nums1, m, nums2, n): """ :type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: void Do not return anything, modify nums1 in-place instead. """ t=m+n-1 l1,l2=m-1,n-1 while...
12ace9bdd4287ee1a2c3b3240635b8375a2a84a9
Tanych/CodeTracking
/42-Trapping-Rain-Water/solution.py
969
3.59375
4
class Solution(object): def trap(self, height): """ :type height: List[int] :rtype: int """ n=len(height) left,right=0,n-1 # using to max to set the wall of each side leftmax=0 rightmax=0 total=0 while left<=right: #...
2af8465247f848eee9295f2e5fd2e33501f5fe1c
Tanych/CodeTracking
/281-Zigzag-Iterator/solution.py
750
3.734375
4
class ZigzagIterator(object): def __init__(self, v1, v2): """ Initialize your data structure here. :type v1: List[int] :type v2: List[int] """ self.res=[] if v1: self.res.append(v1) if v2: self.res.append(v2) def next(self)...
e66c93f6cc74c9b83931d6f0089532001fac06c7
Tanych/CodeTracking
/222-Count-Complete-Tree-Nodes/solution.py
842
4
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 lheight(self,root): depth=0 while root: root=root.left depth+=1 retur...
196df6431d8045e3d1eacab26e32bb63a757cbd1
Tanych/CodeTracking
/381-Insert-Delete-GetRandom-O(1)---Duplicates-allowed/solution.py
1,912
3.921875
4
class RandomizedCollection(object): def __init__(self): """ Initialize your data structure here. """ # saving the data self.data=[] # saving the index self.idxdict={} def insert(self, val): """ Inserts a value to the collection. Returns ...
4b81d6fe1efac29ceeb7066b77453049ceb4647b
Tanych/CodeTracking
/102-Binary-Tree-Level-Order-Traversal/solution.py
1,540
3.671875
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 levelOrdervectical(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ ...
b652101d73cbd57e486a28037e92461797916fb4
Tanych/CodeTracking
/285-Inorder-Successor-in-BST/solution.py
1,079
3.9375
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 recursive(self,root,p): if not root: return None if p.val<root.val: left=self...
0b4be0d8c954387d54765e6786f7d82329c5c7a1
Tanych/CodeTracking
/95-Unique-Binary-Search-Trees-II/solution.py
1,741
3.859375
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 deepcopy(self,root,offset): if not root: return None newroot=TreeNode(root.val+o...
1396faafe38630103002a87674075859a1b6518f
Tanych/CodeTracking
/130-Surrounded-Regions/solution.py
2,217
3.6875
4
class UnionFind(object): def __init__(self,n): self.parent=[-1]*n self.rank=[0]*n self.union=0 for i in xrange(n): self.parent[i]=i def find(self,x): if self.parent[x]==x: return x self.parent[x]=self.find(self.parent[x]) return self.paren...
e450115d8377e0c6a8d9a39fb1c1eb9f7637f511
Tanych/CodeTracking
/309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown/solution.py
1,153
3.53125
4
class Solution(object): def maxProfit(self, prices): """ DP solution: sate: buy[i]: means before day i what is the maxProfit for any sequence end with buy sell[i], rest[i] has the smilar meanings buy[i] = max(rest[i-1]-price, buy[i-1]) sell[i] = max...
71361239a7c21162d7eebbe063b3be54bf153112
Tanych/CodeTracking
/326-Power-of-Three/solution.py
354
3.703125
4
class Solution(object): def __init__(self): self.maxpower=self.max3power_32b() def max3power_32b(self): i,n=0,3 while n<(1<<31-1): n=3**i i+=1 return n def isPowerOfThree(self, n): """ :type n: int :rtype: bool """ return n...
fdcb34af23510292a83b1803a03c24d2ce5ede5b
Tanych/CodeTracking
/36-Valid-Sudoku/solution.py
1,134
3.609375
4
class Solution(object): def isValidSudoku(self, board): """ :type board: List[List[str]] :rtype: bool """ row=len(board) col=len(board[0]) if row!=9 or col!=9: return False # using the moving num to record the occur of num...
8020731ef4fc324aa37d27d1433bde700e3dbc1e
Tanych/CodeTracking
/20-Valid-Parentheses/solution.py
687
3.765625
4
class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ stack = [] for index in range(len(s)): if s[index] == '(' or s[index] == '[' or s[index] == '{': stack.append(s[index]) if s[index] == ')': ...
8be1ce94ef093b50236f7e528c619e75be1686ad
Tanych/CodeTracking
/82-Remove-Duplicates-from-Sorted-List-II/solution.py
1,008
3.671875
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def deleteDuplicates(self, head): """ :type head: ListNode :rtype: ListNode """ if not head or not head.next:...
70b9266405156a9d17651d8a14e7dc212485464f
Tanych/CodeTracking
/234-Palindrome-Linked-List/solution.py
1,662
3.859375
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def lreverse(self,head): if not head: return None if not head.next: return head pre=None cur=...
c94bfca0db9b95d8dbcfbcd61b168a19ad7c3dd7
Tanych/CodeTracking
/384-Shuffle-an-Array/solution.py
910
3.65625
4
class Solution(object): def __init__(self, nums): """ :type nums: List[int] :type size: int """ self.nums=nums self.shuff=[num for num in nums] def reset(self): """ Resets the array to its original configuration and return it. ...
44bb67c215a09a317b2a9db7cbb30b7a7148bcf1
Tanych/CodeTracking
/212-Word-Search-II/solution.py
2,053
3.625
4
class TrieNode(object): def __init__(self): self.childlist=[None]*26 self.val=None class Solution(object): def dfs(self,board,root,i,j,res): original=board[i][j] # if can't find the prefix if original=='*' or not root.childlist[ord(original)-97]: retu...
7dff550a0ca8237a71ebc278fa8722a1395cede8
Tanych/CodeTracking
/10-Regular-Expression-Matching/solution.py
1,044
3.78125
4
class Solution(object): def isMatch(self, s, p): """ :type s: str :type p: str :rtype: bool """ # recursive to solve the problem # if empty pattern if not p: return not s # if the last is '*' if p[-1]=='*': ...
ce6897ba15edf460272f12c01d1dd6b8e4a8296f
ernesto-g/educiaa-micropython-demos
/Intermedio/03_JuegoAdivinarColor/adivinarColor.py
940
3.828125
4
# Juego Adivinar el color con Micropython sobre EDUCIAA # TEC1: Frena el juego de luces. TEC2: Vuelve a empezar import pyb RED=0 YELLOW=1 GREEN=2 led1 = pyb.LED(1) led2 = pyb.LED(2) led3 = pyb.LED(3) switch1 = pyb.Switch(1) # TEC1: stop switch2 = pyb.Switch(2) # TEC2: restart def setLamp(color): if color==R...
4339fde180477acfa1db872480b986b868637204
abhi15sep/Python-Course
/Functions/examples/exercise5.py
1,011
4.03125
4
#The pre-written count_dollar_signs function is broken. It's supposed to return the number of "$" characters in a given string. For example: #count_dollar_signs("$uper $ize") should return 2. . But for some reason, the function always returns either 0 or 1. What's going on? #Without adding any new lines (just move...
52ae48b48dd9f7c9a60970dab786b3a02a7f76b0
abhi15sep/Python-Course
/introduction/loops/Loop_Example/exercise.py
637
4.125
4
# Use a for loop to add up every odd number from 10 to 20 (inclusive) and store the result in the variable x. # Add up all odd numbers between 10 and 20 # Store the result in x: x = 0 # YOUR CODE GOES HERE: #Solution Using a Conditional for n in range(10, 21): #remember range is exclusive, so we have to go up to 21...
684a6a2571adb3bb17ea97230600d5ae76ed6570
abhi15sep/Python-Course
/collection/Dictionaries/examples/Dictionary.py
1,581
4.5625
5
""" A dictionary is very similar to a set, except instead of storing single values like numbers or strings, it associates those values to something else. This is normally a key-value pair. For example, we could create a dictionary that associates each of our friends' names with a number describing how long ago we la...
52432f6633d264b1f53d9c6e8a9bb834e4532d7b
abhi15sep/Python-Course
/introduction/example/lucky.py
502
4.15625
4
#At the top of the file is some starter code that randomly picks a number between 1 and 10, and saves it to a variable called choice. Don't touch those lines! (please). #Your job is to write a simple conditional to check if choice is 7, print out "lucky". Otherwise, print out "unlucky". # NO TOUCHING PLEASE-------...
2eab7e313a1104ca9384d3c73f8e3d3b10ff4491
abhi15sep/Python-Course
/Functions/examples/exercise4.py
600
4.4375
4
#Implement a function yell which accepts a single string argument. It should return(not print) an uppercased version of the string with an exclamation point aded at the end. For example: # yell("go away") # "GO AWAY!" #yell("leave me alone") # "LEAVE ME ALONE!" #You do not need to call the function to pass the ...
b8c247b00db447a205409067aad84ea853ad2040
abhi15sep/Python-Course
/introduction/example/positive_negative_check.py
970
4.46875
4
# In this exercise x and y are two random variables. The code at the top of the file randomly assigns them. #1) If both are positive numbers, print "both positive". #2) If both are negative, print "both negative". #3) Otherwise, tell us which one is positive and which one is negative, e.g. "x is positive and y is ne...
ad9a7d2ecae4bb388a6d782f470ea96d2fae61a7
abhi15sep/Python-Course
/Functions/lambda/exercise/sum_floats.py
387
4.0625
4
#Write a function called "sum_floats."This function should accept a variable number of arguments. The function should return the sum of all the parameters that are floats. If there are no floats the function should return 0 ''' sum_floats(1.5, 2.4, 'awesome', [], 1) # 3.9 sum_floats(1,2,3,4,5) # 0 ''' def sum_floats...
b7ca293a83ee6f3f18657ba6ae42901e366bb70a
sanjaysuresh15/python2nd
/pyb/pybank_sanj.py
834
3.59375
4
import os import csv budget_csv = os.path.join(".", "resources", "budget_data.csv") # Open and read csv total = 0 with open(budget_csv, newline="") as csvfile: csvreader = csv.reader(csvfile, delimiter=",") #define variables month = [] month_list = month money_sum = 0 change = 0 def p...
e8f53fe8692ceebcef6f24d7ca6f6d84c0339f7a
OhOverLord/loft-Python
/Изучение numpy/14.py
627
3.90625
4
""" Считайте 2 числа: n, m. Зафиксируйте значение генератора случайных чисел Numpy с помощью numpy.random.seed(42) Создайте матрицу n*m из случайных чисел (от 0 до 1). Выведите на печать значение среднего для всей матрицы. Sample Input 1: 30 30 Sample Output 1: 0.4923750160905882 Sample Input 2: 12 6 Sample...
df9627b825c32214c312f45d1518e7d70c6485e8
OhOverLord/loft-Python
/Изучение numpy/6.py
678
4.1875
4
""" Считайте 2 числа: n - размер Numpy вектора x - координата элемента вектора, который должен быть равен 1. Остальные элементы вектора должны быть равны 0. Сохраните вектор в переменную Z. Примечание. В этой задаче не нужно ничего выводить на печать. Только создать вектор Z. Sample Input: 10 4 Sample Output: ...
55383abac4ccd9132421457a2e9c86d0fee7ab9f
OhOverLord/loft-Python
/Алгоритмы_ теория и практика. Структуры данных/(3.2.3)Search_sample_in_text.py
1,261
3.921875
4
""" Поиск образца в тексте Sample Input 1: aba abacaba Sample Output 1: 0 4 Sample Input 2: Test testTesttesT Sample Output 2: 4 Sample Input 3: aaaaa baaaaaaa Sample Output 3: 1 2 3 """ def hash(word): """ Функция для хеширования строки :param word: строка :return: хеш строки """ return sum(o...
e7f75007f4dcf4f6fa6db480410dabc7274bd566
OhOverLord/loft-Python
/алгоритмы 1 курс/(2.2.1)small_fibonacci_number.py
648
3.6875
4
""" Выполнил: Филиппов Л. П2-17 Задача: Дано целое число 1≤n≤40, необходимо вычислить n-е число Фибоначчи (напомним, что F0=0, F1=1 и Fn=Fn−1+Fn−2 при n≥2). """ def main(): """ Функция для нахождения n-го числа Фибоначчи :param n: """ fib1 = fib2 = 1 # 2 первых числа Фибоначчи n = int(inp...
3073bd1f1394c84ef2334c4b652089ffe0b28e08
OhOverLord/loft-Python
/Изучение numpy/40.py
673
3.734375
4
""" Считайте 2 числа: seed n С помощью Numpy сгенерируйте n случайных чисел из интервала (0, 1) с фиксированным seed, отсортируйте их по возрастанию и сохраните в переменную Z. Sample Input 1: 42 10 Sample Output 1: [0.05808361 0.15599452 0.15601864 0.37454012 0.59865848 0.60111501 0.70807258 0.73199394 0.8...
35a130451562cfc118d29d5901bc0c581207c5c8
OhOverLord/loft-Python
/Алгоритмы_ теория и практика. Структуры данных/(2.3.2)Parallel_processing.py
797
3.640625
4
""" Параллельная обработка Sample Input: 2 5 1 2 3 4 5 Sample Output: 0 0 1 0 0 1 1 2 0 4 """ from heapq import heapreplace # Функция которая удаляет и возвращает самый маленький элемент из кучи, а также # добавляет новый элемент def main(): """ Функция реализующая параллельную обработку """ n, m = ...
2cfb461c8d8f9f384961850f9d13043e3933d73e
lpawlak1/WDI
/Cwiczenia 1/cw1.py
210
3.609375
4
# Zadanie 1. Proszę napisać program wypisujący elementy ciągu Fibonacciego # mniejsze od miliona. def cw1(): a1 = 1 a2 = 1 while a1 < 10**6: print(a1) a1, a2 = a2, a1+a2
c7a90dc69e72d2260c7b8e1dcaa43c72e174f0d0
lpawlak1/WDI
/Cwiczenia 2/cw20.py
1,517
3.890625
4
# Zadanie 20. Dwie liczby naturalne są różno-cyfrowe jeżeli nie posiadają żadnej wspólnej cyfry. # Proszę napisać program, który wczytuje dwie liczby naturalne i poszukuje najmniejszej podstawy systemu (w zakresie # taka nie istnieje należy wypisać komunikat o jej braku. Na przykład: dla liczb 123 i 522 odpowiedzią ...
32e52deca8b34667a6f7e49bb2e03647cd86da2d
lpawlak1/WDI
/Cwiczenia 2/cw11.py
431
3.640625
4
# Zadanie 11. Napisz program wczytujący liczbę naturalną z klawiatury i odpowiadający na pytanie, czy # jej cyfry stanowią ciąg rosnący. def cw11(): num = int(input(">: ")) a = num % 10 num //= 10 while num != 0: temp = num % 10 num = num // 10 if temp > a: ...
5519187c968157756a35dba6695a090410b5506c
lpawlak1/WDI
/Cwiczenia 7/cw16.py
1,295
3.78125
4
null = None class Node: def __init__(self, value=null, next=null): self.val = value self.next = next def __str__(self): return f"{self.val}-->" def wypisz(first): if first == null: print("List is empty!") while first != null: print(first, end=...
45b26c56cf70b638281a34532750df14527b22af
lpawlak1/WDI
/Cwiczenia 2/cw12.py
515
3.640625
4
# Zadanie 12. Napisz program wczytujący liczbę naturalną z klawiatury i odpowiadający na pytanie, czy # liczba ta zawiera cyfrę równą liczbie swoich cyfr. def cw12(): liczba = int(input("> :")) lenght = 0 num = liczba while num != 0: lenght += 1 num //= 10 num = liczba ...
aab824fcb51e6b5b966a8d9066a831bf89693577
SafiyaJan/Checkers
/CheckersFinal.py
124,894
3.53125
4
## Safiya Jan - 15112 Fall 2016 - Final Project ## #libraries used # from Tkinter import * # import tkinter as tk # import tkMessageBox as tm from tkinter import * from PIL import ImageTk import tkinter.messagebox as tm import re import random import math ''' Functions Used in Two Player Class ''' ''' drawCheckers...
7101eee1179b16a58e0173abcf5dc5c8e1c44184
xin00killo/myPython
/pythonTests/test052 list=[2,3,5,4,9,6],从小到大排序,不许用sort,输出[2,3,4,5,6,9].py
437
3.90625
4
#coding:UTF-8 #__autor__='wyxces' ''' 52、list=[2,3,5,4,9,6],从小到大排序,不许用sort,输出[2,3,4,5,6,9] ''' def mySort(list): for i in range(0,len(list)-1): for j in range(i+1,len(list)): if list[i]>list[j]: temp = list[i] list[i] = list[j] list[j] = temp ...
a93c420af1cf319f2cb23a586c4c0cc952ad6d35
xin00killo/myPython
/pythonTests/test070 去除首尾空格.py
555
3.515625
4
#coding:UTF-8 #__autor__='wyxces' ''' 70、a = "  heh heh  ",去除收尾空格 ''' import re a = "  heh heh  " #正则1 new_a = ''.join(re.findall(r'\s+(\w.*\w)\s+',a)) print(new_a) #正则2 new_a3 = re.sub(r'^(\s+)|(\s+)$','',a) print(new_a3) #方法3 strip new_a2 = a.strip() print(new_a2) #递归调用 def trim(a): if re.match(r'\s',a[0...
e6d3e4e72d08b74e9fe50e61ac128aad90def103
xin00killo/myPython
/basic/str_upper_lower_capitalize_title_swapcase.py
682
3.515625
4
#coding:UTF-8 #__autor__='wyxces' ''' lower() 将字符串转换为小写字符串 upper() 将字符串转换为大写字符串 capitalize() 将字符串首字母变为大写 title() 每个单词的首字母大写 swapcase() 大小写互换 ''' s ="waetuohn;lLL90hgnsa;lier0DCCWybga;ldkeQ3odir" print('原字符串:\n\t',s) s_upper = s.upper() print("转化为大写后为:\n\t", s_upper) s_lower = s.lower() print("转化为大写后为:\n\t", s_lower) ...
d75615d7eb05a023786b2a48e06fd758705fe484
Phenom23/Mini-Experimental-Projects
/Python/Calculator/Calculator 2.3.2 .py
3,797
4.03125
4
#Functions and more ------------------------------------------------------------------------------------------------------------- import time import math def add(x, y): return x + y def subtract(x, y): return x - y def multiply(x, y): return x * y def divide(x, y): return x / fl...
8a2325c79855705a17b6869ed96e6ef74d0b65d9
iramirezc/bedu
/workshops/introduction-to-programming-with-python/examples/tuple.py
298
3.640625
4
# Ejemplo de una Tupla colores = ('verde', 'rojo', 'negro', 'rosa', 'azul') # ¿Cuál es el color 0? print(colores[0]) # ¿Cuál es el color 3? print(colores[3]) # ¿Cuántos colores hay? print('Total colores:', len(colores)) # ¿Se puede cambiar un color? colores[3] = 'blanco' print(colores[3])
5d00ba02dff74ba67af0eac17827f3fcbb445877
iramirezc/bedu
/workshops/introduction-to-programming-with-python/examples/if-statement.py
207
3.890625
4
# ¿Cuál es el mayor de 2 números? numero1 = 5 numero2 = 6 if numero1 > numero2: print('numero1 es mayor') elif numero2 > numero1: print('numero2 es mayor') else: print('Los 2 numeros son iguales')
3ec23099ad572174b7e243eb7e3cdb152df3bac0
akremsa/blackjack
/main.py
3,395
3.859375
4
from logic import card from logic import deck from logic import bank from logic import hand while True: try: print("\nWelcome!") total = int(input("Please provide you bank account total: ")) if total <= 0: raise ValueError("Total amount ...
9d18ab098eb2d59fbba6595cbc157dd3b629d87a
yogabull/LPTHW
/ex14.py
789
4.15625
4
# Exercise 14: Prompting and Passing from sys import argv script, user_name, last_name, Day = argv #prompt is a string. Changing the variable here, changes every instance when it is called. prompt = 'ENTER: ' #the 'f' inside the parenthesis is a function or method to place the argv arguements into the sentence. prin...
e250187c11f7c059a5964f5579481d4c3805ee44
yogabull/LPTHW
/speedTest.py
757
3.875
4
#Facebook user group coding #tuple / list speed compared from time import time start = time() #list version lst = [n for n in range (1000000)] # 1e6 element list for _ in range(100): 999999 in lst #100 look-ups list_time = (time() - start) print(time() -start, "secs -list look-up") print (list_time) start = time() ...
65d2c52a72f7da92158c5712f5face1760a2a61a
yogabull/LPTHW
/ex12.py
369
3.9375
4
print('Exercise 12: Prompting People') age = input('How old are you? ') height = input('How tall are you? ') weight = input('How much do you weigh? ') print(f'So, you\'re {age} old, {height} tall and {weight} heavy.') #look up pydoc # pydoc is a documentation tool to display help about other Python modules. # It is ...
1b74278c00c6a0e00383169cb4fe480c5b06ba91
chlazaris/BMI_final
/hic_to_matrix/read_file.py
831
4.03125
4
#!/bin/python # Import what is necessary import sys import re fname = sys.argv[1] # Open the file and read it ################ FUNCTIONS ##################### ''' This is a function that reads a file line-by-line, strips the new-line character after each line and returns a list where each element is a line. ''' def...
a0d91002e32e15232d37a60e6d131a43652eae04
bietml/ml11
/1. Find-s/1.py
799
3.53125
4
import csv n = 6 # number of attributes a = [ ] print("\n The Given Training Data Set \n") with open('tennis.csv', 'r') as f: reader = csv.reader(f) for row in reader: a.append(row) print(row) print("\n The initial value of hypothesis: ") hypothesis = ['0'] * n print(hypothesis) ...
abee8c92efad3a132ccb694a67c384a952341a80
ScottMorse/DC-Sep-18
/even_odd.py
421
3.984375
4
def parity_check(num): #error catcher if not isinstance(num,int): raise ValueError("Invalid argument. Use integer only.") #checks parity if num % 2 == 0: parity = "even" else: parity = "odd" return parity if __name__ == "__main__": user_input = int(input("En...
8f385e96133d89c94146e91710fbf10db343d57f
lukepreston9/integration
/battleship.py
4,344
4.25
4
# Luke Preston """This program is designed to be a similar replication of the well known game "Battleship". The program will correctly be able to take your guess of where you think the opponents enemy ship is and will give you a "HIT!" or "MISS" response. If you are finally able to sink your opponents battleship, the g...
f8d9c5bae3a530402866985bf95aac7b77568560
PatrickKwong/CS325_Project2_group31
/change_greedy.py
517
3.78125
4
#!/usr/bin/python #Cas Donoghue #Patrick Kwong #Nicholas Vrontakis #Project 2 CS325 # cents = change amount in cents, coins = increasing array of coin values def get_change(coins, cents): change = [] num_coins = 0 for num in range(len(coins)): change.append(0) while (cents > 0): for num...
716a211b8fe21808856d9342769ab4e7bd42e818
TheRakeshPurohit/AlgorithmsONLY
/Tree_Algorithms/LCA_in_BST.py
609
3.765625
4
# -*- coding: utf-8 -*- """ Created on Sat Aug 15 11:12:58 2020 @author: Soham Shah """ # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def lowestCommonAncestor(self, root: 'TreeNode'...
72cac082687c4687c0748d219607281e7b48c683
TheRakeshPurohit/AlgorithmsONLY
/Array/Python/rearrange_array_in_min_max.py
294
3.75
4
def rearrange(arr): n = len(arr) for i in range(n): if i%2 == 0: val = arr.pop(0) arr.append(val) else: val = arr.pop(n-2) arr.append(val) n-=1 print(arr) return arr
f091bd0675a67422a87554a74ac8f34831cf0578
TheRakeshPurohit/AlgorithmsONLY
/Tree_Algorithms/Print-Tree.py
2,097
3.84375
4
# -*- coding: utf-8 -*- """ Created on Wed Aug 19 00:29:22 2020 @author: Soham Shah """ # 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 printTree(self...
ca94bb24c68a4c1c3eebc6b2a9a0d85b224cbfd4
TheRakeshPurohit/AlgorithmsONLY
/Tree_Algorithms/Path_in_ZigZag_Labelled_Binary_Tree.py
618
3.609375
4
# -*- coding: utf-8 -*- """ Created on Tue Sep 22 13:21:13 2020 @author: Soham Shah """ class Solution: def pathInZigZagTree(self, label: int) -> List[int]: ans = [] while label >= 1: ans.insert(0, label) label= label//2 print(ans) for i in range(1,len(an...
c072a8352f79e39437f90284e3bd14f8abe8e1c2
TheRakeshPurohit/AlgorithmsONLY
/Tree_Algorithms/Path-Sum-3.py
3,956
3.609375
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def pathSum(self, root: TreeNode, sum: int) -> int: if not root: return 0 rst = ...
e5133d32acaae42f2faeb716c3f145dcc5db4cd1
TheRakeshPurohit/AlgorithmsONLY
/Searching_Algorithms/Python/minimum_difference_element_in_an_array.py
409
3.609375
4
def binarySearch(arr,n,k): l = 0 r = n-1 while l<=r: mid = (l+r)//2 if arr[mid] == k: return [arr[mid]] if k < arr[mid]: r = mid-1 if k > arr[mid]: l = mid+1 return [l,r] def minimumDifference(arr,n,k): res = binarySearch(arr,n,k) ...
2fed646c3480a468cb0ad80d84c6e434835c8424
TheRakeshPurohit/AlgorithmsONLY
/Sorting_Algorithms/Python/intersection_of_two_sorted_arrays.py
781
3.859375
4
def printIntersection(a, b, n, m): ''' :param a: given sorted array a :param n: size of sorted array a :param b: given sorted array b :param m: size of sorted array b :return: array of intersection of two array or -1 ''' # code here lis = [] N_pointer = 0 M_pointer = 0 wh...
3e3f9b0e367c340f56bf7664ba233717f0bacaaf
TheRakeshPurohit/AlgorithmsONLY
/String/remainder_with_7.py
383
3.828125
4
#your task is to complete this function #Function should return the required answer #You are not allowed to convert string to integer def remainderWith7(string): series = [1,3,2,-1,-3,-2] ans = 0 ind = 0 for i in string[::-1]: ans+=(series[ind]*int(i)) ans%=7 ind = (ind + 1) % 6 ...
a5b42a7ff1ab81dbce34d6d5a9c49917da6436ad
TheRakeshPurohit/AlgorithmsONLY
/Recursion/Python/letter_case_permutation.py
620
3.53125
4
# -*- coding: utf-8 -*- """ Created on Tue Oct 6 00:00:26 2020 @author: Soham Shah """ # Letter Case Permutation string = "a1B2" ans = [] def solve(input, output): if not input: ans.append(output) return if input[0].isalpha(): output1 = output[:] output2 = output[:] ...
d5d323bdb0ae76e3d5dfe758717c34b24333611f
TheRakeshPurohit/AlgorithmsONLY
/Array/Python/first_repeated.py
243
3.640625
4
def firstRepeated(arr, n): #arr : given array #n : size of the array dic = {} for i in range(len(arr)): if arr[i] not in dic: dic[arr[i]] = i+1 else: return dic[arr[i]] return -1
f4071ec7523b9e53c0574023f41e0eda9ab50d07
CaptainTec/LeetCode_Python3
/medium_56_tuple_sorted.py
927
3.515625
4
# arr = [[1, 3], [20, 6], [8, 10], [15, 18]] # # # print(len([_ for _ in sorted(arr, key=lambda x: x[0])])) # print([_ for _ in map(str, arr)]) class LargerNumKey(str): def __lt__(x, y): return x + y > y + x class Solution: def largestNumber(self, nums): print(sorted(map(str, nums))) ...
7f1a2400ac9cb0b6aa6baa671ee4acdf8eaae48d
CaptainTec/LeetCode_Python3
/heap_优先队列_introduction.py
6,183
4.125
4
import heapq """ 默认是小顶堆 一种著名的数据结构是堆(heap),它是一种优先队列。优先队列让你能够以任意顺序添加对象, 并随时(可能是在两次添加对象之间)找出(并删除)最小的元素。相比于列表方法min,这样做的效率要高得多。 实际上,Python没有独立的堆类型,而只有一个包含一些堆操作函数的模块。 这个模块名为heapq(其中的q表示队列),它包含6个函数,其中前4个与堆操作直接相关。必须使用列表来表示堆对象本身。        模块heapq中一些重要的函数        函 数                                            描 述 he...
f3b092247e2a8bb4e440474383490f11d97e0519
awang48/CS143B-Proj2
/pt.py
1,864
3.796875
4
class Pt: """ A page table that simulates a page table. Attributes: _pm (:obj:`list` of int): List of integers, which represents physical memory. _disk (:obj:`list` of :obj:`list` of int): List of list of integers, which represents disk blocks. _availableFrames (:obj:`list` of int): Lis...
adbd3a9d899558e5e1b37e78275d9e0d8b21bad0
CamilaMeira/Little-Games
/jokenpo/jokenpo.py
1,280
3.953125
4
import random import time print('VAMOS JOGAR UM JOGO...') time.sleep(1) itens= ('Pedra', 'Papel', 'Tesoura') computador= random.randint (0, 2) print('''Escolha sua jogada: [0] Pedra [1] Papel [2] Tesoura''') jogador= int (input ('Qual a sua escolha? ')) print('UM') time.sleep(1) print('DOIS') t...
7c750c3b69ccbf0c3daf64454c861ded03a50da4
shangpf1/python_homework
/2019-6-9.py
1,508
3.796875
4
import unittest # from UnitTest_1.function import * # from..import ... :要指定文件的路径 # 定义一个加法的函数 def add(x,y): return x+y # 定义一个减法函数 def minus(x,y): return x-y # 定义一个乘法函数 def multi(x,y): return x*y # 定义一个除法函数 def divide(x,y): return x/y class TestFunc(unittest.TestCase): # unittest.TestCase # 如果想在所有ca...
b7f1467fbb432ee2765720bc0b13744e7783f367
shangpf1/python_homework
/2019-6-13.py
919
4.1875
4
""" 我的练习作业03- python 高级排序-字符长度相同进行排序 """ # 正序(关于正序排序,首先会按字符的长度排序,如果一样的话,会按字符正序的首字母的ASCII码大小排序) strs = ['study','happy','thing'] print('s==>',ord('s'),'h===>',ord('h'),'t===>',ord('t')) strs.sort() print("正序排序为:",strs) """ 倒序(关于倒序排序,和上面的正序刚好相反,从字符的末尾的字符大小进行排序,如果末尾字符相同, 会按倒数第二位的字符大小排序,如此类推) """ print('g====',or...
4f519b831183102235c19d640b73a48670d80830
arianvp/WISB256
/Opdracht2/Sieve_of_E.py
636
3.671875
4
#! /bin/env python3 import sys import time import math def sieve(n): a = [False] * 2 + [True]* (n-1) for i in range(math.ceil(n)): if a[i]: for j in range(i*i,n+1,i): a[j] = False for i in range(n+1): if a[i]: yield i n = int(sys.argv[1]) out = sys.argv[2] t1 ...
a50465cc96c4298098e6a11c5023305bb945a7ea
Greek-and-Roman-God/Athena
/codingtest/week05/word_study.py
341
3.5
4
#단어 공부 word=input() word=word.upper() alpha_dict={} for c in word: if c in alpha_dict: alpha_dict[c]=alpha_dict[c]+1 else: alpha_dict[c]=1 value_list=list(alpha_dict.values()) out="?" if value_list.count(max(value_list))==1: for k,v in alpha_dict.items(): if v==max(value_list): out=k bre...
cb54ea0ba8c3bd3f0a83fec201df7d13d30a7f8f
Greek-and-Roman-God/Athena
/codingtest/week05/sangsu.py
221
3.578125
4
#상근이 동생 상수 def reverse_num(num): reverse=list(str(num)) reverse.reverse() reverse=("".join(reverse)) return reverse a, b=map(int, input().split()) a=reverse_num(a) b=reverse_num(b) print(max(a,b))
dc8fc1e8e7adb4e6862eb7ee9869ebe4b5f4c9ac
Greek-and-Roman-God/Athena
/codingtest/week01/level2/no3.py
733
3.515625
4
#윤년 # 연도가 주어졌을 때, 윤년이면 1, 아니면 0을 출력하는 프로그램을 작성하시오. # 윤년은 연도가 4의 배수이면서, 100의 배수가 아닐 때 또는 400의 배수일 때이다. # 예를 들어, 2012년은 4의 배수이면서 100의 배수가 아니라서 윤년이다. 1900년은 100의 배수이고 400의 배수는 아니기 때문에 윤년이 아니다. 하지만, 2000년은 400의 배수이기 때문에 윤년이다. #첫째 줄에 연도가 주어진다. 연도는 1보다 크거나 같고, 4000보다 작거나 같은 자연수이다. year=int(input()) if year%4==0: if year%...
c5c76a72fd6b68ef61ea764887167bcf6b21f9a2
azamatkb/Function
/10may_2(3).py
279
4.03125
4
#10may_2/3 Напишите функцию, которая спрашивает у пользователя число и выводит... number = int(input('Введите число: ')) def my_func(number): b = str(number) * number return b print(my_func(number))
f4213133305c5fd5d3447e211e47ccc5db11e041
azamatkb/Function
/7may_1.py
659
3.9375
4
#7may_1 Создайте функцию которая берет лист делит его пополам и разворачивает... def revers(): list_1 = ['name', 'age', '1', '19'] a = list(reversed(list_1[len(list_1)//2:])) b = list(reversed(list_1[:len(list_1)//2])) print(b + a) revers() #7may_1 - 2 версия Создайте функцию которая берет лист де...
c1eb8a4a4c4cdbb31ddd4d87a04873f75356ac9b
lizz-beth/pylearn
/rect.py
822
3.875
4
class Rectangle: def __init__(self, width, height): self.width = width self.height = height def area(self): return self.width * self.height def increase_height(self, amount): self.height += amount def perimeter(self): return (self.width + self.height) * 2 ...
756d6245de418cb6be6115a81b49af96a045e5be
Anmol1696/AgmOptimization
/src/map_reading.py
3,271
3.765625
4
import networkx as nx def read_map_file(mapfile_name): """ Return all the lines from the map file, which will later feed into the graph to fill it Some pre-processing is also done before returning the file """ with open(mapfile_name) as file_open: all_lines = file_open.readlines() ...
199d7d11696804d6f62e4398c298fb302307b4cd
ericfp87/day-18-Drawing_different_shapes
/main.py
917
3.65625
4
import turtle as t screen = t.Screen() tim = t.Turtle() tim.shape("arrow") def decagono(): for i in range(10): tim.right(36) tim.forward(50) def eneagono(): for i in range(9): tim.right(40) tim.forward(50) decagono() def octogono(): for i in range(8): tim.righ...
248352a8b862e9a50c12cd3ede66b2ee3c55c415
zhangxin47/Pythoncode3
/Week1類別與物件/autosystem.py
5,312
3.6875
4
import csv import os class Time: def __init__(self, hh , mm ,ss): self.hh = hh self.mm = mm self.ss = ss doubledigit = True @staticmethod #說明接下來為 staticmethod,傳入值不被綁定__init__ 因此可隨心所欲 def setdoubledigit(dd): Date.doubledigit = dd @classmethod #第一個傳入值被綁定,第二個值可當未調用餐數,...
b29329e4fd8ca7db679bc2732363627786389917
init-fun/amazon-coding-assessment-prep
/BFS/3. reverseTraverse.py
1,636
3.90625
4
from collections import deque class Node: def __init__(self, data): self.val = data self.left = None self.right = None class Tree: def __init__(self, data=None): self.root = Node(data) # write you function here def reverseTravese(self): res = deque() ...
24d29f87ae137b87120c4fa69d1b9a60443d7fe1
init-fun/amazon-coding-assessment-prep
/BFS/6. minDepth.py
968
3.890625
4
from collections import deque class Node: def __init__(self, data): self.val = data self.left = None self.right = None class Tree: def __init__(self, data=None): self.root = Node(data) # write you function here def minDepth(self): if not self.root: ...
bcd723f31839dec81e993ddc2beb057b170299ae
jamesoneill54/programming_2
/week_10/reverse_102.py
244
3.796875
4
def swap_first_last(a, first, last): if first >= last: return a[first], a[last] = a[last], a[first] first += 1 last -= 1 swap_first_last(a, first, last) def reverse_list(a): swap_first_last(a, 0, len(a) - 1) return a
54364ac6d5af1daa6c40fd48ce15e9159b8cae4e
jamesoneill54/programming_2
/week_8/time_82.py
1,118
3.96875
4
import sys class Time(object): def __init__(self, hour=0, minute=0, second=0): self.hour = hour self.minute = minute self.second = second def time_to_seconds(self): return self.hour * 60 * 60 + self.minute * 60 + self.second def seconds_to_time(s): minute, second = divmod(s, 6...
11b6bbe0ee3a22c51f118f0436f56a2810b3e941
jamesoneill54/programming_2
/week_5/q1_51.py
381
3.90625
4
import sys def swap_adjacent(s): odds = [l for l in s[::2]] evens = [l for l in s[1::2]] swapped = '' i = 0 while i < len(odds) or i < len(evens): if i < len(evens): swapped += evens[i] if i < len(odds): swapped += odds[i] i += 1 print (swapped) def main(): swa...
6a0b0ba333be0dfeb41d9b86257f21887db82596
jamesoneill54/programming_2
/week_10/count_102.py
87
3.609375
4
def count_letters(s): if s == '': return 0 return count_letters(s[:-1]) + 1
9c26bc9ecbdfa2d7119028d2205c3cc27c03a10d
jamesoneill54/programming_2
/week_2/unique_21.py
348
3.96875
4
import sys import string def unique_token_count(text): text = text.strip().split() a = [] for word in text: word = word.lower().strip(string.punctuation) if word not in a and word != '': a.append(word) return len(a) def main(): print (unique_token_count(sys.stdin.read())) if __nam...
70755bc4fbc8038007005d27ae23a51258aa8d9e
ojibreen/python-data-structure-and-alogorithms
/tests/test_binary_search.py
408
3.546875
4
from search import BinarySearch class TestBinarySearch: def test_binary_search(self): binarySearch = BinarySearch() l = [3,4,5,6,13,101,300,67,48] l.sort() assert binarySearch.search(l, 300, 0, len(l) - 1) == True assert binarySearch.search(l, 1000, 0, len(l) - 1) == False assert binarySearch.search(l, ...
583ba9e2ceb980e0d8598a7ca527e6e91f03fbaa
epogrebnyak/weo-reader
/streamlit_app.py
3,204
3.75
4
import numpy as np import pandas as pd import streamlit as st import weo st.set_page_config( page_title="WEO Reader", page_icon=None, layout="centered", initial_sidebar_state="collapsed", ) st.title("Let's look at WEO dataset") """Picture here""" st.header("Reference") st.header("Load the data") ...
9b42a6f0b8fe9d7ebca325e29b0f1695c24df199
mxcat1/Curso_python3
/Curso Python37 Avanzado/tuplas/tuplas.py
643
4.28125
4
tupla1=("cinco",4,"hola",34) print(tupla1) # convertir una tupla en lista lista1=list(tupla1) print(lista1) #convertir una lista en tupla tupla2=tuple(lista1) print(tupla2) #metodo in print("cinco" in tupla2) # metodo para saber la cantidad de elementos print(tupla2.count(4)) # metodo len para saber la logitud ...
f233618e6a9c0f51f209d0bcffb9a2f741305cd1
PrimeCodingSolutions/otree-core
/otree/oTree/daytrader/make_faces.py
1,270
3.5
4
import cv2 """ https://stackoverflow.com/questions/40895785/using-opencv-to-overlay-transparent-image-onto-another-image """ path = '../_static/daytrader/' color_imgs = ['C0', 'C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9'] faces = ['glad', 'sad'] for c in color_imgs: for face in faces: background ...
46d51164a8c9c6fa05ea61aa65e74107c5f807f9
udayanbb/Coursework
/Neural Nets and SVMs.py
8,029
3.828125
4
# 6.034 Lab 6 2015: Neural Nets & SVMs from nn_problems import * from svm_problems import * from math import e, sqrt #### NEURAL NETS ############################################################### # Wiring a neural net nn_half = [1] nn_angle = [2, 1] nn_cross = [2, 2, 1] nn_stripe = [3, 1] nn_hexagon = [6, 1] ...
324ec6fdee667f74849d3b87dbcc6690b24a2761
funilrys/Python-scripts-collection
/FileLocator/code.py
370
3.640625
4
import os from os.path import join location = str(input("Directory Location : ")) extension = str(input("Extension of files to search for : ")) for (dirname, dirs, files) in os.walk(location): for filename in files: if filename.endswith('.'+extension) : thefile = os.path.join(dirname,filename) ...
2bf7b37044cc69bf729d66cd220517fa3a220bad
funilrys/Python-scripts-collection
/Password_Generator/generate.py
349
3.75
4
import random import string def randompassword(number): chars = random.sample(string.ascii_lowercase + string.digits, number) passw = ''.join(map(str, chars)) return passw amount = int(input("How many passwords:\n")) number = int(input("Lenght of password?\n")) for i in range(amount): print(f" Password: {i} -...
79980e250f7e2e9196fda83a073e6abc25280cb9
damapl/prime-calc
/old_algorithms/recursive_generator_sieve.py
1,396
3.5625
4
# Hits the recursion limit. def x_primes(x, prime_list): for i in xrange(x): yield prime_list.next() def initial_range(lower_bound): while True: yield lower_bound lower_bound = lower_bound + 1 def primes_in_range(lower_bound, upper_bound, prime_list): while True: curr_prim...
8c126279c22a39dd88fa5947d52bf572301271a6
JacobGenander/datx02-16-27
/tensorflow_experiments/jackeTestar/rnn_code_explanation.py
8,277
3.734375
4
''' THIS IS NOT RUNNABLE CODE! I've tried to explain what happens in what seems to be the most essential steps in creating a multi-layerd LSTM cell. The code pieces come from the ptb_word_lm.py example given by TensorFlow. Some explanations may be totally wrong. RNNCell is the most abstract representation of an RNN ...