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
a48b657a7e199eb54e5516628f7d2253b417b482
GMwang550146647/network
/0.leetcode/0.基本的算法/1.递归/5.1.找零问题(字典优化递归).py
1,486
3.59375
4
import numpy as np import time ''' 问题描述: 有25,10,5,1的纸币,然后找找零50元,如何才能用最少的纸币数量 ''' '''1.未经优化的原始递归方法''' class getMinCoins(): def __init__(self,goal,coins=[25,10,5,1]): self.left=goal self.coins=coins #用递归计算会产生好多无效的计算过程,需要用字典记录或者使用字典优化 def recMC(self,left,currentList=[],record={}): if re...
7b744a127c3014f443ffb12e6daee6d8483f1a4d
GMwang550146647/network
/0.leetcode/3.刷题/1.数据结构系列/1.线性结构/3.栈/1.单调栈/255.mid_验证前序遍历序列二叉搜索树.py
2,100
3.578125
4
from fundamentals.test_time import test_time class Solution(): def __init__(self): pass @test_time def verifyPreorder(self, preorder): first_largest = [0] * len(preorder) stack = [] for i in range(len(preorder) - 1, -1, -1): while stack and stack[-1][0] <= preo...
8b61c267e2e4b0da7c2d3565709cdd0dce617ddb
GMwang550146647/network
/python基本语法/1.基本方法/1.0基本语法/9.闭包.py
913
4.1875
4
''' 闭包: 1.函数中定义的函数 2.外部函数把内部函数返回 3.这内部函数引用外部函数的值 作用: 1.保存并返回闭包时的状态(外层函数变量) 实现原理: 由于函数还没去除引用,所以其对应的内存尚未被消掉 ''' '''1.调用外层函数的值''' def outterfunc(c): a=100 def inner_func(): b=99 print(a,b,c) print(locals()) return inner_func x=outterfunc(10) x() '''2.调用同级函数''' def outfun(c): a=10...
f6f6013db17d314ca739a9ebc124637808a114ae
GMwang550146647/network
/0.leetcode/0.基本数据结构/2.树形结构/1.二叉查找树/2.2.树的遍历(栈).py
4,557
3.828125
4
class node(object): def __init__(self, elem=-1, lchild=None, rchild=None): self.elem = elem self.lchild = lchild self.rchild = rchild class tree(object): def __init__(self, arr): self.root = node() self.myqueue = [] self.add_arr(arr) def add_one(self, value...
4f63d8015f9941746f8d00760d7de222308dd31a
GMwang550146647/network
/1.networkProgramming/2.parallelProgramming/3.coroutines/2.pythonCoroutines/2.Awaitables.py
2,275
4.15625
4
""" 三种 Awaitable Objects 1.Coroutines 2.Tasks 3.Futures """ import asyncio import concurrent.futures """ 1.Coroutines async 包装的函数都会转换成一个Coroutines函数,如果没有await,函数不会调用,会返回Coroutines对象 """ def coroutines(): """用于直接运行的任务""" async def nested(): return 42 async def main(): # Nothing happens i...
543392bc28fcddf13642332e1cc9a08678ca5933
GMwang550146647/network
/0.leetcode/3.刷题/1.数据结构系列/1.线性结构/2.链表/1.反转链表/25.hard_K 个一组翻转链表(core).py
3,594
3.515625
4
from fundamentals.test_time import test_time from fundamentals.link_list import LinkList, ListNode class Solution(): def __init__(self): pass # @test_time def reverseKGroup_recur(self, head, k): """ 递归比较优美 """ def reverse(lp, rp): """ 翻转 [l...
eb57caf9e1def9550927a8732b8bf1b8c1e49890
GMwang550146647/network
/0.leetcode/0.基本的算法/1.递归/2.递归可视化:分形树.py
685
3.96875
4
import turtle t=turtle.Turtle() ''' turtle是一个划线的包 爬行: forward(n);backward(n) 转向: left(a) ;right(a) 抬笔放笔:penup(); pendown() 笔属性: pensize(s);pencolor(c) ''' '''1.螺旋线''' def drawSpiral(t,lineLen): if lineLen>0: t.forward(lineLen) t.right(90) drawSpiral(t,lineLen-5) # drawSpiral(t,200) # turtl...
3c892e6eaf3c7172c327304a6eeab9dbefdd3654
GMwang550146647/network
/0.leetcode/0.基本的算法/4.排序/8.(搞笑)线程排序法.py
939
3.625
4
import threading import time class ThreadSort(): def __init__(self,arr): self.arr=arr self.sorted_arr=[] def sleep_print(self,sec): time.sleep(sec/10000.0) # print(sec) self.sorted_arr.append(sec) def thread_sort(self): n_threads=len(self.arr) threads...
fb6fa84a33e3de27d87f751c40ad466850e1b101
GMwang550146647/network
/0.leetcode/0.基本的算法/4.排序/5.归并排序MergeSort.py
625
4.0625
4
def mergeAssis(arr1,arr2): i=0 j=0 arr=[] while i<len(arr1) and j<len(arr2): if arr1[i]<= arr2[j]: arr.append(arr1[i]) i+=1 else: arr.append(arr2[j]) j+=1 if j==len(arr2): arr.extend(arr1[i:]) else: arr.extend(arr2[j...
a6cb32b92bc3b21e20af5d684905bbc72ec2aa82
GMwang550146647/network
/1.networkProgramming/2.parallelProgramming/2.multiThreading/9.0.ThreadPool.py
3,003
3.890625
4
""" 池 程序还没开始的时候,还没提交任务,先创建几个线程或者进程 为什么要用池 先开好,有任务的时候就能直接使用了(开的时候浪费时间) 开好的线程或者进程一直在池中,可以反复使用,极大减少 开启/关闭/调度线程(进程)的时间开销 池中的线程(进程)个数决定了操作系统需要调度的任务个数,控制池中的单位 有利于提高操作系统的效率,减轻操作系统负担 历史 threading 模块 没有提供池 multiprocessing 模块 仿照threading写的 有Pool concurrent.futures模块 线程池,进程池都能使用相似的方式开启/关闭 基本功...
2261efc830be6ad6e80806458ed52babe6ce1783
GMwang550146647/network
/0.leetcode/3.刷题/1.数据结构系列/1.线性结构/3.栈/0.栈(先进后出)/1.计数器/224.hard_基本计算器(core!)(+-()).py
1,933
3.65625
4
from fundamentals.test_time import test_time class Solution(): def __init__(self): pass # @test_time def calculate_recur(self, s): def solve(s): """ 核心: 只计算到 ')'就返回当前算式的结果 返回: 当前算式的结果以及后面剩下的算式 """ ...
2868e36293d4708160e97cb3736ce5bbe7a351a1
GMwang550146647/network
/0.python_higher/2.design_mode/1.创建型模式/1.单例设计模式/tttt.py
555
3.640625
4
class Counter(type): def __init__(self,*args,**kwargs): self.__instance=None def __call__(self, *args, **kwargs): if self.__instance is None: self.__instance=super().__call__(*args,**kwargs) return self.__instance else: return self.__instance class My...
00597ffe70d0e00990e4420d05ceac1d8dcdee3a
GMwang550146647/network
/0.leetcode/3.刷题/1.数据结构系列/1.线性结构/3.栈/1.单调栈/946.mid_验证栈序列(core).py
783
3.59375
4
from fundamentals.test_time import test_time class Solution(): def __init__(self): pass @test_time def validateStackSequences(self, pushed, popped): """ 模拟法:一次push一个,一旦该个和pop中的是一样的,同时pop出来! """ stack = [] i = 0 for num in pushed: stack.a...
fcf2ffff2f47aad7c4a85fcb80bab0498461b513
GMwang550146647/network
/0.leetcode/3.刷题/3.数学/???.素数(core).py
1,332
3.78125
4
from fundamentals.test_time import test_time import math """ 寻找 [2,n)范围的素数 """ class Solution(): def __init__(self): pass @test_time def countPrimes(self, n): """ 从2 计算到 n**0.5 """ def isPrime(n): i = 2 while (i ** 2 <= n): ...
b807a0fb30a03c4ed7fc7cacfeeca4b48a01cd45
Ramanpreet19/Classical-Machine-Learning
/assignment2_coding/dt_fit.py
7,909
3.734375
4
import numpy as np import math import pandas as pd def entropy_func(c, n): """ The math formula """ return -(c*1.0/n)*math.log(c*1.0/n, 2) def entropy_cal(c1, c2): """ Returns entropy of a group of data c1: count of one class c2: count of another class """ if c1== 0 or c2 == 0...
d36b495cfd94ae7f9e4e8aee777dcd207718335b
mozancetin/codesinvideos
/Codes/mac_changer.py
364
3.640625
4
import random liste = [1,2,3,4,5,6,7,8,9,"A","B","C","D","E","F"] mac = [] for i in range(6): a = random.choice(liste) b = random.choice(liste) ikili = str(a) + str(b) mac.append(ikili) ikili = None mac_adresi = mac[0] + ":" + mac[1] + ":" + mac[2] + ":" + mac[3] + ":" + mac[4] + ...
d592ed48572e47bbb7709131bad8c306d86485d9
ftt/programming-praxis
/20090310-word-frequencies/word-frequencies.py
1,144
3.75
4
import sys # generally, Counter from the standard library would be more appropriate def count_words(filename, n): counts = {} with open(filename) as f: line = f.readline() # defaultdict here while line != "": words = (w.strip() for w in line.split()) for w in wo...
c4ecc8e4bd9baab72f92b34bfba6a537ff049fea
ftt/programming-praxis
/20090219-bingo/bingo.py
1,545
3.609375
4
#!/usr/bin/env python import random WIN_INDICES = [ range(0, 5), # columns range(5, 10), range(10, 15), range(15, 20), range(20, 25), range(0, 25, 5), # rows range(1, 25, 5), range(2, 25, 5), range(3, 25, 5), range(4, 25, 5), [0, 6, 12, 18, 24], # diagonals [4, 8, 12,...
6e825754631ff95f6d8748bf06dff4f8322a1d87
srijamk/beaverworks-2018
/student_cost.py
4,092
4.46875
4
""" # Problem Summary You work at a pizza restaurant, which is starting to accept orders online. You need to provide a python function that will accept arbitrary orders, and compute the correct price for the order. A single pizza order is formed as a list of toppings. For example A pizza with no...
45691da5111df0b8a144dbdd5b31204333fb692a
mariamhmahmoud/graph-algos
/prims.py
1,575
3.609375
4
import math import matplotlib.pyplot as plt class Prim: def __init__(self, coords): self.coords = coords self.k = [False] * (len(coords)) self.d = [float('inf')] * (len(coords)) self.v = list(range(0, len(coords))) def algo(self): self.d[0] = 0.0 vertex = 0 for a in range(len(self.coords)): distanc...
e7badf5609e172848b358ba00c9cf4eac3d935c0
ksaittis/learning_python
/shopping_backet_tdd/test/shopping_basket_test.py
1,722
3.828125
4
from dataclasses import dataclass from typing import List from unittest import TestCase @dataclass class Item: unit_price: float quantity: int @dataclass class ShoppingBasket: items: List[Item] def __init__(self): self.items = [] def get_total_value(self): if len(self.items) > ...
e11276920898a8b10094529d4cabf7c1331b2f0e
python-marketing-research/python-marketing-research-1ed
/python_marketing_research_functions/chapter7.py
2,052
3.765625
4
""" This module contains all function from Chapter 7 of Python for Marketing Research and Analytics """ import matplotlib.pyplot as plt import numpy as np from statsmodels.graphics import gofplots, regressionplots def generate_satisfaction_scores(mean, std, halo, score_range=(0, 100...
69d9a53c6608d69a1f5bc9ea910f8cae6796bbcb
OnlyOne101/Big-Hacker-Script
/bighax.py
245
3.765625
4
import os you = input("1337 or not. Type one: ") os.system("cls") if you != "1337": print("Noob lol") print("---------\n\n") you = "Noob" while you == "Noob": print("Hacking your Toaster...") break else: print("Good Boy")
552d6c5111fb64b94986098ba45a4d0395689ca7
simonsayscodes/School
/4/whgjawkg.py
199
3.984375
4
for x in range (1,101): if x % 3 == 0 and x % 5 ==0: print ("FizzBuzz") elif x % 3 == 0: print ("F9zz") elif x % 5 == 0: print ("B9zz") else: print(x)
ee2338dee68c487ab32b37298a631801ba294639
simonsayscodes/School
/4/just playing around.py
152
4.25
4
name = "pimon" age = 18 print(f"Hello my name is {name} and I am {age} ") if name is "Simon": print ("hello") else: print ("What it's not me?")
dd3f71b2c1f249e12b58bee748a8f4fcc7a2e0f0
AndersonNascimentoAFSN/codenation-aceleradev
/data-science-2/main.py
10,322
3.75
4
#!/usr/bin/env python # coding: utf-8 # # Desafio 4 # # Neste desafio, vamos praticar um pouco sobre testes de hipóteses. Utilizaremos o _data set_ [2016 Olympics in Rio de Janeiro](https://www.kaggle.com/rio2016/olympic-games/), que contém dados sobre os atletas das Olimpíadas de 2016 no Rio de Janeiro. # # Esse _d...
3ab42b5c6dd53801665c743fe3c0af359e8064f1
arthurtibame/basic_python_course
/part04_forLoop/00_basicForLoop.py
136
3.765625
4
# 印出 1 到 10 for i in range(0, 11): print(i) print() # 印出 1 到 10 之間的偶數 for i in range(0, 11, 2): print(i)
23fbc464d1ae3da473af5e661c4cf8457925f3b8
arthurtibame/basic_python_course
/part01_basicInformation/00_helloWorld.py
660
3.75
4
# 第一支程式 print('Hello world') # 這是一段註解 # 此段註解不會顯示在程式輸出結果 ''' 此為另一種註解方式 ''' # 試試印出其他東西 print('My name is Allen') print(123) print('字串必須用單引號或雙引號包住') print("這也是字串的表示方式") print('Hello', 'world', '可以用逗號將多個資串隔開', 123, 333) # 跳脫字元 print('使用\n可以換行') print('print使用完畢後,預設會自動換行') print('若要讓\n顯示出來') print('則需要打兩次反斜線\\n') # 使用\t會...
a87cbb87d4f5dd9485b2ce956150d7496c8d9dd9
lavila2010/Ironhack-pre-work
/Bus.py
869
3.75
4
import statistics as stats def main(): stops = [(10, 0), (4, 1), (3, 5), (3, 4), (5, 1), (1, 5), (5, 8), (4, 6), (2, 3)] bus_stops=len(stops) print("Total Bus Stops:", bus_stops) bus_occupation = 0 bus_stop=[] for x,y in stops: bus_in= x bus_out= y buss_flow...
c6f1bccfb26a8c5d86fc0a38b694aef800d22dc6
AirScythe/Maze_Searching
/astar.py
3,453
3.921875
4
# ------------------------------------------------------------------------ # A* Search of maze # # Date:7/20/2021 # Name: Anthony Dawson # ------------------------------------------------------------------------ import graph class astar(object): def __init__(self, maze_graph, start, goal): self.maze_gr...
0c11208cbee7896245286b25769b83843ca1e17e
blackplusy/0318pub
/例子-0328-03.算数运算符.py
113
3.640625
4
#coding=utf-8 a=20 b=3 print(a+b) print(a-b) print(a*b) print(a/b) print(a%b) print(20**3) print(a//b)
c61999b640744b0170cd89e4e95cde2362c84bdc
BCouble/app_grandpy_p7
/pbapp/libs/message.py
1,829
3.515625
4
import random class Message: def __init__(self): self.messages = { "home": { 0: "Bonjour monsieur, une question ?", 1: "Salut le jeune !", 2: "Quel bon vent t'ammène jeune pousse ?" }, "geocode": { ...
6a799c92ff7d804567385b93ae0949c58cd5fd9f
Azure-Whale/Kazuo-Leetcode
/Search/BFS/934. Shortest Bridge.py
2,011
3.953125
4
#https://leetcode.com/problems/shortest-bridge/ """ Find the shortest path between two objects 1. using DFS/BFS find nodes for two objects in the matrix respectively 2. Start from any nodes in either object, using BFS and DP to get the distance between source object and end object 3. once the BFS reaches any node in e...
9c93463506fcd2ddf6ba8b205ab3a7f27ebaf944
Azure-Whale/Kazuo-Leetcode
/Array/238. Product of Array Except Self.py
2,176
4.15625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' @File : 238. Product of Array Except Self.py @Time : 10/21/2020 10:37 PM @Author : Kazuo @Email : azurewhale1127@gmail.com @Software: PyCharm ''' class Solution: """ The solution is to create two lists within same length as the given array, since each...
4e44e154bae977370dce0d4f5a7befb98adf88f2
Azure-Whale/Kazuo-Leetcode
/Recursive/DFS/322. Coin Change.py
1,004
3.78125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' @File : 322. Coin Change.py @Time : 1/22/2021 8:28 PM @Author : Kazuo @Email : azurewhale1127@gmail.com @Software: PyCharm ''' class Solution: def coinChange(self, coins: List[int], amount: int) -> int: # 1. Greedy? No, you may get an answer but n...
77bc714648242ebdd7a0776563623f1ecd323bf5
Azure-Whale/Kazuo-Leetcode
/Company/Intuit/Tree -1.py
2,073
3.890625
4
""" 3道题 1. 给出一堆[parent,child] 然后问 1个parent, 0parent的点 2. 同样的[parent,child] 返回两个点是否有common ancestor 3. 差不多的 pairs, 找出x earliest ancestor。 每题都要分析 复杂度,然后 所有测试都要跑一遍... 写了2题,然后第3题讲完思路 总体而言,挺舒服的一个面试。 随便画个 测试的图          14          / \        1    2      5       /       \   /    \      3         4       10        \       /...
6a500a2b095eb06daebc5213579bb9bebac588a2
Azure-Whale/Kazuo-Leetcode
/Array/1570. Dot Product of Two Sparse Vectors.py
1,274
3.625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' @File : 1570. Dot Product of Two Sparse Vectors.py @Time : 11/16/2020 11:35 AM @Author : Kazuo @Email : azurewhale1127@gmail.com @Software: PyCharm ''' """ Sparse vectors is a vector consist of a lot of 0, if there is only dot computation purpose, we don't nee...
5f0491c0e63d420227692da8fb03d0a1ed01620a
Azure-Whale/Kazuo-Leetcode
/Array/605. Can Place Flowers.py
1,107
4.03125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' @File : 605. Can Place Flowers.py @Time : 11/18/2020 10:02 PM @Author : Kazuo @Email : azurewhale1127@gmail.com @Software: PyCharm ''' class Solution: ''' return True if n(the number of the plants you want to flower) <= maximum planted positions, othe...
5fb3ec9f28316c777e1cbdcb3c5ee215c63b58b7
Azure-Whale/Kazuo-Leetcode
/Stack/155. Min Stack.py
1,347
3.90625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' @File : 155. Min Stack.py @Time : 1/16/2021 6:31 PM @Author : Kazuo @Email : azurewhale1127@gmail.com @Software: PyCharm ''' class MinStack: # it seems that this question doesn't allow you to use min() to record the minium value # therefore, we may re...
823084818f93f68dbde1a8cd7bb13d003f59749f
Azure-Whale/Kazuo-Leetcode
/Array/sliding window/159. Longest Substring with At Most Two Distinct Characters.py
2,886
3.515625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' @File : 159. Longest Substring with At Most Two Distinct Characters.py @Time : 1/23/2021 2:19 PM @Author : Kazuo @Email : azurewhale1127@gmail.com @Software: PyCharm ''' class Solution: def lengthOfLongestSubstringTwoDistinct(self, s: str) -> int: ...
f81fdb8f269ec68ece20816f3bf85f5c5dfb36a1
wanyifu/Quantopian_Test
/Simple_Bollinger.py
2,919
3.5625
4
def initialize(context): # The initialize function sets any data or variables that you'll use in your algorithm. # For instance, you'll want to define the security (or securities) you want to backtest. # You'll also want to define any parameters or values you're going to use later. # It's only ...
654fb6323b4af4a46645322fab069c526002ef3f
wasabigeek/adventofcode2019
/puzzle2.py
2,450
3.671875
4
# warning: mutates intcode def add(start_index, intcode): num1 = _get_num(start_index + 1, intcode) num2 = _get_num(start_index + 2, intcode) output_index = intcode[start_index + 3] if isinstance(num1, Integer) and isinstance(num2, integer): intcode[output_index] = num1 + num2 else: ...
59dcf566438c4bfd1c754cfd0d5505d6c8132452
wasabigeek/adventofcode2019
/puzzle14.py
7,884
3.5625
4
from collections import deque from math import floor, ceil class Chemical: def __init__(self, **kwargs): self.name = kwargs.pop('name') self.reactions_needed = [] if "count_produced" in kwargs: self.count_produced = int(kwargs.pop('count_produced')) def add_needed_reaction(...
0ccc122f640e83a247ca67915f8ffb400601436a
cyr1z/oop_module-rock-paper-scissors-lizard-spock
/game.py
1,602
3.6875
4
""" main game module """ from exceptions import GameOver, EnemyDown from models import Enemy, Player, Inputs, Scores from color import cli_color from settings import LIVES, ENEMY_DOWN_SCORE, GOODBYE_STRING, \ ENEMY_DOWN_STRING, LIVES_STRING, SCORE_FILE def play(): """ - Entering the player's name - Cr...
40afbdd94b3a2f247ab41508a20f9667e033779d
Smoearn/katas
/python/kt8/hydrated.py
763
3.984375
4
def litres(time): return int(time / 2) print(litres(2), 1, 'should return 1 litre'); print(litres(1.4), 0, 'should return 0 litres'); print(litres(12.3), 6, 'should return 6 litres'); print(litres(0.82), 0, 'should return 0 litres'); print(litres(11.8), 5, 'should return 5 litres'); print(litres(1787), 893, 'sh...
9944355759d50508317cfbe562587bf93c874357
Smoearn/katas
/python/kt7/short_word.py
663
4.1875
4
# def find_short(s): # container = s.split(' ') # max_lengt = len(s) # for i in container: # if len(i) < max_lengt: # max_lengt = len(i) # return max_lengt # l: shortest word length def find_short(s): return min([len(x) for x in s.split(' ')]) print(find_short("bitcoin take ...
ad4e5783ab8452552b9e606143057fab8bfcdf84
Hunters422/Basic-Python-Coding-Projects
/python_if.py
290
4.25
4
num1 = 12 key = True if num1 == 12: if key: print('Num1 is equal to Twelve and they have the key!') else: print('Num1 is equal to Twelve and they do no have the key!') elif num1 < 12: print('Num1 is less than Twelve!') else: print('Num1 is not eqaul to Twelve!')
ce6681c883336ae933625d0610b944a8fc24cfc6
fubuloubu/noisy-fox
/file_database/traverse.py
4,363
4.09375
4
# Traverse the tree def traverse(tree, path, value=None): # given path='key0/key1/.../keyN', # split into key='key0' key_split = path.split('/', 1) key = key_split[0] # and new_path='ley1'/.../keyN'. new_path = key_split[-1] # If our tree is a dict if isinstance(tree, dict): # fi...
58fae92d4ee44ea8d15ff66fad848d46ae366042
karlosgevorgyan/python_homework
/python/Homework/Homework.py
282
3.875
4
def odd_numbers(): for i in range(0,50): if i % 2 == 0: print(i) odd_numbers() print('-------------------------') def even_numbers(): for i in range(0,50): if i % 2 == 0: print(i) even_numbers() print('-------------------------')
931e067e089e4112e21b69fee0de9ae709c62f2d
karlosgevorgyan/python_homework
/python/Homework1/Homework_string.py
2,979
3.9375
4
def to_char_array(text): chars = [] for ch in text: chars.append(ch) return chars def to_text_array(chars): value = '' for ch in chars: value += ch return value def reverse(text): chars = to_char_array(text) for i in range(0, len(chars) // 2): tmp = chars[i] ...
795c1cf0bcb53cd79d1ad74b22fd66eba60a62af
FullStackEmbedded/fse2016-python
/unit_tests/sort_utils/use_modules.py
1,843
3.65625
4
#!/bin/env python # -*- coding: utf-8 -*- '''Use all utilities in the other modules in this package.''' import file_diagnostics as diagnostics import sort_sequences from print_file_contents import (choose_file, print_file, print_upper_case, file_backwards) def print_file_diagnostics...
70edceb1e32b994f8082e46b0076c4204509326f
android1and1/mobilesite
/tools/sendmail
1,900
3.5625
4
#!/usr/bin/env python # encoding=utf-8 # sendmail(ver2.1) # send a file's copy as email body.'from' and 'to' is same(itself). # Usage: # ./sendmail FILENAME [ACCOUNT:PASSWORD] # [ACCOUNT:PASSWORD] means this argument is optional,if not exists # in commandline,will open a intersive input. # Sample: # ./sendmail afile....
dbe43fc0b653cd42d69e9cea2794a45cd6c83c8d
akankaku1998/rock-paper-scissors-game
/main.py
1,062
3.953125
4
import random def print_pattern(choice): rock = ''' _______ ---' ____) (_____) (_____) (____) ---.__(___) ''' paper = ''' _______ ---' ____)____ ______) _______) _______) ---.__________) ''' scissors = ''' _______ ---'...
0f4b59a36a74a35226838dca5a1e34880adf5352
navoneelghosh/Gomoku-with-AI
/src/pa2.py
5,874
3.5
4
# Implementation of an AI Player for Gomoku from pa2_gomoku import Player import time import copy weights = {"11111": 150000, "011110": 15000, "011100": 3000, "001110": 3000, "011010": 3000, "010110": 3000, "11110": 3000, "01111": 3000, "11011": 3000, "10111": 3000, "11101": 3000, "001100": 200, ...
0ed2d8ce165381b7ae8d385b10d5cd0b6f9c31db
evangraan/simple-robot-navigation-python-behave-bdd
/prototype/navigate.py
561
3.953125
4
def navigate(instructions): x = 0 y = 0 d = 3 # 3 - north, 2 - west, 1 - south - 0 - east for instruction in instructions: if instruction == 'L': d -= 1 if d < 0: d = 3 if instruction == 'R': d += 1 if d > 3: ...
50c1933e3e19e6685062c3a089667389894ad2af
polarnyne/granbluefantasyversus-fd
/granpanda.py
391
3.75
4
class Character(object): # This is the main class for all characters def __init__(self, name): self.name = name self.movelist = {} names = {'Ferry', 'Lancelot', 'Metera', 'Zeta', 'Beelzebub', 'Djeeta', 'Gran', 'Percival', 'Ladiva', 'Vaseraga', 'Narmaya', 'Zooey', 'Katalina', 'Charlotta', 'Lowa...
7fc02e12e17db1c49570413c13750ea91ff3c3a4
ntmk/battlesnake-2019-pixelated
/app/utils.py
3,605
4.03125
4
def direction(from_cell, to_cell): """ Determine which direction to move\n @param from_cell -> Current cell occupied\n @param to_cell -> Destination cell\n @returns -> Direction to move\n """ dx = to_cell[0] - from_cell[0] dy = to_cell[1] - from_cell[1] if dx == 1: return '...
f1b18f3fc959db741f9d42643a149d175dd1f162
zeejaykay/Python_BootCamp
/calculator.py
1,753
4.34375
4
# using while loop to continuously run the calculator till the user wants to exit while(True): print("\n Zaeem\'s Basic Calculator\n") print("Please enter two numbers on which you wish to perform calculation's and the operand\n") # displaying instructions num_1 = input("Please enter the 1st number:\n") ...
63a84b340f164a8241ccc4934994e21c5f2aa88d
lipegomes/python-tdd-unittest
/src/tests/test_bacon_with_eggs.py
813
4
4
""" TDD - Test Driven Development """ import unittest from src.base.bacon_with_eggs import bacon_with_eggs class TestBaconWithEggs(unittest.TestCase): def test_bacon_with_eggs_assertion_error_do_not_receive_int(self): with self.assertRaises(AssertionError): bacon_with_eggs('') def test_...
ec6ab9b55ed92e3fafbe5a8d969907458f3cace9
Booyaka/repo-github
/python_ht_1_2.py
1,366
3.609375
4
""" 2. Создать список, состоящий из кубов нечётных чисел от 0 до 1000: Вычислить сумму тех чисел из этого списка, сумма цифр которых делится нацело на 7. Например, число «19 ^ 3 = 6859» будем включать в сумму, так как 6 + 8 + 5 + 9 = 28 – делится нацело на 7. Внимание: использовать только арифметические операции! К каж...
267f0bb258c28a237baf5336a210884637880563
Tomoka64/interview_preparation
/linked_list/linked_list_interview_questions/nth_to_last.py
935
4.09375
4
class Node: def __init__(self, head): self.head = head self.next = None class LinkedList: def __init__(self): self.head = None def append(self, element): new_node = Node(element) if self.head == None: self.head = new_node return c...
3514eff213d9fd27ef5b7a4d30406451e2a11c06
Tomoka64/interview_preparation
/linked_list/linked_list_interview_questions/cycle_check.py
527
3.921875
4
class Node(object): def __init__(self, head): self.head = head self.nextnode = None def isCycled(node:Node): pointer_1 = node pointer_2 = node while pointer_2 != None and pointer_2.nextnode != None: pointer_1 = pointer_1.nextnode pointer_2 = pointer_2.nextnode.nextnode ...
0a07e0dd11fa745d2e4624f1e24ad91b1d7ab394
SpikedSynapse/RefractiveIndex-Importer
/res/src/JsonFunction.py
2,132
3.75
4
import os import json class JsonFunction(): """ class for handling json I/O TODO: better file hanlding """ def __init__(self): self.fileContent = str() self.file = os.path.join(os.path.dirname(os.path.dirname(os.path.split(__file__)[0])),"index.json") #The full path of the json f...
38c32f0bf00fe998f9d0739ff94d072e4ea5df25
pedrolp85/python_basics
/lambda_sorted_filter/lamda.py
1,103
3.625
4
numero: int = 1 # variable de tipo int cadena: str = "hola" # variable de tipo string diccionario: Dict[str, str] = {"hola": "adios"} # variable de tipo dict funcion: Callable[[Any], Any] = lambda x: x # variable de tipo function def function(x): return x function(1) # -> 1 suma = lambda x, y: x + y resta = la...
d164c9e6d02a291a69fc457b79789bbdb2932977
pedrolp85/python_basics
/first_class/test.py
3,082
4.3125
4
from typing import List, Dict """ Implementame la clase Person y sus metodos con NamedTupled: https://docs.python.org/3/library/collections.html#collections.namedtuple """ CURRENT_YEAR = 2021 JOB_NAME = ['developer', 'Software Engineer'] def suma_array(numeros: List[float]) -> float: suma = 0.0 for i in num...
61cf1e9b6dbcef0ece433709e4f0685bc52d0b01
joeypurple/button
/buttontest.py
490
3.671875
4
import time import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(23,GPIO.IN, pull_up_down = GPIO.PUD_UP) #initialise a previous input variable to 0 (assume button is set high/up/true) prev_input = 1 while True: #take a reading input = GPIO.input(23) #if the last reading was high/up/ture and this one low/down...
88e69cba39a474480bfb14b421a2e600392199b9
TrendingTechnology/rnpfind
/website/scripts/picklify.py
1,863
4.25
4
""" Picklify is a function that works similar to memoization; it is meant for functions that return a dictionary. Often, such functions will parse a file to generate a dictionary that maps certain keys to values. To save on such overhead costs, we "picklify" them the first time they are called (save the dictionary in a...
5e09a76e38c009cde6cee904ce919220f09be6d7
carolschiro/python-challenge
/PyBank/main7.py
1,778
3.6875
4
import os import csv csvpath = os.path.join ('Resources','budget_data.csv') with open(csvpath, 'r') as csvfile: csvreader = csv.reader(csvfile, delimiter=',') csv_header = next(csvreader) date=[] margin=[] monthlychange=[] for row in csvreader: date.append(row[0]) margin.appe...
fcddbf663493aca5c6a312722d56d503db139c77
Gafficus/Delta-Fall-Semester-2014
/Source code Python/chapter07/pickle_it.py
1,040
3.65625
4
# Pickle It # Demonstrates pickling and shelving data import cPickle, shelve print "Pickling lists." variety = ["sweet", "hot", "dill"] shape = ["whole", "spear", "chip"] brand = ["Claussen", "Heinz", "Vlassic"] pickle_file = open("pickles1.dat", "w") cPickle.dump(variety, pickle_file) cPickle.dump(shape, pickle_file...
03ce63b031ca790b622d518b4b8813642fdf46b6
Gafficus/Delta-Fall-Semester-2014
/CST-186-14FA(Intro Game Prog)/N.G.Chapter5/N.G.Project2.py
954
4.53125
5
#Created by: Nathan Gaffney #21-Sep-2014 #Chapter 5 Project 1 #This program tell the user where they would go. directions = {"north" : "Going north leads to the kitchen.", "south" : "GOing south leads to the dining room.", "east" : "Going east leads to the entry.", "west" : "Go...
583069510e7bc7e0cf6b17ae9e743a8bb50726d1
nmaestasUT/ExcelPython
/fetch.py
1,106
3.796875
4
import pandas as pd from pandas import ExcelWriter from pandas import ExcelFile import xlrd from tkinter import * nameOfFile = input("Enter File Name: ") nameOfSheet = input("Enter Sheet Name: ") currentMonth = input("Enter Month: ") totalPrice = 0 file = nameOfFile df = pd.read_excel(file, sheet_name=nameOfShee...
5fcb85c42fad1675c6aa5d329cda0381a1bb8f0c
ennukim/leetcode
/findMedianSortedArrays.py
1,223
3.640625
4
# Median of Two Sorted Arrays # Amazon Interview Question # Using Binary Search Algorithm def findMedianSortedArrays(nums1, nums2): if len(nums1) > len(nums2): return findMedianSortedArrays(nums2, nums1) start = 0 end = len(nums1) INT_MIN = -2**64 INT_MAX = 2**64 while start <=...
77bd685c0559a06321ab146ce0e16afd29b4054d
ennukim/leetcode
/trapping_rain_water.py
689
3.796875
4
# Trapping Rain Water # Amazon Interview Question def trap(height): left = 0 right = len(height)-1 left_max = 0 right_max = 0 water = 0 while left < right: if height[left] < height[right]: if left_max < height[left]: left_max = height[left] e...
4bfcbba3d5b9597b488932bf5d541bb360b0d611
ennukim/leetcode
/mergeTwoLists_LL.py
977
4.0625
4
class ListNode(object): def __init__(self, val=None, next=None): self.val = val self.next = next # pointer zig zag class Solution(object): def mergeTwoLists(l1, l2): result = cur = ListNode() while l1 != None and l2 != None: #l1 and l2 both have to be not None if l1....
af8f6d7b81f365dd172bde28ead06b4436ba96f2
ennukim/leetcode
/3SumClosest[AS].py
662
3.640625
4
#My initial try def threeSumClosest(nums, target): summed = 0 result = 0 closest = float('inf') nums.sort() length = len(nums) for i in range(length-2): left, right = i+1, length-1 while left < right: summed = nums[i] + nums[left] + nums[right] diff = abs...
ae6692092f5b629f45d404665ee562765fcb24bf
jack-mil/cs50
/cs50/week6_python/hello/hello.py
98
3.84375
4
# Get a name from a user and greet them name = input("What is your name?\n") print("hello,", name)
b5a302eee614f0b89e6056feb5e0c696fbfb60eb
mgraci/ControverSee_Classifier
/Newspaper_scraper.py
1,792
3.875
4
''' I used Newspaper 3k for further scraping data from the URL's collected in the reddit post scraping. Newspaper 3k does a great job at scraping the relevant info from news articles. For more info on Newspaper 3k, check out this link: https://github.com/codelucas/newspaper This script pri...
9fd99b7c8ed48198729cc65de130a6e444e434a2
HulkkonenT/general-purpose-sw-material
/python/calculating_the_statistics_resource.py
1,156
4.03125
4
""" Resource file for calculating the statistics. """ from statistics import median from statistics import mean def calculate_sum(list_of_the_read_numbers): """ Function calculates sum of the numbers in the given list """ return sum(list_of_the_read_numbers) def calculate_mean(list_of_the_read_numbers): ...
dc2c8b21152591e1f9eb98b660dafde6d67bff1c
FelixMayer/classes_store_and_products
/store_and_products.py
1,787
4.0625
4
# Let's give some methods to our Product class: # - update the product's price. If price is increased, it should increase by percentage provided. Else the price should lower based on percentage provided. # - print the name of the product, its category, and its price. # Let's also give some methods to our Stor...
d95d0fc6b2c70a13205902d82ff1ec89aa9bba19
ArystanIgen/Django_Spring_2021
/django_spring/main/qwqw.py
269
3.5
4
dict={ "Task 1":["10/09/2018","12/09/2018","admin","Done"], "Task 2":["10/09/2018","12/09/2018","admin","Done"], "Task 3":["10/09/2018","12/09/2018","admin","Done"], "Task 4":["10/09/2018","12/09/2018","admin","Done"] } for i in dict: print(dict[i])
4fc3b1c621eeaf45191631dd72e5f2a34251efc3
odora/CodesNotes
/Python_100_examples/example1.py
1,947
4.28125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2019/1/26 16:45 @Author : cai examples come from http://www.runoob.com/python/python-exercise-example1.html """ # ============== Example 1 ====================================== # 有四个数字:1、2、3、4,能组成多少个互不相同且无重复数字的三位数?各是多少? # ===================...
d0b0755f9f6294aa650ed379e225587c8ae9d42d
Min-Zhong/Exercise-of-Monte-Carlo-And-Jet-Tutorial
/Exercise4_ExpFallingDistribution.py
1,974
4.0625
4
# This program is used to produce random numbers distributed according to a falling distribution # of the form exp(−x) in the range[0,5] using Inverse Transform method import random import math import numpy as np Naccept1 = 0 Ntotal1 = 0 ExpNumberList1 = [] lamda = 1.0 for iran in range(10000): u = random.random...
8df5eada61288f2795b7455a214eb0d82f4dad0d
nikser86/les2_work
/work4.py
1,063
3.53125
4
# Задание 4. # Создайте словарь характеристик продукта с ключами «title» (значение типа данных str), # «price» (значение численного типа данных), «ingredients» (значение – список строк). d = {'title': 'cocacola', 'price': 25, 'ingredients': ['ingredient_1', 'ingredient_2', 'ingredient_3']} # 1. Добавьте еще одну пару ...
05dd0477cef10059ed9af5cf5da502f780069ca6
ajohnson1031/Intro-Python-I
/src/01_bignum.py
202
3.578125
4
# Print out 2 to the 65536 power # (try doing the same thing in the JS console and see what it outputs) # YOUR CODE HERE def exponential(num, power): print(num**power) exponential(2, 65536)
3de7ac724200fd673a99968a123d7ff119582e90
erniechen30825/ML-For-Beginners
/Microsoft-learn/rock-paper-scissor.py
2,922
3.609375
4
class Participant: def __init__(self, name): self.name = name self.points = 0 self.choice = "" def choose(self): self.choice = input( "{name}, select rock, paper or scissor,lizard or spock: ".format(name=self.name)) print("{name} selects {choice}".format( ...
9a215085e35e75e27e24b0f9aa3990c1a73012ce
anshshankar/Algo-toolbox
/Algorithmic Warm Up/Last Digit of the Sum of Squares of Fibonacci Numbers/last_digit_of_the_sum_of_squares_of_fibonacci_numbers.py
1,000
3.90625
4
# python3 def last_digit_of_the_sum_of_squares_of_fibonacci_numbers_naive(n): assert 0 <= n <= 10 ** 18 if n <= 1: return n fibonacci_numbers = [0] * (n + 1) fibonacci_numbers[0] = 0 fibonacci_numbers[1] = 1 for i in range(2, n + 1): fibonacci_numbers[i] = fibonacci_numbers[i...
c51aed283b9d1146e068c0dd08fd9ae574737c93
eyyeung/stacks-functions
/decimal_to_any_base.py
920
3.921875
4
from stacks import Stack # converts a decimal number to a number with base up to base 16 def toBase(decimal,base): # if base is greater than 16, raise error if base >16 or base <=0: raise ValueError ('base must be between 1 and 16') elif isinstance(decimal,int)==False: raise ValueError('the...
5d3cd506fbe3688bebc1dbb6ebda406f2a8380f3
CrisRonda/devsuConcurso
/6clock.py
614
3.609375
4
def angulo(hour, minute): resp = hour*30 + minute*0.5 - minute*6 if(hour*30 + minute*0.5 > minute*6 ): return abs(360-resp) return abs(resp) def angles(times): resultado= 0 for time in times: separacion= time.split(":",2) if separacion[0].isdigit() and separacion[0].isdigit...
64f04193517dea19c5cced41fbceb9093f5f229a
javabyranjith/python
/py-core/string/string-fn.py
295
4.15625
4
name = 'Ranjith' print(len(name)) print(name.count('a')) print(name.upper()) # original string won't be modified print(name.lower()) print(name.find('j')) print(name.find('H')) # find returns index print(name.find('an')) print(name.replace('ji', 'gi')) print('jith' in name) # checks contains
6be1fb0c7c6bbffc06959a58e7ee23e332b7ee11
csh3299/PythonforEverybody
/json2.py
650
3.796875
4
#Extract data from JSON # Python 2.7 # Sample data: http://python-data.dr-chuck.net/comments_42.json (Sum=2553) # Actual data: http://python-data.dr-chuck.net/comments_267880.json (Sum ends with 96) import json import urllib2 address = raw_input('Enter location: ') if len(address) < 1 : url = 'http://python-da...
0f73da6d6ee29c9cb24a6705193a3abb3285cb96
heiyixiushi/ProgrammingLanguage
/Python/BookSRC/Liaoxuefeng/Python3/function/alterable_arguments.py
208
4
4
# Calculate 1 + 2*2 + 3*3 + ... def calc(*numbers): sum = 0 for n in numbers: sum = sum + n * n return sum print(calc()) print(calc(1,2)) nums = [1,2,3] print(calc(*nums))
a4776c5eef5449f977f2eac9a2137e9709bae18f
jeremy-truxton/week8
/Banking.py
5,941
4.09375
4
#Made a SuperClass called BankAccount class BankAccount: def __init__(self, accountnumber, balance): self.accountnumber = accountnumber self.balance = balance def withdrawl(self, withdrawn): if float(withdrawn) > self.balance: return "You do not have a large enough...
dc04fb45db7a16bae44deaebf0e4c7729f46c6ca
kevmct90/PythonProjects
/Python-Programming for Everybody/Week 10 Tuples/Code/Lab 10.6 Tuples are Comparable.py
488
4.125
4
__author__ = 'Kevin' # 08/04/2015 # Tuples are Comparable # The comparison operators work with tuples and other sequences. If the first item is equal, Python goes on to the # next element, and so on, until it finds elements that differ. print (0, 1, 2) < (5, 1, 2) # True print (0, 1, 2000000) < (0, 3, 4) # True prin...
82fd7d65065d50bbaad30424ca08ecf393f428b2
kevmct90/PythonProjects
/Python-Programming for Everybody/Week 9 Dictionaries/Code/Lab 9.6 Get Method for Dictionaries.py
764
3.953125
4
__author__ = 'Kevin' # 06/04/2015 # This pattern of checking to see if a key is already in a dictionary and assuming a default value if the key is not # there is so common, that there is a method called get() that does this for us. # Default value if key does not exist (and no Traceback). # counts = dict() # names =...
c92f83c292adb69c7e378bc0fe2fb91e8b2e2b9d
kevmct90/PythonProjects
/Python-Programming for Everybody/Week 3 Conditional/Week 3.3 Try and Except Example.py
361
3.796875
4
# Rewrite your pay computation to give the employee # 1.5 times the hourly rate for hours worked above 40 hours. # Enter Hours: 45 # Enter Rate: 10 # Pay: 475.0 inp = raw_input("Enter Hours:") hrs = int(inp) inp = raw_input("Enter Rate:") rte=float(inp) # print rte, hrs if hrs <=40: pay = hrs*rte else: pay = (...
3a7ecaea275e0022dc6bb928872e6d9a11360ef7
kevmct90/PythonProjects
/Python-Programming for Everybody/Week 9 Dictionaries/Code/Lab 9.10 Two Iteration Variables.py
844
4.28125
4
__author__ = 'Kevin' # 06/04/2015 # We loop through the key-value pairs in a dictionary using *two* iteration variables. # Each iteration, the first variable is the key and the second variable is the corresponding value for the key. jjj = {'chuck': 1, 'fred': 42, 'jan': 100} for aaa,bbb in jjj.items(): print aaa...
b9516444d75abd0141d923136db6dfe47c7ad99d
kevmct90/PythonProjects
/Python-Programming for Everybody/Week 8 Lists/Code/Lab 8.10 Building a list from scratch.py
448
4.4375
4
__author__ = 'Kevin' # 05/04/2015 # BUILDING A LIST FROM SCRATCH # We can create an empty list and then add elements using the append method stuff = list() print stuff stuff.append("book") print stuff other_stuff = [] print other_stuff other_stuff.append("other book") print other_stuff # The list stays in order ...
18a316129cc590ba81d98d033617cd7776154603
kevmct90/PythonProjects
/Python-Programming for Everybody/Week 7 Files/Code/Lab 7.1 Opening a File.py
849
4.125
4
__author__ = 'Kevin' # 24/03/2015 # Opening a File # Before we can read the contents of the file, we must tell Python which file we are going to work with and what we will # be doing with the file # This is done with the open() function # open() returns a 'file handle' - a variable used to perform operations on the ...
adce15e53894f9d2aa0d483f4484e7ce2dbbe559
kevmct90/PythonProjects
/Python-Programming for Everybody/Week 8 Lists/Code/Lab 8.11 Is something in a List.py
376
3.953125
4
__author__ = 'Kevin' # 05/04/2015 # Python provides two operators that let you check if an item is in a list something = range(1, 9) print something # [1, 2, 3, 4, 5, 6, 7, 8] print 9 in something # False print 8 in something # True print 20 not in something # True # These are logical operators...
51ce3c640601771132427ca633d37b66e0d86302
kevmct90/PythonProjects
/Python-Programming for Everybody/Week 3 Conditional/Week 3.3 Try and Except.py
340
4.25
4
# You surround a dangerous section of code with try and except # If the code in the try works - the except is skipped # If the code in the try fails - it jumps to the except section astr = 'Hello Bob' try: istr = int(astr) except: istr = -1 print "First",istr astr = '123' try: istr = int(astr) except: istr = -1 ...