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
957dc325a45ac31a36958d6afdd2327917062303
HackThePlanetKC/AdventOfCode2020
/DayOneCheck.py
437
3.765625
4
target = 2020 with open("DayOneInput.txt") as numbers: for itemOne in numbers: for itemTwo in numbers: combined = int(itemOne) + int(itemTwo) #print(itemOne, " and ", itemTwo, " equal: ", combined) if int(itemOne) + int(itemTwo)==2020: print("Numbers are: ",itemOne,itemTwo) ...
24409c8cc7b6c497409449e8327e5f16a2162020
qufeichen/Python
/asciiUni.py
352
4.15625
4
# program that prints out a table with integers from decimal 0 to 255, it's hex number, and the character corresponding to the unicode with UTF-8 encoding # using a loop for x in range(0, 256): print('{0:d} {0:#04x} {0:c}'.format(x)) # using list comprehension ll = [('{0:d} {0:#04x} {0:c}'.format(x)) for x in range(...
1f9126dc889bcbcb4454e538e13ccc05d0f1f083
computingForSocialScience/cfss-homework-jinguancai
/Assignment6/fetchArtist.py
1,613
3.515625
4
import grequests from bs4 import BeautifulSoup from datetime import datetime import time import re import sys from io import open def fetchArtistId(name): """Using the Spotify API search method, take a string that is the artist's name, and return a Spotify artist ID. """ url = "https://api.spot...
893fc1f94334c2954ffa35205a21173f16bb7779
nateKiprotich/Python-Basics
/Multi-threading/sync/lock.py
693
4.03125
4
import threading from threading import Lock x = 0 """ Lock () ensures that only 1 thread which has acquired the lock is able to perform operation. Other threads wait for the lock to be released. """ lock = Lock() def increment(): global x lock.acquire() x += 1 lock.release() def operation():...
a4169cd1d2a8d5fd69cf068a373ee000d50d3678
nateKiprotich/Python-Basics
/data_structures/time.py
309
3.59375
4
import time nums = [] start_time = time.time() for i in range(100000): nums.append(i) print("Append time is : %s" %(time.time() - start_time)) start_time = time.time() nums = [] for i in range(100000): nums.insert(0,i) print("Insert to start of list time is : %s " %(time.time() - start_time))
3e5f129ede3b16b2b29ce2093393b9832a96653b
nateKiprotich/Python-Basics
/functions/factorial.py
298
3.78125
4
def fact(n): if n == 0: return 1 return n*fact(n-1) x = fact(0) print(x) # Loop through entire text character by character def loop_text(txt, i): if(i == len(txt)): return print(txt[i]) loop_text(txt, i+1) loop_text("Hey nate. Are you doormaker ?", 0)
8e2c71cd0cf2b33304f7d4745191a7c2a675412f
nateKiprotich/Python-Basics
/data_structures/sorting.py
943
4.09375
4
num = [15, 16, -3, 98, 126, 78, 36, 3, -2, 18] # sort num = sorted(num) print(num) # sort Descending num = sorted(num, reverse=True) print(num) names = ['Pete', 'Doe', 'Jane', 'Mercy', 'Grace', 'Harry', 'Potter'] # Same sort as above applies. # sorting based on length of string def name_sorter(x): return len...
4fd81b41dc1ce79e8384ae3ba11908152cb6601e
su-3i025-projet/coop-pathfinding-nassims
/autre/pySpriteWorld-forStudents/pathSlicingStrategy.py
3,109
3.6875
4
import utils_a as ut from strategy import Strategy class PathSlicingStrategy(Strategy): """ Class that represents Path Slicing Strategy """ def __init__(self, players, game): """ :param players: list of players (playerPath object) :param game: ...
12a011962adc8344af0b6b6e8c0d9aad07ef97c4
su-3i025-projet/coop-pathfinding-nassims
/autre/pySpriteWorld-forStudents/playerPath.py
3,366
3.71875
4
import utils_a as ut from AStar import aStar from astartdi import aStartrue class PlayerPath: """ Class that represents a player and the path that he will use to get the goal """ def __init__(self ,number ,initState, goalState, wallStates, game): """ :param number: int ...
b478f3c2f53320928f1767e0c448d5d0e38a1aac
mahakalai/maha
/pset3-1.py
263
3.6875
4
l1=[int(x) for x in input().split()] l2=[int(x) for x in input().split()] l3=[int(x) for x in input().split()] if l1[0]==l2[0] and l2[0]==l3[0] and l3[0]==l1[0]: print("yes") elif l1[1]==l2[1] and l2[1]==l3[1] and l3[1]==l1[1]: print("yes") else: print("no")
c73a233d09d6af3548ab91ff95bdb12e82549eaf
VishavdeepSingh/hello-world
/assignment11.py
363
3.984375
4
#Q1 import re a=input("Enter an E-mail") b=re.findall('^[0-9A-Za-z][\w_]*[@](gmail.com|yahoo.com)',a) if b: print("Valid email") else: print("Invalid email") #Q2 import re c=input("Enter a mobile number with country code") d=re.findall('^[+]91[6-9][0-9]{9}',c) if d: print("Indian Number") ...
aa61e0534852801212f910fefbcc9c8c2cac786b
VishavdeepSingh/hello-world
/assignment7.py
464
3.921875
4
#DICTIONARY #Q1 dict={} for i in range(1,4): k=(input('ENTER KEY')) v=(input('ENTER VALUE')) dict[k]=v print(dict) #Q2 dict_n={} dict_m={} for i in range(1,3): name=(input('ENTER NAME')) for j in range(1,3): subject=(input('ENTER SUBJECT')) marks=float(input('ENTER MARKS')) ...
2a49d2dab7eb96141f793866a7f883dfa669e4bc
soul80386/python_base
/python100days/day002/crapsgame.py
1,664
3.859375
4
""" craps赌博游戏: 玩家掷两个骰子,点数为1-6, 如果第一次点数和为7或11,玩家胜 第一次点数和为2、3、12,玩家输 如果为其他点数,记录第一次点数和,然后继续掷骰子 直至点数和等于第一次掷骰点数和,玩家胜 如果过胜之前掷出和为7,玩家输 """ import random import math def crapsrandom(): x = math.floor(random.random() *10) + 1 while x > 6: x = math.floor(random.random() *10) + 1 return x def carps...
4ee992e14b9d1376a8352978fb4927caf8d3b34b
ZhuXingWuChang/CollegePython
/pythonGrammar.py
24,742
4.28125
4
# ---------------------------python的注释--------------------------- # 单行注释 """ 第一种多行注释 第一种多行注释 """ ''' 第二种多行注释 第二种多行注释 ''' # ---------------------------python的变量--------------------------- # my_name = "张三" # print(my_name) # # myAge = 23 # print(myAge) # # a = 1 # print(type(a)) # 整形 # # b = 1.1 # pri...
4497e40775c7f4149c5d72987b6499041aeea342
ZhuXingWuChang/CollegePython
/spider/requests模块基础/requests肯德基餐厅.py
1,486
3.71875
4
""" 分页数据的爬取操作 爬取肯德基的餐厅位置数据 url: https://www.kfc.com.cn/kfccda/storelist/index.aspx 分析 1.在录入关键字文本框中,输入关键字,按下搜索按钮,url并没有变,说明发起的是一个ajax请求 - 当前页面刷新出来的位置信息一定是通过ajax请求得到的数据 什么是ajax: https://wiki.jikexueyuan.com/project/ajax/what-is.html 2.基于抓包工具定位到该ajax请求的数据包,从该数据包中捕获到: (1)请求的url ...
859c35f9a9bcdcfbe3da843f8296b00f23c37f95
ZhuXingWuChang/CollegePython
/pythonCrashCourse/chapter3/cars.py
602
4.34375
4
# 给sort()方法传入reverse=True参数,会使列表本身被修改(可变对象) cars = ['bmw', 'audi', 'toyota', 'subaru'] cars.sort(reverse=True) print(cars) cars.sort() print(cars) # 使用sorted(ListName)方法,会返回一个新的排序后的列表(不可变对象) cars = ['bmw', 'audi', 'toyota', 'subaru'] print("\nHere is the original list: ") print(cars) print("\nHere is the sorted list...
f4659eaf2c19ab3c69bcce89b02f3a371927eb5a
ZhuXingWuChang/CollegePython
/pythonCrashCourse/chapter3/motorcycles.py
862
3.75
4
motorcycles = ['honda', 'yamaha', 'suzuki'] print(motorcycles) motorcycles[0] = 'ducati' print(motorcycles) motorcycles[0] = 'honda' motorcycles.append('ducati') print(motorcycles) motorcycles.insert(0, 'ducati') del motorcycles[0] print(motorcycles) popped_motorcycles = motorcycles.pop() print(motorcycles) print(...
0468d5427211b1e637074e82f2569b146d962b50
ZhuXingWuChang/CollegePython
/pythonCrashCourse/chapter6/practice6_5.py
271
3.828125
4
country_rivers = { 'nile': 'egypt', 'yellow river': 'china', 'yangtze': 'china', 'ganges river': 'india', 'mississippi': 'america', } for river in country_rivers.keys(): print(f"The {river.title()} runs through {country_rivers[river].title()}.")
7d58cede8f4d2c8f3bef1667b3be17515019a263
Afsaan/Python
/iterate.py
148
4.0625
4
a = (1,2,3,4,5,6,7,8) b = iter(a) print(next(b)) print(next(b)) print(next(b)) # you can iterate with the help of loop for i in a: print(i)
ad6bf12575e9fe07cc9bf1cd67899aceaf75831c
Afsaan/Python
/OOP Concept/static_method.py
989
3.875
4
class Employee: raise_amount = 1.05 # class attribute employee_count = 0 # to count the number of employee def __init__(self , first , last , pay): self.first = first self.last = last self.pay = pay self.email = self.first +"" +self.last+"@gmail.com" Employee.empl...
1776979ab7b67efba43a4501267cc9b9faa341f1
TTUXL/RadioML
/tersorflow tutorial/regression.py
895
3.578125
4
import tensorflow as tf import numpy as np x_data=np.random.randn(100) y_data=0.1*x_data+0.2 #构建一个线性模型 k=tf.Variable(0.) b=tf.Variable(0.) y=k*x_data+b #定义一个二次代价函数 loss=tf.reduce_mean(tf.square(y_data-y)) #定义一个梯度下降法训练的优化器 运用已经封装好的GradientDescentOptimizer,学习率是0.2 optimizer=tf.train.GradientDescentOptimizer(0.2) #训练...
f2a34668c27bc15c17545666e077ad857937c554
PravinSelva5/LeetCode_Grind
/Dynamic Programming/BestTimetoBuyandSellaStock.py
1,006
4.125
4
''' Say you have an array for which the ith element is the price of a given stock on day i. If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit. Note that you cannot sell a stock before you buy one. ------- RES...
536dcd5bd574ec6f170881aa4234b76d3efb6d37
PravinSelva5/LeetCode_Grind
/Stacks and Queues/stacks.py
886
3.765625
4
''' - Linear data structure which has the order of last in first out (LIFO) - pop removes the top element from the stack and shows the value - top shows the value of the top element - push, pushes a new element to the stack (array) ---------------------------------------------------------------- Time Complexity for p...
61e7b8959277116449669550eebafbdb511c8875
PravinSelva5/LeetCode_Grind
/Math/RobotToReturnToOrigin.py
1,464
4.09375
4
''' There is a robot starting at position (0, 0), the origin, on a 2D plane. Given a sequence of its moves, judge if this robot ends up at (0, 0) after it completes its moves. The move sequence is represented by a string, and the character moves[i] represents its ith move. Valid moves are R (right), L (left), U (up), ...
56f6771bd0b84ac0c4e3ab80a40b22b338c057c4
PravinSelva5/LeetCode_Grind
/SingleNumber.py
905
3.671875
4
class Solution: def singleNumber(self, nums: List[int]) -> int: ''' Create a dictionary that will maintain the number of occurences for each integer Run a for-loop through given list: if the current integer is present: add 1 to its key value e...
cb703c9557acc726e98b92e58393419dc264db85
PravinSelva5/LeetCode_Grind
/Linked_Lists/LinkedListCycle.py
1,401
3.828125
4
''' Given head, the head of a linked list, determine if the linked list has a cycle in it. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connec...
e238362a9fe70015b725ea93b7d4ea60663dfcab
PravinSelva5/LeetCode_Grind
/RemoveVowelsFromAString.py
1,081
4.21875
4
''' Given a string S, remove the vowels 'a', 'e', 'i', 'o', and 'u' from it, and return the new string. Example 1: Input: "leetcodeisacommunityforcoders" Output: "ltcdscmmntyfrcdrs" Example 2: Input: "aeiou" Output: "" Runtime: 28 ms, faster than 75.93% of Python3 online submissions for Remove Vowels from a Stri...
1f5c2a31e43d65a1bb470666f432c53b1e0bd8c9
PravinSelva5/LeetCode_Grind
/SlidingWindowTechnique.py
1,204
4.125
4
# It is an optimization technique. # Given an array of integers of size N, find maximum sum of K consecutive elements ''' USEFUL FOR: - Things we iterate over sequentially - Look for words such as contiguous, fixed sized - Strings, arrays, linked-lists - Minimum, maximum, longest, shortest, co...
41fa5b705be4a2f44f143a811186796fa94f9e01
PravinSelva5/LeetCode_Grind
/Trees and Graphs/symmetricTree.py
1,008
4.28125
4
''' Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). ------------------- Results ------------------- Time Complexity: O(N) Space Complexity: O(N) Runtime: 28 ms, faster than 93.85% of Python3 online submissions for Symmetric Tree. Memory Usage: 14.4 MB, less than 52.06% ...
f2ffc91fccd29b356507835afeee81972434f5d1
PravinSelva5/LeetCode_Grind
/Math/MissingNumber.py
1,020
3.890625
4
''' Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array. Time Complexity - O(N) Space Complexity - O(1) Runtime: 136 ms, faster than 37.28% of Python3 online submissions for Missing Number. Memory Usage: 15.4 MB, less than 25.91% o...
f15a98c15e7e6527966b9dc71ed7525aa02dc163
PravinSelva5/LeetCode_Grind
/Stacks_And_Queues/MovingAverageFromDataStream.py
1,124
4.09375
4
''' Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window. ''' class MovingAverage: def __init__(self, size: int): """ Initialize your data structure here. """ self.queue = [0] * size self.front = 0 self...
7cabf6be4d6c2b465dcdcdfb75e83441fb8c1fd5
PravinSelva5/LeetCode_Grind
/Linked_Lists/RemoveNthNodeFromEndOfList.py
1,247
4.1875
4
''' Given the head of a linked list, remove the nth node from the end of the list and return its head. BECASUE THE GIVEN LIST IS SINGLY-LINKED, THE HARDEST PART OF THIS QUESTION, IS FIGURING OUT WHICH NODE IS THE Nth ONE THAT NEEDS TO BE REMOVED -------- RESULTS -------- Time Complexity: O(N) Space Complexity: O(1) ...
9ee562a0c867c164558a362629732cd514632ca5
PravinSelva5/LeetCode_Grind
/Array_101/MergeSortedArray.py
1,051
4.21875
4
''' Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. Notes The number of elements initialized in nums1 and nums2 are m and n respectively. You may assume that nums1 has enough space (size that is equal to m + n) to hold additional elements from nums2. Unfortunately had to r...
4d8c4cd3b1005c20887c69c87e0b127c1b0189d5
PravinSelva5/LeetCode_Grind
/Linked_Lists/MergeTwoSortedLists.py
1,762
4.25
4
''' Merge two sorted linked lists and return it as a new sorted list. The new list should be made by splicing together the nodes of the first two lists. Runtime: 40 ms, faster than 39.21% of Python3 online submissions for Merge Two Sorted Lists. Memory Usage: 14.3 MB, less than 8.31% of Python3 online submissions for ...
faf85a3ab722036a21c279cc40c82edc3922d000
laohixdxm/Algorithm
/LeetCode/Python/MinDepthOfBinaryTree.py
810
3.5
4
from collections import deque __author__ = 'yi' class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def minDepth(self, root): store = deque([root]) right_most = root level = 1 while store is not None:...
14958e600c2fb486480f78cc98f877ae36bca63a
laohixdxm/Algorithm
/LeetCode/Python/ReverseWords.py
553
3.71875
4
__author__ = 'yi' class Solution: # @param s, a string # @return a string def reverseWords(self, s): reversed = '' lists = list(s) j = len(s) for i in range(len(s))[::-1]: if lists[i] == ' ': j = i elif lists[i - 1] == ' ' or i == 0: ...
1f582d13f3269ef03bfd1c6631c3db12e9cd5df5
Dynortice/Project-Euler
/problems/0206/compute.py
320
3.5
4
from euler.big_int import BigInt def compute() -> BigInt: number = BigInt(138_902_663) j = 3 while not all((number * number)[i * 2] == str(i + 1) for i in range(9)): if j == 3: number -= 6 j = 7 else: number -= 4 j = 3 return number * 10
93a8a8cb72782f6ae273b0d533c465532b1fd161
Dynortice/Project-Euler
/problems/0099/compute.py
405
3.5
4
from math import log10 def compute(path: str) -> int: base_exp = [tuple(map(int, i.split(','))) for i in open(path).read().split('\n')] max_exponent = 0 result = 0 for i in range(len(base_exp)): base, exponent = base_exp[i] exponent = log10(base) * exponent if exponent > max_ex...
f803d3ce5a3d64fdee66f42e8adc535916626077
Dynortice/Project-Euler
/problems/0692/compute.py
396
3.5
4
from euler.calculus import fibonacci_index, fibonacci_numbers def compute(n: int): index = fibonacci_index(n) fibonacci = list(fibonacci_numbers(index)) last_sum, new_sum = 0, 0 result = sum(fibonacci[:5]) - 1 for i in range(5, index + 1): last_sum, new_sum = new_sum, new_sum + last_sum + ...
4ac8c1f0f20000749a703b189ab7f48f490d0693
jmahess/cashregister
/cashregister.py
7,819
4.21875
4
#!/usr/bin/env python3 # Author: John Maheswaran import csv # used to read csv files from pytrie import StringTrie # used to match prefixes efficiently. # A trie allows you to match prefixes efficiently instead of the naive approach of looking # through all the strings and checking one by one, if we used a list inst...
f07c769f189c6001d80e8cbfe250698ca2713500
dwkeis/self-learning
/day7_decorator/restaurant.py
1,015
4.09375
4
"""try to perform a decorator module""" class Resturant: """make a base class""" def __init__(self): pass class Order(Resturant): """to take order from this class""" def salad(self): """to add dish into the list by calling method""" return Jumbo.addup('salad') def main(self...
caa50632f567c52e0674d8011531355004b30cfe
dwkeis/self-learning
/day15_facade/facade.py
891
3.609375
4
#facade module trying """many complicate class here""" class Sub_Class: def Method_One(self): print("1") class Sub_Class_2: def Method_Two(self): print("2") class Sub_Class_3: def Method_Three(self): print("3") class Class_One: def Method_Four(self): print("4") """a fac...
480fbd431ed529d6cc8b30ed2e902d271cea3d84
dwkeis/self-learning
/day3_strategy_pattern/fries.py
869
4.15625
4
"""is a test for factory model""" class Fries(): """define fries""" def describe(self): pass class NoSalt(Fries): """define fries without salt""" def __init__(self,flavor): self.__name = flavor def describe(self): print("i am " + self.__name + " fries") class Default(Fries)...
4af459a2b85317efdb6e66c7c679eb80446388ab
arturhbs/Categorical-Prediction
/iris.py
1,129
3.5625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- from sklearn.datasets import load_iris iris = load_iris() #observações x = iris.data print (x) #target y = iris.target print (y) #shape(length) das observações print (iris.data.shape) #shape(length) da target print (iris.target.shape) # Usando KNN para treinamento do...
d5b8e2582ec270f139982ce93dd16071bdef2645
elmo366036/Fundamentals-of-Computing
/Principles of Computing 2/week2_project.py
4,845
3.59375
4
""" Student code for Word Wrangler game http://www.codeskulptor.org/#user45_TXhDDQH2G7_20.py Takes a long time to create the words """ import urllib2 import codeskulptor import poc_wrangler_provided as provided codeskulptor.set_timeout(300) WORDFILE = "assets_scrabble_words3.txt" # Functions to mani...
22f1d2008932fc6f5b9a13eefc0bccdd5cc220dd
elmo366036/Fundamentals-of-Computing
/Algorithmic Thinking 1/Projects/week2a.py
2,151
3.671875
4
'''Week 2 http://www.codeskulptor.org/#user45_AtEVRULics_10.py ''' EX_GRAPH0 = {0:set([1,2]), 1:set([]), 2:set([])} EX_GRAPH1 = {0:set([1,4,5]), 1:set([2,6]), 2:set([3]), 3:set([0]), 4:set([1]), 5:set([2]), 6:set([])} EX_GRAPH2 = {0:set([1,4,5]), 1:set([2,6]), 2:set([3,7]), 3:set...
dbfab6a190985c1e51faf45c1d06c9666064ab04
elmo366036/Fundamentals-of-Computing
/Algorithmic Thinking 2/Projects/alg_project3.py
4,401
4.03125
4
""" Student template code for Project 3 Student will implement five functions: slow_closest_pair(cluster_list) fast_closest_pair(cluster_list) closest_pair_strip(cluster_list, horiz_center, half_width) hierarchical_clustering(cluster_list, num_clusters) kmeans_clustering(cluster_list, num_clusters, num_iterati...
f3e0537df94a56bf3f0881361fb4853fd7dd6641
teambi0s/InCTFi
/2018/Forensics/EvilCrypter/Admin/evilscript.py
316
3.5
4
import sys import string def xor(s): a = ''.join(chr(ord(i)^3) for i in s) return a def encoder(x): return x.encode("base64") if __name__ == "__main__": f = open("C:\\Users\\hello\\Desktop\\vip.txt", "w") arr = sys.argv[1] arr = encoder(xor(arr)) f.write(arr) f.close()
19eec2a9621ff416b156c05f551fa4d72ef25ba0
learning-d/c-to-f
/c-to-f.py
97
3.609375
4
c = input("请输入摄氏温度: ") c = float(c) f = c * 5/ 9 + 32 print("华氏温度为:",f)
820998ccf560bf9cca27f5b092624154058f762a
yathartha3/Deep-Learning-HW
/DL_HW2 /MLP_Skeleton.py
11,089
3.75
4
""" Yathartha Tuladhar """ from __future__ import division from __future__ import print_function import sys import cPickle import numpy as np import matplotlib.pyplot as plt # This is a class for a LinearTransform layer which takes an input # weight matrix W and computes W x as the forward step class LinearTransf...
146b1098deab1d4334990e51bfde7e2d75c8419c
IyvonneBett/Data-Science
/Lesson 3.py
520
4.25
4
# Looping...repeating a task n times eg playing music, generating payslip n times # two types of while/ for loop x = 1 while x <= 10: # n times print('Increment..',x) # 1 to 10 x = x + 1 # Loop works with this update #int(input('Enter some money')) # another to print 10 to 1 y = 10 while y >= 1: ...
773a39799c284b01f24d1e495a85367b636187ec
davidpetro88/python-playground
/python-oo/car.py
343
3.609375
4
class Car: x = 'Abcd' def __init__(self, name, make, year): self.name = name self.make = make self.year = year def drive(self): return self.name + ' started' @staticmethod def hello(x): print(x + ': Cool statatic method') @classmethod def show(cls...
3c36331dbd1566e2b65ca1bc7bcaa45e117deb35
ksolo/LearnPythonTheHardWay
/ex36.py
1,454
3.890625
4
from sys import exit def room_one(): print "You're now in the welcome center main lobby." print "There is a swarm of zombies about to enter the other door." print "1 - Run to the gift shop" print "2 - Go back to camp" print "3 - Run for the gun over the boar's head" answer = raw_input("> ") if answ...
bacb22852208ebcffa247e81e047b240f31a8988
DaniilWild/Work_in_home
/piano_play/piano_var.py
6,578
3.5
4
import pygame import play #дополнительный вариант для заинтересованных детей (ставить мелодию на паузу или менять инструмент) #простое решение: создать глобальные переменные и переключать их #второе решение "в лоб": без класса Game - считывать заново набор звуков для музыкального инструмента #третье решение: завести о...
18b114b7063d871595fd2c7cfd896371d1242c2f
Bharadwaja92/GameDevelopment
/Dhaadi/Dhaadi.py
14,250
3.5
4
import pygame from pygame.locals import * import sys BOARD_WIDTH = 7 BOARD_HEIGHT = 6 DIFFICULTY = 2 SPACE_SIZE = 50 FPS = 30 WINDOW_WIDTH, WINDOW_HEIGHT = 640, 480 # 480, 480 X_MARGIN = (WINDOW_WIDTH - (BOARD_WIDTH * SPACE_SIZE)) // 2 Y_MARGIN = (WINDOW_HEIGHT - (BOARD_HEIGHT * SPACE_SIZE)) // 2 # X_MARGIN = 50 ...
ae80883ddf0bce7a2d5dd643a24ce65c19e2fcf8
jaykothari-github/Guess-number
/number_game.py
3,704
3.6875
4
from tkinter import * from random import randrange from tkinter.messagebox import showinfo,showerror rw = Tk() rw.title('Guess the Number!!') rw.geometry('600x400+300+100') rw.resizable(width=False, height=False) fm = Frame(rw,bg='black',height=400, width=600) fm.pack() cc = str(randrange(1,100)) print(...
4f1c0501cce22f31fb7b5814d948ddaafdbe754a
vazkarvishal/AoC2020
/03/main.py
1,567
3.515625
4
import logging logging.basicConfig() logging.getLogger().setLevel(logging.INFO) def move_toboggan(steps_to_right, steps_down): lines = open("./input.txt", "r").readlines() characters_in_one_line = len(lines[0].strip()) move_right = 0 trees = 0 step_down_counter = steps_down for idx, route in enumerate(li...
50a14906a8062b1c0b300082b3060e3f3e5f09bc
anthaas/Advent-of-Code-2019
/day6/part1.py
427
3.5625
4
#!/usr/bin/python3 dict = {} with open('input.txt') as f: for line in f: parent,child = line.rstrip().split(")") dict[child] = parent def calculate_orbit(element): if dict.get(element) != None: return 1 + calculate_orbit(dict.get(element)) return 0 unique_objects = set(list(dict.keys()) + list(dict.value...
4de2c33b533eae46e6e9840257de88f8ade182a0
camille-004/CoderSchool
/graphs/fetch_neighbors_appliction/node.py
336
3.703125
4
''' Node class. Represents a node in a graph. ''' class Node: def __init__(self, n_id, val, neighbors = []): self.id = n_id self.val = val self.neighbors = neighbors def set_neighbors(self, neighbors): self.neighbors = neighbors def get_neighbors(self): return...
612e6ca68736df4026f8ee1b45d0480181e177ae
nate-d-olson/CBBG_Rosalind_Bioinf
/ba1k_KC.py
1,894
3.921875
4
#!/usr/bin/python # File created on Oct 3, 2015 __author__ = "Kenneth Cheng" __credits__ = ["Kenneth Cheng"] __version__ = "0.0.1-dev" __maintainer__ = "Kenneth Cheng" __email__ = "" """ Definition: Given an integer k, we define the frequency array of a string Text as an array of length 4**k, where the i-th e...
e658de8a57be2b804a85dc0c12b5f0219ac18988
nate-d-olson/CBBG_Rosalind_Bioinf
/ba1a_KC.py
1,082
4.09375
4
#!/usr/bin/python # File created on 11 Sep 2015 __author__ = "Kenneth Cheng" __credits__ = ["Kenneth Cheng"] __version__ = "0.0.1-dev" __maintainer__ = "Kenneth Cheng" __email__ = "" """ Problem Description: Compute the Number of Times a Pattern Appears in a Text Given two strings: text and pattern. Retu...
353ed22d539dabc1fba75eafd035919644c41f3c
basakkang/daily-python
/generator/generator_best_practice.py
857
3.671875
4
import math def wave_cascading(amplitude_it, steps): step_size = 2 * math.pi / steps for step in range(steps): radians = step * step_size fraction = math.sin(radians) amplitude = next(amplitude_it) # 다음 입력 받기 output = amplitude * fraction yield output def complex_wave_c...
9fdbd29148d4ec7e7e37e4c7d7bd2be65252a81f
basakkang/daily-python
/basics/time_example.py
1,028
3.953125
4
import datetime import time # seconds from epoch t = time.time() # local time to string ct = time.ctime(t) print(t) print(ct) # UTC Coordinated Universal Time # timezone is offset from UTC # time as a tuple # Year # Month as an integer, ranging between 1 (January) and 12 (December) # Day of the month # Hour as an ...
368d9056aa46feb9b33ec608c21469ad2dc60df7
basakkang/daily-python
/basics/exception_example.py
730
4.03125
4
import sys # We can use raise to throw an exception if a condition occurs def intend_exception(x): if x < 8: print('come') else: raise Exception('Under 8 only') def linux_method(): print(sys.platform) assert ('linux' in sys.platform), "Linux only" if __name__ == "__main__": ...
f02faf53abcaeb1b8de2c43e3bbf4c314b0cfbd7
Haakooto/Astprosjekt
/1_the_Rocket_Engine/rocket.py
2,808
3.59375
4
""" Program for rakett klasse All kode er egenskrevet I resultatene presenterer vi plot av akselerasjon, fart og posisjon. For dette måtte vi skrive om koden til å ta vare på verdiene for r og v, men klarte senere å slette denne koden. """ import numpy as np import sys, os import ast2000tools.constants as const cl...
d5ed3e136af1cde84c3598a77f6be45f0f0798c9
danoand/cs-module-project-hash-tables
/applications/lookup_table/lookup_table.py
891
3.578125
4
# Imports import random import math # Define a lookup table (dict) lookup_dict = {} def slowfun_too_slow(x, y): v = math.pow(x, y) v = math.factorial(v) v //= (x + y) v %= 982451653 return v def slowfun(x, y): """ Rewrite slowfun_too_slow() in here so that the program produces the same ...
a2a02007370aebcc4cd7aabe96433a95f09ad037
RichardPersaud/Python
/2021/HomeSense.py
3,268
3.53125
4
# # importing subprocess # import subprocess # # getting meta data of the wifi network # meta_data = subprocess.check_output(['netsh', 'wlan', 'show', 'profiles']) # # decoding meta data from byte to string # data = meta_data.decode('utf-8', errors ="backslashreplace") # # spliting data by line by line # # st...
a95fa15b2395e5e04c1c2383f7080bc013307658
R0YLUO/Algorithms-and-Data-Structures
/sorting/counting_sort.py
3,600
4.1875
4
"""Stable counting sort algorithms""" def counting_sort(lst: list) -> list: """Sorts a given list of integers into ascending order @complexity: O(N+U), where N is length of list, and U is range of largest and smallest value in list """ if not check_all_integers(lst): raise Exception("Lis...
bff349b3cf94bd9cf6fd561259023d81318d9773
R0YLUO/Algorithms-and-Data-Structures
/data_structures/queue.py
1,384
4.1875
4
"""Implementation of a queue using a python list""" from typing import Generic, TypeVar T = TypeVar('T') class Queue(Generic[T]): def __init__(self) -> None: """Instantiates an empty list""" self.length = 0 self.list = [] def __len__(self) -> int: """Length of our queue""" ...
36131e269728e7573a366ecde5bb68178834c161
pranaymate/100Plus_Python_Exercises
/21.py
1,152
4.25
4
#~ 21. A website requires the users to input username and password to register. Write a program to check the validity of password input by users. #~ Following are the criteria for checking the password: #~ 1. At least 1 letter between [a-z] #~ 2. At least 1 number between [0-9] #~ 1. At least 1 letter between [A-Z] #~ ...
cb085973dc8a164bcdb82b3beb80310303f0ceee
pranaymate/100Plus_Python_Exercises
/04.py
569
4.40625
4
#~ 04. Write a program which accepts a sequence of comma-separated numbers from console and generate a list and a tuple which contains every number. #~ Suppose the following input is supplied to the program: #~ 34,67,55,33,12,98 #~ Then, the output should be: #~ ['34', '67', '55', '33', '12', '98'] #~ ('34', '67', '55'...
3a6da2770d72955dd5330363f7a126a033e49d0e
pranaymate/100Plus_Python_Exercises
/12.py
632
4.4375
4
#~ 12. Write a program that accepts sequence of lines as input and prints the lines after making all characters in the sentence capitalized. #~ Suppose the following input is supplied to the program: #~ Hello world #~ Practice makes perfect #~ Then, the output should be: #~ HELLO WORLD #~ PRACTICE MAKES PERFECT #~ Hin...
d659dfbd1e19535991ee23656b92cc325657a8ee
carodewig/advent-of-code
/advent-py/2021/day_09.py
2,616
3.59375
4
""" day 9: smoke basin """ from collections import namedtuple from queue import Queue from functools import reduce Location = namedtuple("Location", ["x", "y"]) class HeightMap: def __init__(self, heightmap): self.heightmap = heightmap def adjacent_locations(self, loc): for (d...
18800df77859a0c8b9bb95b977333342e79c2ff8
carodewig/advent-of-code
/advent-py/2015/day_10.py
1,033
3.59375
4
""" day 10: elves look, elves say """ def translate_one(string): if not string: return "" if not len(set(string)) == 1: raise Exception(f"String must have only one unique characters (ie 1, 11); {string} provided") return f"{len(string)}{string[0]}" def translate(string): output_str...
e3fd20579a00cae23b99fc5741a3ca6d729aa554
carodewig/advent-of-code
/advent-py/2019/day_06.py
2,617
3.625
4
""" day 6: universal orbit map https://adventofcode.com/2019/day/6 """ from collections import defaultdict import attr @attr.s(slots=True) class OrbitMap: orbit_map = attr.ib() def get_parent_for(self, name): for possible_parent in self.orbit_map: if name in self.orbit_map[possible_pare...
ce838e78ca47cf910487eadea572d379f673b83a
shakur2222/Python
/arp.py
3,452
3.640625
4
from netmiko import ConnectHandler import getpass import sys import re ##### device connection section ##### ip = input("IP\Hostname of switch: ") device= { 'device_type': 'cisco_ios', 'ip': ip, } ...
9c0f2fbdc2741a07d4c8159c2591ed13006281fa
jeosol/real-python-nlp
/tokenization.py
2,161
3.9375
4
# Tokenization in spaCy # Tokenization is the next step after sentence detection. it allows you to identify # the basic units in your text. These basic units are called tokens. Tokenization is useful # because it breaks a text into meaningful units. These units are used for further analysis, like # part of speech taggi...
da263bf8615c2d7682b627f180e0e3ec79fb3975
Orenef11/tree_simulator
/input_generator/building_a_Yule_tree_2.py
9,266
3.703125
4
class TreeNode: def __init__(self): self.father=None self.son=None self.brother=None self.generation=None # do we need that here? self.value=None self.time=None # ----------------------------------------------------------------------------- def FindMRCA(node1,node2): ...
2d957b68a47a8f25462b33124e61e57354ca62af
unixwar/variousProjects
/removeDups.py
249
3.890625
4
# Remove all duplicates from a string Eg: String: AABGFHHHAB => ABGFHAB''' myDups = 'AABGFHHHAB1120023GGXMNZAAZ1998' noDups = [] for char in myDups: if char not in noDups: noDups.append(char) newNoDups = ''.join(noDups) print(newNoDups)
630d4bf29c223263b9c6afae25c73b7929864e0d
armenjuhl/Pick-6-Lottery-Game
/src/pick6.py
1,361
3.8125
4
# Written by Armen Juhl 4/1/2020 import random def main(): val_flag = False while not val_flag: test_input = str(input('Pick 6 numbers between 1 and 99 separated by spaces')) try: split_list = list(test_input.split(' ')) validated_list = list() for i in spl...
6f34fc28b3a0bc6c4d27509f4bc994ab369fc75c
aashutosh1803/systemDesign
/snakes_and_ladder/game.py
3,937
3.5
4
import random import time from collections import defaultdict from constants import * from colorama import Fore class Snake: def __init__(self): self.snakes = SNAKES def getSnakes(self): return self.snakes class Ladder: def __init__(self): self.ladders = LADDERS def getLadder(self): return self.ladd...
d87cc475a6c1e401b29a54ad9ad10aaf53eccf2a
yuvapriya/DynamicProgramming
/memoizedFib.py
676
3.859375
4
def memoize(f): # define "wrapper" function that checks cache for # previously computed answer, only calling f if this # is a new problem. def memf(*x): if x not in memf.cache: memf.cache[x] = f(*x) print memf.cache.keys() print memf.cache.values() ...
34cd0120d5ac168b074abdbd2d396e7f87f40a56
SiddheshBala/CRC-simulation-using-python
/senderprog.py
1,198
3.609375
4
import socket from utilities import * data = input("Enter the data to be transmitted: ") #BinaryCheck function check whether the entered string is in binary form while True: if BinaryCheck(data): break; else: data = input("Please enter a valid binary for the data: ") key ...
af1bd2dccee82b3f9d94bd77aa3dca4c45d4ae5b
zmarvel/playground
/project7/routing.py
8,336
3.75
4
import os, string, sys import copy from Queue import Queue from collections import deque, defaultdict from math import sqrt from random import shuffle # appends padding spaces if the number is smaller than the largest value # e.g. if the largest val=1245, 1 will be represented as '1 ' def format_num(n, maxSpaces): ...
267f4c3280e9a66140cbee9c5b442ac05b0a8892
Nmeece/MIT_OpenCourseware_Python
/MIT_OCW/Textbook Finger Exercises/3-2_String_Sum.py
875
3.703125
4
# -*- coding: utf-8 -*- """ Created on Fri Nov 13 12:58:52 2020 Finger Exercise for section 3.2 of the Introduction to Comoputation and Programming Using Python textbook. Prompt: Let s be a string that contains a sequence of decimal numbers seperated by commas, e.g., s = '1.23,2.4,3.123'. Write a prog...
f67dc2f0ab519d287974c0c6ddc403eed51a59fe
Nmeece/MIT_OpenCourseware_Python
/MIT_OCW/MIT_OCW_PSets/PS3_Scrabble/Test_Files/is_word_vaild_wildcard.py
1,979
4.15625
4
''' Safe space to try writing the is_word_valid function. Modified to accomodate for wildcards. '*' is the wildcard character. should a word be entered with a wildcard, the wildcard shall be replaced by a vowel until a word found in the wordlist is created OR no good word is found. Nygel M. 29DEC2020 ''' VOWELS = '...
c76aa569359b635c9993b1cb9547a52c8de258cc
Nmeece/MIT_OpenCourseware_Python
/MIT_OCW/MIT_OCW_PSets/PS2_Hangman/hangman.py
16,465
4.15625
4
# Problem Set 2, hangman.py # Name: # Collaborators: # Time spent: # Hangman Game # ----------------------------------- # Helper code # You don't need to understand this helper code, # but you will have to know how to use the functions # (so be sure to read the docstrings!) import random import string WORDLIST_FILEN...
cff8632ee7bdc15fef9966dee6c1b3aa65b40153
kevinlzw/shopping-cart-python
/src/model/loyaltypoint.py
605
3.515625
4
class LoyaltyPoint(): RATIO = 100 def __init__(self, loyalty_point): self.loyalty_point = loyalty_point def add_loyalty_point(self, point): if not isinstance(point, int): raise AttributeError('输入数据不为整型') self.loyalty_point += point def get_loyalty_point(self): ...
f2b9f9b3b5c68ce81099202f954ca98f4a335d12
DayuanTan/CMSC441_641_algorithm
/files/heapsort/heap_sort.py
1,115
3.921875
4
import random import math # Dayuan Tan created on Sep. 30, 2018 # max heap sort # generate 10 random numbers to be sorted data = [] for i in range(1,10,1): data.append(random.randint(1,100)) print('Unsorted array is: ', data) def swap(a, b): return b, a def max_heapify(data, i, heap_size): left = 2 * i ...
3dc7edff89dab7a5e5a90e7bb0b75389a1af03dd
brettlod/flicklist-python
/counting.py
641
3.75
4
#sentence=input("Please enter a sentence:") sentence=("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc accumsan sem ut ligula scelerisque sollicitudin. Ut at sagittis augue. Praesent quis rhoncus justo. Aliquam erat volutpat. Donec sit amet suscipit metus, non lobortis massa. Vestibulum augue ex, dapibus ...
fb3af632ddec34ecf691bc3262d439e2f05ca9f4
FakhrEldeen/DES-Encryption-Decryption-in-python-
/Key Generation.py
3,763
3.734375
4
#This Code written by Fakhr Eldeen Gamal #This is Key Generation Functions for DES Encryption Algorithm #Values of First Permutation Box PC1 = [57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35, 27, 19, 11, 3, 60, 52, 44, 36, 63, 55, 47, 39, 31, 23, 15, 7, 62, 54, 46, 38, 3...
66d1585f86c77e41c3bd059974497218401a045f
Butyavka/guess_number
/guess_number.py
2,716
3.625
4
from tkinter import * from tkinter import messagebox as mb import random class Window: def __init__(self, width, height, title="Вход", resizable=(False, False)): self.root = Tk() self.root.title(title) # self.root.geometry(f"{width}x{height}+200+200") self.root.resizable = (resizab...
ce583b686a49a0fd61c23d90c02868738b9582d8
lecina/RL_examples
/example7_2.py
20,198
3.890625
4
import numpy as np import random import matplotlib.pyplot as plt """ Example 7.2 of Reinforcement Learning: an introduction. Summary. Random walk where there are two terminal states and we get a +1 reward when we terminate in one of them and -1 in the other. Otherwise the reward is 0. """ class S...
b5708a6969bd175903d5f219294b7ef112386ea2
Anshikaverma24/List
/List/count odd, even.py
361
4
4
elements = [23, 14, 56, 12, 19, 9, 15, 25, 31, 42, 43] length= len(elements) index=0 odd_numbers=0 even_numbers=0 while index<length: if elements[index]%2!=0: odd_numbers=odd_numbers+1 elif elements[index]%2==0: even_numbers=even_numbers+1 index+=1 print("ODD NUMBER : ", str(odd_numbers)) pr...
8e4d6edf26660b44ab79c561f811fbf03bb41b6d
PlanetKev/KevTECH
/Prime Number Analyser.py
6,073
4.375
4
import time import matplotlib.pyplot as plt # Time module is used to time how long computations of the prime range take and also to sleep print "KevTECH Simple Prime Number Analyser" print "------------------------------------\n" # Actual Prime True or False Function def isitPrime(n): if n == 1: return Fa...
76ea6e0e54b8897ec344e77dd2af9350cbadca59
ChaitanyaPulekar27/Python-Programs
/Simple interest.py
179
3.78125
4
p=input("Enter the Principle Amount") r=input("Enter the Rate of Interest") t=input("Enter the Time in Years") a=float(p)*float(r)*float(t)/100 print("Simple Interst is",a)
b13dbe84dfa4fddabb9a784743577be4799d485d
LiamMullen8/Image2ASCII
/ascii.py
2,811
3.5625
4
from PIL import Image, ImageDraw, ImageFont, ImageEnhance import math # these are the characters that make up the image, can do many combinations for different effects chars = "$@B%8&WM#*oahkbdpqwmZO0GQLCJUYXzcvunxrjft/\\|()1{}[]?-_+~<>i!lI;:,\"^`'. "[::-1] #chars = list(".,/\[]{}()OQPHZNRGKBMX") charArr = list(char...
691af67d856274a7c8e1027e27e48eceae5e8181
wilcer1/War-assignment
/cardhand.py
1,352
4.15625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Class for cards in hand.""" import random class Cardhand: """cardhand class.""" def __init__(self): """Initialize class.""" self.hand = [] def cards_remaining(self): """Check how many cards remain in hand.""" return len(...
b3d69db64f64f67926d981a97881c655c3716799
heikoschmidt1187/DailyCodingChallenges
/day10.py
1,501
3.78125
4
#!/bin/python3 """ Implement a job scheduler which takes in a function f and an integer n, and calls f after n milliseconds. """ import threading import time class Scheduler(): def __init__(self): # save the function object and the target timestamp self.functions = [] s = threadi...
813d679785214c619e9e39942fd323cff7681671
heikoschmidt1187/DailyCodingChallenges
/day11.py
2,071
3.828125
4
#!/bin/python3 """ Implement an autocomplete system. That is, given a query string s and a set of all possibly query strings, return all strings in the set that have s as a prefix. For example, given the query string de and the set of strings [dog, deer, deal], return [deer, deal]. Hint: Try preprocessing the diction...