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
beee89d2212a24835b2a701c229d2b65c2dca06b
dippingconda/python_algorithm_interview
/intersection-of-two-arrays.py
901
3.828125
4
""" https://leetcode.com/problems/intersection-of-two-arrays """ from typing import List, Set def intersection(nums1: List[int], nums2: List[int]) -> List[int]: return list(set(nums1) & set(nums2)) def solution(nums1: List[int], nums2: List[int]) -> List[int]: result: Set = set() nums1.sort() nums2...
f41e8bdcb13f0289f83a17ebfc3063792577debe
dippingconda/python_algorithm_interview
/different-ways-to-add-parentheses.py
910
3.78125
4
""" https://leetcode.com/problems/different-ways-to-add-parentheses """ from typing import List def diff_ways_to_compute(expr: str) -> List[int]: def compute(left: List[int], right: List[int], op: str) -> List[int]: results = [] for l_item in left: for r_item in right: ...
ea989e7e5724e6fa2739742dfca5e5a3b427c7cc
dippingconda/python_algorithm_interview
/array-partition-i.py
1,402
3.625
4
""" https://leetcode.com/problems/array-partition-i """ from typing import List def merge_sort(arr: List[int]) -> List[int]: if len(arr) <= 1: return arr mid = len(arr) // 2 left_arr = arr[:mid] right_arr = arr[mid:] left = merge_sort(left_arr) right = merge_sort(right_arr) return...
29ca0219ee70bdfee939806f6b3b8ed81ff8d796
dippingconda/python_algorithm_interview
/reorder-data-in-log-files.py
620
3.546875
4
""" https://leetcode.com/problems/reorder-data-in-log-files """ from typing import List def reorderLogFiles(logs: List[str]) -> List[str]: digits, letters = [], [] for log in logs: if log.split()[1].isdigit(): digits.append(log) else: letters.append(log) letters.sor...
f7fd95e1fdca9fa4d68d169784ed559e7a200eb8
dippingconda/python_algorithm_interview
/implement-trie-prefix-tree.py
1,230
4.0625
4
""" https://leetcode.com/problems/implement-trie-prefix-tree """ class TrieNode: def __init__(self): self.word = False self.children = {} class Trie: def __init__(self): self.root = TrieNode() def insert(self, word: str) -> None: node = self.root for char in word...
fd49d27a6a37f23568d4c1a66222a13338701034
dippingconda/python_algorithm_interview
/valid-parentheses.py
871
3.984375
4
""" https://leetcode.com/problems/valid-parentheses """ def valid_parentheses(parentheses: str) -> bool: look_up = {')': '(', ']': '[', '}': '{'} stack = [] for s in parentheses: if s not in look_up: stack.append(s) # 모두 닫는 괄호인 경우라서 스택이 비었거나, 스택과 ...
d8baf0a5375fccff99bc3fe1a1967199c2e00dbd
DREADNAUGHT160/PongGame1
/main.py
1,620
3.734375
4
# importing area from turtle import Turtle, Screen from pad import Paddle from ball import Ball from score import Score import time # screen class calling screen = Screen() screen.bgcolor("black") screen.setup(width=800, height=600) screen.title("pong game") screen.listen() screen.tracer(0) # setting a...
93c6201a68232fed4c581fb11bd4a6c9cd3feae3
MartyVos/Les7
/pe7_2.py
254
3.78125
4
while 1: woord = str(input("Geef een string van vier letter: ")) if len(woord) != 4: lengte = len(woord) print(woord, "heeft", lengte, "letters") else: break print("Inlezen van correcte string:", woord, "is geslaagd")
ff31607d3e479baf11103e6ffcbcef842ce4dcea
douglasbarley/msds
/602/assignment3_vJSbox.py
5,845
4.3125
4
''' Assignment #3 ''' import csv, json, math, pandas as pd, requests, unittest, uuid # ------ Create your classes here \/ \/ \/ ------ ''' Remember, here immutable means there are no setter methods. States can change with the methods required below i.e. combine(), invert(). So for example if s1 is an instanc...
a14d399308752977a8ab418a924341897024b098
Alowirdhi/ReadingReport
/ranking_books.py
1,394
3.546875
4
import operator def ranking_books(value): result_list = {} strInput = open('inputFile.txt', 'r').read() counter = strInput.lower().count("member ") for i in range(1, counter + 1): finalindex = len(strInput) FirstIndex = strInput.index("Member " + str(i)) if i != counter...
9972c62138982306314e86c5ab1ec2b09b892670
paleboot/sololearn-challenges
/passwordValidator.py
283
3.671875
4
import re def check(passCheck): match = re.match(r"([!@#$%^&*()\-+[\]'\";?/<>,\.=\\\|`~]?[a-zA-Z0-9][!@#$%^&*()\-+[\]'\";?/<>,\.=\\\|`~]?){5,10}", passCheck, ) if(match): print("true") else: print("false") passW = input("Insert Password: ") check(passW)
cd79b861a02135518e333f0324ee021ea701731c
stevexenios/INSIGHT_DAPSE
/python/utils/house_5.py
782
3.53125
4
''' Test House 2. This one complements data from house 3, since they are the same house. Data streaming from 3 iot devices (Temperature(C), CO, Energy). Location is in form address only. ''' from house_3 import house_3_device from devices import mutator def extract_house_5_data(v): location_string = v['Address']...
cbb0d322f10052b8abdf82289465f3f1b4f4b144
miriamlam1/csc349
/asgn7-miriamlam1/reduction.py
1,943
3.625
4
# Assignment 7: Reductions # By Miriam Lam # Input: # Output: 3 sat import sys import re from graph import Graph from subgraph_isomorphism import isomorphic_subgraph ''' input: a graph G and a natural number k output: a clique on k vertices within G, if one exists ''' def clique(g, k): h = ...
b9b013282f5482cab0e245c2883912cf355d88c2
miriamlam1/csc349
/asgn2-miriamlam1/singleton.py
751
4.03125
4
# singleton element # input A: a sorted list where only one element in it is unique # output: the singleton element in the sorted list import sys def make_list(fname): f = open(fname, "r") A = list(f) f.close() return A def singleton(A): if len(A) == 1: return A[0] mi...
97768ac6a85598e6d16f875504162a5d12fcae67
minskiter/leetcode
/codepython/392.py
297
3.609375
4
class Solution: def isSubsequence(self, s: str, t: str) -> bool: i = iter(s) si = next(i) for ch in t: if si == ch: si = next(i) return next(si, None) == None if __name__ == "__main__": # it = iter([1,2]) # print(next(it))
df31f19bf1dafc450471f21b4d6047125a94b6bd
minskiter/leetcode
/codepython/386_2.py
707
3.5
4
from typing import List class Solution: def lexicalOrder(self, n: int) -> List[int]: orders = [1] last = 1 while len(orders) < n: while last*10 <= n and len(orders)<n: last *= 10 orders.append(last) while last > 0 and last % 10 == 9: ...
9d6133817f503da17d9e48e2365bbccdc53cd036
zhangqicheng/blog
/utils/pager.py
2,627
3.53125
4
#封装一个类 class PageInfo(object): def __init__(self,current_page,all_count,per_page,base_url,show_page=11): """ :param current_page: 当前页码 :param all_count: 总的数据个数 :param per_page: 每页显示的数据个数 :base_url: 要显示的url地址 """ try: self.cur...
c26d64922bfda2368424cf8ae53200cd51c2f3ce
BarSick69/Tema_de_acasa
/2.py
137
3.78125
4
l1=int(input("")) l2=int(input("")) l3=int(input("")) if(l1<l2+l3 and l2<l3+l1 and l3<l2+l1): print("da") else: print("Nu")
ba0ec1736112b3eeff879e9b2b3a6744c3908580
JeremyLleva/LeetCodePractice
/Python/LonestSubStringWithoutRepeating.py
574
3.53125
4
#Given a string, find the length of the longest substring without repeating characters. #Sliding door solution. class Solution: def lengthOfLongestSubstring(self, s: str) -> int: maxWindow = 0 start = end = 0 alphabets = set() while( end < len(s) ): if( s[end] n...
0934df7d93296da6032d1486582fa378346b015a
joe-bq/algorithms
/python/balanced_parentheses_solutionII.py
628
3.734375
4
############################################# # # balanced_parentheses_solutionII.py # # this is a program to show you how to list all the possible balanced parentheses # ############################################# def association(seq, **kw): grouper = kw.get("grouper", lambda x, y: (x, y)) lifter = kw...
82e116e91b864622372f9c478580161f9cfbf84d
joe-bq/algorithms
/sortings/heap/heap.py
2,246
4
4
##### # file: heap.py # description: this file will show you operations, concept and implementation of the heap algorithms with heap # author: Admnistrator ### import sys class Heap(object): def __initialize__(self, A): if isinstance(A, int): self.length = A else if isinstance(A, list)...
184de35590496bb68c5b206432a49f9b240d2a46
joe-bq/algorithms
/sortings/bubble/bubble_rampUp_lowToHighIter.py
702
4.375
4
####################### # File: # bubbleSort_rampUp_lowToHighIter.py # Author: # Administrator # Description: # this program will show you how to write the insertion sort with the Python code. ####################### import sys def bubble_rampUp(a): length = len(a) for i in range(length-1, -1,-1)...
72691439f883e609654d73c8800cb6f36cc78d87
rnithin1/art-160-minigame
/newer/walmartCovid/Enemy.py
1,569
3.84375
4
import time import random class Enemy: """ Tile class that retains the x, y, image and size of the tile. """ def __init__(self, pos, x, y, image, tiles, moveTime, Game): """ pos is position, x is width of board, y height of board, is image is the enemy sprite, imgSize is the size ...
f0c8f15eb1f1b424469131b3ec03add16df63934
ikmaki14/python-shapes
/pythonshapes_starter.py
330
4.03125
4
from turtle import * import math # Name your Turtle. t = Turtle() # Set Up your screen and starting position. setup(500,300) x_pos = -250 y_pos = -150 t.setposition(x_pos, y_pos) ### Write your code below: pendown() for i in range(4): forward(100) right(90) circle(50, 360, 6) penup() # Close window on click. exit...
9c44c57155900c2266757c9d8f748e82e830c9d4
heeSchae/python
/Binary.py
909
4.09375
4
from datetime import date #Write your code here! def binary_search_year(searchList, year): searchList.sort() if 1 <= len(searchList) -1: mid = len(searchList)//2 if searchList[mid].year == year: return True elif searchList[mid].year > year: return binary_search_...
64610633b780dff052ef036f8bca0b2524e6d3b8
CodeCure-SMU/Algorithm-2021-S
/Yunhee/Baekjoon_2751_Week1_Yunhee.py
159
3.53125
4
import sys num = list() a=int(input()) for i in range(a): b = int(sys.stdin.readline()) num.append(b) num.sort() for i in num: print(i)
5ec214dcddcf23a5b226221ed81fd9f7be53d20f
singhujjwal/python
/interview_questions/biggest_unique_substring.py
682
3.75
4
class Solution: def biggest_unique_substring(self, input: str) -> str: from typing import Set, Dict dict_res = Dict() res = Set() before,after = 0 max_substring = "" for before in range(len(input)): if input[before] not in dict_res.keys(): ...
134cbfec8e9be55ad8c13c5e4957267ed6498f69
singhujjwal/python
/2017_May23/proc/multiprocessing/test_proc.py
586
3.609375
4
from multiprocessing import Process from time import sleep def foo(): for i in 1, 2, 3, 4, 5, 6, 7, 8, 9, 10: print "In foo: counting", i sleep(1) def bar(): for i in 1, 2, 3, 4, 5, 6, 7, 8, 9, 10: print "In bar: counting", i sleep(1) if __name__ == '__main__': t1 = Proc...
607450e15218f165a7dfafc863de07e08101e4ae
singhujjwal/python
/fastapi/some-python-test.py
185
3.65625
4
#!/usr/bin/python3 class Cat: def __init__(self, name:str): self.name = name if __name__ == '__main__': print ("My name is Singh...") fluffy = Cat(name = 'My Fluffy')
5781fff7ad852f1351497e6d1a8ff523c8de95b7
singhujjwal/python
/2017_May23/generators/for_implementation.py
363
3.8125
4
a = [10, 20, 30, 40, 50] #for i in a: # print i, length = len(a) iterator = iter(a) while length: i = iterator.next() # Body of for loop print i, length -= 1 # ----------------------------- iterator = iter(a) try: while True: i = iterator.next() # Body of 'for' loop ...
cb750213624989f4b548af6437054a1ccf83c54d
singhujjwal/python
/2017_May23/threads/thread_share_data_with_rlock.py
805
3.625
4
from threading import Thread, RLock as Lock from random import random from time import sleep SIZE = 10000 a = range(SIZE) a_lock = Lock() def nullify_three_multiples(i): with a_lock: if a[i] % 3 == 0: a[i] = 0 def square_list_item(i): with a_lock: a[i] = a[i] * a[i] nullify_three_mu...
21d9eeff943681bc85b4719a4157edcab272ec4e
singhujjwal/python
/2017_May23/proc/pool/pool_map_pmap.py
486
3.625
4
from multiprocessing import Pool from time import sleep, time def square(x): #sleep(0.5) y = 0 for i in xrange(10000): for j in xrange(1000): y += i * j return x*x data = range(32) p = Pool(64) #print "Starting map..." #start = time() #result = map(square, data) #print "Result: "...
97688f0da9c7d8fd1c3099027ba372a2d91aa5ba
singhujjwal/python
/2017_May23/threads/t2.py
414
3.53125
4
from time import sleep from threading import Thread def count(name, n): for i in range(n): sleep(1) print "In {}: counting {}".format(name, i) t1 = Thread(target=count, args=("foo", 10)) t2 = Thread(target=count, args=("bar", 10)) t1.start() t2.start() count("main", 5) t1.join() print "Thread ...
3977aefc94a612d738ce8aa2097bd680759bfb2b
singhujjwal/python
/2017_May23/threads/queue_mbox.py
1,440
3.625
4
from threading import Thread from queue import Queue from random import sample, random from time import sleep SAMPLE_SIZE = 10 data_queue = Queue(SAMPLE_SIZE) result_queue = Queue(SAMPLE_SIZE) def producer(): batch_count = 0 while True: batch_count += 1 dataset = sample(tuple(range(1, 100)), ...
127c6ec7cc2414a1dfe0fd99ae3a0defb5feb423
singhujjwal/python
/2017_May23/generators/counter.py
146
3.5625
4
def count(): i = 0 while True: yield i i += 1 def chain(*sequence): for i in sequence: for j in i: yield j
666b436669de5224ed17494a6a8a3906a87ea12a
singhujjwal/python
/2017_May23/threads/queue_test.py
756
3.609375
4
#!/usr/bin/env python from threading import Thread import time from Queue import Queue class Send(Thread): def __init__(self, queue): Thread.__init__(self) self.queue = queue self.count = 0 def run(self): while True: self.count += 1 self.que...
8fcb7b82752f768c0f992df69857b9cde803f8d4
singhujjwal/python
/fastapi/things-async.py
695
4.625
5
#!/usr/bin/python3 # # # yield example # yield applies to the generators and is now used to do async programming as well. def test_yield(some_list): for i in some_list: if i%2 == 0: yield i # Normal list iterator mylist = [x*x for x in range(3)] for i in mylist: print (i) for i in mylis...
53305282ebe078ac56343d1c2fb30bc52fc20482
anselb/Advanced-Recursion-and-Graphs
/Code/challenge_1/adjacency_list.py
4,658
4.15625
4
#!python class Graph(object): """ Graph Class A basic implementation of a graph as an adjacency list. """ def __init__(self, weighted=False, directed=True): """Initialize a graph implemented as an adjacency list.""" self.graph = {} self.weights = {} self.weighted = wei...
ccf823cf89117f85ab0b39dd2ad5f39a4ecf9952
Zioq/Python_Programming_MasterClass
/chapter_1/strings.py
233
4
4
# String print print('Hello World') print("Double quotes in Python") print('Include double "quotes" in strings') greeting = "Hello" # Add input name = input("Please enter your name: ") # If we want a pace, print(greeting+' '+name)
43bf5eb282d00c935f878fe5d785d724307abb40
ethanial1/Braille_lectors
/src/imagen.py
2,415
3.5
4
import cv2 as cv import numpy as np # Clase que contiene todos los métodos del procesamiento de imágenes class Imagen(object): def __init__(self, imagen): # abrir la imagen con cv2 self.imagen_original = cv.imread(imagen) # verificamos que la imagen se puede abrir if self.imagen_original is None: ...
ae3e947e4d2e6a75691963ddadc394d91cfabaf2
shrivarsingh/freecodecamp-learn-python
/03 Lists/ListFunctions.py
743
3.96875
4
lucky_numbers = [42, 4, 8, 15, 16, 23] friends = ["Kevin", "Karen", "Jim", "Oscar", "Toby"] friends2 = friends.copy() print(friends) print(friends2) friends.extend(lucky_numbers) print(friends) friends = ["Kevin", "Karen", "Jim", "Oscar", "Toby"] friends.append("Creed") friends.insert(1, "Kelly") friends.remove("Ji...
4dd828096a5eb69c493930c8381a4b0bb6e7f9ca
si20094536/Pyton-scripting-course-L1
/q4.py
673
4.375
4
## 4. Given a list of non-empty tuples, return a list sorted in increasing order by the last element in each tuple. ##e.g. [(1, 7), (1, 3), (3, 4, 5), (2, 2)] yields [(2, 2), (1, 3), (3, 4, 5), (1, 7)] ## Hint: use a custom key= function to extract the last element form each tuple. ##i. [(1, 3), (3, 2), (2, 1...
037c848d12cec0728a92cb5e50ffc79e411db459
manigurusankar10/python-wumpus
/wumpus.py
7,820
3.625
4
import random ### Class for individual rooms in the cave class Room(): def __init__(self, name, value): self.wumpus = False self.pit = False self.bat = False self.gold = False self.name = name self.empty = True self.value = value ### Class for all the rooms in the cave. class Cave(): #intial functio...
9acba907b818c3e591571dbadaf3bdb751b91d99
kishan-pj/python_lab_exercise_1
/pythonproject_lab2/temperature.py
323
4.5
4
# if temperature is greater than 30, it's a hot day other wise if it's less than 10; # it's a cold day;otherwise,it's neither hot nor cold. temperature=int(input("enter the number: ")) if temperature>30: print("it's hot day") elif temperature<10: print("it's cold day") else: print("it's neither hot nor col...
8d8fff8b1f4ac7d1e6b2e77857d855380769d878
kishan-pj/python_lab_exercise_1
/pythonproject_lab2/Qno.5positive_negative_zero.py
277
4.40625
4
# for given integer x print true if it is positive,print false if it is negative and print # zero if it is 0. x=int(input("enter the number: ")) if x>0: print("the number is positive ") elif x<0: print("the number is negative ") else: print("the number is zero ")
1d32702262eea6ddd58d869c713f7089361a5947
cwkarwisch/CS50-psets
/vigenere/vigenere.py
2,383
4.4375
4
import sys from cs50 import get_string def main(): # Test if the user has only input two strings (the name of the program and the keyword) if len(sys.argv) != 2: print("Usage: ./vigenere keyword") sys.exit(1) # Test if the keyword is strictly alphabetic if not sys.argv[1].isalpha(): ...
a1b3992db13011c41310624a99e5de95d9a3c5b6
DaniilKrk/HW
/L02/L02_Normal.py
3,008
3.859375
4
# Задача-1: # Дан список, заполненный произвольными целыми числами, получите новый список, # элементами которого будут квадратные корни элементов исходного списка, # но только если результаты извлечения корня не имеют десятичной части и # если такой корень вообще можно извлечь # Пример: Дано: [2, -5, 8, 9, -25, 25, 4] ...
ace9475322402f6e2d26e2e1fba19fbd3bd5d66e
DaniilKrk/HW
/L03/L03_Easy.py
3,156
3.8125
4
# Задание-1: # Напишите функцию, округляющую полученное произвольное десятичное число # до кол-ва знаков (кол-во знаков передается вторым аргументом). # Округление должно происходить по математическим правилам (0.6 --> 1, 0.4 --> 0). # Для решения задачи не используйте встроенные функции и функции из модуля math. def ...
8846ad408c13ac7049845b06e45d0ed2b9876141
414c4f4e45/15_3sum
/main.py
2,080
3.5
4
# URL: explanation and solution # https://leetcode.com/problems/3sum/discuss/7498/Python-solution-with-detailed-explanationzzu from typing import List class Solution: def getKey(self, keys: List[int]): return ''.join(str(keys)) def threeSum(self, nums: List[int]) -> List[List[int]]: nums.sort() size ...
6c25f51fbdc3a77c7494b2e19829ae0b50b05a21
YasminMichels/infosatc-lp-avaliativo-02
/ex6.py
328
4.03125
4
listacor = ["vermelho","roxo","preto","azul"] print(listacor) print("O item vermelho está na posição:",listacor.index("vermelho")) print("O item roxo está na posição:",listacor.index("roxo")) print("O item preto está na posição:",listacor.index("preto")) print("O item azul está na posição:",listacor.index("azul"))
62e3f49b61473d752a24a0adff73fe31f0bb0eba
lilawren/ctci-python-solutions
/2 - Linked Lists/2.4.py
789
3.6875
4
# partition linked list by element x from LinkedList import Node def LLpartition(head, x): n = head lesser = None greatereq = None if n.next == None: return n while n != None: if int(n.data) < x: #lesser list if lesser == None: lesser = Node(n.data) lesser.next = None else: lesser.append...
ebf94bbc6e211f774b0257b005621c73fd52aa17
lilawren/ctci-python-solutions
/2 - Linked Lists/2.3.py
366
4.03125
4
# Delete middle node from LinkedList import Node head = Node("1") head.appendToTail("2") head.appendToTail("1") head.appendToTail("4") def removeMid(node): if node == None or node.next == None: return else: d = node.next node.data = d.data node.next = d.next d.data = None d.next = None head.printLL()...
c77a643a493eeef599040156c2133bd68ac3c594
lilawren/ctci-python-solutions
/1 - Arrays and Strings/1.3.py
336
3.96875
4
# Write a method to replace all spaces in a string with '%20' and you are given the true length of a string # do not go beyond true length def URLify(str, length): res = "" if length > len(str): return for i in range(length): if str[i] == ' ': res += "%20" else: res += str[i] print(res) URLify("wa wee...
9cbecbbf553b0adca9db52de0a75a9446702d8a6
lilawren/ctci-python-solutions
/8 - Recursion and Dynamic Programming/8.11.py
925
3.65625
4
# calc ways to represent n cents using quarters, dimes, nickels, and pennies numways = 0 def coins(target, n, memo, cur): global numways if n < 0: return if n == 0 and cur not in memo and meets_target(target, cur): numways+=1 print("way: " + str(cur)) memo.append(cur) ...
0fd2cc66f9b6088ecec33b0f0411f24ae7b48f0b
lilawren/ctci-python-solutions
/8 - Recursion and Dynamic Programming/8.4.py
846
3.84375
4
# return subsets import copy def subset(A, ss): if len(A) > 0: #print(ss) # make copy for i in range(0, len(ss)): ss.append(copy.deepcopy(ss[i])) #print(ss) #add values to the subsets first = A[0] for i in range(int(len(ss)/2), len(ss)): ...
93e8cfa767219b12aaa32df33f8eb3c9324a9d59
lilawren/ctci-python-solutions
/4 - Trees and Graphs/4.12.py
602
3.734375
4
# return number of paths in binary tree with sum of target #we reuse this function a lot def countFromRoot(root, target, cursum): cursum += root.data totalpaths = 0 if cursum == target: totalpaths+=1 totalpaths += countFromRoot(root.left, target) totalpaths += countFromRoot(root.right, target) return totalp...
127bf8f2ffa8294fde6f070a00923bf44ff903b4
lilawren/ctci-python-solutions
/4 - Trees and Graphs/4.3.py
908
3.78125
4
# create a LL for each depth in a binary tree class LLNode: next = None data = "" def __init__(self, n, d): self.next = n self.data = d class Node: data = "" left = None right = None def __init__(self, d, l, r): self.data = d self.left = l self.right = r LL = [] def preOrder(root, depth): if ro...
06e0e771ab81918bebd45d424b0dc332f9a54774
Python-lab-cycle/ThasniPK
/colornotinboth.py
230
3.84375
4
color1=input("enter a set of colors(space separated):") color2=input("enter a set of colors(space separated):") c1=set(color1.split()) c2=set(color2.split()) print("the difference between",c1,"and",c2,"is",c1.difference(c2))
d8b0b1e56c6a86a79339c437e790e8024b0b837d
gundamze/Trading
/Tutorial/Tutorial_Plot.py
3,693
3.75
4
from pandas import DataFrame, Series import numpy as np """________________________________________________________________________ example 1 1. the parameter summary http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.plot 2. the matplotlib tutorial htt...
389ad31f0f185d1f4c5302c070cb531b6b222be2
SamCasavant/TextAdventure
/things.py
3,949
3.5625
4
class ThingMixin: def lookAt(self): print(self.name) if self.name != self.description: print(self.description) for tag in self.tags: if tag in ["eat", "take", "drink"]: print(f"I can {tag} this.") elif tag in ["take_req"]: p...
eb6b446a8af08b0593c2f8c63511193d0355285b
eMintyBoy/pyLabs
/Tanya/LR5/lr5_zad1.py
841
4.1875
4
# Дан одномерный массив, состоящий из N вещественных элементов. Ввести массив с клавиатуры. Найти и вывести минимальный по модулю элемент. Вывести массив на экран в обратном порядке. list = [] N = int(input("Введите количество элементов списка: ")) print("Введите элементы списка: ") for i in range(N): a = int(in...
d953047f445cd44a59bb93ed44c1eefe7dd0f6a5
JordanKeller/data_structures_and_algorithms_python
/LinkedListStack.py
658
3.609375
4
import DoublyLinkedList as DL # relies upon the file DoublyLinkedList.py class LinkedListStack(DL.DoublyLinkedList): """Linked list based stack implementation. Supports push and pop methods with O(1) speed.""" def __init__(self): super().__init__() def get_top(self): return self.get_head() def push(s...
4e3796776bf5a292d95f7ff63e0218f14fe4e3fb
JordanKeller/data_structures_and_algorithms_python
/LinkedListQueue.py
656
3.75
4
import DoublyLinkedList as DL # relies upon the file DoublyLinkedList.py class LinkedListQueue(DL.DoublyLinkedList): """Linked list based queue implementation. Supports enqueue and dequeue methods with O(1) speed.""" def __init__(self): super().__init__() def get_head(self): return super().get_head() def ...
ce6a09f9e1b13bc8456bb3410a58aa051e553b6d
JordanKeller/data_structures_and_algorithms_python
/climbing_stairs.py
489
4.21875
4
def climbing_stairs(n): """Input a positive integer n. Climb n steps, taking either a single stair or two stairs with each step. Output the distinct ways to climb to the top of the stairs.""" a = 1 b = 2 if n == 1: return a if n == 2: return b # n >= 3 for i in range(n - 2): c = a + b a = b b ...
d233b344e6cf26a470eea9fec5685fc6fa334339
Localvox/vivialconnect-python
/vivialconnect/resources/user.py
1,473
3.53125
4
""" .. module:: user :synopsis: User module. """ from vivialconnect.resources.resource import Resource from vivialconnect.resources.countable import Countable class User(Resource, Countable): """Use the User resource to manage users and user passwords in the API. User properties ============= ======...
234fba390121fdc6f3dd8801cfabe9d5b4d5f5e4
LIKELION-VN-WORKS/class-stuffs
/week3-2/python_fundamentals/4_set.py
675
3.78125
4
# set(집합) : # type 1 : {'1',2,'likelion'} / type 2 : set([1,2,3]) a = {'1', 2, 'likelion','1', (3,4), True} b = {2, 'likelion', True, False, (5,6)} print(a|b) # union(합집합) print(a&b) # intersection(교집합) print(a-b) # difference(차집합) # An object is hashable if it has a hash value which never changes during its lifetime...
c5638370b40b921c0a7f5ab0bea016c7b2ad98b3
maganaluis/leetcode
/mergeTrees.py
1,755
3.9375
4
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class BinaryTree: def __init__(self, node): self.root = TreeNode(node) def get_node(self, root, x): if root.val == x: return root if root.left: return self.get_node(root.left, x) if root.right: return sel...
07987037e1adc8569f871c2df2fc9c0a20d19f47
fatanu/Python-Self-Study
/May-23.py
496
3.921875
4
# def factorial(n): # if n< 2: # return 1 # return n * factorial(n-1) i = 1 while i < 6: print(i) if i == 3: break i += 1 i = 0 while i < 6: i += 1 if i == 3: continue print(i) def myfunc(e): return len(e) cars = ["Ford", "Mitsubishi", "BMW", "VW"] cars.sort(reverse=True, key=m...
34e839e5a57942916950a475e8654ce4b21a121c
rob-dalton/pretty-pipeline
/pretty_pipeline/pipeline.py
2,949
3.65625
4
from typing import List, Union class Step(object): """Step to run in a Pipeline. A Step is a function and a set of arguments that are called during Pipeline.run(). """ def __init__(self, func, *args, **kwargs): self.func = func self.args = args self.kwargs = kwargs def...
bbdc9a562338830d393ffaa290329b92f730b274
manimaran1997/Python-Basics
/ch_08_OOP/Projects/ch_04_Inheritance/ex_inheritance.py
2,861
4.125
4
# coding: utf-8 # In[42]: class Employee: employeeCounter = 0; def __init__(self,firstName,lastName): self.firstName = firstName self.lastName = lastName Employee.employeeCounter += 1 print(" hello i employee") def displayEmployeeName(self): ...
1f2aecc0de33c798ece74a255b1eb8c10b6e2909
manimaran1997/Python-Basics
/ch_07_Data Structures in Python/ch_02_Sequence Types/ch_01_List/Project/01_Basics Of List/pythonList.py
1,658
4.1875
4
# coding: utf-8 # # 1.Create List # In[1]: #1.1 by brackets # In[2]: list1 = [1,2,3,4] # In[3]: print(list1) # In[4]: list2 = [1,2.5,3+5j,"ahmed"] # In[5]: print(list2) # In[6]: #1.2 By Constructor # In[7]: list3 = list((1,2,3,"hello world")) # In[8]: print(list3) # # 2.add Item # In[10]: l...
8bb9975be7bb02559d749cc312819ef251f9dc01
manimaran1997/Python-Basics
/ch_08_OOP/Projects/ch_03_Methods/ch_03_Static Method/STATIC+METHOD.py
1,012
3.546875
4
# coding: utf-8 # In[12]: class Employee : #this is class variable employeeCounter = 0 #constructor def __init__(self,firstName,lastName): self.firstName =firstName self.lastName = lastName Employee.employeeCounter += 1 #normal or regular method and t...
346b282db6ddfbcd641af88a0a1fe62d337ebfaa
kaustubhhiware/journey_to_centre_of_code
/hackerEarth/code-rush_ktj/going_doctor.py
170
3.625
4
import fileinput for line in fileinput.input(): # print line.strip().split() l = line.strip().split() if (len(l[0]) < len(l[1])): print "no" else: print "go"
bc630f04ab840c1064a7b5ad785c8d3ffec71579
anaxronik/python-algoritms
/1. Введение/1.6/task.py
293
3.5625
4
num = int(input('Введите целое число: ')) ans = input('Перевести в байты - "b", в килобайты "k": ') ans = ans.lower() if ans == 'b': print('=', num * 1024) elif ans == 'k': print('= ', num / 1024) else: print('Неверный ввод')
df4c2f94eaa3e3117fd9d58c1277f27a1020af6a
ajmalbinnizam/python-DSA
/begin/fun.py
164
3.734375
4
get(name) def get(name): name=raw(input('enter ur name')) age=int(input('enter ur name')) place=input('enter ur place') def display(): print("h")
93d2ab8026b1f783ce433b9d1b25819ea485db49
ajmalbinnizam/python-DSA
/oops/poops.py
399
3.671875
4
# class computer: # # # # def __init__(self,cpu,ram): # # self.cpu=cpu # # self.ram=ram # # # # def config(self): # # print("config is",self.cpu,self.ram) # # # # # # com=computer("16 ",5) # # com1=computer("ijd",3) # # com.config() # # computer.config(com1) class comp: def __init__...
cb2beaf2dc7761d2afdbbc216081beb5d9c102a3
ajmalbinnizam/python-DSA
/dsa/linear search.py
225
3.703125
4
def search(lis,n): global i i=1 for i in range(len(lis)): if lis[i]==n: return lis[i] lis=[3,4,6,7,9,3,] n=9 if search(lis,n): print("value found",i+1) else: print("value not found")
328c2b5f6b63d370ef9bbf0dbd43f9fb6dad9abe
ajmalbinnizam/python-DSA
/begin/function.py
4,082
4.0625
4
# def add(x,y): # c=x+y # d=x-y # return c,d # # result1,rslt2=add(2,4) # print(result1,rslt2) # a=10 # b=20 # def add(a,b): # result=a+b #local variable # print("addittion",result) # return # add(a,b) #global variable # print("add outside",result) #local variable # def add(): # a=int(input...
7c3360b7942cbe023ea53d9cd3e0489ce918fa18
Zian-Zhou/DataStructure-Algorithm-Python
/python数据结构与算法/BinTree.py
9,755
3.734375
4
from BinNode import BinNode from Queue import Queue from Stack import Stack ''' class BinNode: def __init__(self, val = None, left = None, right = None): self.value = val self.lChild = None self.rChild = None ''' class BinTree(object): """docstring for BinTree newTree = BinTree()#实例化一棵树,此时根节点,左孩子,右孩子均为None n...
cde32c34b6225e5330029dd5b4ac34461f508d8e
Zian-Zhou/DataStructure-Algorithm-Python
/leetcode/动态规划/96. 不同的二叉搜索树.py
1,660
3.9375
4
#96. 不同的二叉搜索树 ''' 给定一个整数 n,求以 1 ... n 为节点组成的二叉搜索树有多少种? 示例: 输入: 3 输出: 5 解释: 给定 n = 3, 一共有 5 种不同结构的二叉搜索树: 1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3 ''' ''' 二叉搜索树,因此根节点确定下来,其...
53c6fc08ee569ceffc384f663713ea9372163cee
Zian-Zhou/DataStructure-Algorithm-Python
/leetcode/多数之和/1-两数之和.py
1,751
3.765625
4
''' 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。 你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。 示例: 给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1] ''' #https://blog.csdn.net/linfeng886/article/details/79772348 #暴力法 def twoSum(nums,target): l = len(nums) for i in...
565e5bf3c47985e711ef4af1a7fbfa4433d4a234
Zian-Zhou/DataStructure-Algorithm-Python
/leetcode/动态规划/764. 最大加号标志.py
2,747
3.578125
4
#764. 最大加号标志 ''' https://leetcode-cn.com/problems/largest-plus-sign/ 在一个大小在 (0, 0) 到 (N-1, N-1) 的2D网格 grid 中,除了在 mines 中给出的单元为 0, 其他每个单元都是 1。网格中包含 1 的最大的轴对齐加号标志是多少阶? 返回加号标志的阶数。如果未找到加号标志,则返回 0。 一个 k" 阶由 1 组成的“轴对称”加号标志具有中心网格 grid[x][y] = 1 , 以及4个从中心向上、向下、向左、向右延伸,长度为 k-1,由 1 组成的臂。 下面给出 k" 阶“轴对称”加号标志的示例。 注意,只有加号标志的所有网格...
c7654b357a7bcb44ab8e8e938d1731bc1089f12e
aleksandrabliznyuchenko/homework
/1st year/python_hw/hw8_4.py
1,213
3.9375
4
riddles = {('чайная'): 'ложка', ('Карнавальная'): 'ночь',('Снежная'): 'королева',('Лебединое'): 'озеро',('Северный'): 'полюс', ('алая'): 'роза', ('Балтийское'): 'море'} pluses = 0 mistakes = 0 print('Отгадайте слово по его описанию: \n') for key in riddles.keys(): print(key, '.' * len(key)) ri...
a140f986e0cd62d4e2f7482e3db8987d38cda613
ranchirino/machine-learning-with-scikit-learn-and-tensorflow
/ex7_8.py
3,402
3.8125
4
# Voting Classifier # Exercise: Load the MNIST data and split it into a training set, a validation set, # and a test set (e.g., use 50,000 instances for training, 10,000 for validation, and 10,000 for testing). from sklearn.datasets import fetch_mldata mnist = fetch_mldata('MNIST original') from sklearn.model_...
754abb23effd5aa59d066e4b852dd2983e8c4bdc
ranchirino/machine-learning-with-scikit-learn-and-tensorflow
/4_training_models.py
17,379
4.1875
4
# Linear Regression # a linear model makes a prediction by simply computing a weighted # sum of the input features, plus a constant called the bias term (also called the intercept # term) # y = θ0 + θ1*x1 + θ2*x2 + ⋯ + θn*xn # y = θT*X # Let’s generate some linear-looking data import numpy as np import matp...
6f64e3368dffa3abc1e9fd59feb5fd41540a8430
vishwanath1306/OS-Project
/tests.py
8,378
3.671875
4
import unittest from simulator import Simulator from algorithms.scheduling import Scheduling class testAlgorithmsBaseFunctions(unittest.TestCase): """Tests base functions in Scheduling.""" _requirements = [-5, 15, 40, 65, 20, -35] _reqs_no_pf = [15, 40, 65, 20] def setUp(self): self.sched...
dcb68350c5bc17d244003a6b2a9e8b41e5145071
GeovanaStefani/Quine_McCluskey
/Quine_McCluskey.py
25,993
3.59375
4
from Constantes import * def transforma_em_binario(termos): """ Transforma os termos, em binarios. O primeiro for percorre a lista de termos para poder verificar cada um. O segundo for, analisa todos os caracteres do termo, verificando apenas as variaveis, não os sinais de barramento. Dessa forma,...
6ec2717c680d47f5538ce42ad8148570b7dd5257
BarberAlec/Common-Interview-Questions
/tests/test_min_int.py
968
3.515625
4
"""Run tests on MinInt functions""" from unittest import TestCase from min_int import MinInt class TestMinInt(TestCase): """ Run all methods prefixed with 'test' """ def setUp(self) -> None: """ This is called _before_ each test """ max_int = 100000 ...
ea98367033c8c94358e5ce8acba56ae8e730b7b0
asosa1/ClingoParallelSolver
/graph_generator.py
1,352
3.515625
4
import random def generate_graph(n): graph = [[-1 for i in range(n)] for j in range(n)] for i in range(n): for j in range(n): if j == i: graph[i][j] = 1 if graph[i][j] == -1: temp = int(rando()) graph[i][j] = temp graph [j][i] = temp return graph def rando(percentage = 33): return rand...
c380edaae8661d21363c2ea2fe90f59d3879306c
efitzpatrick/Tkinter
/firstRealExample.py
2,121
4.375
4
# www.tkdocs.com/tutorial/firstexample.html #tells python that we need the modlues tkinter and ttk # tkinter is the standard binding to Tk (what is a binding?) # ttk is Python's binding to the newer themed widgets that were added to 8.5 from tkinter import * from tkinter import ttk #calculate procedure def calculate(*...
529d030e81a7ceaa4e5428450d3f6f8f0a96eb61
lpgarzonr/PythonKatas
/multiplyNumbers.py
435
3.734375
4
def multiplyNumbers(numA, numB): small = numA if numA < numB else numB big = numA if numA > numB else numB return multiply(big, small) def multiply(baseNum, timesNum): if baseNum == 0: return 0 if timesNum == 1: return baseNum halffTimes = timesNum // 2 halfSum = multiply(baseNum, halffTimes) res = (times...
2efda3f9ac25f68e1de60fecdd769aa8a8ab5046
lpgarzonr/PythonKatas
/coinsCount.py
423
3.890625
4
def coinsCount(value): numberOfCoins = 0 coinsValues = [25, 5, 1] for coinValue in coinsValues: coins = getNumberOfCoins(value, coinValue) numberOfCoins += coins value -= coins * coinValue if value == 0: break return numberOfCoins def getNumberOfCoins(value, coinValue): return int(value/coinValue) pr...
9f25b4ed4201d5b39624efa5f86655df4c218e75
lpgarzonr/PythonKatas
/reverseNum.py
418
3.8125
4
def reverse(x): powValue = len(str(abs(x))) - 1 isNegative = x < 0 reversedNumber = getReverseValue(abs(x), powValue) return -reversedNumber if isNegative else reversedNumber def getReverseValue(x, powValue): if x < 10: return x lastDigit = x % 10 newNumber = x // 10 return lastDigit * pow(10, powValue) + ge...
4457b252db358fb1e12578705448cd477c16f3f1
stjordanis/H2-Computing-Practicals
/Homework/Submissions_2/q4.py
176
4.0625
4
def power(x, n): if n == 0: answer = 1 elif n == 0: answer = x else: answer = x * power(x,n-1) return answer a = power(3,5) print (a)
f1a6ecf361ed227dabf3ed67b67df0330fe13d42
stjordanis/H2-Computing-Practicals
/Homework/Submissions_1/q1.py
94
3.84375
4
""" What is the output of the following code? a=5 b=a+7 a = 10 print(str(b)) ANSWER: 12 """
266e0e0c64444e68fc2030224dd6ce2e27c9a45a
makacyge/Projekt_X
/less_7.py
3,490
3.84375
4
# 2) Даны два словаря my_dict_1 и my_dict_2. # а) Создать список из ключей, которые есть в обоих словарях. my_dict_1 = {6:12,8:59,7:78,5:45} my_dict_2 = {6:89,1:12,3:15,7:77} result = list(set(my_dict_1.keys()).intersection(set(my_dict_2.keys()))) print(result) # б) Создать список из ключей, которые есть в первом, но ...
ab109d2fe92626578d5872922a415ac1a8462d32
Krish-master/Whitehat-projects
/identity_card.py
2,579
3.546875
4
from tkinter import * root = Tk() root.title("Driving License") root.geometry("300x400") root.configure(bg="white") canvas = Canvas(root, width=300, height=400) canvas.create_image(0, 0, anchor=NW) canvas.create_rectangle(0, 0, 300, 55, fill="purple") canvas.create_rectangle(0, 345, 300, 400, fill="purp...
e26de92d2b15f03a58b5f61df9e925bc703b1085
iprateekgulati/Testing
/ece650a1.py
11,014
3.84375
4
import sys import re import ast from decimal import Decimal database = dict() def can_change(x): if x in database: return True else: return False def case_insesitive(x): y = x.lower() return y def add_street(x,y): if(Is_valid_street(x)): if(do_parentheses_match...
4fee01e07be799ec8ae882a73f928c3dac945d72
bolmstedt/advent-of-code-python
/app/y2020/d08_handheld_halting.py
2,193
3.53125
4
"""Solution for day 8, 2020.""" from typing import List, Set, Tuple, Union from app.base_solver import BaseSolver NOOP = 0 JUMP = 1 ACC = 2 OPS = { 'nop': NOOP, 'jmp': JUMP, 'acc': ACC, } SWITCH = {NOOP: JUMP, JUMP: NOOP} class Solver(BaseSolver): """Solver for day 8, 2020.""" day = '08' ye...
48ebbb7bd22661d3f3e9eb16e55a97ee6aeb9968
bolmstedt/advent-of-code-python
/app/y2019/d01_the_tyranny_of_the_rocket_equation.py
1,081
3.5625
4
"""Solution for day 1, 2019.""" import math from typing import Union from app.base_solver import BaseSolver class Solver(BaseSolver): """Solver for day 1, 2019.""" day = '01' year = '2019' name = r"""The Tyranny of the Rocket Equation""" def part_one(self, data: str) -> Union[int, str]: ...