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
210f9f40e874132f1f0799802af0d281c48f40cf
binorelawan/beginner-project
/calculate_hour.py
405
4.03125
4
hour = int(input("Starting time (hours): ")) mins = int(input("Starting time (minutes): ")) dura = int(input("Event duration (minutes): ")) # Write your code here. total_mins = dura + mins if total_mins >= 60: mins = total_mins % 60 hour += total_mins // 60 else: mins = total_mins hour print(hour, mi...
221d807669cd442b42b46da9b7805af44a9736d0
JannisK89/AdventOfCode2020
/Day1/part1.py
397
3.5625
4
# https://adventofcode.com/2020/day/1 def findAndMultiply(inputFile): with open(inputFile,'r') as file: inputList = file.readlines() for firstNumber in inputList: for secondNumber in inputList: if int(firstNumber) + int(secondNumber) == 2020: retur...
82edd4367b7976bce4e63b0d8b6e98f789c943d5
BasantaChaulagain/Leetcode
/Linked List/addTwoNumbers.py
594
3.671875
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def addTwoNumbers(self, l1, l2): carry=0 res=l3=ListNode(-1) while(l1 or l2 or carry): fv=l1.val if l1 else 0 ...
6a27a805800a40b750146c8c0f7a0f4c9237882a
BasantaChaulagain/Leetcode
/Linked List/getIntersectionNode.py
802
3.671875
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def getIntersectionNode(self, headA, headB): if(headA==None or headB==None): return None valA=[] while(headA!=None): ...
dfd05d4114a44b5f3a8328f34bab29dab7f07ed4
kabitakumari20/list_logical
/position_of_list.py
181
3.828125
4
list1=[2, 3, 8, 4, 7, 9, 8, 2, 6, 5, 1, 6, 1, 2, 3, 4, 6, 9, 1, 2] i=0 num=int(input("enter the psition=")) while i<len(list1): if num==i: print(list1[i]) i=i+1
1d4988cf942defaa202d6b203462c97be5b58250
kabitakumari20/list_logical
/leep_year.py
171
4.0625
4
def is_leap(): if year%4==0 and year%100!=0 or year%400==0: return True else: return False year = int(input("enter the num=")) print(is_leap())
20cae087775c407f93307037e0a8982ab30e78c9
kabitakumari20/list_logical
/from_user_dublicate_count.py
382
3.859375
4
num=int(input("enter the num=")) b=1 empty=[] while b<=num: num1=int(input("enter the num=")) empty.append(num1) b=b+1 i=0 count=0 empty1=[] while i<len(empty): j=i+1 while j<len(empty): if empty[i]==empty[j]: count=count+1 empty1.append(empty[i]) # count=...
ca438b02c8cde32403d362805c1ca690df548d53
Vinodhini-2497/Assignment-7
/arr5.py
574
4.09375
4
#Program to check if given array is Monotonic import array import logging as l l.basicConfig(filename='arr5.log', level=l.INFO, format='%(asctime)s-%(message)s') def monoarr(a): try: for i in range(len(a)-1): if a[i]<=a[i+1]: return ("The given array is monotonic increasing",a) ...
549e864c0397a5606d8eed081c09974f1d9b85f1
jtraver/dev
/python3/yml/sudoku2.py
26,110
3.515625
4
#!/usr/bin/env python3 #!/usr/bin/python import yaml import sys def verify_cols(grid): # print "verify_cols" for icol in range(9): for c1 in range(9): ccell = cols[icol][c1] gx, gy, sx, sy = get_grid_coordinates_from_col(icol, c1) cell = grid[gx][gy][sx][sy] ...
5d31511a91d462a363bfb8cc446d3ad46896ae31
jtraver/dev
/python/datetime/warning.py
8,092
3.765625
4
#!/usr/bin/python # -*- coding: iso-8859-15 -*- import time import datetime d = datetime.datetime.now() print "d = %s" % str(d) print "d = %s" % str(type(d)) print "d = %s" % str(dir(d)) print d print d.strftime("%y%m%d%H%M%S%f") print "date str %s" % str(d) print "date strftime %s" % d.strftime("%y%m%d%H%M%S%f") # ...
122331398cb2a7a23cd4d247d29714ce4e863025
jtraver/dev
/python3/if/if1.py
397
4.21875
4
#!/usr/bin/env python3 #!/usr/bin/python str1 = 'test1' if str1 == 'test1' or str1 == 'test2': print('1 or 2') elif str1 == 'test3' or str1 == 'test4': print("3 or 4") else: print("else") str1 = '' if str1: print(("'%s' is True" % str1)) else: print(("'%s' is False" % str1)) str1 = ' ' if str1: ...
b016974af9f86d1227ab52b0fedd0b2efc84fbe6
jtraver/dev
/python/prime/gap1.py
634
3.515625
4
#!/usr/bin/python import sys limit = 1000000 primes = [ 2 ] def is_prime(candi): for i1 in range(0, len(primes)): p1 = primes[i1] if p1 * p1 > candi: break if candi % p1 == 0: return False return True lastprime = 3 maxgap = 0 for c1 in range(3, limit, 2): ...
15211a189f322676f6862bc54f92cdc396909ba7
manuel103/Distributed-Objects
/Serialization & Deserialization/database/database.py
1,411
4.0625
4
import sqlite3 import json import collections from json2xml import json2xml from json2xml.utils import readfromjson conn = sqlite3.connect('database/students.db') cursor = conn.cursor() # allows sql commands execution # Create students table cursor.execute("""CREATE TABLE students ( name text, std_class tex...
82f292e5c7d52587c846a4dfd473c40e01ad0dc3
shyraffy/my-programs
/Python/zip_folders.py
1,224
3.703125
4
# Created by Shyraffy # This script zips all the folders in the source directory and puts # the zip file in the destiny directory. import shutil import os, sys def zip_folders(src, dest): # Makes a list with all the folders in the source directory folders = [folder for folder in os.listdir(src) if o...
42935b9d0e234b656f619a21435c63bf4d308d98
mike4741/python
/add_number.py
49
3.59375
4
num1= 12 num2 =3 num3 = num1 +num2 print (num3)
1d958a6ff7298e518f60c2e34edd9547b80d41bd
ssanche70/guayabita_renew
/probador_vamos.py
728
3.53125
4
from vamos import * from random import randrange jugador1 = Jugador('Juan', 100) jugador2 = Jugador('Andres', 200) def lance(p,s): if s != 0: print('Primero lance', p) print('Segundo lanzamiento', s) if s > p: print('Retira lo que aposto') return (1) else...
a5d35db6ab53b794495a9d951a7dddb07fea8ac7
jake-kim1/BuddySquared
/person.py
2,053
3.671875
4
class Person: def __init__(self, name, year, major, concentrations, classes, interests, description, priority): self.name = name #String self.year = year #Int self.major = major # String self.concentrations = concentrations # String self.classes = classes #[String] se...
02a44b36014a7acea1763cfb18e4582f9fa0b9c3
lorlor/Python-on-9403
/bonecard_1008.py
639
4.03125
4
#! /usr/bin/env python ### Note - ### Essentially speaking, the total of methods how to paving the ### sidewalk is a Fibonacci number sequence. Because we can get a ### recurrsion equation f(n) = f(n-1) + f(n-2) def Fib(n): if n == 1: return 1 elif n == 2: return 1 else: t1, t2 = 1, 1 tmp = 0 for i i...
167302a920668d2308caad225411a4e4fb9c86ec
Shaunwei/hysteria_mode
/leetcode/LinkedList/Convert Sorted List to Binary Search Tree.py
387
3.921875
4
''' Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. ''' from utils import * class TreeNode: def __init__(self, x): self.val = x self.left = self.right = None def sorted_list_to_bst(head): pass if __name__ == '__main__': he...
14f571a84dddc2a82d1597c09e79bf80fb4e5334
Shaunwei/hysteria_mode
/leetcode/LinkedList/Remove Duplicates from Sorted List.py
594
4
4
''' Given a sorted linked list, delete all duplicates such that each element appear only once. For example, Given 1->1->2, return 1->2. Given 1->1->2->3->3, return 1->2->3. ''' from utils import build_ll from utils import print_ll def delete_duplicates(head): if not head or not head.next: return head ...
877d5abd6b46fb7e42e5a14e3003697d40a938df
Shaunwei/hysteria_mode
/leetcode/array/1_18.py
798
3.65625
4
''' Problem: Climbing Stairs algorithm: f(n) = f(n-1) + f(n-2) Dynamic processing tags: ''' class Solution: @classmethod # Time: O(n) # Space: O(n) def solve(self, problems): # Solution here n = problems f1 = 1 f2 = 2 n -= 2 while n > 0: ...
869f8820c6c6f310a2a6a93a2988de7fae9a10cf
Shaunwei/hysteria_mode
/leetcode/array/1_1.py
1,138
3.78125
4
''' Remove Duplicates From Sorted Array algorithm: keep update pointer if cur val == pointer: continue else: update and advance pointer return [0, pointer + 1] tags: two pointers, +1 problem ''' class Solution: @classmethod def solve(self, problems): ...
847927d84d5607ca8cccc8ffd50a186a4cf64953
Shaunwei/hysteria_mode
/leetcode/LinkedList/Add Two Numbers.py
902
3.890625
4
''' You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 ''' from utils import build_ll from utils import ...
a0fa4727e2731b7374341473531b3ed1f5f8e4d0
Shaunwei/hysteria_mode
/leetcode/LinkedList/Reverse Linked List II.py
768
4.34375
4
''' Reverse a linked list from position m to n. Do it in-place and in one-pass. For example: Given 1->2->3->4->5->NULL, m = 2 and n = 4, return 1->4->3->2->5->NULL. Note: Given m, n satisfy the following condition: 1 ≤ m ≤ n ≤ length of list. ''' from utils import * def reverse_btw(head, m, n): prev = dummy = N...
bdfc825da54ba3c0a1b97e53fe777ad546236492
ingydotnet/tiddlyweb
/tiddlyweb/filters/select.py
4,013
3.71875
4
""" Filter routines for selecting some tiddlers from a collection of tiddlers, usually by an attribute of the tiddlers. The syntax is: select=attribute:value select=attribute:!value select=attribute:>value select=attribute:<value ATTRIBUTE_SELECTOR is checked for a function which returns true or fals...
0ebb2af5a476036cd25885b27a8d3c313ccd7200
kfg021/Wikipedia-Pathfinding
/wikipath.py
4,350
3.609375
4
# HOW TO USE: # # Install dependencies: # pip3 install requests # pip3 install beautifulsoup4 # # To run, use the following terminal command: # python3 wikipath.py name_of_start_page name_of_end_page maximum_distance # # maximum_distance represents how many 'layers' to search outward from...
4d4c2457203d5aec05fbd5f5cbb86376c0860cb8
robertoweller/acha_formato
/main.py
624
3.671875
4
import json # procura = input("Digite: ") local = "Programming_Languages_Extensions.json" arq_jso = open(local, "r") # Carregar arquivos json arq_jso = json.load(arq_jso) print("Digite o final do formato junto com o ponto, exemplo '.p'") print("Type the ending, the format with just the dot, example '.p'\n") whil...
9d4ab5d534c25e85943d2bd77f0bbc3638b0754a
Programming-Metholodogy-II-Fa18/midterm-a-gabriel-shen1
/problem2.py
389
3.6875
4
# -*- coding: utf-8 -*- """ Created on Fri Nov 2 17:11:57 2018 @author: gs716 """ class problem2: def __init__(self): self.alist =[] def add(self,a): self.alist.insert(0,a) def remove(self): print(self.alist.pop()) def getValue(self,i): if i < len(self.alist): ...
ba35d814e24e21dc83c304a35933b79f35f77ff9
howardc72150/programming_assessment
/04_ask_area_perimeter.py
1,011
4.3125
4
# Component 3 # Asks the user if they want the program to calculate # the area or perimeter of the shape. # Initialize variables accepted_inputs = ['perimeter', 'area'] # Check if user input is a valid method. def check_input(question): error = "Please enter either area or perimeter." valid = False whil...
b10316bd9fe621938d431bb8d491a2934c16f5e4
glamas/store
/python/projecteuler.net/p17.py
2,335
3.703125
4
#!/usr/bin/python # -*- coding: UTF-8 -*- if __name__ == "__main__": """ If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total. If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters w...
3796eb70e4cd0762b943ae60535f4eee8e345a24
glamas/store
/python/projecteuler.net/p10.py
361
3.8125
4
#!/usr/bin/python #-*- coding: UTF-8 -*- from common_func import * if __name__ == "__main__": '''The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million. ''' result = 2 m = 3 while m < 2000000: if is_prime(m): result...
3a19e87e1a5c786eb3d983a1d8b087c91656bece
janealdash/T2.7
/task2.7.py
99
3.9375
4
a = int(input('Your number ')) if a > 0: print(1) elif a < 0: print(-1) else: print(0)
879401d4f237afe3bcda0af822b562cbc289e26b
rishabhborn2win/C_CPP_DS-ALGO
/C:C++ Programs/main.py
184
4.21875
4
num = int(input("Enter a number: ")) while(num<100): print("Please enter a Number which is more then three digits") num = int(input("Enter a number: ")) else: print(num%10)
4f4dad2b5d2e9f8429f6c1ef10eea02f69c990e8
amandazerquera/uno
/standard.cards.py
205
3.5625
4
class Cards: cards = ["green", "yellow", "blue", "red"] def __init__(self, color, number): self.color = color self.number = number def card(self) return self.color + self.number
8bbcda0b8746baa03ea6d967bae2be5b0853fb12
JessicaDeMota/CSCI-135
/5 whole integers.py
593
4.21875
4
#Jessica De Mota Munoz #jessica.demotamunoz86@myhunter.cuny.edu #October,3rd,2019 #import a turtle to be able to draw and do a graphic #get user input #ask user for 5 whole integers #for each number turn the turtle left and the turtle move toward 100 import turtle jd = turtle.Turtle() #we have to create a for loop t...
69f18ee65958e1b3c1be22d1059512d811ab4fa2
Greensly/InfoGeneral
/Python Exercise/Exercises N°1/Palindromo.py
419
3.796875
4
def palindromo(Word): large = len(Word) wordInv = "" for i in range(large): wordInv += Word[large-1-i] for j in range(large): if wordInv[j] == Word[j]: n = j+1 if n == large: print("La palabra es Palindrome") else: print("La palabra no es Palindrome") ...
fc68944e3baffa747b9f88fd365bc37b5397b19c
Greensly/InfoGeneral
/Python Exercise/Exercises N°1/InversionCadena.py
290
3.703125
4
InputChain = str(input("Ingrese una palabra o frase")) OutputChain = "" sizeChain = len(InputChain) print(sizeChain) for i in range(sizeChain): OutputChain += InputChain[sizeChain-1-i] print("La palabra o frase original es: ",InputChain) print(" y al invertirla que en:",OutputChain)
9e260e95a255ff243e0b5be58f0361668307e2db
jatin9909/python_programs
/BlackJack_game.py
1,721
3.890625
4
import random def calculate_score(ls): sum=0 for i in ls: sum+=i if sum==21 and len(cards)==2: return 0 if 11 in cards and sum>21: cards.remove(11) card.append(1) return sum(ls) def compare(user_score, computer_score): if user_score>21 and computer_score>21: return "You want over, you lose" ...
d6dfc0559311cafccf6078bd47d4b261d7fb41ef
kjleitz/Keegleship
/ships.py
1,092
3.890625
4
class Ship: def __init__(self, name): self.name = name namedict = {"Aircraft Carrier": 5, "Battleship": 4, "Submarine": 3, "Destroyer": 3, "Patrol Boat": 2,} if self.name not in namedict: # pass ...
0efa0d37d644a94edd4976129886fccc8f9f53c6
shilpasingh07/Coursera-Assignments-Python-for-Everybody
/Course-2/week_3_2.py
355
3.671875
4
#Program to handle file # Use the file name mbox-short.txt as the file name fname = input("Enter file name: ") fh = open(fname) count=0 total=0 for line in fh: if line.startswith("X-DSPAM-Confidence:") : lx=line.find(":") nl=float(line[lx+1:]) total=total+nl count=count+1 print("Ave...
38c0e1ed60f1b7fa6a72836fba00685dc8a0bc54
damiansp/completePython
/fluent/02_array_sequence/genexp.py
351
3.640625
4
import array symbols = '$¢£¥€¤' print((ord(s) for s in symbols)) print(tuple(ord(s) for s in symbols)) ords = (ord(s) for s in symbols) print(next(ords)) a = array.array('I', (ord(s) for s in symbols)) print(a) colors = ['red', 'blue'] sizes = list('SML') for tshirt in ('%s %s' % (c, s) for c in colors for s in siz...
a56872b558270256f120076898bb73a85b8e64f1
damiansp/completePython
/pytut/abstract_classes.py
1,539
4.09375
4
from abc import ABC, abstractmethod class Employee(ABC): def __init__(self, name, surname): self.name = name self.surname = surname @property def full_name(self): return f'{self.surname.upper()}, {self.name}' @abstractmethod def get_salary(self): pass class ...
9f8ac459e85c017aebaaa2e27f56c951f256c544
damiansp/completePython
/oneoffs/multiprocessing/07_barrier/barrier.py
598
3.515625
4
from multiprocessing import Barrier, Process from random import random from time import sleep def main(): N_PROCS = 10 barrier = Barrier(N_PROCS + 1) for i in range(N_PROCS): worker = Process(target=task, args=(barrier, i)) worker.start() print('Main waiting on all results') barrie...
656c3011e0e148d5989299cc50296be45382e660
damiansp/completePython
/serious/10_performance_optimization/named_tup.py
244
3.796875
4
from collections import namedtuple class Point: def __init__(self, x, y): self.x = x self.y = y p = Point(1, 2) print(p.__dict__) p.z = 42 print(p.__dict__) Fubar = namedtuple('Fubar', ['x', 'y']) print(Fubar(42, 43))
7f23b5c699cad4f4a7f30661ea327d0201a9dfe6
damiansp/completePython
/bee/01basics/basics.py
689
4.34375
4
#!/usr/bin/env python3 import cmath # complex math # Getting Input from User meaning = input('The meaning of life: ') print('%s, is it?' %meaning) x = int(input('x: ')) # 3 only? y = int(input('y: ')) print('xy = %d' %(x * y)) # cmath and Complex Numbers print(cmath.sqrt(-1)) print((1 + 3j) * (9 + 4j)) #name = raw...
61db9ef9382dade80611175968258ac477de2f52
damiansp/completePython
/effective/05_classes_interfaces/40_super.py
2,714
3.578125
4
# old way class MyBaseClass: def __init__(self, val): self.val = val class MyChildClass(MyBaseClass): def __init__(self): MyBaseClass.__init__(self, 5) # but... class TimesTwo: def __init__(self): self.val *= 2 class PlusFive: def __init__(self): self.val += 5 ...
852a75dff88c8c907a8162c4ce64e8447869b580
damiansp/completePython
/graphics/I_basics/01_lines/end_caps.py
357
3.65625
4
from tkinter import * root = Tk() root.title('Round line end-caps') HEIGHT, WIDTH = 130, 450 PAD = 20 canvas = Canvas(root, width=WIDTH, height=HEIGHT) canvas.grid(row=0, column=1) x1 = PAD y1 = PAD x2 = WIDTH - PAD y2 = PAD for i in range(5): canvas.create_line( x1, y1 + 20*i, x2, y2 + 20*i, capstyle=R...
8e3b17c4daba1cd7be9f6a04494ef134e61f347d
damiansp/completePython
/dev_gen/collections_mod/counters.py
210
3.53125
4
from collections import Counter # init examples c1 = Counter(['A', 'B', 'A', 'C', 'B', 'A', 'B', 'C']) c2 = Counter({'A': 3, 'B': 2, 'C': 5}) c3 = Counter(A=4, B=6, C=8) for c in [c1, c2, c3]: print(c)
9d659ed298e6d5008ce3b96bafc6351e3616808c
damiansp/completePython
/graphics/I_basics/02_ovals/arc_circle.py
288
3.609375
4
from tkinter import * root = Tk() root.title('Arc Circle') W, H = 500, 500 PAD = 50 canvas = Canvas(root, width=W, height=H, background='white') canvas.grid(row=0, column=1) bb = PAD, PAD, W - PAD, H - PAD canvas.create_arc(bb, start=0, extent=359.9999, fill='cyan') root.mainloop()
aa940eb745da4ea35e6346eefc17b5142fb6980a
damiansp/completePython
/concurrency/mastering/03_working_with_threads/threading_mod.py
947
3.65625
4
from math import sqrt import threading def main(): inputs = [2, 193, 323, 1327, 433_785_905, 433_785_907, 433_785_909] threads = [] for x in inputs: thread = MyThread(x) thread.start() threads.append(thread) for thread in threads: thread.join() print('Dunzo!') ...
29299711daa5fc493dc56a43b91ea1898dd348ae
damiansp/completePython
/fluent/01_data_model/Vector.py
1,151
3.875
4
from math import hypot def main(): test() def test(): add_test() abs_test() mul_test() print('All tests passed!') def add_test(): v1 = Vector(2, 4) v2 = Vector(2, 1) assert(v1 + v2 == Vector(4, 5)) print('addition_test passed') def abs_test(): v = Vector(3, 4) ass...
bb48b4c1976c04b49b17e8d89faae0bf18b326ef
damiansp/completePython
/effective/03_functions/21_closure_scope.py
1,438
3.8125
4
def sort_priority(values, group): def helper(x): if x in group: return (0, x) return (1, x) values.sort(key=helper) numbers = [8, 3, 1, 2, 5, 4, 7, 6] group = {2, 3, 7} sort_priority(numbers, group) print(numbers) # 2 3 7 1 4 5 6 8 def sort_priority2(values, group): found = Fa...
720928911d3fb3139222a5fb5d0cbd0161d82d85
damiansp/completePython
/fluent/05_first_class_functions/higher_order_functions.py
799
3.859375
4
from functools import reduce from operator import add fruits = ['strawberry', 'fig', 'apple', 'cherry', 'raspberry', 'banana'] print(sorted(fruits, key=len)) def reverse(string): return string[::-1] print(reverse('testing')) print(sorted(fruits, key=reverse)) # NOTE py 2: apply(f, args, kwargs) -> # py 3:...
1eb37725e3eb011942c59c8fcb1789c2d36a4a0b
damiansp/completePython
/effective/03_functions/20_raise_not_None.py
453
3.65625
4
# Prefer raising exceptions to returning None def careful_divide(a, b): try: return True, a / b except ZeroDivisionError: return False, None def better_divide(a, b): try: return a / b except ZeroDivisionError: raise ValueError('Invalid inputs') def alternate_divide(a...
18b3559c627510121c91353d13611b493b15e22c
damiansp/completePython
/graphics/I_basics/01_lines/rect.py
387
3.640625
4
from tkinter import * root = Tk().title('Rectangle') HEIGHT, WIDTH = 500, 700 PAD = 20 canvas = Canvas(root, height=HEIGHT, width=WIDTH, background='black') colors = ['darkblue', 'darkred', 'darkgreen', 'black'] canvas.grid(row=0, column=1) for i in range(4): pad = PAD * (i + 1) canvas.create_rectangle(pad, ...
760eb15479fa10d33a2ce61f3901f839872d2fa6
damiansp/completePython
/common/edit_dist/example.py
6,014
3.53125
4
''' This module uses the Viterbi algorithm to allow for fuzzy matching used to match typos to the best match in a set of candidates by selecting the candidate with the least distance from the input (or None if distance > max_dist threshold). ''' import numpy as np ''' Class for determining the edit distance between p...
e997597049b06cf41b428ca30aa7392ba87e3cca
Skymon92/PythonAcademy
/Esercizi 26.02/esercizio_10.py
647
4.0625
4
def Permutazioni(n): '''Create a function that takes a variable number of arguments, each argument representing the number of items in a group, and returns the number of permutations (combinations) of items that you could get by taking one item from each group''' perm = 1 counter = 0 if len(n)==0...
9870b2a720a4af06d395aa7c36c7ee973c2140f9
Prema-Rahuraman/ktern_apicall
/imp.py
1,988
3.765625
4
from tkinter import * import sqlite3 root = Tk() root.geometry('550x650') root.maxsize(550,650) root.minsize(550,650) root.title('ktern') name=StringVar() email=StringVar() var= StringVar() var1 =IntVar() def database(): Name=name.get() Email=email.get() gender=var.get() Mob=var1.get() conn...
acd235819785d72bdc6a4e2ea94a0517094b0ddd
WayneZhao1/MyApps
/TicTacToe/tic_tac_toe.py
2,875
4.21875
4
''' Author: Wayne Zhao This is a Tic Toc game. Requirements: . 2 players should be able to play the game (both sitting at the same computer) . The board should be printed out every time a player makes a move . You should be able to accept input of the player position and then place a symbol on the board ''' #i...
71ba67f937fc8e59164b392a3e49a26b87bff128
samy19980109/LeetCode
/LeetCode Hard/Merge K Sorted Lists.py
1,270
4.09375
4
# Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. # Example: # # Input: # [ # 1->4->5, # 1->3->4, # 2->6 # ] # Output: 1->1->2->3->4->4->5->6 # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next ...
5d5ce67b3457edcff1233a81b1aff6a395ea31cb
mayoms/algorithms
/eulerian_circuit/eulerian.py
2,820
3.890625
4
# This is my first solution for finding a eulerian tour. The input is a list of edges # represented as paired tuples e.g. (1,2). It is assumed that the list contains # a complete tour, so no testing is done to verify criteria. # A helper fuction that finds the next node, takes 2 parameters, an edge (pair of nodes) # ...
ebbaf2e61db5ddd6270e7e4d35c7b3ec522497a0
xsank/cabbird
/leetcode/construct_the_rectangle.py
373
3.75
4
import math def constructRectangle(area): sqrt = int(math.sqrt(area)) if sqrt * sqrt == area: return [sqrt, sqrt] else: for i in range(sqrt, 0, -1): if not area % i: return [area / i, i] if __name__ == "__main__": print(constructRectangle(4)) print(con...
bcd9628e4e593687f266135437ada730397aadd2
xsank/cabbird
/leetcode/add_digits.py
230
3.765625
4
def addDigits(num): while num / 10: t = num num = 0 while t: num += t % 10 t /= 10 return num if __name__ == "__main__": print(addDigits(38)) print(addDigits(540))
0c5718503bd96df26af21049fe8cc87fa2710ec2
xsank/cabbird
/tree/binary_search_tree.py
400
3.828125
4
from binary_tree import BinaryTree class BinarySearchTree(BinaryTree): def __init__(self, value=0): super(BinarySearchTree, self).__init__(value) def insert(self, node): if node.value > self.value: self.right = self.right and self.right.insert(node) or node else: ...
1abe0ad2341298be296a7b753027f062b3c3bc6b
xsank/cabbird
/leetcode/set_matrix_zeroes.py
652
3.84375
4
def setZeroes(matrix): if not matrix: return [] row = len(matrix) column = len(matrix[0]) rows = set() columns = set() for i in range(row): for j in range(column): if matrix[i][j] == 0: rows.add(i) columns.add(j) for c in columns: ...
7990fd89e283cd3dda6387882de9bae096b28497
xsank/cabbird
/leetcode/word_pattern.py
390
3.65625
4
def wordPattern(pattern, str): strs = str.split() return map(pattern.find, pattern) == map(strs.index, strs) if __name__ == "__main__": print(wordPattern("abba", "dog cat cat dog")) print(wordPattern("abba", "dog cat cat fish")) print(wordPattern("aaaa", "dog cat cat dog")) print(wordPattern("...
9ed79182d2f395e843bc041155ca8a112585516d
xsank/cabbird
/leetcode/odd_even_linked_list.py
502
3.65625
4
from structure.listnode import * def oddEvenList(head): if not head: return None even_head = head todd_head = odd_head = head.next while todd_head and todd_head.next: even_head.next = todd_head.next even_head = even_head.next todd_head.next = even_head.next todd...
d373db4c707b72717d5003bc9d5d1bdc791c9fee
xsank/cabbird
/leetcode/isomorphic_strings.py
494
3.75
4
def isIsomorphic(s, t): map = {} for i, c in enumerate(s): if (t[i] in map.values() and c not in map) or (c in map and map[c] != t[i]): return False else: map[c] = t[i] return True if __name__ == "__main__": print(isIsomorphic("egg", "add")) print(isIsomorph...
2de162c95224c527f2dcbb98b504d554cb6c1b47
xsank/cabbird
/leetcode/add_two_numbers.py
959
3.515625
4
from structure.listnode import * def addTwoNumbers(l1, l2): head = None tail = None carry = 0 while l1 is not None and l2 is not None: cur_val = (l1.val + l2.val + carry) % 10 tmp_carry = (l1.val + l2.val + carry) / 10 node = ListNode(cur_val) if head is None: ...
10f26fc2ae698706ad01d1279da15ed6a087c984
xsank/cabbird
/leetcode/palindrome_linked_list.py
958
3.546875
4
from structure.listnode import * def isPalindrome(head): if not head or not head.next: return True fast_p = slow_p = head while fast_p.next and fast_p.next.next: fast_p = fast_p.next.next slow_p = slow_p.next sec_p = slow_p.next slow_p.next = None while sec_p.next: ...
0c2e5ec226547c8d73e67b642e0fa7babe97f15a
xsank/cabbird
/leetcode/minimum_moves_to_equal_array_elements.py
125
3.5
4
def minMoves(nums): return sum(nums) - len(nums) * min(nums) if __name__ == "__main__": print(minMoves([1, 2, 3]))
cd9435ed5220ceea914907af8ebb700f8a25cbb0
xsank/cabbird
/leetcode/n_queens_II.py
948
3.703125
4
def isAblePlace(board, row, col, size): for i in range(row): if board[i][col] == 'Q': return False if col - i - 1 >= 0 and board[row - i - 1][col - i - 1] == 'Q': return False if col + i + 1 < size and board[row - i - 1][col + i + 1] == 'Q': return False ...
680b5ad24f372a9b7c15ac6c798aa066a9a66d8b
xsank/cabbird
/leetcode/find_the_duplicate_number.py
373
3.71875
4
def findDuplicate(nums): slow = 0 fast = 0 while True: slow = nums[slow] fast = nums[nums[fast]] if slow == fast: break fast = 0 while True: slow = nums[slow] fast = nums[fast] if slow == fast: break return fast if __name_...
b3008dd4fea15c7161de783e162974d967412ce1
xsank/cabbird
/leetcode/remove_duplicates_from_sorted_array.py
299
3.796875
4
def removeDuplicates(A): length = len(A) if length <= 1: return length index = 0 for i in xrange(length): if A[index] != A[i]: index += 1 A[index] = A[i] return index + 1 if __name__ == "__main__": print(removeDuplicates([1, 2, 3]))
10ef322e262b4ab3de53119266ddaab707eb8376
xsank/cabbird
/leetcode/reverse_string.py
104
3.5
4
def reverseString(s): return s[::-1] if __name__ == "__main__": print(reverseString("hello"))
687aac0b102860469737d1041747fc01c7f552cf
xsank/cabbird
/leetcode/detect_capital.py
395
3.828125
4
def detectCapitalUse(word): def isBigC(c): return 'A' <= c <= 'Z' total = index = 0 for i, c in enumerate(word): if isBigC(c): total += 1 index = i return True if total == len(word) or (total == 1 and index == 0) or total == 0 else False if __name__ == "__main_...
d92d76bc4c9fe971c27b403d58c36e424b847fb1
xsank/cabbird
/leetcode/binary_tree_level_order_traversal.py
768
3.75
4
from structure.treenode import * def _levelOrder(root): queue = [root] res = [] while queue: node = queue.pop(0) if node: res.append(node.val) if node.left: queue.append(node.left) if node.right: queue.append(node.right) ...
9e198ffb5c3ce8932f3868a0655e370a2c52e6b5
xsank/cabbird
/leetcode/symmetric_tree.py
488
4.09375
4
from structure.treenode import * def isSymmetric(root): if not root: return True return compare(root.left, root.right) def compare(left, right): if not left and not right: return True elif left and right: if left.val == right.val: return compare(left.left, right.r...
1a5644dc532cc91fcab9dda99c1862aa966268fa
xsank/cabbird
/leetcode/unique_paths.py
457
3.5625
4
def rec_uniquePaths(m, n): if m == 1 or n == 1: return 1 return uniquePaths(m - 1, n) + uniquePaths(m, n - 1) def uniquePaths(m, n): grid = [[1] * n for i in range(m)] for i in range(1, m): for j in range(1, n): grid[i][j] = grid[i - 1][j] + grid[i][j - 1] return grid[m...
0e90625ddcef756dad2c998ceada1c04dc9d80d8
xsank/cabbird
/leetcode/sum_root_to_leaf_numbers.py
478
3.5625
4
from structure.treenode import * def sumNumbers(root): res = [0] genNum(res, 0, root) return sum(res) def genNum(res, s, root): if root: s *= 10 s += root.val if root.left: genNum(res, s, root.left) if root.right: genNum(res, s, root.right) ...
bac207275404f15832344da5306c9c43ec00ef58
xsank/cabbird
/leetcode/maximum_subarray.py
286
3.796875
4
def maxSubArray(nums): _sum = 0 _max = -1 << 31 for i in nums: _sum += i if i >= _sum: _sum = i if _sum >= _max: _max = _sum return _max if __name__ == "__main__": print(maxSubArray([-2, 1, -3, 4, -1, 2, 1, -5, 4]))
6b1d1a31a8feb5d4ac3644b39e76c808c9d04a0c
xsank/cabbird
/leetcode/binary_tree_paths.py
478
3.5
4
from structure.treenode import * def binaryTreePaths(root): res = [] genTreePaths(res, [], root) return res def genTreePaths(res, tl, root): if root: tl.append(root.val) if not root.left and not root.right: res.append('->'.join(map(str, tl))) genTreePaths(res, tl[...
d57362541fa9ff528ca2f3cd9f6d9f17064a6871
xsank/cabbird
/tree/binary_tree.py
217
3.59375
4
class BinaryTree(object): def __init__(self, value=0): self.value = value self.left = None self.right = None def is_leaf(self): return self.left is None and self.right is None
cced5a7bd6465ad63b76992386e65d438373c353
xsank/cabbird
/leetcode/sort_characters_by_frequency.py
323
3.828125
4
import collections def frequencySort(s): counter = collections.Counter(s) res = [] for c, n in counter.most_common(): res += [c for i in range(n)] return "".join(res) if __name__ == "__main__": print(frequencySort("tree")) print(frequencySort("cccaaa")) print(frequencySort("Aabb"...
19c09703c1e08e8960a51f7751b88333b50f0bc0
Jigar54/Python
/kthLevelOrder.py
1,753
3.875
4
# 1st input :- Number of test cases # 2nd input :- Numbers to be inserted in the tree # 3rd input :- k (it will find the kth level order traversal of the tree! from Queue import * class tree(): def __init__(self): self.root = None def insert(self, parent, n): if parent == None: ...
5c6d470ae8effa795b1c948e220b62a5a25c5560
jyu/Tomata
/temp/2 Layer.py
1,729
4.03125
4
import numpy as np # 2 layer neural net # http://iamtrask.github.io/2015/07/12/basic-python-network/ # Sigmoid function # Translates from numbers to range of 0 to 1 def sigmoid(x): return 1/(1+np.exp(-x)) # Deriv function of sigmoid (tells confidence) # Gets derivative of the point from range of 0 t...
d840f131cf9d99f52824192c557b9fdf88d9ab68
RokonUZ/Python_OOPS
/class_and_instance_variable.py
2,472
4.8125
5
# instance variables are different for different objects # that is they can be assigned different values for different objects # and if we change one object it is not going to change the other object # but if we want a variable in such a way that if we change it's value then # it should be changed for all other variab...
c8e2bb2b63a655bba28bf757482ba6a59d610a29
RokonUZ/Python_OOPS
/basics.py
1,114
4.53125
5
# working on basics of the python OOP's concepts class Computer: def __init__(self, cpu, ram): # this is the constructor in python # generally we use this for initializing the variables because thats what the # constructor does # main advantage or we can say that the behaviour of t...
981a8202e22c568ff7b58973259d4a90f881cfa3
sycomix/AI-Linux
/measurement_scripts/weight_plot.py
2,195
3.78125
4
from matplotlib import style import sys import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation # This script takes 3 arguments: # # 1. The filename where the data are saved for then plotting # - SynchCounter.txt # - loadweight.txt # - blockweight.txt # ...
7db77acb977ad899f620bde2af6cf3cad55bd45e
CraigJPerry/project_euler
/euler/problems/p12.py
2,272
4.0625
4
# !/usr/bin/env python # encoding: utf-8 """Highly divisible triangular number. Project Euler, Problem 12. https://projecteuler.net/problem=12 The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be...
ec8a469ced63be5ab90e41aadae2849d5cd04bfd
sjethi/Email-Demo
/EmailDemo.py
1,866
4.15625
4
#! /usr/bin/python # this is a python email sending demo import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText print("composing!") print("Welcome to Your name's email system!") you = input("Please input recipient's address:\n") # me == my email address # you == recipient's...
2a886ae3ad19f1c2aa6d687f485dc0c8ab8cffdc
huas-hui/hua-shui
/111/公约数.py
260
3.59375
4
num1=int(input("请输入第一个数:")) num2=int(input("请输入第二个数:")) if num1>num2: min=num2 else: min=num1 for i in range(1,min+1): if(num1 % i==0)and(num2%i==0): c=i print('这两个数的最大公约数是:%d'%c)
d1656696811a0a9d02b392c66583e2ef9c01712b
KurskiySergey/Python_Algos
/Урок 1. Практическое задание/task_7.py
1,709
4.53125
5
""" 7. По длинам трех отрезков, введенных пользователем, определить возможность существования треугольника, составленного из этих отрезков. Если такой треугольник существует, то определить, является ли он разносторонним, равнобедренным или равносторонним. """ try: LENGTH_1 = float(input("Введите длину первого отре...
f457cf0bd8713eeaf48327a182b69ea32f7acba7
FloWebDev/roboc-python
/util.py
2,944
3.828125
4
#!/usr/bin/python3.8 # -*- coding: utf-8 -*- """Ce module contient les variables et fonctions utiles au bon fonctionnement du jeu.""" import pickle # Liste des commandes autorisées commande_list = ['Q', 'N', 'E', 'S', 'O'] but_du_jeu = 'Le but du jeu : Tu es un robot (X) et tu dois sortir du labyrinthe en trouvant l...
ff0536e0cb805afcd210cbcc90949e264ac33c3e
varshajayaraman/WayFinder
/BFS_vjayar6.py
9,505
3.765625
4
import Queue import random import time import os import itertools import psutil class Board: def __init__(self): self.board = [[], [], [], []] #[[1,2,3,4], [5,6,7,8], [9,10,11,12], [13,14,0,15]] self.goal = ((1,2,3,4), (5,6,7,8), (9,10,11,12), (13,14,15,0)) #Coding the goal-state ...
147b4ae22a148a254de17b3dbf030cd38c10a0dc
Simochenko/ITVDN_Python_oop
/OOP_2/Магические методы __len__ и __abs__. (Dunder methods).py
3,264
4.09375
4
# Магические методы __len__ (срабатывает при вызове функции len()) и __abs__(срабатывает при вызове функции abs()) class Person: def __init__(self, name, surname): self.name = name self.surname = surname # Не все объекты поддерживают функцию len() print(len('hfd90a8f')) # Вернёт 8 print(l...
6abf08e9db8f7961e9ae79d5f2a1262c678f56f1
Simochenko/ITVDN_Python_oop
/OOP_2/Магические методы __eq__ и __hash__. Dunder methods в Python.py
3,938
3.96875
4
# Магические методы __eq__ и __hash__ class Point0: pass p1 = Point0() # любое значение в Python это объект (экземпляр) print(f'p1 is instance of Point0? - {isinstance(p1, Point0)}') # при создании объекта в Python ему задаётся определённое поведение print(f'Repr p1 = {p1.__repr__()}') print(f'Hash p1 = {p1.__ha...
2dbadca53d0601fe6876eb2bcc05e4d61c0e4757
aditigarg-28/AlgoExpert
/0004. branch-sums.py
573
3.625
4
#o(n) time | o(n) space class BinaryTree: def __init__(self,value): self.value=value self.left=None self.right=None def branchSums(root): sums=[] calculateBranchSums(root,0,sums) return sums def calculateBranchSums(node,runningSum,sums): if node is None: ret...
7f32e5b9b10dc2808100d1375870e20a731584c4
yyogeshchaudhary/PYTHON
/4oct/defaultArrgumet.py
557
4.25
4
# /usr/bin/python ''' Default Arrgument: def functionName(var1, var2, var3=10) var3=10 : is called as default arrgument and we can call function with 2 or 3 parameters if we call the function with 3 parameter then it will override the value of var3 with given value every default parameter should be trailing param...
35bf8abfac68432e60f458c2797b7457216e84f1
1907cloudgcp/project-0-MasterKuan
/src/main/python/com/revature/client/controller/settingsmenu.py
1,512
4.125
4
HIDE = 0 # Run until exit def run_settings_menu(): while True: print("Hide is " + str(HIDE)) action = settings_menu() if action == 0: return 0 elif action == 1: change_hide_password() def get_hide(): global HIDE return HIDE # Get user input until...