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
c82f373f42c0124c42d3ec8dd89184a0897998a1
jabhij/DAT208x_Python_DataScience
/NUMPY/LAB1/L2.py
614
4.5
4
""" Instructions -- Create a Numpy array from height. Name this new array np_height. Print np_height. Multiply np_height with 0.0254 to convert all height measurements from inches to meters. Store the new values in a new array, np_height_m. Print out np_height_m and check if the output makes sense. """ # height is a...
a98c810b07c63632e9dfd6b421642e914fa3b377
y3rsh/fun_cli_client
/find_country.py
1,545
3.765625
4
import string import country_controller controller = country_controller.CountryController() def invalid_chars(): allowed_punctuation = ["_", "'", '"', "^", "-", "(", ")", ","] punctuation = string.punctuation for s in allowed_punctuation: punctuation = punctuation.replace(s, "") return set(pu...
83d880a35ae04e0e869226e8bd95db9329c37aa0
renlei-great/git_window-
/python数据结构/python黑马数据结构/第一天,list的时间复杂度/test.py
290
3.703125
4
l1 = [1,2,3] l2 = [4,5,6] # li = l1 + l2 l1.extend(l2) print('extend:',l1) l1 = [1,2,3] l2 = [4,5,6] l1.append(l2) # print('extend:',l1) print('append:',l1) # print('+:',li) class Base(): pass class a(Base): pass class b(Base): pass a1 = a() print(isinstance(a1, Base))
047c21dee36566ae4418ea818a644d274bd3ae46
renlei-great/git_window-
/每天一问/AdvancePython-master/chapter02/company_test.py
365
3.859375
4
class Company(object): def __init__(self, name_list): self.name_list = name_list def __getitem__(self, item): return self.name_list[item] # def __len__(self): # return 1 company = Company(["renl", "anj", "lvfei"]) print(type(company)) company1 = company[:2] print(type(company1))...
2f144a584185f1b98ebb78009fb866838885d681
renlei-great/git_window-
/python数据结构/和刘亮讨论/插入排序.py
422
3.78125
4
lista = [12, 4, 5, 6, 22, 3, 43, 654, 765, 7, 234] def insert_sort(alist): """插入排序""" n = len(alist) for i in range(1, n): # cur = i-1 while i -1 >=0: if alist[i] > alist[i-1]: break else: alist[i], alist[i-1] = alist[i-1], alist[i]...
790cc6bb71e52bf2f7531f28eb13bf9a9271aa15
renlei-great/git_window-
/python数据结构/和刘亮讨论/队列实现栈.py
737
3.96875
4
class Stack(): def __init__(self): self.__stack = list() def push(self, item): self.__stack.append(item) def pop(self): self.__stack.pop() def size(self): print(len(self.__stack)) def empty(self): return not self.__stack def __str__(self): # f...
a412be3f9d46560531ef50a8b3e829bd14096509
renlei-great/git_window-
/python数据结构/python黑马数据结构/链表/double_link_list.py
2,472
3.84375
4
"""重要的就是要考虑周全,普通情况和特殊情况""" from python数据结构.python黑马数据结构.链表.single_link_list import BaseLinkList class Node: def __init__(self, item): self.item = item self.prev = None self.next = None class DoubleLinkList(BaseLinkList): """双链表""" def __init__(self, node=None): self.head ...
65fdf45b52a7e52bcedffca7eed5b21b59fda411
renlei-great/git_window-
/每天一问/2020.3.20/id的判断.py
2,766
3.671875
4
# tu = (1,2,3) # tu1 = (1,2,3) # print(id(tu), id(tu1)) # # li = {1:1} # li1 = {1:1} # print(id(li), id(li1)) # # st = '12' # st1 = '12' # print(id(st), id(st1)) # class Test(): # def __init__(self,name, list_test = None): # if list_test is None: # self.list_test = [] # self.name = name...
48af0e19786bf6073b8a277c33ec5d2abf149d28
renlei-great/git_window-
/python数据结构/和刘亮讨论/冒牌排序.py
530
3.828125
4
import random # lista = [12, 4, 5, 6, 22, 3, 43, 654, 765, 7, 234] lista = [random.randint(1,100) for i in range(15)] ls = [i+1 if i == j else j if i < j else j-1 for i in range(10) for j in range(10)] print(ls) def bubble_sort(alist): """冒泡排序""" n = len(alist) - 1 for j in range(n, 0, -1): for ...
c0de00c3a3ca203ed3aa6aaa1ac2794b8afe6e23
renlei-great/git_window-
/python数据结构/python黑马数据结构/面试题学习/插入排序.py
559
3.734375
4
import random lista = [random.randint(0,10) for i in range(10)] # lista = [12, 4, 5, 6, 22, 3, 43, 654, 765, 7, 234] def insert_sort(alist): """ 插入排序 思想:每次找出最大的插到最前的一个 :param alist: :return: """ n = len(alist) for j in range(0, n): min_num = j for i in range(j+1,n): ...
540f5d14d08623729ce38abe2e6eea6b18e2bdd0
renlei-great/git_window-
/python数据结构/python黑马数据结构/排序于搜索/希尔排序.py
867
3.625
4
# lista = [12, 4, 5, 6, 22, 3, 43, 654, 765, 7, 234] # lista = [-3, 4, 5, 6, 22, -12, 43, 654, 765, 7, 234] import random, time lista = [random.randint(0,200) for i in range(80)] # 希尔排序 # 希尔排序是基于插入排序进行了分类分层,将一个无序序列分为多个子序序列去进行插入排序 def shell_sort(alist): n = len(alist) gap = n // 2 coont = 1 while gap ...
bbc384375ea724bc383760d0bdec90912e69ea2f
renlei-great/git_window-
/python数据结构/尚硅谷数据结构/排序/插入排序/插入排序.py
472
3.5
4
lista = [12, 4, 5, 6, 22, 3, 43, 654, 765, 7, 234] # import random, time # lista = [random.randint(0,200) for i in range(80000)] def insert_sort(alist): """插入排序""" n = len(alist) for j in range(1, n): for i in range(j, 0, -1): if alist[i] < alist[i-1]: alist[i], alist[i...
7ab808499d7462bc48cd27881ebf2e2cc06df73e
renlei-great/git_window-
/每天一问/2020.2.25/生成器.py
292
3.75
4
a = (i*2 for i in range(10)) print(next(a)) print(next(a)) # next(a) # for i in a: # print(i) # # # next(a) # def scq(): # # i = 1 # for i in range(2): # temp = yield i # print(temp) # a = scq() # print(next(a)) # print(next(a)) # print(next(a)) # print(next(a))
7665f78cf9d3ab4c004b7d3088283b51451aab45
renlei-great/git_window-
/python数据结构/和刘亮讨论/二分查找2.py
458
3.765625
4
alist = [3, 6, 6, 14, 38, 47, 49, 59, 63, 78, 83, 85, 88, 89, 92] def binary_search(alist, item): """二分查找""" n = len(alist) if n <= 0: return False bim = n // 2 print(bim) if alist[bim] == item: return True if alist[bim] > item: return binary_search(alist[0:bim], i...
401ebe39c1a84852792cd56972ad59b9529b69d2
renlei-great/git_window-
/python数据结构/和刘亮讨论/快速排序.py
759
3.546875
4
lista = [12, 4, 5, 6, 22, 3, 43, 654, 765, 7, 234] # lista = [78, 45, 984, 42, 5, 6, 22, 3 , 2] def quick_sort(alist, start=None, end=None): """快速排序""" if start is None and end is None: start = 0 end= len(alist) - 1 if end - start <= 0: return l_cur = start r_cur = end ...
1c0357c5d25156eb2b9024fa411639ad0ff2aec9
Atrociou/Saved-Things
/todo.py
619
4.1875
4
print("Welcome to the To Do List") todoList = ["Homework", "Read", "Practice" ] while True: print("Enter a to add an item") print("Enter r to remove an item") print("Enter p to print the list") print("Enter q to quit") choice = input("Make your choice: ") if choice == "q": exit() break elif choi...
e195504bdd5d0ee818f90dc01ac274986b848259
Kabix1/Ruby
/kalkyl_olle.py
747
4
4
def calc(input_string): operations = ["+", "-", "*", "/", "^"] for ops in operations: if input_string.find(ops) >= 0: segmented_input = input_string.split(ops) total = calc(segmented_input[0]) for segment in segmented_input[1:]: if ops == "+": ...
b3c45da5ad19c24f4757126d4f892b408b47b86e
switchfootsid/tdttt
/tictactoe_test.py
2,948
3.734375
4
import unittest from tictactoe import * class TestTicTacToe(unittest.TestCase): def testStateEq(self): s1 = State() s1.s = (PlayerCircle, PlayerNone, PlayerNone, PlayerNone, PlayerNone, PlayerNone, PlayerNone, PlayerNone, PlayerNone, ) s2 = State() s2.s = (PlayerCircle, ...
7ca8bdfb4b5f89ec06fb494a75413184f153401d
NISHU-KUMARI809/python--codes
/abbreviation.py
522
4.25
4
# python program to print initials of a name def name(s): # split the string into a list l = s.split() new = "" # traverse in the list for i in range(len(l) - 1): s = l[i] # adds the capital first character new += (s[0].upper() + '.') # l[-1] gives last it...
079c4b1eba8b3e74d4d751b747cd3ba9c38e4db1
Paloma-Cruz/URI-ONLINE-JUDGE
/Consumo.py
76
3.796875
4
x = int(input()) y = float(input()) total = x / y print('%.3f km/l' %total)
ea7f6a4ce2e95d008fb15229ebf00c802e14a948
ManoharSuman/CRUD-Application
/mybook.py
5,893
3.75
4
from tkinter import Tk, Button, Label, Scrollbar, Listbox, StringVar, N, S, E, W, END from tkinter import ttk from tkinter import messagebox import mysql.connector as mysql # Insert Function def insert(): title_label = title_entry.get() title_label1 = title_entry1.get() title_label2 = title_entry2.get() ...
84cc5b21b739888beecad6abda420ce2d6c74941
Chuphay/python
/alg/week2/comparisons.py
1,343
3.671875
4
import random def comparisons(l): global out out = 0 def quicksort(l): if len(l) <= 1: return l else: #rdm = random.randint(0,len(l)-1) if len(l)%2 == 0: mid = (l[len(l)/2-1],len(l)/2-1) else: mid = (l[len...
fd432ef43669515067d986203d26440ff8414a6e
Chuphay/python
/projects/codes/codes/frequency.py
2,774
3.515625
4
def letters(s): s = s.replace("\n" , "") s = s.replace(" ","") dict = {} for i in s: try: dict[i] += 100.0/len(s) except KeyError: dict[i] = 100.0/len(s) return dict def words(s): s = s.replace("\n" , "") s = s.split(" ") dict = {} f...
f266de074211c4efacce38ce094e3f6ec96369d1
Chuphay/python
/projects/codes/codes/caesar_cipher.py
1,338
3.796875
4
alpha = "abcdefghijklmnopqrstuvwxyz" #ALPHA = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" craze = "OIVDCQZWFMKTGSNPRAHJUXBEYL" def encrypt(s,key): alpha = "abcdefghijklmnopqrstuvwxyz" s = s.replace("\n", "") s = s.lower() output = "" for i in s: try: j = (alpha.index(i)+key)%len(alpha) ...
a42f840b2b70c5ae3adcbbefb583ac55bbd1da88
Chuphay/python
/alg/week1/tp9.py
841
4.03125
4
def merge_sort(array_nums): if(len(array_nums) > 2): array_left = merge_sort(array_nums[:int(len(array_nums) / 2)]) array_right = merge_sort(array_nums[int(len(array_nums) / 2):]) else: if(len(array_nums) == 2): if(array_nums[0] > array_nums[1]): array_nums[0]...
b2f24f2107e8122a54fe84147f5fff3b6bbe1f67
LimeOrangeTree/PYTHON
/function6.py
1,757
3.84375
4
# def f1(): # print("f1()",a,b) # # print("f1()",a,b,c) # def f2(): # c=30 # a=1 # print("f2()",a,b,c) # a=10 # b=20 # f1() # f2() # print(a) def f3(v): print("함수f3",v) s=0 for i in v: s=s+i return s import random # a=[random.randrange(101) for _ in range...
53302b9934f7758c85c628c00e0b60087005f734
LimeOrangeTree/PYTHON
/class1.py
1,576
3.59375
4
# 클래스:현실세계의 사물을 컴퓨터안에서 구현하기 위한 개념, 설계도 # 자동차 # 속성(바퀴, 변속, 연료, 속도, 모델명,...) -->필드,멤버변수(변수) # 기능(속도를 높이다, 속도를 내리다,...) -->메서드(함수) # # 클래스의 정의 # class 클래스명: # 구현내용 # 1.클래스 정의 class Car: wheel=0 method="" fuel="" speed=0 model="" def speedUp(self,value): ...
a1ce6f8c2cc7cc4582aee679f7d05e66aa7b32d4
geekben/codeiscool
/leetcode/1096.py
1,816
3.59375
4
''' "{{a,z},a{b,c},{ab,z}}" "{a,a}" "{a,b}{a,b}" "{a,b}{c,{d,e}}" "{a,b}" "{a}" ''' class Solution(object): def product(self, e1, e2): ret = set() for i in e1: for j in e2: ret.add(i+j) return list(ret) def add(self, e1 , e2): t = set(e1+e2) re...
516ff8cd69b2b3461e77235c44be87d73619bc5a
geekben/codeiscool
/leetcode/113.py
816
3.640625
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def pathSum(self, root, targetSum): """ :type root: TreeNode :type t...
5f0877388ac5b447ee7351a9d8cf86772525513b
geekben/codeiscool
/leetcode/111.py
662
3.828125
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def minDepth(self, root): """ :type root: TreeNode :rtype: int ...
6c8e860f0ac34f6199c71ba0b528622dc980e61a
xdc7/pythonworkout
/chapter-03/01-extra-02-sum-plus-minus.py
1,155
4.15625
4
""" Write a function that takes a list or tuple of numbers. Return the result of alternately adding and subtracting numbers from each other. So calling the function as plus_minus([10, 20, 30, 40, 50, 60]) , you’ll get back the result of 10+20-30+40-50+60 , or 50 . """ import unittest def plus_minus(sequence): sum...
182bc373458a808387825084a7927ff50288e270
xdc7/pythonworkout
/chapter-02/05-stringsort.py
984
4.25
4
""" In this exercise, you’ll explore this idea by writing a function, strsort, that takes a single string as its input, and returns a string. The returned string should contain the same characters as the input, except that its characters should be sorted in order, from smallest Unicode value to highest Unicode value. ...
ba737f0be6d0b303e1c3898d8a9f62350d10a4ec
xdc7/pythonworkout
/chapter-03/03-extra-02-sort-lists-by-inner-list-sum.py
534
4.0625
4
""" Given a list of lists, with each list containing zero or more numbers, sort by the sum of each inner list’s numbers. """ from operator import itemgetter, attrgetter def listSummer(listOfNumbers): result = 0 if not listOfNumbers: return result for n in listOfNumbers: result += n return result def sort...
bf444140753a2c8ee6a5d728b060e26d1d34c01e
xdc7/pythonworkout
/chapter-02/03-extra-02-transpose.py
1,514
3.859375
4
""" Write a function that transposes a list of strings, in which each string contains multiple words separated by whitespace. So if you were to pass the list ['abc def ghi', 'jkl mno pqr', 'stu vwx yz'] to the function, it would return ['abc jkl stu', 'def mno vwx', 'ghi pqr yz']. [ 'abc def ghi', 'jkl mno pqr', 'st...
92188bb3349159b96640692939e9b784426ee41d
xdc7/pythonworkout
/chapter-04/03-restaurant.py
1,383
4.28125
4
""" create a new dictionary, called menu, representing the possible items you can order at a restaurant. The keys will be strings, and the values will be prices (i.e., integers). The program will then ask the user to enter an order: If the user enters the name of a dish on the menu, then the program prints the price a...
a265236d9b35352de75c292cd30b2b66301aae55
xdc7/pythonworkout
/chapter-02/01-pig-latin.py
987
4.25
4
"""write a Python program that asks the user to enter an English word. Your program should then print the word, translated into Pig Latin. You may assume that the word contains no capital letters or punctuation. # How to translate a word to pig latin: * If the word begins with a vowel (a, e, i, o, or u), then add way...
476c3f377be42a32630992fd0fbbc18bce1c9288
xdc7/pythonworkout
/chapter-05/5.2.2-factors.py
1,054
4.28125
4
""" Ask the user to enter integers, separated by spaces. From this input, create a dictionary whose keys are the factors for each number, and the values are lists containing those of the users' integers that are multiples of those factors. """ def calculateFactors(num): factors = [] for i in range (1, num + 1...
52b3d82fd33c70819763939cbb87f065b384b761
xdc7/pythonworkout
/chapter-01/01-number-guessing-game.py
1,116
4.09375
4
import random print ("I'm going guess a number between 0 and 100. Let's see if you can guess it. You have 3 tries. Good Luck! ") winningNumber = random.randint(0,100) counter = 0 success = False while True: userInput = input("Please enter a number between 0 and 100 to see if you guessed right.. ") counter +=...
bfdc1168bf7bbbf621d41de4efb479b1bf4a11fe
xdc7/pythonworkout
/chapter-01/05-extra-01-hex-to-dec.py
1,737
4.25
4
""" Write a program that takes a hex number and returns the decimal equivalent. That is, if the user enters 50, then we will assume that it is a hex number (equal to 0x50), and will print the value 80 on the screen. Implement the above program such that it doesn’t use the int function at all, but rather uses the builti...
244711d401f665a1ad3d655e23c03c7b5414355c
rui725/save22-calib-test
/calculator/test.py
2,217
3.515625
4
import calculatorv2 import unittest class TestCalculator(unittest.TestCase): def test_Add(self): self.assertEqual(calculatorv2.add(1,1),2) with self.assertRaises(TypeError): calculatorv2.add('1',1) # def test_DivideByZero(self): # self.assertFalse(calculatorv2.divide(1,...
0bcf8c8edc408cabefeeafbdd0564addfa20d3ee
peteroh23/Python_CS1110
/a3_final.py
9,276
4.4375
4
""" Functions for Assignment A3 This file contains the functions for the assignment. You should replace the stubs with your own implementations. Magd Bayoumi mb2363 Junghwan (Peter) Oh jo299 October 2, 2017 """ import cornell import math def complement_rgb(rgb): """ Returns: the complement of color rgb. ...
9fb834431395e7c1731816ab96d9eda79cb95faa
keerthivasan0108/basic_python
/data_type_operations/listops.py
575
4.0625
4
x=["karthik","keerthi","gokul"] y=x[1:2] print(y) # its prints index 1 to 2 from list x x.append("raja") print(x) # append a new value in list x x.pop(3) print(x) z=len(x) print(z) a=max(x) print(a) b=min(x) print(b) t=(1,2,3,"k") j=list(t) print(j) f=[12,308,"jh","h"] h=[13,456,"fgh","ss"] f.exten...
4a1ba50c77e7bdc28ad299bb8cdb41e95491172f
naijopkr/bubble-sort
/__main__.py
349
3.8125
4
from bubble_sort import bubble_sort from random import randint if __name__ == '__main__': unsorted_list = [] for i in range(10): unsorted_list.append(randint(0, 100)) sorted_list = bubble_sort(unsorted_list) print('### ORIGINAL ###') print(unsorted_list) print() print('### SORTED ...
9a55d30e41d994379846f228ac70d648dcc39943
DynamicDawson/Blackjack
/account.py
817
3.53125
4
import random import sys class Account: def __init__(self, balance, owner): # private self.__balance = balance self.__minimum_deposit = 5 # public self.owner = owner # take money out def withdraw(self, amount_to_withdraw, quiet=True): if amount_to_withdra...
ecac4b547ee1a6aebd96a0adffd1d7c9c766baa4
wiltrahan/web-caesar
/caesar.py
772
3.890625
4
def alphabet_position(letter): return ord(letter) def rotate_character(char, rot): if char.isalpha(): rotate = alphabet_position(char) else: return char if rotate >= 97 and rotate <= 122: #for lower case cipher = chr(((rotate - 97 + rot) % 26) + 97) return cipher ...
647d4d4a359e45238661383f9e0468f310ec02ac
nicolasgasco/python_twitter_analyzer
/older_scripts/data_analysis.py
2,283
3.765625
4
import os import tweepy import json import re from pprint import pprint def json_to_list(filename): """Function to import data set from a JSON file""" with open(filename) as f: tweets = json.load(f) return tweets def calculate_average_tweet(dataset): """Function to calculate the average lengt...
38a591219f2e390385353788fa8c1eb969e4d253
maurice-gallagher/exercises
/chapter-5/ex-5-6.py
2,004
4.5
4
# Programming Exercise 5-6 # # Program to compute calories from fat and carbohydrate. # This program accepts fat grams and carbohydrate grams consumed from a user, # uses global constants to calculate the fat calories and carb calories, # then passes them to a function for formatted display on the screen. # Glo...
9c91cf1be003d87994b420f33fd68852a7ac0023
rletilly/TD2_blockchain_programming
/Some_math_functions.py
7,778
4.0625
4
class Point: def __init__(self, x=0, y=0, z=0): self.x = x self.y = y self.z = z class Math: @classmethod def multiply(cls, p, n, N, A, P): """ Fast way to multily point and scalar in elliptic curves :param p: First Point to mutiply :param n: Scalar...
44675ef8643b07667ea30633c2623a4a5cdda4ee
sivanelavalli/python-all
/nesteddict.py
215
3.78125
4
mydict= {'x': {'items':['a','b','c']},'y': {'items':['d','e','f']},'z':{'items':['a','b','c']}} for v in mydict.values(): for c in v.values(): for i in c: print(i,end="") print()
57dc9ca81d87c80e76f425daa458726041568c5b
sivanelavalli/python-all
/lambda.py
133
3.546875
4
from functools import * numbers=range(10) new_list=[] x=[lambda n:n**2 for n in numbers if n%2==0] new_list.append(x) print(new_list)
7e73c6098239bc7f221f48e075bb6efe6192b365
sivanelavalli/python-all
/avgofnumbers.py
285
3.796875
4
class Test: def fun1(self): n=int(input("Enter a number of elements to be inserted")) a=[] for i in range(0,n): e=int(input("Enter a number:")) a.append(e) avg=sum(a)/n print("The average of list is :",round(avg,2)) t=Test() t.fun1()
9e0eaeb5f42df5fadff93afa54568bbd62d3a981
sivanelavalli/python-all
/randomnumber.py
438
4.0625
4
import random print("Start the game") while True: n=int(input("Enter the number between 1 to 10: ")) i=random.randint(1,10) if(n!=i): print("Your number is: ",n) print("Random number is: ",i) print("Your guess is wrong") continue else: print("Your number is: ", n)...
e381b07f7d861761a73092a8ec900ff8315230bf
HowardHung2/YoutubeCourse_Python_Basic_20210804
/basic_calculator.py
547
3.953125
4
# 建立一個基本計算機 from typing import AsyncGenerator name = input("請輸入您的名字 : ") print("哈囉, " + name + "\n歡迎體驗簡易計算機") print("====第一部分 整數計算機====") num1 = input("請輸入第一個整數數字 :") num2 = input("請輸入第二個整數數字 : ") print(int(num1)+int(num2)) print("====第二部分 小數計算機====") num3 = input("請輸入第一個小數數字 :") num4 = input("請輸入第二個小數數字 : ") print(...
9c8aff30d002d28716a346e86ec80aad952b694a
kaneki666/Hackerrank-Solve
/cats-mouse.py
124
3.859375
4
c1=5 c2=4 m =3 if abs(c1-m)< abs(c2-m): print("c1") elif abs(c1-m) == abs(c2-m): print("m") else: print("c2")
54a79c7755d6c804387a8035e557d25e80f95586
kaneki666/Hackerrank-Solve
/designer-pdf-viewer.py
287
3.515625
4
from string import ascii_lowercase word = "name" result = [] a = [1, 3, 1, 3, 1, 4, 1, 3, 2, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5] for i in word: result.append(a[ascii_lowercase.index(i)]) print(result) h = max(result) print(h) pdf = h* len(word) print(pdf)
ea4c0e06472028fbf78b54bdeccb909f84d3a8ea
kaneki666/Hackerrank-Solve
/bucket sort.py
1,003
4
4
import math def insertion_sort(collection): for index in range(1, len(collection)): while 0 < index and collection[index] < collection[index - 1]: collection[index], collection[ index - 1] = collection[index - 1], collection[index] index -= 1 return col...
66d6a2acb02bcd6459dc8b078edd146ae2149b85
turtlegraphics/advent-of-code-2018
/day20/Parser.py
1,608
3.515625
4
import Node class Parser: def __init__(self,path,debug=False): self.debug = debug self.path = path self.current = 1 self.root = self.parse_and(0) def debug_out(self,who,depth): if self.debug: print '-'*depth+who,'self.current=',self.current, prin...
e9b8e0b6afffde1421bcf2623ee54096dbc14282
zlatianiliev/MachineLearning
/regression/support_vector_regression.py
997
3.59375
4
import numpy as np import matplotlib.pyplot as plt import pandas as pd from sklearn.svm import SVR from sklearn.preprocessing import StandardScaler # import dataset dataset = pd.read_csv('../data/Position_Salaries.csv') X = dataset.iloc[:, 1:2].values y = dataset.iloc[:, 2].values.reshape(-1,1) # Feature Scaling sc...
79a78be865d066b2308d2e5fb1ecd4d68c40e13f
ARTEAGA1811/PracticandoEjerciciosPython
/teoria/metodosFib.py
579
3.71875
4
def calcularFibonnaci(num): #0:0 1:1 2:2 3:3 4:5 5:8 liFib = list() liFib.append(0) liFib.append(1) liFib.append(2) for i in range(3, num+1, 1): liFib.append(liFib[i-1]+liFib[i-2]) return liFib[num] def calcularFibOptimizado(num): nmenosDos = 1 nmenosUno = 2 resul...
97f35d24dfc164c19fed024b60972a7db7681a90
ARTEAGA1811/PracticandoEjerciciosPython
/General/trollCoder.py
1,240
3.609375
4
def enviarBits(miLista): mensaje = 'Q' for i in miLista: mensaje+= ' '+str(i) return mensaje def cambiarBit(miLista, ind): if(miLista[ind] == 0): miLista[ind] = 1 else: miLista[ind] = 0 def enviarRespuesta(miLista): mensaje = 'A' for i in miLista: ...
88db24679a426c77ca07afabc2214fd937f7df16
stravajiaxen/project-euler-solutions
/project-euler-solutions/p1/euler1.py
735
3.921875
4
""" Copyright Matt DeMartino (Stravajiaxen) Licensed under MIT License -- do whatever you want with this, just don't sue me! This code attempts to solve Project Euler (projecteuler.net) Problem #1 Multiples of 3 and 5 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The ...
45a831a210c1014203a25caf5634abafed1d3ce0
stravajiaxen/project-euler-solutions
/project-euler-solutions/p23/euler23.py
3,538
3.734375
4
""" Copyright Matt DeMartino (Stravajiaxen) Licensed under MIT License -- do whatever you want with this, just don't sue me! This code attempts to solve Project Euler (projecteuler.net) Problem #23 Non-abundant sums A perfect number is a number for which the sum of its proper divisors is exactly equal to the number....
dcbc49b023df83bed2d0e53d8a42233bd9350f17
nazariyv/leetcode
/solutions/medium/search_in_a_sorted_array_of_unknown_size/main.py
546
3.625
4
#!/usr/bin/env python class ArrayReader: def get(self, index: int) -> int: ... class Solution: def search(self, reader: 'ArrayReader', t: int) -> int: l, r = 0, 2 ** 31 - 1 while l <= r: mid = l + (r - l) // 2 val = reader.get(mid) if val == t: ...
da5c9b5e198faf5d27c557e7143483690dbd25bd
nazariyv/leetcode
/solutions/medium/online_stock_span/main.py
422
3.734375
4
#!/usr/bin/env python from typing import List, Tuple class StockSpanner(object): def __init__(self) -> None: self.stack: List[Tuple[int, int]] = [] def next(self, price: int) -> int: weight = 1 while self.stack and self.stack[-1][0] <= price: weight += self.stack.pop()[1] ...
dbec9a2d077d6a10e907c36263ab1ff729ccb1fb
nazariyv/leetcode
/contests/02_05_2020/3.py
924
3.796875
4
#!/usr/bin/env python # def checkIfCanBreak(s1: str, s2: str) -> bool: # sorted1 = sorted(s1) # sorted2 = sorted(s2) # result = 0 # for idx in range(len(s1)): # if sorted1[idx] < sorted2[idx]: # if result not in (0, 1): # return False # result = 1 # ...
8dcce1b7ddfd7fd9b9c6c8ef6359628b90fe1ae9
nazariyv/leetcode
/solutions/easy/merge_sorted_array/main.py
5,181
3.546875
4
#!/usr/bin/env python from array import array from typing import List, Optional class Stack: def __init__(self): self.stack = [] def push(self, x: int) -> None: self.stack.append(x) def pop(self) -> Optional[int]: if not self.stack: return None else: ...
73c69eef48ca6c8c8b7b63469ab0615ce479b1dc
nazariyv/leetcode
/contests/02_05_2020/1.py
175
3.515625
4
#!/usr/bin/env python def candies(cands: List[int], extraCandies: int) -> List[bool]: largest = max(cands) return [cand + extraCandies >= largest for cand in cands]
5ae4dcf374a47f87dde1656ae615ef103fa491c2
nazariyv/leetcode
/solutions/medium/binary_tree_preorder_traversal/main.py
782
3.59375
4
#!/usr/bin/env python from typing import List from solutions.minions import Tree as TreeNode # recursive def preorderTraversal(root: TreeNode) -> List[int]: if not root: return [] res = [] res.append(root.val) res += preorderTraversal(root.left) res += preorderTraversal(root.right) re...
0b8aa888c296b4456b1af73c99514c79b3856d3b
nazariyv/leetcode
/solutions/easy/reverse_linked_list/main.py
1,157
3.53125
4
#!/usr/bin/env python from solutions.minions import TestCase as T, TestRunner as TR, ListNode def main(head: ListNode) -> ListNode: prev_node = None curr_node = head while curr_node: next_node = curr_node.next # Remember next node curr_node.next = prev_node # REVERSE! None, first time rou...
5bb552a315296aa7ac2b492f3bb3e4d2bb23570f
nazariyv/leetcode
/solutions/medium/valid_parenthesis_string/repro.error.py
928
3.734375
4
#!/usr/bin/env python from typing import Generator def combo_generator(s: str, stars: int) -> Generator[str, None, None]: if stars == 0: print(s) yield s return else: star_ix = s.find("*") left_part = s[:star_ix] right_part = s[star_ix + 1:] ...
667c668af92cafa7af07828df395d4d43b948b75
nazariyv/leetcode
/solutions/medium/bitwise_and_of_numbers_range/main.py
554
4.3125
4
#!/usr/bin/env python # Although there is a loop in the algorithm, the number of iterations is bounded by the number of bits that an integer has, which is fixed. def bit_shift(m: int, n: int) -> int: shifts = 0 while m != n: m >>= 1 n >>= 1 shifts += 1 return 1 << shifts # if n...
215968c294e72b0174a201b58044eb843de25257
arunava001OS/STANDARD-ALGORITHMS
/DIVIDE AND CONQUER/kthrankfinding.py
592
3.671875
4
##ERRORO def FindAprxmedian(array): print("ARRAY") print(array) A = [] for i in range(0,len(array)+1,5): print("I") print(i) if(len(array)-i>=5): test = A[i:i+5] else: test = A[i:] test = test.sort() print("TEST") print(tes...
f27912df4ef1ed93c492ec5c52c7b142fcb5fa13
mcuong223/multivariate-linear-regression-model
/tools.py
1,012
3.875
4
from statistics import mean from sklearn import preprocessing import pandas import matplotlib.pyplot as plt def slope(xs, ys): """ Calculate and return the slope of the best-fit-line Parameters ---------- xs : array-like or sparse matrix x values ys : array_lik...
c8acbe7fcf63326f76f371039681e30928046805
Hemie143/Smart_Calculator
/Problems/Tallest people/task.py
202
3.9375
4
def tallest_people(**people): max_height = max(people.values()) result = {k: v for k, v in people.items() if v == max_height} for k, v in sorted(result.items()): print(f'{k} : {v}')
a43d05240cc40858fcdcece90b749048d57d44c1
Hemie143/Smart_Calculator
/Problems/Frequency Dictionary/task.py
177
3.6875
4
# put your python code here entry = input().split() entry = [e.lower() for e in entry] data = {e: entry.count(e) for e in entry} for k, v in data.items(): print(f'{k} {v}')
3fa831562da12e110dd14e03e19b131f5fecab54
jwalton3141/jwalton3141.github.io
/assets/posts/rose_plots/rose_plots.py
3,627
3.578125
4
#!/usr/bin/env python3.5 import numpy as np import matplotlib.pyplot as plt def rose_plot1(ax, angles, bins=16, density=None, xticks=True, **param_dict): """ Plots polar histogram of angles. ax must have been created with using kwarg subplot_kw=dict(projection='polar'). """ # To be safe, make a coppy...
014aff8932647d19ab77c2152348581eaa5a4e2c
isabelleferreira3000/ces-22-exercicios
/Slide 1/questao-3-11.py
222
3.640625
4
import turtle wn = turtle.Screen() wn.bgcolor("white") tess = turtle.Turtle() tess.shape("blank") for i in range(5): tess.forward(100) # Move tess along tess.right(144) # ... and turn her wn.mainloop()
46dff65b60a582e572a9b4b3256aae5d48b8432e
isabelleferreira3000/ces-22-exercicios
/2o bimestre/Design Pattern/Decorador.py
802
3.6875
4
# the Window base class class Window(object): def draw(self, device): device.append('flat window') def info(self): pass # The decorator pattern approch class WindowDecorator: def __init__(self, w): self.window = w def draw(self, device): self.window.draw(device) ...
f720cb806c84d05a14467c406f26b9701bf540dd
xingexu/PythonFiles
/SQlite.py
872
3.984375
4
import sqlite3 with sqlite3.connect("PhoneBook.db") as db: cursor = db.cursor() cursor.execute(""" CREATE TABLE IF NOT EXISTS Names( id integer PRIMARY KEY firstname text, surname text, phonenumber text); """) cursor.execute(""" INSERT INTO Names(id,firstname,surname,phonenumber) VALUES("1","Simon", "Howels","01...
bd3ab7799d3ec2939234d30a9ddaf2e4b96e8c32
trew13690/CSC101Code
/Work/Week5/classlevel.py
421
3.828125
4
def Level(Ncredits): classlevel = "None" if Ncredits<45: classlevel = "Freshman" elif Ncredits >=45 and Ncredits <= 89 : classlevel = "Sophomore" elif Ncredits >= 90 and Ncredits <=135: classlevel = "Junior" else: classlevel = "Senior" #Write the rest of the code needed to classify eac...
db083e52934de50a6dadd2ee7da9327955800469
trew13690/CSC101Code
/Work/Week 6/loops.py
1,744
4.09375
4
#loops.py will compute the feul efficiency of a multi-leg journey def main(): print('Welcome to the efficient fuel program!\n') data = [] data = promptUser() print("This is the data for each leg") for num in range(len(data)): print('_' * 20) print("Leg "+ str(num) + '| MPG was at :'...
057b68dfbdd6924620d0dbe02d29f24e6d5fc920
Ghejt/ezpython
/Lab5B-Commpression.py
246
3.734375
4
def compress(word): x = 0 while x < len(word): number = str(word.count(word[x])) if x == len(word) - 1: print("") elif word[x] != word[x + 1]: print(word[x] + number, end="") x += 1
d1339632685bfd9d2301cadf78d79419530d1d32
gul18/PythonCode-
/Patterns/Alphabetic_pattern.py
141
3.578125
4
#print pattern 1 for i in range(1, 6): for j in range(65, 65+i): a = chr(j) print(a, end="") else : print()
86d16463ae3f57e3e9ba9ecb1cd60310aa381b1c
BahaaShammary/Python
/Numpy/Data Structures.py
6,253
4.15625
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: mylist = [1, 2, 3, 4 ,1, 2, 50] # In[ ]: print(mylist[len(list)-1]) # In[ ]: for i in range(1, 10, 2): print(i) # In[ ]: days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] # In[ ]: days.insert(5, 'Bunday') # In[ ]...
2152b6190e71655b52c43fabfd4fa3bf24e945f2
Mintri1199/Interview-Practice
/2019 Stuffs/valid_boomerang.py
1,106
3.78125
4
# A boomerang is a set of 3 points that are all distinct and not in a straight line. # # Given a list of three points in the plane, return whether these points are a boomerang. # Input: [[1,1],[2,3],[3,2]] # Output: true # Input: [[1,1],[2,2],[3,3]] # Output: false import operator import functools def isBoomerang(po...
15f34243924674a331388065469337f84faf8efd
Mintri1199/Interview-Practice
/2019 Stuffs/SPD2.4/two_sum_binary_tree.py
756
3.6875
4
from binary_tree import BinarySearchTree import queue # Two sum but binary search tree for the data structure tree = BinarySearchTree([6, 4, 9, 1, 3, 7, 8]) def two_sum(input, t): result = [] visited_nodes = set() # level order traversal and search for compliment q = queue.LifoQueue() q.put(input...
6aef1e977dab320b4f6e71192e045f3d1924315d
Mintri1199/Interview-Practice
/2019 Stuffs/SPD2.4/combine_linked_lists.py
2,093
3.828125
4
# Given an array of k linked lists, # each of whose items are in sorted order, # combine all nodes (do not create new nodes) into a single linked list with all items in order. class Node: def __init__(self, data): self.data = data self.next = None class LinkedListIterator: def __init__(self,...
36cc9d8e29fdbd91be8490fd2312207ac501c5a7
Mintri1199/Interview-Practice
/2019 Stuffs/group_questions/linked_list_convergence.py
2,199
3.828125
4
class Node: def __init__(self, data): self.data = data self.next = None class LinkedListIterator: def __init__(self, head): self.current = head def __iter__(self): return self def __next__(self): if not self.current: raise StopIteration els...
bc33ce706a85ee11b4aeb822256b4c23bf7f1a5e
karina-chi/python-10-2020
/Lesson2/task2.py
716
4.21875
4
# Для списка реализовать обмен значений соседних элементов, т.е. # Значениями обмениваются элементы с индексами 0 и 1, 2 и 3 и т.д. # При нечетном количестве элементов последний сохранить на своем месте. # Для заполнения списка элементов необходимо использовать функцию input(). items = input("Укажите значения спи...
681f5923ba73a1cb00f0a65491810337d8b9cc92
karina-chi/python-10-2020
/Lesson4/task5.py
704
4.03125
4
# Реализовать формирование списка, используя функцию range() и возможности генератора. # В список должны войти четные числа от 100 до 1000 (включая границы). # Необходимо получить результат вычисления произведения всех элементов списка. # Подсказка: использовать функцию reduce(). from functools import reduce n...
c40475129a14dba4617b6c8ccac4c513195218ee
karina-chi/python-10-2020
/Lesson1/task3.py
130
3.578125
4
n = int(input("Введите целое число: ")) x = str(n) nn = int(x + x) nnn = int(x + x + x) print(n + nn + nnn)
ae2b39c93186f43ca855506bd4152e818fbb8117
melaniemai/host
/newHostSocket.py
590
3.609375
4
import socket import sys def getHostName(): hostname = socket.gethostname() print("Host Name for this machine : " + hostname) def getIP(): print("IPv4 Address Assigned to this machine are :") ipadd = socket.gethostbyname_ex(socket.gethostname())[-1] for i in ipadd: print("\t " + i) # ...
e305999659409116a695be650da868d41cad775c
sandeepbaldawa/Programming-Concepts-Python
/recursion/regex_matching_1.py
1,453
4.28125
4
''' Implement a regular expression function isMatch that supports the '.' and '*' symbols. The function receives two strings - text and pattern - and should return true if the text matches the pattern as a regular expression. For simplicity, assume that the actual symbols '.' and '*' do not appear in the text string...
96a0bc369ee2198c2bc03d5d555d6449a4339693
sandeepbaldawa/Programming-Concepts-Python
/recursion/cryptarithm.py
2,093
4.28125
4
Cryptarithm Overview The general idea of a cryptarithm is to assign integers to letters. For example, SEND + MORE = MONEY is “9567 + 1085 = 10652” Q. How to attack this problem? -Need list of unique letters -Try all possible assignments of single digits -Different arrangemen...
940b8a11fe2ca8eead03a329f77dd09aca8eda60
sandeepbaldawa/Programming-Concepts-Python
/bitwsei/reverse_num.py
162
3.859375
4
def reverse(x): res , last_digit = 0, 0 while(x): last_digit = x % 10 res = res * 10 + last_digit x = x/10 return res print reverse(321)
755b00e91ec28072644b1b471699d63b758e5c09
sandeepbaldawa/Programming-Concepts-Python
/data_structures/disjoint_sets/merge_tables.py
3,143
4.0625
4
''' Problem Introduction In this problem, your goal is to simulate a sequence of merge operations with tables in a database. Problem Description Task. There are n tables stored in some database. The tables are numbered from 1 to n. All tables share the same set of columns. Each table contains either several rows with r...
d4590a47cef2e5a4cdbbf496893113fd67c9c42f
sandeepbaldawa/Programming-Concepts-Python
/recursion/flip_game.py
974
3.765625
4
""" You are playing the following Flip Game with your friend: Given a string that contains only these two characters: + and -, you and your friend take turns to flip two consecutive "++" into "--". The game ends when a person can no longer make a move and therefore the other person will be the winner. Write a functio...
0cf648492830abdbcf8991d522a359407fa22b19
sandeepbaldawa/Programming-Concepts-Python
/trees/get_lca.py
862
3.625
4
# https://www.youtube.com/watch?v=NBcqBddFbZw # https://www.youtube.com/watch?v=bl-gwEwm8CM from print_tree import * def getLca(curr, A, B): assert(A != B) if not curr: return None # Try to find node A and node B if (curr == A or curr == B): return curr left = getLca(curr.left, ...
de4ec11e99f35ec81f0e4f052f612e7003d3a516
sandeepbaldawa/Programming-Concepts-Python
/strings/diff_dates.py
174
3.609375
4
from datetime import datetime def days_between(d1, d2): d1 = datetime.strptime(d1, "%Y-%m-%d") d2 = datetime.strptime(d2, "%Y-%m-%d") return abs((d2 - d1).days)
fa675e0433e9375f293d7ced5fbe8d62c6df2c23
sandeepbaldawa/Programming-Concepts-Python
/lcode/fb/medium_power.py
727
3.71875
4
''' Brute force is doing a x*x*x*x..n which takes O(2^N) where N is number of bits needed to represent x For optimizing if LSB of x is 0(product of "2") then result is (x^n/2)^2 else result is x * (x^n/2)^2 Also x^(y0 + y1) = x^y0 * x^y1 eg:- x^9 = x^(1010) = x^101 * x^101 x^101 = x^100 * x = x^10 * x^10 * x x 9 ...