blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
ffc1682c80e2832036efcca28d793d23926e97a3
tpobst/temp
/ex15.py
1,088
4.0625
4
#import argv from sys from sys import argv #argv wants a filename with the run command (%run C:/Users/Tim/temp/ex15.py C:/Users/Tim/temp/ex15_sample.txt #) #argv unpacks the variables script and filename and filename is assigned the file typed with the run command script, filename = argv #the variable txt is assigned ...
8c10c922a60bd31d3973f50e06872d10b8bbd449
lizzzcai/leetcode
/python/dynamic_programming/0887_Super_Egg_Drop.py
4,325
3.921875
4
''' 03/06/2020 887. Super Egg Drop - Hard Tag: Dynamic Programming, Binary Search, Math You are given K eggs, and you have access to a building with N floors from 1 to N. Each egg is identical in function, and if an egg breaks, you cannot drop it again. You know that there exists a floor F with 0 <= F <= N such t...
7f6fbfb8c373cbe1e36333e2343bbe99550e1927
dimk00z/summer_yandex_algorithmic_course
/Homework_2/D_More_than_your_neighbors/D_More_than_your_neighbors.py
485
3.515625
4
def count_neighbors(number_list): neighbors_count = 0 for element_position, element in enumerate(number_list[1:-1:]): if (element > number_list[element_position]) \ and (element > number_list[element_position+2]): neighbors_count += 1 return str(neighbors_count) with o...
3d2d3a46dbe04db8963f89891cfd0c7962ce5e21
hassxa96/Programacion
/EjerciciosPOO/Ejercicio8.py
1,748
3.84375
4
""" Desarrollar un programa que conste de una clase padre Cuenta y dos subclases PlazoFijo y CajaAhorro. Definir los atributos titular y cantidad y un método para imprimir los datos en la clase Cuenta. La clase CajaAhorro tendrá un método para heredar los datos y uno para mostrar la información. La clase PlazoFijo t...
17b3fab549301f28a5b5fbfc0e631a2589e2d253
maheshagadiyar/newproject
/two functions with argument.py
183
3.546875
4
def div(a,b): return a/b def squareroot(c): return c**(1/2) def square(d): return d*d def cube(e): return e**3 result=cube(square(squareroot(div(45,5)))) print(result)
8f89b898169528e3c644c27b845b795e60dfeedb
RyanFTseng/Projects
/regex/phonenumber regex.py
138
3.84375
4
import re print('enter number') x=input() a=re.match('\d{3}-\d{3}-\d{4}',x) if a == None: print('not found') else: print('found')
d1ce894430d7d2a2972be43f04796755940f97ce
ispastlibrary/Titan
/2015/AST1/vezbovni/Dejan/10.py
294
3.59375
4
lista1 = [1, 2, 3] lista2 = [5, 4, 10] #print(lista[2]) #lista=lista1+lista2 import numpy as np #lista1=np.array([1, 2, 3]) #for i in range(len(lista1)): # print(i) #lista1.insert(2, 93) #print(lista1) #k = 100 #l = 200 #b = 100 #x=np.arange(k, l, b) #print(x) a = np.sin(np.pi/2) print(a)
3141389bb519e9d9e3b739cae0fd5c442d8c872a
jackrapp/python_challenge
/PyPoll/main.py
1,844
3.890625
4
#election data columns: voter ID, county, candidate import os import csv total = 0 winner= 0 candidate_list={} #function for adding name and votes to dictionary def sort_list(name): if name in candidate_list: #find vote count votes = candidate_list[str(name)] #increase vote count by 1 ...
de7bc4e69b24263ad4be5f8bf6bc3a05c19996aa
dletk/COMP380-Spring-2018
/openCV_code/inclass_activity_1/mileStone_3.py
580
3.5625
4
import cv2 image = cv2.imread("TestImages/SnowLeo2.jpg") # Draw a cile around the leopard's head cv2.circle(image, (120, 130), 70, (207, 142, 27), thickness=3) # Draw a rectangle over its body cv2.rectangle(image, (190, 100), (530, 300), (0, 0, 120), thickness=cv2.FILLED) # Draw some lines as the tail for i in rang...
ced974a774b0623bde93666c8b4306998e4ecda1
ibrahimnagib/Game-of-Life
/Life.py
8,795
4.4375
4
# Life.py # Ibrahim Nagib # In 2422 class Abstract_Cell: """ class Abstract_Cell creates Abstract_Cell objects that can become either a Fredkin_Cell or a Conway_Cell, both are derived from this Parent class """ def __init__(self, symbol): self.symbol = symbol self.live_neighbo...
c04f1a5ea0f0eb58b2f35b6954e87d8f328d3367
EtsuNDmA/stud_tasks
/Python_functions/task_7.py
2,114
3.953125
4
# -*- coding: utf-8 -*- VOWELS = 'a', 'e', 'i', 'o', 'u', 'y' def string_to_groups(string): list_words = string.split() assert len(list_words) == 3, 'String have to consist of exactly 3 words' result = {} for word in list_words: group0 = set() group1 = set() group2 = set() ...
517e53b5379a247f2289835692d6a3e37ab785f5
luhu888/python-Demo
/tuple.py
870
4.0625
4
#!/usr/bin/python #-*- coding: UTF-8 -*- __author__ = 'Administrator' ''' classmates=['ha','en','yu','wo','ta'] classmates.insert(1,'luhu') classmates.append('ll') classmates.append('ll') classmates.append('ll') classmates.pop(2) classmates[3]='lll' print classmates list=[12,23,2,34,[1,2,3,4,5,],89,'ll'] #list里面可以嵌套...
90fa1697d1f295b92a6a6ed8bb66f744d5cb16b7
NicolasStefanelli/Codex
/c_lib/files.py
5,215
3.859375
4
""" Author:Jarvis Lu Date: 2/27/2020 This file contains the File class. The majority of editing of a file's content happens within the file class """ from .import include from .import function from .import variable from file_io import writer """ Initialization of the File class @param file_path...
3ee372ca4398acf8e80e8aec9d533273e23241c3
clondon/check_emails
/checkmails.py
2,476
3.90625
4
# Queue and threads in Python # https://www.youtube.com/watch?v=NwH0HvMI4EA # Import Queue module from queue import Queue # Import threading modules import threading # Import time module for using stop watch import time # Net work sockets import socket # email protocols import smtplib # Setup Threading queue pr...
0a01d0f7fb97a32864d822ce91db5f501e5850a6
mhunsaker7/lc101
/crypto/helpers.py
733
3.90625
4
import string def alphabet_position(letter): lower_letter = letter.lower() alphabet = "abcdefghijklmnopqrstuvwxyz" return alphabet.index(lower_letter) def rotate_character(char, rot): if str(char) in string.digits: return char elif str(char) in string.punctuation or str(char) in string.dig...
fbb5785a4eebf34e1d5ee1b00f06361b975796c7
kangli-bionic/Coding
/python_learning/6.00.2x/week1/greedy.py
2,221
4.3125
4
#python3 class item(object): """ creates an instance of class object item """ def __init__(self,name,value,weight): self.name=name self.value=value self.weight=weight def __str__(self): return self.name+' :<'+str(self.value)+','+str(self.weight)+'>' def getName(...
d0a00a29547240e8b69018059ea7e13977a50dc1
thorn3r/sudokuSolver
/stripper.py
352
3.53125
4
class Stripper: @staticmethod def strip(fileName): with open(fileName) as f: cont = f.read() cont = cont.strip() #strip out newline chars l = [char for char in cont if '\n' not in char] #convert chars to ints l = [int(c) for c in l] ...
f0480d2f5fb8f8557702eef94fb2bfec6ee6b4d6
tarunluthra123/Competitive-Programming
/Leetcode/Validate Binary Search Tree.py
491
3.84375
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isValidBST(self, root: TreeNode, minVal = -(1<<32), maxVal = (1<<32)) -> bool: if not root: ...
b0a88105d8cec9a6334b45b562f74c673bd6dd74
Ming-H/leetcode
/59.spiral-matrix-ii.py
407
3.515625
4
# # @lc app=leetcode id=59 lang=python3 # # [59] Spiral Matrix II # # @lc code=start class Solution: def generateMatrix(self, n: int) -> List[List[int]]: """ !!!!!!!!!!!!!!!!!!!!!!!! """ matrix, l = [], n*n+1 while l > 1: l, r = l - len(matrix), l ma...
ac945bd059d1f034b479695819a469c4dd1ad691
oxnz/sketchbook
/sat/indexedsat.py
2,473
3.703125
4
""" Solve a SAT problem by truth-table enumeration with pruning and unit propagation. Sped up with an index from each variable to the clauses using it. """ ## solve([]) #. {} ## solve([[]]) ## solve([[1]]) #. {1: True} ## solve([[1,-2], [2,-3], [1,3]]) #. {1: True, 2: False, 3: False} import sat from sat import assig...
865667c9ac05a7bfaa7bcf0eb7f3b3a698fd1484
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/ethan_nguyen/lesson10/mailroom_fp.py
6,965
3.65625
4
import sys, os import pytest from functools import reduce #create a donor_db as a dict donor_db = {"William Gates, III": [653772.32, 12.50], "Jeff Bezos": [877.33], "Paul Allen": [663.23, 47, 10.50], "Mark Zuckerberg": [1663.23, 4300.87, 10432.0], "Donald Trump": [50000...
f36e25d2a73a3fffed9c19ae93745ae5b7bb2972
Brycham/205-project
/Crop.py
285
3.515625
4
# Thomas Lopes # 05/12/2018 # This code takes a full path and return the filename def crop(sentence): path = "" for letter in sentence: if(letter == "/"): path = "" else: path += letter return path print(crop("C:/Users/Thomas/205git"))
01c6492a90f3c9588bbd9317405671da2c5b0fa4
udamadu11/Serial_number_tool
/Improve.py
1,011
3.59375
4
import xlsxwriter file_name = input("Enter File name: ex: file.xlsx : ") pattern = input("Enter Pattern: ex: 01H : ") start_number = int(input('Start Number : ex: 4654900 : ')) end_number = int(input('End Number : ex: 4656900 : ')) first_row = input("Enter First Row name : ex: IGT8_0.6M / LED : ") second_row = input("E...
74c6107a790191f52d504ca37d29d182e3992e33
sachaBD/engg1300-week1-B-extra-content
/resistor_uncertainty.py
1,866
3.953125
4
import random import matplotlib.pyplot as plt """ Generate the combined series resistance for n resistance with a value resistance and a random tolerance. """ def n_series_resistors(n, resistance, tolerance): total = 0 for i in range(0,n): actualR = resistance * ( 1 - tolerance * (random.random() * 2 ...
db736317d33df2c83577cc8156abf08096c6b002
tesera/prelurn
/prelurn/describe.py
2,867
3.53125
4
"""Functions for describing data""" import numpy as np import pandas as pd from collections import OrderedDict def _pandas_describe(df, **kwargs): """ Wrapper to dataFrame.describe with desired default arguments :param df: data frame :param **kwargs: keyword arguments to DataFrame.describe """ re...
d4150298be286c6105bf705205aa35f3b04f7d63
kenrick90/Regex-Substitution
/Regex Substitution.py
253
3.71875
4
import re dict = {" && ":" AND ", " || ":" OR "} para=[] l = int(input()) for i in range(l): para.append(input()) for line in para: line = str(re.sub(r" &&(?= )"," and",line)) line = re.sub(' \|\|(?= )',' or',line) print(line)
c0fa97c9bce9c9a9a9fcd1c6ca637b5d0cdc42f7
joseph-mutu/Codes-of-Algorithms-and-Data-Structure
/Leetcode/[171]Exceel 表格数字 -- 逆序.py
458
3.703125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2020-03-05 14:22:53 # @Author : mutudeh (josephmathone@gmail.com) # @Link : ${link} # @Version : $Id$ import os class Solution(object): def titleToNumber(self, s): if not s: return 0 num = 0 mul = 1 for lett...
59aa87cdc16664a874edbc236bf8ae35e3c4de6f
selvatp/CS1XA3
/Lab02/myconvert.py
375
4.3125
4
# myconvert.py # A program to convert Celsius temperatures to Fahrenheit and # prints a table of Celsius temperatures and the Fahrenheit equivalents # every 8 degrees from 0C to 100C # by: Piranaven Selvathayabaran def main(): print("Celsius | Fahrenheit") for i in range(0,101,8): fa...
9b464d06a777eb6f6ffaaf2ec29f821fd984faa8
patrykstefanski/dc-lang
/scripts/gen_matrix.py
266
3.515625
4
import random import sys if len(sys.argv) < 2: print('Usage: {} <N> [SEED]'.format(sys.argv[0])) sys.exit(1) n = int(sys.argv[1]) if len(sys.argv) >= 3: random.seed(sys.argv[2]) print(n) for i in range(2 * n * n): print(random.randint(-1000, 1000))
880313d2f76219c4203d9be285a8b4324e96cd29
Psp29onetwo/python
/zipfunction.py
113
3.8125
4
list1 = [1, 2, 3, 4, 5, 6] list2 = [7, 8, 9, 1, 2, 3] zipped_list = list(zip(list1, list2)) print(zipped_list)
1b293c2199aca78fd775305bd43d86acfe06a0b8
judigunkel/Exercicios-Python
/Mundo 2/ex041.py
679
3.984375
4
""" A Confederação Nacional de Natação precisa de um programa wue leia o ano de nascimento de um atleta e mostre sua categoria, de acordo com a idade: Até 09 anos - Mirim Até 14 anos - Infantil Até 19 anos - Junior Até 25 anos - Sênior Acima - Master """ from datetime import date nasc = int(input('Ano de nascimento: '...
eaae22fdca519eb39ddca227462fa4185c781a07
accus84/python_bootcamp_28032020
/moje_skrypty/20200523_moje/basic/04_napisy.py
142
3.5625
4
n1 = "Ala" n2 = "kot" print(n1 + " " + n2) # łączenie napisów - konkatenacja print(f"{n1} {n2}") print("{a} {b}".format(a = n1, b = n2))
c5386f3f4a6d663ba98b5115a2ea2702ec96de7e
HarshaRathi/PPL-Assignment
/Assign3/line.py
300
3.828125
4
import turtle class line(): def __init__(self , len = 5): self.__len = len def get_len(self): return self.__len def draw(self): t = turtle.Turtle() t.forward(self.__len) l = line(400) print("Length of line = ",l.get_len()) l.draw() turtle.done()
3daf2131c2c05cd19609ac537f49bc56edabb295
Jhancrp/Examen_Final
/Final/Modulo3/banco.py
799
3.578125
4
#Ejercicio 01 mastercard= [51, 52, 53, 54 , 55] american_expres = [34,37] visa = [4] def luhn(ccn): c = [int(x) for x in ccn[::-2]] u2 = [(2*int(y))//10+(2*int(y))%10 for y in ccn[-2::-2]] print(f"numero = {ccn}") return sum(c+u2)%10 == 0 prueba = 49927398716 #con este numero funciona p...
e2db0bfcfdfa9e4bcaea32df1a295b21ba1cca62
ehoney12/comp110-21f-workspace
/exercises/ex03/tar_heels.py
397
3.75
4
"""An exercise in remainders and boolean logic.""" __author__ = "730240245" # Begin your solution here... int1: int = int(input("Enter an int: ")) divis_by_2: int = (int1 % 2) divis_by_7: int = (int1 % 7) if divis_by_2 == 0: if divis_by_7 == 0: print("TAR HEELS") else: print("TAR") else: ...
d138888489d9c5bfcd5050469cf0b0cde9434f44
Aeternix1/Python-Crash-Course
/Chapter_6/6.4_glossary2.py
543
3.984375
4
#Glossary but without the print statements glossary = { 'loop':'A means to accomplish a process several times', 'if': 'A particular form of boolean', 'list': 'set of values stored sequentially in memory', 'boolean':'a conditional statement', 'style': 'Style is an important part of programming', ...
baee40593ee9a221617eea3e1fe7488713a3c9c0
angel19951/holbertonschool-higher_level_programming
/0x0C-python-almost_a_circle/models/square.py
2,600
4.125
4
#!/usr/bin/python3 """ This module contains a Square class """ from models.rectangle import Rectangle from models.base import Base class Square(Rectangle): """ Square class """ def __init__(self, size, x=0, y=0, id=None): """ Initializes a square class that inherits from rectangle ...
df81954a358fa3139677a07b150494e005fb8c81
ariadnei/rkiapp
/site_ver/7.py
3,691
3.734375
4
''' 7. Образовать слова от слов в скобках и ставить в пропуски ''' def main(level): import app.exc.functions as fun import app.exc.formation as form task_name = 7 task = 'Вставьте в пропуски (1) - ({}) слова, образованные от слов в скобках. Поставьте эти слова в правильную форму.\n{}' #TODO: добав...
86810068371413cc41f0e544739323a3755e25f6
aurel1212/Sp2018-Online
/students/alex_skrn/Lesson06Activity/calculator/subtracter.py
328
3.8125
4
#!/usr/bin/env python3 """This module provides a subtraction operator.""" class Subtracter(object): """Provide a class for subtracting one number from the other.""" @staticmethod def calc(operand_1, operand_2): """Take two operands and subtract one from the other.""" return operand_1 - op...
fc3cb94fadf7a82391b1adb0da5334c9dcc15bf9
Dmitrygold70/rted-myPythonWork
/Day07/classes/example01/point4.py
783
3.765625
4
class Point: count = 0 def __init__(self, x=0, y=0): self.x = x self.y = y Point.count += 1 def __del__(self): Point.count -= 1 def show(self): print("({}, {})".format(self.x, self.y)) if __name__ == '__main__': p1 = Point(10, 20) p1.show() print...
2a570809d7d1e04c9e354ab775f1ceeb31a0b447
chintanaprabhu/leetcode
/Python3-Solutions/Sort Colors.py
786
3.65625
4
class Solution: def sortColors(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ rightOfZero = currIndex = 0 leftOfTwo = len(nums)-1 while currIndex <= leftOfTwo: if(nums[currIndex] == 0): nums[ri...
4c333d550d39e1c71024f88b9360b57983343e83
qqmadeinchina/myhomeocde
/homework_zero_class/lesson16/单例模式-times_1.py
2,069
3.640625
4
#!D:\Program Files\Anaconda3 # -*- coding: utf-8 -*- # @Time : 2020/8/8 13:54 # @Author : 老萝卜 # @File : 单例模式-times_1.py # @Software: PyCharm Community Edition # 单例模式是设计模式的一种 # 单例模式 保证系统中的一个类只有一个实例, class Person: pass p1 = Person() p2 = Person() print(p1) print(p2) # <__main__.Person object at 0x00000000021E97F0>...
94e8bd8c6c398ac43b896752fe2e2624499b91af
samuellly/dojo_assignment_file
/dojo_python/fundamentals/star.py
1,031
3.734375
4
x = [4, 6, 1, 3, 5, 7, 25] def print_Stars(arr): for i in arr: print i * "*" print_Stars(x) #2nd Star assignment x = [4, "Tom", 1, "Michael", 5, 7, "Jimmy Smith"] def print_Stars(arr): for i in range(len(arr)): if isinstance(arr[i], int): print arr[i] * "*" elif isinstance(arr[i], str): ...
ab7f13c776fb4e0b8346b5f7d1dafae9ad3a901f
924235317/leetcode
/114_flatten_binary_tree_to_linked_list.py
876
3.84375
4
from treenode import * def flatten(root: TreeNode) -> None: def flattenCore(root): if root and not root.left and not root.right: return root if root.left and root.right: tmp = root.right t = flattenCore(root.left) root.right = root.left t...
a70b0d9eb2e191f7c3638443ffe5eae6fb57fc11
HLNN/leetcode
/src/0540-single-element-in-a-sorted-array/single-element-in-a-sorted-array.py
636
3.671875
4
# You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. # # Return the single element that appears only once. # # Your solution must run in O(log n) time and O(1) space. # #   # Example 1: # Input: nums = [1,1,2,3,3,4,4,8,8...
99617d7d030c6a612adfa9b3e82dc1efefb315d7
thezencode/project_euler
/problem3.py
644
3.734375
4
import math import time def is_prime(n): for x in range(2, int(math.sqrt(n)) + 1): if n % x == 0: return False return True def return_prime_factors(a_number): factors = [a_number] while True: if is_prime(factors[0]): break for i in range(2, int(fac...
13c2e648a216e168c2c062d21dec4311e6a5ecac
yiyang7/warfarin-bandit
/src/visualize.py
3,034
3.765625
4
""" Helper methods for visualizing simulation results """ import numpy as np import matplotlib.pyplot as plt def plot_regret(reward_histories, plot_legend, plot_bound=False, drop_k=0): """ Plots regret vs. t reward_history: array of reward_history arrays plot_legend: legend for the pl...
522a655c0bd5d237ef7a681f13928cf5f01bfee6
yongxuUSTC/leetcode_my
/median_of_two_sorted_arrays.py
3,338
3.5625
4
class Solution(object): def findMedianSortedArrays(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: float """ ###method1: #nums3=[] #i=0 #j=0 #while(i<len(nums1) and j < len(nums2)): # if (nums1[...
e36ad46bc89127df55ef3f64b21d206834500fbd
dhirensr/Ctci-problems-python
/leetocde/bstfromPreorder.py
1,636
3.859375
4
import queue class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def bstFromPreorder(preorder,inorder,start,end): if len(preorder)==0: return None elif (start > end): return None elif( start ==end): root = TreeNode(inord...
9a6dcffb3b8c7af0fb2f8b774a0e36d8ee18fc53
jingyiZhang123/leetcode_practice
/array/remove_duplicated_from_sorted_array2_80.py
1,230
4.03125
4
""" Follow up for "Remove Duplicates": What if duplicates are allowed at most twice? For example, Given sorted array nums = [1,1,1,2,2,3], Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3. It doesn't matter what you leave beyond the new length. """ class...
0a470515f9aa9cc918eb85ebee38f9607377bcc7
DrishtiSabhaya/ParkingManagementSystem
/Training/parking_color.py
2,002
3.578125
4
#Building the CNN #importing libraries from keras.models import Sequential from keras.layers import Convolution2D from keras.layers import MaxPooling2D from keras.layers import Flatten from keras.layers import Dense from PIL import Image #Initializing CNN classifier = Sequential() #Color version #Step-1 ...
a923848e72d3cc98e73c5df962003cf868f53c68
HamedSanaei/CloudProject
/DataCenterTopologies/Switch.py
1,077
3.515625
4
# this is an object oriented way but is not completed class Switch: # class level attributes #firstOutput: Switch = Switch(10) # self means compiler prepare currnet instance as a value for the called method # constructor method def __init__(self, number, stype): # instance level attributes ...
8c3c264b352fb9dab27208dd526e647446e7c4ae
mdilauro39/ifdytn210
/sistemagestioninstituto/original/pais_view.py
2,380
3.5
4
# -*- coding: utf-8 *-* class PaisView: def __init__(self): self.tab1 = " " self.tab2 = " " * 2 self.tab3 = " " * 3 self.txt_opt = "%sElija una opción: " % self.tab2 self.txt_nombre = "%sPaís: " % self.tab3 self.txt_apellido = "%sAbreviatura: " % self.tab3...
dc30ad813259a9a771356b6a409f2bc995fa123c
donhuvy/fluent-python
/02-array-seq/bisect_grade.py
404
3.546875
4
''' Ref: https://docs.python.org/3/library/bisect.html ''' import bisect def grade(score, breakpoints=[60, 70, 80, 90], grades='FDCBA'): # bisect.biset_left would be the wrong one to use here :) i = bisect.bisect(breakpoints, score) return grades[i] if __name__ == "__main__": scores = [33, 99, 77, 70...
f5d82c152bdf7445bd7a1f7bf0c500f92e2b601f
kmzn128/CCI_Python
/CCI_1/CCI_10/10_1_2.py
607
3.75
4
def _insert(li, el, l, r): if(r-l < 0): return if(r-l == 0): if(li[l] > el): li.insert(l,el) else: #if(l == len(li)): # li.append(el) #else: li.insert(l+1, el) mid = l + (r-l)//2 if(el < li[mid]): _insert(li,el...
4172c269bbae488c99dacff5fdd3f1c393a06314
nixonpj/leetcode
/Number of 1 Bits.py
629
3.734375
4
""" Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight). Constraints: The input must be a binary string of length 32. Follow up: If this function is called many times, how would you optimize it? """ class Solution: def hammingWeight(s...
bbb4c8f0789e09408fe7b233ac52191926c940ed
tushargoyal02/pyautogui_repo
/basic_cmd.py
699
3.59375
4
# SOME COMMAN COMMAND FOR FUTURE import pyautogui # move the cursor left right up to the point according to current location ''' - up and bottom (-x mean to the left, -y mean to the up) # Click mouse button -> pyautogui.rightClick() -> pyautogui.doubleClick() -> pyautogui.click(button='right', click=2, interval=0...
201aa841324e1b0cbbf30b8d9378de0acf6a0dda
williamf1/Maths-Cheating-Device
/pover-of.py
1,410
4.0625
4
import time #hi #start print(""" o o o o o o o o o o o o o o o o o o o o o o o o o o o o (for the power of) """) #login needspassword=True while needspassword==...
d8a782bf78cbb1db7a6dd77ddf3376495deb9411
bkyileo/algorithm-practice
/python/Combination Sum II.py
1,334
3.8125
4
# coding=utf-8 __author__ = 'BK' ''' Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. Each number in C may only be used once in the combination. Note: All numbers (including target) will be positive integers. Elements in a co...
17c8262752f9ebccdd3275d32e7f1b3dbe477372
rafaelgama/Curso_Python
/Udemy/Secao3/aula68.py
1,070
4.09375
4
# Zip - Unindo iteráveis # Zip_longest - Itertools from itertools import zip_longest, count # O Zip une os Iteraveis com a mesma quantidade descartando o que sobra. #Exemplos de ZIP cidades = ['São Paulo','Belo horizonte','Salvador','Campinas'] estados = ['SP','MG','BA'] cid_est = zip(cidades, estados) print(cid_est)...
ffa082853669da04b93d0afd82004fcc1441973a
moontasirabtahee/Problem-Solving
/Leetcode/1389. Create Target Array in the Given Order.py
327
3.625
4
from typing import List class Solution: def createTargetArray(self, nums: List[int], index: List[int]) -> List[int]: target_array = [] for n, i in zip(nums, index): target_array.insert(i, n) return target_array sol = Solution() print(sol.createTargetArray([1,2,3,4,0], [0,1,2,...
19b60d8ad9343d5698d10530cdaa7595d9defa8a
bluejok3/TADEJ_Louis_M1RES
/Python_M1.py
15,002
3.96875
4
#TD1 #!/usr/bin/env python # coding: utf-8 # In[1]: x = 5 y = 10 z = 7 print ( x + y - z ) # In[3]: a = "je suis" b = "un beau" c = "gosse" print (a, b, c) # In[5]: print ( 10000 > 1) print ( 1==1) print (1 < 0) # In[3]: prenom = "Louis " nom = "Tadej" nom_complet = prenom + nom print (nom_complet) i= 0 ...
c67a2f09b9e40519ab6ca472d90a351932e49eda
DEADalus9/Test
/Lesson_4/Task_2.py
3,050
3.984375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed May 20 19:14:01 2020 @author: vladislav MATHEMATICAL PENDULUM """ import graphics as gr import math G = 0.1 SIZE_X = 400 SIZE_Y = 400 BALL_RADIUS = 10 window = gr.GraphWin('MATHEMATICAL PENDULUM', SIZE_X, SIZE_Y) # Initial point of pendulum coords...
bfb00704f74b832d5e21bf2956f7a619c4d8e4da
nandhakumarm/InterviewBit
/LinkedList/swapInPairs.py
1,243
3.859375
4
class ListNode(object): def __init__(self,val): self.val=val self.next=None class Solution(object): def printList(self,A): temp=A while temp!=None: print temp.val, temp=temp.next print "done" def swapPairs(self, head): headtemp=Li...
40a544242594dbde0c1fff9007fea7488bf14bc5
libus1204/bigdata2019
/01. Jump to python/chap05/Restaurant_ver_2.py
1,026
3.546875
4
class MyRestaurant_ver_2: def __init__(self, name, type): self.restaurant_name = name self.cuisine_type = type def describe_restaurant(self): print("저희 레스토랑 명칭은 '%s'이고, %s 전문점입니다." %(self.restaurant_name, self.cuisine_type)) print("저희 %s 레스토랑이 오픈했습니다." % self.restaurant_name) ...
23d8a2a2e8bf67696f7c27c36a500f3e6a930f47
andriyl1993/Diploma
/letters.py
574
3.734375
4
# -*- coding: utf-8 -*- UKR_ALPHABET = "абвгдеиіїжзийклмнопрстуфхцчшщьєюяАБВГДИІЇЖЗИЙКЛМНОПРСТУФХЦЧШЩЬЄЮЯ" def ukr_letter(letter): return letter in UKR_ALPHABET def work_ukr_chars(word): for s in word: if not ukr_letter(s): return False return True def get_words(word): res = [] start = 0 for i, s in enum...
ff9b9d75bfe8cf77665d502ea0c3cd82329994fa
ankitrana1256/LeetcodeSolutions
/Valid Number[ 82.42% ].py
1,225
3.5625
4
# VALIDATE NUMBERS #s = "0e1" #s = "0" #s = "2" #s = "0089" #s = "-0.1" #s = "+3.14" #s = "4." #s = "-.9" #s ="-90E3" #s = "3e+7" #s = "+6e-1" #s = "53.5e93" #s = "-123.456e789" # NON VALIDATE NUMBERS #s = "abc" #s = "1a" #s = "1e" #s = "e3" #s = "99e2.5" #s = "--6" #s = "-+3" #s = "95a54e53" ...
6d9269d2dd3aa1b54190e2a9245efb320390e57c
fantasylsc/LeetCode
/Algorithm/Python/25/0023_Merge_k_Sorted_Lists.py
2,376
4
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 ...
8a00bd639cd42e5d1e5a00bda63699962d624a6d
bestchanges/hello_python
/sessions/4/pavel_shchegolevatykh/conv.py
2,229
4.09375
4
import rates def print_rates(exchange_rates_to_print): print('output:') for rate in exchange_rates_to_print: print(f'{rate[0]} {rate[1]}') def get_rates(): value_to_convert = input('input value to check (e.g. 10 USD): ') processed_value = value_to_convert.split(' ', 1) try: ...
dad555e524a50bed1f6cfa0e801d77276d91a728
ElliotMoffatt/NetworksCoursework
/gvch48_question1.py
8,311
3.875
4
# -*- coding: utf-8 -*- """ Created on Sat Oct 27 15:36:22 2018 @author: gvch48 """ import random import queue import matplotlib.pyplot as plt def make_ring_group_graph(m,k,p,q): #initialize empty grqph ring_group_graph = {} for vertex in range(m*k): ring_group_graph[vertex] = [] for vertex in rang...
f9953dcd1cd11c34076f20712da03c3404553284
kuan1/test-python
/100days/02-计算圆.py
217
3.875
4
''' 输入半径计算周长和面积 ''' import math radius = float(input('请输入半径')) perimeter = 2 * math.pi * radius area = math.pi * radius ** 2 print(f'周长:{perimeter}') print(f'面积:{area}')
f2444ebb4e218320a1592ae70cff14312652348d
chinatsui/DimondDog
/algorithm/exercise/hash_table/first_unique_character_in_string.py
754
3.734375
4
""" LeetCode-387 Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1. Examples: s = "leetcode" return 0. s = "loveleetcode", return 2. Note: You may assume the string contain only lowercase letters. """ class Solution: @staticmethod def first_...
7933d6fb9bd3ebc440693853af938faf3b7f50ad
DS-PATIL-2019/Trees-4
/KthSmallest.py
701
3.6875
4
""" The approach here is very simple just do a inorder traversal and store the values in the array and return the kth index from the array. A optimization for this could be to keep the count of k and decrease the value of k at every node traversal and then when your k value hits 0 return the node value. Leetcode - Run...
68ff0eb6eec8ada8ffe8e79c335932a87f4a43d6
DayDreamChaser/OnlineJudge
/PTA/B_level/1094_GoogleRecruit.py
726
3.8125
4
# 1094 谷歌的招聘 # 在这个问题上, 用C/C++ 比python快 4倍, 内存只用python的1/8 import math input_nums = input() L, N = [int(num) for num in input_nums.split(" ")] number = input() #length = L def is_prime_sqrt(N): if N <= 1: return False else: flag = True num = int(math.sqrt(N)) for i in range(2, num+1): if (...
5aeaa8f455435c223fc073f562771679a4bcc85a
BrunoCerberus/Algoritmo
/Ex85.py
519
3.546875
4
""" Faca um algoritmo (pseudocodigo) que leia um vetor (A) de 10 posicoes. Em seguida, compacte o vetor, retirando os valores 0(zero) e negativos, colocando apenas em um vetor B de 10 posicoes os valores validos de forma consecutiva, as posicoes nao utilizadas devem ficar ao final e com valor 0(zero). """ from ra...
b0252c3660d4a8e8dad10eae7ff89af943a7e71b
S1DAL3X/Python
/EncryptCaesar.py
1,336
3.75
4
#скрипт для шифровки\\дешифровки текста по принципу шифра Цезаря alphavite = list(' abcdefghijklmnopqrstuvwxyz/\!?&,')#33 output = [] def coder(text, key): text = text.lower() for label in text: position = alphavite.index(label) newPos = position + key while newPos > len(alphavi...
2840c8924380c965bd979fed1a430f116749c51a
rice-apps/petition-app
/controllers/netid2name.py
529
3.71875
4
import urllib2 import json api_key = "" def netid2name(netid): # Get the JSON response from the server api_response_string = urllib2.urlopen("http://api.riceapps.org/api/people?key=" + api_key + "&net_id=" + netid).read() api_response = json.loads(api_response_string) # Do something useful with it ...
856d36caf10689fb73a001cd1d610a7cdade356d
nevilkandathil/coding-questions
/003 Closest Value BST/c_BST.py
1,333
3.84375
4
def findClosestValueInBst(tree, target): return closestValue(tree, target, tree.value) ''' Method 1 Average: time O(log(n))| space O(1) Worst: time O(n) | space O(1) ''' # Using recursion def closestValue(tree, target, closest): currentNode = tree while currentNode is not None: if abs(target - close...
93d1a777adff41a8c493fb378f1898866855aec5
whwatkinson/maze
/walls/mk1/simple_wall.py
3,871
3.78125
4
from random import randint, getrandbits, choice from typing import Tuple, List from collections import namedtuple from datetime import datetime WallMeta = namedtuple('WallMeta', [ "vertical", "wall_length", "x", "y", "wall_coords", "is_door", "door_coords" ]) class SimpleWall: def _...
1c88b6c3ed35e1ecea5f6ef50974a2ae34b5d04d
JosephAlonzo/Practicas-Python
/ejerciciosEvaluacion/ejercicio10.py
497
3.890625
4
class Rimas(): def __init__(self, word1, word2): self.word1 = word1 self.word2 = word2 def checkIfRhyme(self): if(self.word1[-3:] == self.word2[-3:]): return "Las palabras riman" elif (self.word1[-2:] == self.word2[-2:]): return "las palabras riman un poc...
a0f7cb00714a7ae715ff7c9119f3384873be63d7
zhanglintc/algorithm
/sort/sort.py
4,070
3.734375
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- # -*- mode: python -*- # vi: set ft=python : def timer(func): import functools @functools.wraps(func) def wrapper(*args, **kwargs): import time t1 = time.time() res = func(*args, **kwargs) t2 = time.time() print(f"{func.__na...
b72c2a0c6674a26af3a291aa51b44482b521632d
shuvo14051/python-data-algo
/Problem-solving/HackerRank/HackFest 2020-Cyclic Binary String.py
893
3.6875
4
string = input() li_of_string = [] result = [] if int(string) == 0: print("-1") else: for i in string: li_of_string.append(i) for i in range(len(li_of_string)): number = 0 string2 = '' item = li_of_string.pop() li_of_string.insert(0, item) for i in li_of_st...
d985a26b5f3d3b53e2d344a54b39d20c42f67ed0
yasiriqbal1/concept-to-clinic-1
/prediction/src/algorithms/evaluation/metrics.py
949
3.546875
4
import numpy as np def get_accuracy(true_positives, true_negatives, false_positives, false_negatives): """ The accuracy is the ability to correctly predict the class of an observation. Args: true_positives: amount of items that have correctly been identifies as positives true_negative...
f40c1786ae3658bd586faefd54713fc32ace1625
MilanMolnar/Codecool_SI_week3
/Game statistics reports/part2/printing.py
2,973
3.75
4
from reports2 import get_most_played, sum_sold, get_selling_avg, count_longest_title, get_date_avg, get_game, \ count_grouped_by_genre, get_date_ordered # Printing functions def print_get_most_played(): print("The title of the most played game in the file is:", get_most_played("game_stat.txt") + ".") def prin...
ec08f30607302176b4210dbab6c732821ee9d52d
mattielangford/stats_midterm
/stats_midterm.py
193
3.515625
4
import numpy as np ## To know P(A|B) What is A and B? a = 'Knows the material' b = 'Answered correctly' p_a = 0.60 p_b_a = 0.85 p_b = 1 - 0.15 - 0.20 p_a_b = (p_b_a * p_a) / p_b print(p_a_b)
c69edd2652a8c86769187db8dcb0d948a78918cf
cpeixin/leetcode-bbbbrent
/geekAlgorithm010/Week06/unique-paths-ii.py
2,270
3.703125
4
# coding: utf-8 # Author:Brent # Date :2020/7/16 10:37 PM # Tool :PyCharm # Describe :一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为“Start” )。 # # 机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为“Finish”)。 # # 现在考虑网格中有障碍物。那么从左上角到右下角将会有多少条不同的路径? # # 来源:力扣(LeetCode) # 链接:https://leetcode-cn.com/problems/unique-paths-ii class Solution(object...
7a3b13e7497d4ab49ff8cd4b2dff7d1c961010dd
chenxu0602/LeetCode
/305.number-of-islands-ii.py
3,079
3.75
4
# # @lc app=leetcode id=305 lang=python3 # # [305] Number of Islands II # # https://leetcode.com/problems/number-of-islands-ii/description/ # # algorithms # Hard (40.57%) # Likes: 705 # Dislikes: 15 # Total Accepted: 67.8K # Total Submissions: 167.2K # Testcase Example: '3\n3\n[[0,0],[0,1],[1,2],[2,1]]' # # A 2d...
f824ca7510d775b15a3c8171a7fb18b4721c7e43
umunusb1/PythonMaterial
/python3/07_Functions/009_default_args.py
1,980
4.4375
4
#!/usr/bin/python3 """ Purpose: Functions Demo Function with default arguments """ # def addition(num1, num2): # return num1 + num2 def addition(var1, var2, var3=0): return var1 + var2 + var3 print(f'{addition(10, 20) =}') print(f'{addition(10, 20, 30) =}') # print(dir(addition)) print(f'{addition._...
aa067e050061f56bda08b4749a6e4722fc5a9ae0
rgrishigajra/Competitive-Problems
/leetcode/75. Sort Colors Medium.py
494
3.9375
4
def sortColors(nums) -> None: """ Do not return anything, modify nums in-place instead. """ start = 0 end = len(nums) - 1 idx = 0 while idx <= end: if nums[idx] == 0: nums[idx], nums[start] = nums[start], nums[idx] start += 1 idx += 1 ...
fbf9ec70a4398209d4ad3556c8691ab75d3efeef
asswecanfat/git_place
/杂项/网站检验.py
317
3.5
4
import urllib.request as urr import chardet as c respone = input('请输入URL:') ass = urr.urlopen(respone).read() v = c.detect(ass) if v['encoding'] == 'utf-8': print('该网站编码方式是:' + v['encoding']) elif v['encoding'] == 'GB2312': print('该网站使用的编码是:' + v['encoding'])
5a34d03447c38a292b4595eb553770ccc05b924b
Taoge123/OptimizedLeetcode
/LeetcodeNew/TwoPointers/LC_028_Implement_strStr.py
1,497
4
4
""" Implement strStr(). Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. Example 1: Input: haystack = "hello", needle = "ll" Output: 2 Example 2: Input: haystack = "aaaaa", needle = "bba" Output: -1 """ class Solution1: def strStr(self, haystack, needle...
5879b1d5b0d71cb9a57c9d8e2ee12a2c31821f41
daniel-reich/turbo-robot
/QcswPnY2cAbrfwuWE_17.py
649
4.375
4
""" Create a function that filters out factorials from a list. A factorial is a number that can be represented in the following manner: n! = n * (n-1) * (n-2) * ... * 3 * 2 * 1 Recursively, this can be represented as: n! = n * (n-1)! ### Examples filter_factorials([1, 2, 3, 4, 5, 6, 7]) ➞ [1, 2, 6] ...
f9308006515865a750a85d83205066d086fac221
Jeanrain-lee/lab-python
/lec01/ex04.py
687
3.765625
4
""" 연산자(operator) - 할당(assignment): = - 산술 연산: +, -, *, **, /, //, % - 복합 할당 연산: +=, -=, *=, /=, ... - 비교 연산: >, >=, <, <=, ==, != - 논리 연산: and, or, not - identity 연산: is, is not(id() 함수의 리턴값이 같은 지 다른 지) """ x = 1 # 연산자 오른쪽의 값을 연산자 왼쪽의 변수에 저장(할당) # 1 = x print(2 ** 3) # 2 x 2 x 2 print(10 / 3) print(10 // 3) # 정수 나...
97153124d7a14a42f6d2d2e8702d6a20aa2f6371
ankitdipto/ImageInfoExtractor
/OCR/python files/OCRengine.py
1,587
3.546875
4
from PIL import Image from PIL import ImageFilter import pytesseract import requests import cv2 import os pytesseract.pytesseract.tesseract_cmd= r"C:\Program Files\Tesseract-OCR\tesseract.exe" def image_preprocess(image): ''' 1)resizing the image so that OCR can prepossess it in a better way 2)converting im...
8f81baeeab865f930a2a7d388af9625712b91544
agile-course/runmoar
/runmoar/running_calendar/utils.py
329
3.5
4
from datetime import datetime, timedelta def toDate(input_date): return datetime.strptime(input_date, '%Y-%m-%d') def getDateRange(start_date, end_date): dates_to_check = [] while start_date <= end_date: dates_to_check.append(start_date) start_date += timedelta(days=1) return dates_...
2d3b15511b9a77a0a0b921055d30914d9dfc48f5
riyag283/Leetcode-July-20-Challenge
/quest12.py
238
3.65625
4
def funct(n): binary = '' while n > 0: if n & 1: binary += '1' else: binary += '0' n >>= 1 return int(binary,2) #binary = '11101' #print(int(binary,2)) print(funct(4294967293))
4011fa3e1467604fe02dbad202d4168b8f3d6a65
Stranger65536/AlgoExpert
/medium/hasSingleCycle/program.py
2,346
4.09375
4
# # Single Cycle Check # You're given an array of integers where each integer represents # a jump of its value in the array. For instance, the integer 2 # represents a jump of two indices forward in the array; the integer # -3 represents a jump of three indices backward in the array. # # If a jump spills past the array...
7413a034468b07278ec678dbea5f712751f15347
m4mayank/ComplexAlgos
/rearrange_array.py
636
3.875
4
#!/usr/local/bin/python3.7 #Rearrange a given array so that Arr[i] becomes Arr[Arr[i]] with O(1) extra space. # #Example: # Input : [1, 0] # Return : [0, 1] #Lets say N = size of the array. Then, following holds true : # 1) All elements in the array are in the range [0, N-1] # 2) N * N does not overflow fo...
6b7894b77d9fe77f50df91ce5f8502d6931af1fd
Bajo-presion/3er_Anio_instancia_Marzo
/Estudiantes.py
3,780
3.53125
4
import random from Estadistica import * #CLASE ESTUDIANTE - USADO PARA CREAR BASE DE DATOS # Si bien su atributo tiene el nombre completo, el nombre de clase debe ser sencillo class Estudiante(): # y único para poder acceder a el fácilmente def __init__(self, nombre=None, ...
5156de2b523cb82ffb32b78983b997cd84316539
Offliners/Python_Practice
/code/054.py
135
3.9375
4
# "f-strings" or # string interpolation # (available in Python 3.6+) name = "Eric" print(f"Hello, {name}!") # Output: # Hello, Eric!