blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
94a56f3603f97449915e13c0b7436bd443909072
PacktPublishing/Software-Architecture-with-Python
/Chapter08/pipe_recent_gen.py
935
3.65625
4
# Code Listing #12 """ Using generators, print details of the most recently modified file, matching a pattern. """ # pipe_recent_gen.py import glob import os from time import sleep def watch(pattern): """ Watch a folder for modified files matching a pattern """ while True: files = glob.glob(p...
b8e6af4affac0d2ae50f36296cc55f52c6b44af3
PacktPublishing/Software-Architecture-with-Python
/Chapter04/defaultdict_example.py
1,374
4.1875
4
# Code Listing #7 """ Examples of using defaultdict """ from collections import defaultdict counts = {} text="""Python is an interpreted language. Python is an object-oriented language. Python is easy to learn. Python is an open source language. """ word="Python" # Implementations with simple dictionary for word ...
e533dfcf88350f562a93a36b2289a8be79421159
PacktPublishing/Software-Architecture-with-Python
/Chapter02/codecomments3.py
1,279
3.671875
4
# Code listing #5 def fetch_url(url, ntries=3, timeout=30): """ Fetch a given url and return its contents. @params url - The URL to be fetched. ntries - The maximum number of retries. timeout - Timout per call in seconds. @returns O...
056b26ee4d7d1091beace07a1e2804213bfd9877
rxxxxxxb/PracticeOnRepeat
/Data Structure/Linked List/try_list.py
649
3.921875
4
class Node: def __init__(self,data,next): self.data = data self.next = next class LinkedList: def __init__(self,head = None): self.head = head def input(self,data): node = Node(data,self.head) self.head = node def PrintAll(self): currentNode = self.head...
3fec66e37a1402b28180b44cd575db2eaa892d72
rxxxxxxb/PracticeOnRepeat
/Data Structure/Linked List/linked_practice.py
523
3.75
4
class Node: def __init__(self,data,string,next): self.data = data self.string = string self.next = next def str(self): return self.data,self.string class LinkedList: def __init__(self,head = None): self.head = head def insert(self,data,string): node ...
97b15762af24ba6fb59fc4f11320e99ffcec6cf4
rxxxxxxb/PracticeOnRepeat
/Python Statement/practice1.py
540
4.125
4
# Use for, .split(), and if to create a Statement that will print out words that start with 's' st = 'Print only the words that start with s in this sentence' for word in st.split(): if word[0] == 's': print(word) # even number using range li = list(range(1,15,2)) print(li) #List comprehension to ...
d59bdfa7817454d2028ce23039ad8f5ebb7aee96
rxxxxxxb/PracticeOnRepeat
/book_practice.py
1,126
3.96875
4
class Author: def __init__(self,book): # self.name = name self.books = book # self.publishedTime= publishedTime def info(self): print("Writer name :" ,self.name.title()) print("Published Year :" ,self.publishedTime.title()) # def booklist(self):...
ea8f53ebeb17c928a0332326419ba16f94ef1c6b
YashasCS/OpenCV_tutorial
/basic.py
532
3.546875
4
import cv2 as cv img = cv.imread('Photos/cat.jpg') cv.imshow('cat',img ) # converting to grayscale gray = cv.cvtColor(img,cv.COLOR_BGR2HSV_FULL) #cvt stands for converting colour cv.imshow('gray',gray) # blurring an image blur = cv.GaussianBlur(img, (7,7), cv.BORDER_DEFAULT) # always has to be odd the kernel ...
139cc61aca2dc4d17f7c6188b877ebece08842e4
davidaceves/Data-Structures
/queue_and_stack/dll_queue.py
1,106
3.703125
4
import sys sys.path.append('../doubly_linked_list') from doubly_linked_list import DoublyLinkedList, ListNode #FIFO class Queue: def __init__(self): self.size = 0 self.storage = DoublyLinkedList() def __str__(self): cur_node = self.storage.head output = '' output += st...
cb572ff9d3251bbeacf36e9e9516970154c8df4e
kovacsbalazspeter21/f0003
/f0003a.py
346
3.515625
4
##F0003a: Írj programot, amely külön-külön megkérdi a vezeték- és a keresztneved, majd kiírja őket egy mondatban, pl: A te neved Kovács Boldizsár. (A pontot se felejtsd el!) Megoldás itt. vezetéknév = input('Mi a vezetékneved?') keresztnév = input('Mi a keresztneved?') print('A te neved ', vezetéknév, ' ', kereszt...
74b45f78de31e40a9ce64502f39e67ddc88b34cc
fuzhongyu/python_learn
/src/com/fucai/MuliTread.py
773
3.765625
4
#! /usr/bin/evn python3 # -*- coding: utf-8 -*- 'muli thread' import threading __author__ = 'fucai' #创建锁 lock = threading.Lock() #创建全局变量 thread_local = threading.local def loop(): #加锁 lock.acquire() try: print('thread %s is running...' % threading.current_thread().name) n = 0 wh...
b0761cc32b38a82c8d59a2d93eec71df98b5e3bb
srotavele/Python2.21_MASTER
/fundamentals/OOP/User_Assignment/chaining_methods.py
1,466
4.09375
4
#!/Library/Frameworks/Python.framework/Versions/3.9/bin/python3 class User: def __init__(self, name, email_address): self.name = name self.email = email_address self.account = BankAccount(int_rate = 1.02, balance = 500) def make_deposit(self, amount): self.account.deposit +...
b668068768fb5835eac9d575ac7ca4d078a88b0f
serabakpak/HB_Spring2016
/find_average.py
119
3.765625
4
def find_average(num1,num2): total = num1 + num2 average = float(total / 2) return average print find_average(5,12)
ba521e55854c06c491f2d263630bd81617ac40e9
pablonxh/Pycharm_100DaysOfCode
/D6 - Functions.py
803
3.84375
4
#Functions # def newfunction(): # print("This is your functions") # print(len("number")) # # newfunction() # # # #While Loops # # def circle(): # turn_left() # turn_left() # turn_left() # # def jump(): # turn_left() # move() # circle() # move() # circle() # move() # turn...
2245773a1aaf4e13c6b11fd66b11993dc1ff4665
AerinSwift/Lesson_01
/Lesson_01.py
5,495
4.28125
4
# 1.Поработайте с переменными, создайте несколько, выведите на экран. # Запросите у пользователя некоторые числа и строки и сохраните в переменные, затем выведите на экран. user_string = input("Введите текстовую строку: ") print("Введенная строка: "+user_string) user_number = int(input("Введите целое число: ")) print...
4b3adb598dd38700c4f5e58f3baed50233202cf5
EgorMichel/2021_Michel_infa
/1st week/tort8.py
102
3.703125
4
import turtle as t t.shape('turtle') for i in range(100): t.forward(i * 10) t.left(90)
96c410fc3e5f7a58407157b284ae2229d2da1950
EgorMichel/2021_Michel_infa
/5th week/finak.py
7,102
3.625
4
import pygame from random import randint import time pygame.init() FPS = 60 screen = pygame.display.set_mode((1200, 800)) RED = (255, 0, 0) BLUE = (0, 0, 255) YELLOW = (255, 255, 0) GREEN = (0, 255, 0) MAGENTA = (255, 0, 255) CYAN = (0, 255, 255) BLACK = (0, 0, 0) COLORS = [RED, BLUE, YELLOW, GREEN, MAGENTA, CYAN] #...
f9e1890036e236f32f26b833c3cf7d329c49dc14
migeed-z/small_step_interpreter
/Transform.py
600
3.671875
4
from ast import Expr, Assign def transform(ast_list): """ Transforms an AST list into a single expression :param ast_list: List of AST :return: List of AST """ res_exprs = [] for ast in ast_list: res_exprs.append(transform_expr(ast)) return res_exprs def transform_expr(ast): ...
70c96ccdda8fec43e4dc2d85ba761bae2c4de876
heyimbarathy/py_is_easy_assignments
/pirple_functions.py
978
4.15625
4
# ----------------------------------------------------------------------------------- # HOMEWORK #2: FUNCTIONS # ----------------------------------------------------------------------------------- '''create 3 functions (with the same name as those attributes), which should return the corresponding value for the attrib...
910185af5c3818d848aa569d6e57de868c9cb790
heyimbarathy/py_is_easy_assignments
/pirple_lists.py
1,311
4.15625
4
# ----------------------------------------------------------------------------------- # HOMEWORK #4: LISTS # ----------------------------------------------------------------------------------- '''Create a function that allows you to add things to a list. Anything that's passed to this function should get added to myUni...
e8512576db826d332dea90e3c3a6abde2f09418b
claymaks/python_switch
/python_switch.py
711
3.625
4
def func1(): print("Hello") def func2(): print("Goodbye") def func3(): print("Default") def inline_try(x): try: return int(x) except ValueError: return x switch = { 1 : func1, 2 : func2, } if __name__ == "__main__": import time start = time.time() for i in ...
023a3be16441a18f8217e0aa19744459404ed4d5
vvk2001github/codewars_train
/SimpleEncryption1/simpleencryption1.py
989
4.03125
4
def decrypt(encrypted_text, n): if encrypted_text == None or encrypted_text == '' or n <= 0: return encrypted_text str_len:int = len(encrypted_text) half_str_len = str_len // 2 result: str = ''.ljust(str_len) for j in range(n): res_list = list(result) for i in range(half_str_...
6247819bfefde9ffa5e8b6cbcb2d3ea2ba189aba
vvk2001github/codewars_train
/commonDenominators/commonDenominators.py
632
3.59375
4
def convertFracts(lst): if lst == None or lst ==[] or lst == [[]]: return [] if len(lst) == 1: return lst[0] def gcd(a, b): if b == 0: return a else: return gcd(b, a % b) def lcm(a, b): return a // gcd(a, b) * b lcm_res = lcm(lst[0...
e4e98c9cc3baebeab977ae02f501455038066151
EconomistGrant/2021_Spring
/6.006 Algo/ass/ass0/tests.py
1,371
3.546875
4
import unittest from common import common def common(lists): ''' Input: lists | Array of arrays of positive integers Output: num_common | number of numbers common to all arrays ''' num_common = 0 ################## # YOUR CODE HERE # ################## if len(lists) == 0: ...
a4517342b8814029c3d1a506e2e8edd0b49a8830
andreim9816/Facultate
/Anul II/Sem 2/Inteligenta artificala/Knowledge representation/Lab4-6/8 puzzle/244_Manolache_Andrei_Lab5_Pb2_VAR2.py
11,661
3.546875
4
import copy import time import math """ definirea problemei """ # Rezolvarea problemei 2 (8 puzzle), VAR2. nr_euristica = 1 # Manhattan # Functie care returneaza True daca o pozitie [lin][col] se afla in interiorul unei matrice patratice de dimensiuni L_matrice x L_matrice def interior(lin, col, L_matrice): if ...
7ced50c8e59c51f24cfa8d3af34a4fe8878ce31a
Rushi-Prajapati/python
/assignment_2/prog_2.py
146
3.890625
4
def f(n): if n<=1: return n else: return(f(n-1)+f(n-2)) n = int(input("enter number")) for i in range(n): print(f(i),end=" ")
7b81eaa16d63071a24a954c827a0304167ed07c3
Rushi-Prajapati/python
/assignment_1/prog_10.py
173
4
4
l=list(range(1,101)) odd=list() sum = 0 for n in l: if n%2 !=0 : odd.append(n) sum += n print(sum,"is the sum of odd number between 1 to 100")
29cc26a015801f4d1fe5e4c5ab103118b98e47bf
Segoka/python_learning
/colacao.py
650
4.125
4
print("*****Preparación de Colacao******") leche = input("Primero de todo.... tienes leche? [s/n] ") colacao = input("Y... tienes colacao? [s/n] ") if leche == "s" and colacao == "s": print("Perfecto!! Pon la leche en un vaso luego el colacao y a disfrutar :)") elif leche != "s" and colacao == "s": ...
5045f39041869fd81a8c406159a1bec39e4b7372
abdelilah-web/games
/Game.py
2,707
4.15625
4
class Game: ## Constractor for the main game def __init__(self): print('Welcome to our Games') print('choose a game : ') print('press [1] to play the Even-odd game') print('Press [2] to play the Average game') print('Press [3] to play the Multiplication') self.ch...
4fb937fbdce6560e0a63ae7c71bf97a4983305b7
bghoang/coding-challenge-me
/leetcode/DynamicProgramming/fib.py
313
3.53125
4
class Solution: def fib(self, N: int) -> int: if N == 1: return 1 if N == 0: return 0 first = 0 second = 1 for _ in range(2, N+1): total = first + second first = second second = total return second
b9b5e983017845ef38400a7d8ad8c9e35333d405
bghoang/coding-challenge-me
/leetcode/Other (not caterogize yet)/maxProductThreeNumbers.py
1,411
4.25
4
''' Given an integer array, find three numbers whose product is maximum and output the maximum product. Example 1: Input: [1,2,3] Output: 6 Example 2: Input: [1,2,3,4] Output: 24 ''' ''' First solution: O(nlogn) runtime/ O(logn) space caus of sortings Sort the array, Find the product of the last 3 numbers Find the...
447a319a8258d66b9892e0d3a95b6dee0e18ef34
bghoang/coding-challenge-me
/leetcode/HashMap/intersectionOfTwoLinkedList.py
571
3.734375
4
''' Optimal solution: Use a dict (hashmap), go through each element in list1, save the elements in the hashmap Go through list2, check if there is an element that match an element in the hashmap If there is, then return that element, Else keep going through, If could not find any then return null Runtime: O(n) Space:...
f9d4b2a739dd299f5965f3e05a5e2b1aa054e697
deepthi-tech/dp
/nm.py
137
3.953125
4
n=int(input()) if(n==1 or n==2 or n==3 or n==4 or n==5 or n==6 or n==7 or n==8 or n==9 or n==10): print("yes") else: print("no")
f0008819a37a9f1f8b38dd669a7e180e2b1eace4
sd-2020-30431/assignment-2-andreisas
/CS_app/sqlite_demo.py
599
3.796875
4
import sqlite3 from models import Employee conn = sqlite3.connect('employee.db') conn.row_factory = sqlite3.Row cursor = conn.cursor() #cursor.execute('CREATE TABLE users (id INTEGER PRIMARY KEY, first TEXT, last TEXT)') #cursor.execute('INSERT INTO users VALUES(?, ?, ?)', (1, 'Donald', 'Duck')) #cursor.execute('IN...
3172bb254a6a345218c2e37edac4ecc94246c8da
Vianey25/POO_1720110416
/Semana_2/programa8.py
1,528
3.703125
4
class Calculadora(): ''' Atributos ''' marca = None color = None tipo_de_calculadora = None tamano = None tipo_de_corriente = None fabricacion = None modelo = None material = None lenjuage = None def __init__(self): print("clase calculadora") ...
c503fc48c314befba33ee364ad1dd3e96c0df497
flo2002/network_availability_tester
/network_availability_tester.py
1,032
3.6875
4
# import all the required packages import os import time import datetime # define a function to check, if we can ping def check_ping(): # define the domain, which I want to ping hostname = "google.com" # generate the raw response if I ping the upper hostname response = os.system("ping -n 1 " ...
524646bf92d1076216d95b06881b834afeee827f
nadeeshajay/100daysofPython
/locator.py
309
3.765625
4
row1 = ["X", "X", "X"] row2 = ["X", "X", "X"] row3 = ["X", "X", "X"] row4 = ["X", "X", "X"] map = [row1, row2, row3, row4] print(f"{row1}\n{row2}\n{row3}") x = int(input("Type the row number(x) : ")) y = int(input("Type the coloumn number(y) : ")) map[x-1][y-1] = "O" print(f"{row1}\n{row2}\n{row3}\n{row4}")
72fe17f5f09894b24ed20ba255a2119795fe3a64
nadeeshajay/100daysofPython
/headsORtails.py
172
3.75
4
import random test_seed = int(input('Input a seed number : ')) random.seed(test_seed) side = random.randint(0,1) if side ==1 : print('Heads') else : print('Tails')
372923582ba1ccbe0bee1dcb363561fc627bd4dd
hawksong/pythontest
/pylearn/src/spider1/stuent.py
453
3.625
4
''' Created on 2017年12月11日 @author: user ''' """ """ class Student(object): ''' this is a Student class ''' count = 0 books = [] def __init__(self, name, age): self.name = name self.age = age pass #print (Student.__name__) #print (Student.__d...
21d6bd9aa573549ceb4906dd18ff4eba0c75d31a
kamalikap/Simple-Python-Programs
/Basic_Programs/json_conversion.py
901
3.71875
4
import json # Write to a JSON file data = {} data['people'] = [] data['people'].append({ 'name': 'Scott', 'website': 'stackabuse.com', 'from': 'Nebraska' }) data['people'].append({ 'name': 'Larry', 'website': 'google.com', 'from': 'Michigan' }) data['people'].append({ 'name': 'T...
69e9894aba9365a843e2c77364ef70b04ff9925b
kamalikap/Simple-Python-Programs
/Object-Oriented-Programming/3. Static_method.py
1,211
3.765625
4
class Employee: num_of_emps = 0 raise_amount = 1.04 def __init__(self,first,last, pay): self.first = first self.last = last self.pay = pay self.email = first + "." + last + '@company.com' Employee.num_of_emps += 1 def fullname(self): return '{} {}' .format(self.first, self.last) def apply_raise(...
ec337eb5ab273d3697103a3eaed8ff5807563f36
annafeferman/laboratorna_robota_6
/lab6_4.py
466
4
4
while True: while True: try: t = int(input('Input minutes: ')) break except(ValueError, TypeError): print('Incorrect input!') if 1 <= (t % 6) <= 3: print('Green') elif (t % 6) == 4: print('Yellow') else: print('Red') print(f...
a8be92104364d6d3f243ba157160abf88b054213
liupeiyu/LeetCode
/theoryandalgorithms/FindRepeatNumber.py
818
3.71875
4
#encoding:utf-8 ''' 找出数组中重复的数字。 在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。 示例 1: 输入: [2, 3, 1, 0, 2, 5, 3] 输出:2 或 3 ''' class Solution: def findRepeatNumber(self, nums:[list]) -> list: di={} result=[] for i in nums: if i n...
2eca1c0eaeaa32441f7599bf887eac5ba65bd143
lj015625/CodeSnippet
/src/main/python/string/reverseWords.py
1,517
4
4
# O(N) time O(N) space def reverseWordsInString(string): reversedWords = [] # reverse the whole string for word in string[::-1].split(' '): # re-reverse the word reversedWords.append(word[::-1]) return " ".join(reversedWords) # O(N) time O(N) space at character level def reverseWordsI...
40d808c8f3d2896726f13b3af4322bef642c35a4
lj015625/CodeSnippet
/src/main/python/math/primeToN.py
477
3.953125
4
"""Given an integer NN, write a Python function that returns all of the prime numbers up to NN. """ def prime_numbers(N): primes = [] for num in range(2, N): # all prime numbers are greater than 1 # for i in range(2, num): # if (num % i) == 0: # break # e...
26b2d8323f01fbfbb1bf214076df886fe8592539
lj015625/CodeSnippet
/src/main/python/math/shortestDistance.py
1,796
4.09375
4
""" Let’s say we have a group of N friends represented by a list of dictionaries where each value is a friend name and their location on a three dimensional scale of (x, y, z). The friends want to host a party but want the friend with the optimal location (least distance to travel as a group) to host it. Write a funct...
2e221c7dd3bb4e3e8825ace9eb163e7e76a0e690
lj015625/CodeSnippet
/src/main/python/string/stringRecurringChar.py
513
4.09375
4
"""Given a string, write a function recurring_char to find its first recurring character. Return None if there is no recurring character. Treat upper and lower case letters as distinct characters. You may assume the input string includes no spaces.""" def recurring_char(input): seen = set() for char in input:...
cb09f4b47168ed1b2da14bdedfd92ed3d85fe226
lj015625/CodeSnippet
/src/main/python/array/countSmaller.py
1,234
3.859375
4
from sortedcontainers import SortedList, SortedDict class Solution(object): """ Count number of integers that is smaller than current number in array from left to right. """ def countSmaller(self, nums): """ :type nums: List[int] :rtype: List[int] """ output = ...
1e024ce6147c58ee87df7809993dadfd268fb778
lj015625/CodeSnippet
/src/main/python/math/normalTruncatedDist.py
785
3.65625
4
"""Given a percentile_threshold, sample size N, and mean and standard deviation m and sd of the normal distribution, write a function truncated_dist to simulate a normal distribution truncated at percentile_threshold. """ import numpy as np import scipy.stats as st def truncated_dist(m, sd, n, percentile_threshold):...
17756e03f8022ead554e7ec67add12ea22a45cb5
lj015625/CodeSnippet
/src/main/python/stack/minMaxStack.py
1,932
4.125
4
""" Write a class for Min Max Stack. Pushing and Popping value from the stack; Peeking value at top of the stack; Getting both minimum and maximum value in the stack at any time. """ from collections import deque class MinMaxStack: def __init__(self): # doubly linked list deque is more efficient to imple...
c23bd89f460b4c0fc6cf0d97f143daa8cc92ab8a
lj015625/CodeSnippet
/src/main/python/tree/minDirectionalGridTraversal.py
1,837
3.78125
4
""" You are given the layout of a rectangular building with rooms forming a grid. Each room has four doors to the room to the north, east, south, and west where exactly one door is unlocked and the other three doors are locked. In each time step, you can move to an adjacent room via an unlocked door. Your task is to d...
1eb9ea42636070ce4ff1c3d55b47af033e426a4a
lj015625/CodeSnippet
/src/main/python/array/arrayEvenOdd.py
621
3.96875
4
class Solution(object): """ Rearrange an array to even and odd """ def even_odd (self, A): next_even, next_odd = 0, len(A) - 1 while next_even < next_odd: # if it is even then increment next_even pointer if A[next_even] % 2 == 0: next_even += 1 ...
941a851de51adbd3bf0c3b1fd5a3d0d9dffead41
lj015625/CodeSnippet
/src/main/python/dp/knapsackProblem.py
2,038
3.84375
4
""" Given an array of arrays where each subarray hold two integer values represent an item. The first value is item's value, the second value is item's weight. You are also given maximum capacity. Your goal is find maximum combined value of items without exceed capacity. """ # O(nc) time O(c) space where n is number ...
b2add09722df9057898576f31849a1ed2e15d9b5
lj015625/CodeSnippet
/src/main/python/math/rmse.py
248
3.75
4
import math def calculate_rmse(y_pred, y_true): sum = 0 n = len(y_pred) for i in range(n): sum += (y_true[i] - y_pred[i])**2 return math.sqrt(sum/n) y_pred = [3,4,5] y_true = [3,4,5] print(calculate_rmse(y_pred, y_true))
eba700f8e66ac1f029d9e6875d2c80cb7c7c66f7
lj015625/CodeSnippet
/src/main/python/tree/binarySearchTree.py
1,334
3.828125
4
# This is the class of the input tree. Do not edit. class BST: def __init__(self, value): self.value = value self.left = None self.right = None # avg O(log(n)) time O(1) space # worst O(n) time O(1) space def findClosestValueInBst(tree, target): currentNode = tree closest = currentN...
f5da06da78a80316d1fc71d9d053ea3d123b223d
lj015625/CodeSnippet
/src/main/python/math/linearReg.py
794
3.578125
4
import numpy as np import matplotlib.pyplot as plt # generate x and y x = np.linspace(0, 1, 10) y = 1 + x + x * np.random.random(len(x)) # assemble matrix A A = np.vstack([x, np.ones(len(x))]).T # turn y into a column vector y = y[:, np.newaxis] AT = np.transpose(np.array(A)) print("A_T = ", AT) # calculating transp...
e2dd0a447a252f904e5b7e88709f8ae2e5f08a16
lj015625/CodeSnippet
/src/main/python/dp/minNumberOfBills.py
1,144
3.6875
4
""" Count the minimum number of bills to get to an amount. If cannot find a combination then return -1. """ # O(nd) time O(n) space n is amount d is len of bills def minNumberOfCoinsForChange(amount, bills): if amount <= 0: return 0 minNumOfBills = [float('inf') for _ in range(amount + 1)] # min...
be3b497959a4393ca2217a6af33c4ca131ad9bd0
lj015625/CodeSnippet
/src/main/python/date/calendar.py
127
3.765625
4
import calendar month,day,year=map(int,input().split()) print((calendar.day_name[calendar.weekday(year, month, day)]).upper())
f2e670471bfa9bcac1e5f983ecdb0240eeaaf1f2
lj015625/CodeSnippet
/src/main/python/array/sumOfTwoNum.py
1,598
4.125
4
"""Given an array and a target integer, write a function sum_pair_indices that returns the indices of two integers in the array that add up to the target integer if not found such just return empty list. Note: even though there could be many solutions, only one needs to be returned.""" def sum_pair_indices(array, targ...
a7c6bd9c2f79c33c32646b3f452ed91c37b143ed
lj015625/CodeSnippet
/src/main/python/bit/randomNumberGenerator.py
609
3.640625
4
import random class Solution(object): def uniform_random(self, lower_bound, upper_bound): random_number = upper_bound - lower_bound + 1 while True: result, i = 0, 0 # generate a number in range while (1 << i) < random_number: zero_one_random = ra...
153468d2ee32d18c1fe7cd6ee705d0f2e38c6ac2
lj015625/CodeSnippet
/src/main/python/string/anagram.py
626
4.28125
4
"""Given two strings, write a function to return True if the strings are anagrams of each other and False if they are not. A word is not an anagram of itself. """ def is_anagram(string1, string2): if string1 == string2 or len(string1) != len(string2): return False string1_list = sorted(string1) str...
0ec7e4634e85cfae038a0bea9490a6017fc03c80
lj015625/CodeSnippet
/src/main/python/dp/levenshteinDistance.py
2,286
3.75
4
""" Write a function that takes in two strings and returns the minimum number of edit operations (insert, delete, substitute) a char to obtain the second string. """ # O(nm) time | O(nm) space def levenshteinDistance(str1, str2): edits = [[x for x in range(len(str1) + 1)] for y in range(len(str2) + 1)] # [[0,...
0fc4dfbc158bfe4b0ae056234ace677f183041a7
lj015625/CodeSnippet
/src/main/python/basics/stack.py
199
3.515625
4
from collections import deque myStack = deque() myStack.append('a') myStack.append('b') myStack.append('c') deque(['a', 'b', 'c']) print(myStack.pop()) print(myStack.pop()) print(myStack.pop())
ce33d6bb0f0db42a8a0b28543f1ea6895da0d00c
lj015625/CodeSnippet
/src/main/python/tree/binarySearch.py
1,055
4.1875
4
def binary_search_iterative(array, target): if not array: return -1 left = 0 right = len(array)-1 while left <= right: mid = (left + right) // 2 # found the target if array[mid] == target: return mid # if target is in first half then search from the st...
71ceb723b11835af04b120753f37b61a73314990
anshtyagi23/AP-Practical-File
/9)Writing and understanding program in Python/addition.py
123
3.890625
4
def add(x,y): total = float(a)+float(b); return total print("Enter two number:") a = input() b= input() print(add(a,b));
9cbd1e12462dca500576a0e85fe787354a95509f
dannywu0820/Python_Practice
/design_patterns/abstract_factory/Gun.py
282
3.765625
4
from abc import ABCMeta, abstractmethod class Gun(metaclass=ABCMeta): @abstractmethod def toString(self): pass class UFOGun(Gun): def toString(self): return "1000 damage" class RocketGun(Gun): def toString(self): return "10 damage"
84627275b770e477defe2c643614815b629f46f7
sanuma02/sent
/app.py
1,916
3.515625
4
# General: import tweepy # To consume Twitter's API import pandas as pd # To handle data import numpy as np # For number computing # For plotting and visualization: from IPython.display import display import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import seaborn as sns # We ...
43321f1dafa31535a447f5c9a42cb07ef7f192ab
prajwalkm/text_spider
/src_with_license/src/build/scripts-2.7/text-spider
2,202
3.59375
4
#!python # Copyright (c) 2017, Pan Labs (panorbit.in). # This file is licensed under the MIT License. # See the LICENSE file. import sys from text_spider.spider import Spider #this function prints help commands to run crawler def get_help(): print(""" Usage: text-spider [commands] [URL] [allowed_domain] [...
137491470eeae0ee18655f0c7283f2e4022f5df1
ozbej/Faculty-of-Computer-and-Information-Science
/Undergraduate/Python programming/naloga7 - menjave.py
2,213
3.640625
4
#Obvezna def zamenjaj(s, i, j): s[i], s[j] = s[j], s[i] def zamenjan(s, i, j): t = s[:] zamenjaj(t, i, j) return t #Dodatna def uredi(s): t = s[:] menjave = [] oznaka = len(s) - 1 menjano = True while menjano: menjano = False for i in range(0, oznaka): ...
104c71d19cad29f8ca83d2eb184ca23df508f3db
dellsystem/ssuns-2011
/options
669
3.59375
4
#!/usr/bin/env python import sys import string # Convert a list of options into an html select element if len(sys.argv) < 2: print "Usage: ./options filename" exit(1) file = open(sys.argv[1]) i = 0 for line in file: i = i + 1 """ # First make the country name usable for the value lowercase = ...
0ecfc8d40c1d7eba616676d03f04bb9bf187dc09
xamuel98/The-internship
/aliceAndBob.py
414
4.4375
4
# Prompt user to enter a string username = str(input("Enter your username, username should be alice or bob: ")) ''' Convert the username to lowercase letters and compare if the what the user entered correlates with accepted string ''' if username.lower() == "alice" or username.lower() == "bob": pr...
91d461a46d16bbc0d4f64edd22fe751b732c08de
shareef-u-din/Datastructures-Python3
/Search/demo.py
280
3.5625
4
from Search import BinarySearch from Search import LinearSearch list=[10,20,30,40,50,60] #binary search test print(" Binary Seach Return Value : ",BinarySearch.binary_search(list,-1)) #linear search test print(" Linear Seach Return Value : ",LinearSearch.linear_search(list,60))
6c45b1932cf00bf308d9b4d1db7d02668a4f1a15
SiddharthJadhav99/Python_Basics
/loops.py
212
4.09375
4
name="Harry" for character in name: print(character) for i in [0,1,2,3,4,5]: print(i) for j in range(6): print(j) names=["Harry", "Ron", "Hermione"] for name in names: print(name)
0db46af767d153c8124d7a8f3e5f8835ec4787a2
lavanyagadde/python
/ICP6/SourceCode/task.py
1,229
3.546875
4
# Kmeans, Null values, elbow method and silhouette score import pandas as pd from sklearn.cluster import KMeans import matplotlib.pyplot as plt from sklearn import metrics # reading the data from file cc_dataset = pd.read_csv('CC.csv') # finding the null values nullvalues = cc_dataset.isnull().sum() print(nullvalues)...
762fbdde61f1e98e52ac08ef17c84bf0ce3199ec
lavanyagadde/python
/ICP4/SourceCode/svm_python.py
886
3.578125
4
import pandas as pd from sklearn.model_selection import train_test_split from sklearn.svm import SVC from sklearn.metrics import classification_report, accuracy_score # reading the dataset glass_data = pd.read_csv('glass.csv') # x_train = glass_data[['RI','Na','Mg','Al','Si','K','Ca','Ba','Fe']] x_train = glass_data.d...
db3bf927534efa97fb2b307ccf7b6a5a41f4b660
sho-87/pyutils_sh
/pyutils_sh/gaze.py
3,192
3.765625
4
""" Functions for calculating various gaze/eye-tracking related statistics. """ import numpy as np def cross_correlation(person1, person2, framerate=25, constrain_seconds=2): """ Calculate cross-correlation between two gaze signals. This function takes 2 lists/arrays of data, each containing an individu...
bf00a004feaaea36f1fff17c0a3a7b8e89dadc90
dusda/magique
/data_builders/synergies/analyze_decks_by_card.py
3,579
3.625
4
#!/usr/bin/env python3 import re import json from pprint import pprint import itertools import sys # This file looks at each list of decks, and extracts a list of cards present in each deck. Then it computes # the conditional probability, given that card B appears in a deck, that card A also appears in a deck. if le...
4a8dd8cb11f1f8fcb2d94733909620c16c7ce547
tek-life/algorithm-practice
/236_lowest_common_ancestor_of_a_binary_tree.py
1,800
3.84375
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None #Algorithm 1. May lead out of memory class Solution(object): def DFS(self,target, root, li): if not root: return None if root is...
3fd636b94e876d923862d5c30b36c30fcef28fdf
tek-life/algorithm-practice
/113_path_sum_2.py
1,469
3.828125
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 DFS(self,root,li,sum): """ More clear way if not root.left and not root.right: if...
ed4ebe2d41a2da81d843004f32223f0662e59053
ParulProgrammingHub/assignment-1-kheniparth1998
/prog10.py
308
4.125
4
principle=input("enter principle amount : ") time=input("enter time in years : ") rate=input("enter the interest rate per year in percentage : ") def simple_interest(principle,time,rate): s=(principle*rate*time)/100 return s print "simple interest is : ",simple_interest(principle,rate,time)
3d899dae2b6744c2bae839703e0ef15b6ada26ef
JinuAugustine98/Tea-Quality-Analyser
/contour.py
1,254
3.515625
4
import cv2 import numpy as np def contour_area(input_image, save_path, calibration): img = cv2.imread(input_image, cv2.IMREAD_UNCHANGED) #convert img to grey img_grey = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) #set a thresh thresh = 100 #get threshold image ret,thresh_img = cv2.threshold(img_...
dfaba9621d7f3d1fc130280d471823bde8f3ab90
darcosubin/newre
/len.py
195
3.5
4
#!/usr/bin/env python words=['cat','window','supercalifragilisticexpialidocious']; for w in words: print w, len(w); for w in words[:]: if len(w)>6: words.insert(1,w); print words;
c886cc3c2a913230be66e1f51813a9f1f6e6fadc
Zestx/helloworld.py
/helloworld.py
586
3.90625
4
######################################## # Simple 'Hello World' python program. # ######################################## avar, bvar = 12.0, 2 str1 = "Hello" str2 = "World" int1 = 12 cvar = avar + bvar print (str1 + " " + str2) print (avar) print (float(bvar)) print ("result {w1} {w2}".format(w2 = str1, w1 = str2)) ...
8885ad50f6f851661dedd724a1b7e438d299fddc
WangDongDong1234/python_code
/part2/26.py
914
3.5
4
# class B: # def __getitem__(self, item): # print("执行我了",item) # return "bbb" # # def __setitem__(self, key, value): # print(key,value) # # b=B() # r=b["a"] # print(r) # b["b"]="B" # class C: # def __getitem__(self, item): # return getattr(self,item) # # def __setitem__...
21943f3457560dccdecc3ccc2337176e0ea98173
WangDongDong1234/python_code
/part2/21.py
928
3.703125
4
# l=["a","b","c"] # #it=iter(l) # it=l.__iter__() # #next=next(it) # next=it.__next__() # print(next) # class Mylist: # def __init__(self): # self.list=[1,2,3] # # def __len__(self): # return len(self.list) # # l=Mylist() # print(len(l)) # class Single: # __ISINCTANCE=None # def __new_...
1d69b67d3668372e49dbdb53c135b4770a11d98b
WangDongDong1234/python_code
/牛客/01输出指定长度子串.py
135
3.703125
4
str=input().strip() n=int(input()) if n>len(str): print(-1) else: for i in range(n,len(str)): print(str[i-n:i],end=" ")
3993689551ceed1cf1878340872846df0863556e
WangDongDong1234/python_code
/高级算法复习/ppt复习/2-2冒泡排序.py
268
4.1875
4
""" 冒泡排序 """ def bubbleSort(array): for i in range(len(array)-1): for j in range(0,len(array)-1-i): if array[j]>array[j+1]: array[j],array[j+1]=array[j+1],array[j] array=[2,1,5,6,3,4,9,8,7] bubbleSort(array) print(array)
dfd65b916322b90e93f9ad1073f313e3cf4f78b1
WangDongDong1234/python_code
/afterclass/homework3/1.py
384
3.6875
4
str1=input() str2=input() same_str=[] for item in str1: if item in str2: same_str.append(item) # print(same_str) sam_str="" for item in same_str: sam_str+=item # print(sam_str) tmp_str1="" tmp_str2="" for item in str1: if item in sam_str: tmp_str1+=item for item in str2: if item in sam_s...
214d221db50ebc4a72206fe41be839cd0839c9d0
WangDongDong1234/python_code
/part3/12管道.py
921
3.59375
4
from multiprocessing import Pipe from multiprocessing import Process from multiprocessing import Lock import time #用管道实现生产者和消费者 def producer(p,l): parent, son=p son.close() for i in range(10): parent.send('hello'+str(i)) parent.close() def consumer(p,l,name): parent, son = p parent.clos...
5de413cce14f94e7bba0776620f47e8d21874efe
WangDongDong1234/python_code
/part2/17.py
222
3.609375
4
class A: pass class B(A): pass b=B() print(type(b) )#<class '__main__.B'> print(type(b) is B)#True print(isinstance(b,B))#True print(isinstance(b,A))#True print(issubclass(B,A))#True print(issubclass(A,B))#False
8a32cb8681927e9a76d4f5bc82fabde06bd40197
WangDongDong1234/python_code
/力扣/动态规划/04不同路径.py
1,441
3.59375
4
""" 一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为“Start” )。 机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为“Finish”)。 问总共有多少条不同的路径? 思路:动态规划 1 只能向下或者向右走。所以当在i=0 或者 j = 0时 等于1 2 dp[i] [j] = dp[i-1][j] + dp[i][j-1]; """ class Solution: def uniquePaths(self, m: int, n: int) -> int: array=[] for i in range(m): ...
c6085b2e343dfbf75a7cc155e73d0a58bd69d842
WangDongDong1234/python_code
/高级算法复习/第一次课后作业/02-2最大字段和问题.py
2,597
3.6875
4
""" https://www.cnblogs.com/aabbcc/p/6504605.html 分治法求解 分治法思路如下: 将序列a[1:n]分成长度相等的两段a[1:n/2]和a[n/2+1:n],分别求出这两段的最大字段和,则a[1:n]的最大子段和有三中情形: [1]、a[1:n]的最大子段和与a[1:n/2]的最大子段和相同; [2]、a[1:n]的最大子段和与a[n/2+1:n]的最大子段和相同; [3]、a[1:n]的最大字段和为,且1<=i<=n/2,n/2+1<=j<=n。 可用递归方法求得情形[1],[2]。对于情形[3],可以看出a[n...
ce24b105840a4eb1d62695b745d92afdcd38e9b3
WangDongDong1234/python_code
/classroom/homowork6/5.py
182
3.640625
4
n=int(input()) def fun(n): if n==1: return 1 if n==2: return 2 return fun(n-2)+fun(n-1) for i in range(n): test_n=int(input()) print(fun(test_n))
8893ee5abc4e4d7f6c733e0578a47a929eb78345
WangDongDong1234/python_code
/afterclass/homework3/8.2.py
1,674
3.75
4
#归并排序的非递归实现 def merge(seq,low,mid,height): """合并两个已排序好的列表,产生一个新的已排序好的列表""" # 通过low,mid height 将[low:mid) [mid:height)提取出来 left = seq[low:mid] right = seq[mid:height] # print('left:', left, 'right:', right) k = 0 #left的下标 j = 0 #right的下标 result = [] #保存本次排序好的内容 #将最小的元素依次添加到result...
58551b6e4d95df3a12f266bc553b324f5bd14794
WangDongDong1234/python_code
/afterclass/homework5/04.py
3,842
3.53125
4
"""   该题关键在于如何划分各L型骨牌所在位置区域。我们发现,L型骨牌占三个方格,我们可以把棋盘从中央分为四块,那么这四块子棋盘中仅一块是有特殊方格的,可以用一块骨牌使得其他三块子棋盘均被覆盖。以此为原则,无论这种分法是否最终可解,我们首先保证了每个子棋盘都有一个特殊方格,所以,分治的模型就出来了。 """ n=int(input()) for m in range(n): start_special_str = input().strip() start_special = [int(item) for item in start_special_str.split(' ')] # 开始的标号 ...
94d8572e332155dbd891f51eecdd01f7fde330a8
pandaking969/chapter7
/PIPI 3/main.py
1,164
3.96875
4
import math #Exercitiu 1 Write a program to unpack a tuple in several variables x = (1, 2, 3, 4, 5, 6, 7, 8, 9, "maine", False, None) #x1, x2, x3, x4 = x Aci depinde de numaru de obiecte din tupel #print(x1) #print(x2) #Exercitiu 2 #Write a program to add an item based on user input y = int(input()) x += (y, ...
6c6cd89c3c9e5b783c78eba63d85736272909e6b
quadrant26/python
/Tkinter/scale.py
438
3.515625
4
from tkinter import * master = Tk() ''' Scale tickinterval=5 # 刻度表 resolution=5 # 精度 == 步长 length=200 # 长度 ''' s1 = Scale(master, from_=0, to=40, tickinterval=5, length=200) s1.pack() s2 = Scale(master, from_=0, to=200, orient=HORIZONTAL, resolution=15, length=600) s2.pack() def show(): pr...
e4d1896cd27eb4a22b52478fdff6c168facbcb34
quadrant26/python
/oop/game.py
757
3.515625
4
import random class Game: gui = 1 fish = 10 fish_move = 1 gui_tili = 100 def __init__(self): print("Game start......") self.guidict = dict() self.guidict.setdefault("gui") self.guidict['gui'] = [random.randint(0,10), random.randint(0,10)] # 设置乌龟出现的位置 ...
5afbefd90034b76d2b90d53ce5a09ae5d411bf8a
quadrant26/python
/oop/stack.py
1,229
3.984375
4
class Stack: def __init__(self): self.s = "fishc" def isEmpty(self): if self.s: return True else: return False def push(self, x): self.s = str(x) + self.s print(self.s) def pops(self): one = self.s[0] self.s ...
fb58fe7a42a7c3209db8cebd62330578bc64b3f9
quadrant26/python
/magic/m_ex_42.py
1,210
3.953125
4
# 计算时间差值 import time as t class Time: def __init__(self, func, number=100000): # self.unit = ["年", "月", "日", "时", "分", "秒"] self.begin = 0 self.end = 0 self.prompt = "未开始计时" self.default_time = t.perf_counter self.func = func self.number = number ...