blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
a5b3299aa32bcc19a8a77b0e3d02b619ae82d0b8 | gb07bh/Alien_Invasion | /alien.py | 1,225 | 3.625 | 4 | import pygame
from pygame.sprite import Sprite
class Alien(Sprite):
#To represent alien in the fleet(Single)
def __init__(self, ai_settings, screen):
#initializing Alien and its position on screen
super(Alien,self).__init__()
self.screen = screen
self.ai_settings = ... |
02732c58436f8952e652c530a54694cfab81a11c | odunet/FamilyTree | /package/person.py | 8,877 | 4 | 4 | from .gender import Gender
class Person():
"""
Class used to represent a single member of the Family structure.
It also provides methosd to manage the relationships with other members of the larger family tree
...
Attributes
----------
gender : String
a string representing the ge... |
ab1d5fa65e5e9121bde5ccdf99cfe19886efb6ba | sam-072/competative-programming | /number theory/totalno_sum.py | 770 | 3.828125 | 4 | def gcd(a,b):
if b==0:
return a
else:
return gcd(b,a%b)
def extended_gcd(a,b):
if b==0:
return a,1,0
gcd,x1,y1=extended_gcd(b,a%b)
x=y1
y=x1-(a//b)*y1
return gcd,x,y
def modlo_inverse(a,m):
gcd,x,y=extended_gcd(a,m)
# print(gcd,x,y)
return x
if __name__... |
6decad8d848c52619d775fc688634e1d66fef897 | mougua/webp2gif | /webp.py | 3,007 | 3.828125 | 4 | #!/usr/bin/env python
# Convert PNG images to GIF, preserving transparency
# 2008 - http://www.coderholic.com/png2gif
import sys
from PIL import Image
import random
import optparse
import os
import os.path
def unique_color(image):
"""find a color that doesn't exist in the image
"""
colors = image.getdata()
while... |
511eb6e624bc550367514f458df8f3017fab5723 | pcon0718/drive_calculator | /drive_calculator.py | 537 | 4.15625 | 4 | # Retreive input from users
drive_size = input("Drive size (in TB): ")
drive_quantity = input("Drive quantity: ")
drive_cost = input("Drive cost (in USD): ")
# Convert strings into integers and float
drive_size = float(drive_size)
drive_cost = float(drive_cost)
drive_quantity = int(drive_quantity)
# Do some calculati... |
99261aeaf95e6e286630db616d07ce10ff7be95e | mvm68/codecademy | /games.py | 9,503 | 3.84375 | 4 | import random
money = 100
#Write your game of chance functions here
def check_bet(amount):
if amount <= money and amount > 0:
return False
else:
return True
def coin_flip(guess, bet):
if check_bet(bet):
print("CoinFlip BetError: You are betting " + str(bet) + " dollars. That is e... |
bc1a7c95557df44fd8b140d6f5ec54f4bb02096e | clevercoderjoy/tik_tak_toe | /tik_tak_toe.py | 8,784 | 4.09375 | 4 | # idea
# we need a board to play the game
# a function to display the board
# a function to play the game
# a function to ask what player 1 wants, i.e. 'x' or 'o'
# a funtion to handle turn
# a funtion to take input from user
# a funtion to check if input is valid or not
# a function to disp... |
d009fb9cbdb806eb5b1445e4c417493095e508f7 | dontru/ue-crypto | /5/homophonic/preprocess/encrypted.py | 90 | 3.53125 | 4 | def encrypted(text: str) -> str:
return ''.join(c for c in text.strip() if c != '\n')
|
8f3f29a3f56dfbb5f5454508fb88f7d2df354922 | dontru/ue-crypto | /5/tests/CipherTest.py | 1,622 | 3.5625 | 4 | import unittest
from homophonic import Cipher
class CipherTest(unittest.TestCase):
def test_encrypt(self):
cipher = Cipher(substitution={'a': ['0', '1'], 'b': ['2']})
encrypted = cipher.encrypt('abcd')
self.assertTrue(encrypted == '02cd' or encrypted == '12cd')
def test_decrypt(self)... |
498d65b759baf417be426bacf91cdf6e02bd4d5c | rehhg/household-finance | /db.py | 1,615 | 3.734375 | 4 | import sqlite3
from abc import ABC, abstractmethod
class AbstractDB(ABC):
@abstractmethod
def insert(self, description: str, costs: str, total: str):
pass
@abstractmethod
def update(self, description: str, costs: str, total: str, id: str):
pass
@abstractmethod
def delete(sel... |
99f80886946df6333b81405527b266ab2b710eeb | xuleichao/xlc | /py_learning/test.py | 299 | 3.578125 | 4 | def sushu(a):
for i in range(2,int(math.sqrt(a))):
if a%i==0:
break
#return(False)
else:
return(True)
a=2
count=0
import math
while count<6:
m=2**a-1
if sushu(a) and sushu(m):
print m
count+=1
a+=1
|
a6d19d2a4d99697017aafa3cfc3b82fcad94e947 | anikethsuresh/Employing-PageRank-in-k-means | /DistanceMetric.py | 6,503 | 4.0625 | 4 | """
Class to implement the distance metrics - Euclidean distance and Shortest distance to nodes in a Graph
"""
import time
import numpy as np
import networkx as nx
class DistanceMetric():
"""
Class to perform distance calculation between nodes, points and vertices
"""
def __init__(self, name="euclide... |
61cf4100607e36cc0f16be927d8f8d1b3b26500a | KEClaytor/YAYTracker | /button.py | 1,628 | 3.578125 | 4 | import digitalio
class Button:
""" Button convenience class.
Create a button:
>>> button = Button(board.D3, digitalio.Pull.UP)
Update the button state:
>>> button.update()
And then check for conditions:
>>> if button.pressed():
>>> ...
>>> if button.just_pressed():
>>> ... |
091fba31e974a4cee22e02ba3dd67bc3b9c389bf | tkacha201/automate_the_boring_stuff_udemy | /py_auto_gui_commands.py | 1,316 | 3.765625 | 4 | import pyautogui
print(pyautogui.size()) #gets screen size
print(pyautogui.position()) #get current coordinates of cursor
pyautogui.moveTo(10, 10, duration=1.5) #uses x nad y coordinates, duration makes it slower, this is 1.5 seconds
pyautogui.moveRel(200,0, duration=2) #this moves the mouse to the right by 200 pixels... |
39bbc388db80f24f34cef582eb340e96d83deb7a | vamc-stash/Data-Structures-and-Algorithms | /DataStructures/Queue/python/Queue.py | 814 | 3.71875 | 4 | import sys
class Queue:
def __init__(self):
self.arr = []
def __isEmpty(self):
return len(self.arr)
def enqueue(self, val):
(self.arr).append(val)
def dequeue(self):
if self.__isEmpty() == 0:
print("Queue is empty, cant perform pop()")
return
(self.arr).pop(0)
def peek(self):
if self.__isEmp... |
53bab46ac8009405bd0819f3b0ec6ed543e31336 | tommycarleo/CS104-01 | /conditions.py | 422 | 4 | 4 | temp = 0
while temp != 999:
temp = int(input("Please enter a new temperature or 999 to End"))
if temp == 999:
break
if temp > 90:
print ("Wear Shorts")
elif temp > 70:
print ("Short sleeves are fine")
elif temp > 50:
print ("Wear a jacket")
elif temp > 32:
... |
e1297b164838d12e893f9fda26b2f5a57dbb796f | carlosriverosv/python_bootcamp_w2 | /Contact.py | 1,093 | 4.09375 | 4 | from datetime import datetime
class Contact:
def __init__(self, name, last_name, age, phone, email):
self.name = name
self.last_name = last_name
self.age = age
self.phones = []
self.phones.append(phone)
self.email = email
self.created_at = datetime.now()
... |
1c39efeaea40ca7798819a25849156f537306f02 | g-ych/CS229 | /ps1/src/linearclass/logreg.py | 2,934 | 3.9375 | 4 | import numpy as np
import util
def sigmoid(x):
return 1 /(1 + np.exp(-x))
def main(train_path, valid_path, save_path):
"""Problem: Logistic regression with Newton's Method.
Args:
train_path: Path to CSV file containing dataset for training.
valid_path: Path to CSV file containing dataset for validation.
sav... |
6052c66859b6e1cc82bad31512deb27ea859b7f8 | jiejunping/python | /more_effective/decorator.py | 2,028 | 4.0625 | 4 | # 不带参数的
def outer1(func):
print("outer 开始执行")
def inner():
print("认证成功")
result = func()
print("日志添加成功")
return result
return inner
# 带参数的
def outer2(func):
print("outer 带参数的装饰器开始执行")
# 参数arg、*args、 ** kwargs三个参数的位置必须是一定的。必须是(arg, *args, **kwargs) 这个顺序
# *args... |
66978bfeb958ac37e838b7d25db69fb6fbfa0b4f | greenphantom/SwagBot | /command_functions.py | 1,150 | 3.625 | 4 | # Command function module
class Command:
def __init__(self, primary_call, desc="", func=None):
self.primary_keyword = primary_call
self.command_desc = desc
self.operation = func
def __contains__(self, keyword):
if keyword.lower() in self.keywords or keyword.lower() == self.prima... |
a4850a7fc38e5d9051a58331448875237b4ae7bd | bmonikraj/ML_Skin_Segmentation_on_RGB_color | /SkinSegmentationML.py | 8,360 | 3.578125 | 4 | '''
Skin color segmentation based on R,G,B component given for training set.
Here we can use K means clustering because the skin color cluster will be required and all other data not coming under the cluser
can be ignored and classified as non skin
We are trying to find one cluster basically which will denote skin and... |
b23be809f35948cdd3401decc4da368d8fd365e4 | hybridthesis/Project-Euler | /math_func.py | 2,162 | 3.828125 | 4 | def getNextPrime(self, prime):
if self.isPrime(prime): prime = prime + 1
while not self.isPrime(prime):
prime = prime + 1
return prime
def lcm(self, *args):
if type(args[0]) is type(list()):
args = args[0]
num = list(args)
prime_factors = []
prime = 2
previous_list... |
ecc95e047b6c3479898039e4e64f6d9a6bf32589 | Vetchadines/python-excersie | /pra2.py | 888 | 4.03125 | 4 | x = int(input('Enters Your Temperacture: '))
if x >= 25:
print('It\'s a hot day drink plenty of water')
elif x <= 12:
print('It\'s So Cold Wear warm clothes')
else:
print('It\'s a lovely day')
#execrsie of payment of house
good_credit = input('1.yes , 2.No: ')
if good_credit == '1':
house_value = 10000... |
c0f8ccf25df7ea7b7dd113bfaeb41c785b915641 | Moverr/ML | /numpyarray.py | 211 | 3.5625 | 4 | import numpy as np
# convert list into array
dataset = [[1,2,3],[3,4,5],[6,7,8],[11,12,34]]
#convert dataset to numpy aarrya ndArray
ndArray = np.array(dataset)
print("Numpy Array X:\n{}".format(ndArray))
|
c79aae813f5e6af88cfb8563cce5d15d2ef55180 | Tim-Nosco/timsat2 | /util.py | 6,858 | 3.75 | 4 | class Assignment:
#each value in the assignment stack is a struct:
#1) the decision level: Int
#2) the variable: *Variable
#3) the value: Bool
#4) the clause(if applicable): Clause or None
def __init__(self,dl,var,val,clause):
self.dl = dl
self.var = var
self.val = val
... |
d0f381bfa65ab4819d12d08f7f3324d5661d547c | SreeramSP/Python-Function-Files-and-Dictionary-University-of-Michigan- | /The textfile, travel_plans.txt, contains the summer travel plans for someone with some commentary.py | 281 | 4.09375 | 4 | #The textfile, travel_plans.txt, contains the summer travel plans for someone with some commentary. Find the total number of characters in the file and save to the variable num.
travel_file=open('travel_plans.txt','r')
num=0
for i in travel_file:
num=num+len(i)
print(num) |
898e92c4a6f2c604058665e8ff2c779353e06915 | SreeramSP/Python-Function-Files-and-Dictionary-University-of-Michigan- | /#Create the dictionary characters that .py | 447 | 4.40625 | 4 | #Create the dictionary characters that shows each character from the string sally and its frequency. Then, find the most frequent letter based on the dictionary. Assign this letter to the variable best_char.
sally = "sally sells sea shells by the sea shore"
characters={}
for i in sally:
characters[i]=characte... |
c73656bce92d7e8ccaaf4bc861b19db9128fd162 | SreeramSP/Python-Function-Files-and-Dictionary-University-of-Michigan- | /#Write a function, accum, that takes a list.py | 217 | 3.90625 | 4 | #Write a function, accum, that takes a list of integers as input and returns the sum of those integers.
def accum(l):
i=0
for j in l:
i=i+j
return i
list1=[1,2,3,4,5]
print(accum(list1))
|
96742d7985d8ab2b8704c3e9c9565843e64d2537 | SreeramSP/Python-Function-Files-and-Dictionary-University-of-Michigan- | /With only one line of code, assign the variables city, country, and year to the values of the tuple olymp.py | 196 | 3.515625 | 4 | #With only one line of code, assign the variables city, country, and year to the values of the tuple olymp.
olymp = ('Rio', 'Brazil', 2016)
city=olymp[0]
country=olymp[1]
year=olymp[2]
|
d05928cbcf32335ddc8cd8c1c95f79dbaa5f8303 | SreeramSP/Python-Function-Files-and-Dictionary-University-of-Michigan- | /#Provided is a string saved to the variable.py | 294 | 4 | 4 | #Provided is a string saved to the variable name s1. Create a dictionary named counts that contains each letter in s1 and the number of times it occurs.
s1 = "hello"
counts={}
for i in s1:
if i in counts:
counts[i]=counts[i]+1
else:
counts[i]=1
print(counts)
|
20f87999c2e67adb73991243be4678ae36218201 | milanoderby/Python | /while_for.py | 112 | 4.09375 | 4 | n = 0
while n<3:
print("print")
n = n+1
numbers = list(range(10))
for num in numbers:
print(num)
|
f183358cf91cfc699be5b828ff182e6eecbd9960 | manasanoolu7/SqliteDB_Deployment_House_Price_Prediction | /pipeline/database/csv_to_SQLite_conversion_02.py | 3,173 | 4.03125 | 4 |
import sqlite3
import pandas as pd
def create_immo_table():
"""
This function makes the SQLite database
"""
connection = sqlite3.connect('immo_data.db')
cursor = connection.cursor()
cursor.execute('CREATE TABLE IF NOT EXISTS immo(ID integer primary key, property_type_HOUSE integer, '
... |
2ffea666ef4282adb75ff28360f10f9412751818 | mattbierner/The-Jungle-Exclamation-Point | /count.py | 275 | 3.609375 | 4 | import ast
import sys
def count(tokens):
words = len(tokens)
exclamations = tokens.count('Jurgis')
return float(exclamations) / words
def count_chapters(chapters):
return [count(x) for x in chapters]
print count_chapters(ast.literal_eval(sys.stdin.read())) |
1c691296744ca3e2d079988fa16696568ca64890 | krustea/mystery-number | /game.py | 1,895 | 3.640625 | 4 | import random
import sqlite3
from player import Player
class Game:
def __init__(self):
self.value = 0
self.player = Player()
self.player.set_nickname()
self.player.set_life()
print('tu t\'appelles : ', self.player.nickname, ' et tu as :', self.player.life, 'vies')
def ... |
8bea683db850063b8d017da7ac1646fc41a0a535 | alexandreLamarre/Go-AI-backend | /src/dlgo/agent/helpers.py | 1,335 | 3.71875 | 4 | from src.dlgo.gotypes import Point
def is_point_an_eye(board, point, color):
''' An eye is an empty point.
All adjacent points must contain friendly stones
We most control three out of the four corners if the point
is in the middle of the board, on the edge must control all 3
corner... |
35c3f8e67779509efd933ffa686632452741731b | Scott-S-Lin/Python_ittraining | /0409上午/enumerate.py | 170 | 3.515625 | 4 | ary = [11,22,33,44,55]
'''
for e in ary:
print(e)
print()
for i in range(len(ary)):
print('#',i,sep='')
'''
for i,e in enumerate(ary,0):
print(i,e)
|
415ccd8d6e4fc4d734cca8a652221c36965aa717 | Scott-S-Lin/Python_ittraining | /0319/type.py | 554 | 3.921875 | 4 | x = 123 #將x設定為整數int型態
print(type(x))
y = '123' #將y設定為字串str型態
print(type(y))
z = 123.0 #將z設定為浮點數float型態
print(type(z))
x = 123+0j #將x設定為複數complex型態
print(type(x))
y = True #將y設定為布林bool型態
print(type(y))
z=(123,456)#將x設定為序對tuple型態
print(type(z))
x = [123] #將x設定為清單list型態
print(type(x))
... |
1074970d5161dbc0fbfe41403d13200648814ea1 | Scott-S-Lin/Python_ittraining | /0409上午/p02_func_return1.py | 216 | 3.625 | 4 |
def f1(n,m):
print('f1() n*m =',n*m)
def f2(n,m):
return n*m
n1 = 5
n2 = 10
f1(n1,n2)
ans = f2(n1,n2)
print('f2() n*m =',ans)
print('相乘的結果 =',ans)
print('f2() + 50 =',ans+50)
|
7dc03fcd3579c2a18e2d8744bee79c2c20012bd8 | Scott-S-Lin/Python_ittraining | /0326下午/p05_stars000.py | 124 | 3.921875 | 4 | #n = int(input())
h=5
n=8
for i in range(h):
for j in range(n):
print('*',end=' ')
print()
|
8dd8cfa5c3c456f773dab281053fba060ac475d3 | Scott-S-Lin/Python_ittraining | /0326上午/p03_while_數字處理.py | 174 | 3.859375 | 4 | while(True):
s = input()
if s=='y':
print("run")
else:
break
'''
IN = input()
while IN == 'y' :
print('run')
IN = input()
'''
|
f9b492013070b4c6467b0b6c535dcb339d39d110 | gabsgasps/First-API-Pyhton | /pass-break-contine.py | 97 | 3.828125 | 4 | numero = 20
while True:
numero-=numero
print(numero)
if (numero == 2):
break |
a87a7fc63c229aa03c00dad24c322f5544b264c7 | mzshieh/snp2016 | /lec10/lec10-3.py | 381 | 3.5625 | 4 | # Provide a function to compute the offset of certain direction and step size
import math
def offset(direction, step):
theta = direction * math.acos(-1.0) / 6
return step * math.sin(theta), -step * math.cos(theta)
while True:
try:
hour_hand = float(input('Input ihe direction of clock: '))
... |
3820324111232ec039fa0e9a59bc1b99efd60530 | mzshieh/snp2016 | /lec09/exercise/task1.alt.py | 370 | 3.96875 | 4 | while True:
# read a float
try:
a = input()
a = float(a)
except:
break
if (a-int(a)==0.5 or a-int(a)==-0.5):
if(int(a)%2 == 0):
print(int(a))
else:
print(int(a+a-int(a)))
elif (a < 0):
print(int(a-0.5))
elif (a > 0):
... |
513134515c5f4f812256da69684bca621ee0ed53 | mzshieh/snp2016 | /lec11/lec11-2-buggy.py | 1,698 | 3.65625 | 4 | # Bull and Cow: 2-digit version
def valid(number):
if number < 0 or number > 99:
return False
try:
d1 = number % 10
d2 = number // 10
return d1 != d2
except:
return False
def countA(x,y):
ret = 0
if x % 10 == y % 10:
ret = ret + 1
if x //... |
c6c63c9cd4f1aac6a5f6d0bb19e69d4f19045899 | rok1202/algorithm | /소수 만들기.py | 497 | 3.625 | 4 | def check_num(nums) :
for i in range(2, nums):
if nums % i == 0:
return False
return True
def solution(nums):
answer = -1
cnt = 0
for i in range(0, len(nums)):
for j in range(i+1, len(nums)):
for k in range(j+1, len(nums)):
total = nums[i] + n... |
a9acba2069fc73e53bb8f6ab39b8674dfed19041 | Lopez-Samuel/PythonProjects | /rec06.py | 6,297 | 3.984375 | 4 | #!C:\Python27\python.exe
'''
CS1114
Programmer: Samuel Lopez
User Name: SL4506
Submission: rec06.py
This is a python program that will sell three different types of stamps.
Asks for the user name, and only gives change in coins, not dollar bills.
At the end of the program the user is asked to rate the machine; and ... |
51167f76ff7408c047426077570d44c3e6f99a83 | kurborg/DailyCodingProblems | /DailyCodingProblems/src/python/linkedList.py | 845 | 3.96875 | 4 | """
An object for storing a single node of a linked list.
Models 2 attributes, data and the link to the next node in the list
run python -i linkedList.py to start an interactive python terminal passing
in our file for class use
"""
class node:
data = None
nextNode = None
def __init__ (self,data):
... |
ce31e272f33bf24004482756795d30feba5fd593 | kurborg/DailyCodingProblems | /DailyCodingProblems/src/python/lowHighIndexTarget.py | 1,784 | 3.875 | 4 | """
Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value.
If target is not found in the array, return [-1, -1].
You must write an algorithm with O(log n) runtime complexity.
"""
# This is O(n) time complexity
def searchRange(self, nums, target)... |
83a318d0648d2b599850444f5c039c90ed4993ee | kurborg/DailyCodingProblems | /DailyCodingProblems/src/python/recursiveBinarySearch.py | 815 | 4.28125 | 4 | def recursiveBinarySearch(list, target):
if len(list) == 0:
return -1
else:
midpoint = (len(list))// 2
"""Time complexity is O(log n) because we are dividing the list by 2 through each recursive call"""
"""Space Complexity is O(log n) because we are creating a new array in each... |
a34b7fa1aa512bbcc96160a78b769aafe8fc18d2 | SteveImmanuel/modern-cryptography | /crypt/utils/file_util.py | 684 | 3.546875 | 4 | def load_file(filepath: str, chunk_size: int):
"""
Load file by chunk_size in bytes
"""
with open(filepath, 'rb') as file_in:
buffer = file_in.read(chunk_size)
while buffer != b'':
yield buffer
buffer = file_in.read(chunk_size)
def read_file(path: str) -> str:
... |
9d5a2b112a510ec490a9a70a33f90a90b5aa43bd | SteveImmanuel/modern-cryptography | /crypt/engine/data.py | 328 | 3.65625 | 4 | from enum import Enum
class DataType(Enum):
TEXT = 'text'
FILE = 'file'
class Data():
def __init__(self, data_type: DataType, value: str, output_path: str = None):
self.data_type = data_type
self.value = value
if self.data_type == DataType.FILE:
self.output_path = out... |
adbac07f4814c954a2dc3388b172197561cdfb37 | hgokhru101/python-automation | /regex_search.py | 689 | 4.21875 | 4 | # Regex search
# Traversing all the .txt files in a folder and searching for any line that matches regex
# Printing the result
import os
import re
# Opening .txt file
file_open = open(filename,'r')
try:
# User supplied regular expression
regex_in = raw_input("Enter the regular expression")
# Performing searc... |
ecae6b34dceadd263fa576e9791716cd4eecc76b | MakeSchool-17/twitter-bot-python-kazoo-kmt | /dictionary_words.py | 1,163 | 3.9375 | 4 | import random
import sys
def pickup_words(number_of_output_words):
text_file = open('text_for_test.txt', "r")
list_of_words = list(text_file)
# [brian] You forgot to close the file! In this program it'll get closed
# when the script finishes, but in a larger program this could be a pretty
# terri... |
038e138750ed746f71d19c78059ecb5ec21663fd | Masyko/Back_End_Python | /tic_tac_toe.py | 2,759 | 3.96875 | 4 | """ Task 1"""
board = list(range(1, 10))
wins_combo = [(1, 2, 3),
(1, 4, 7),
(4, 5, 6),
(7, 8, 9),
(2, 5, 8),
(3, 6, 9),
(1, 5, 9),
(3, 5, 7)]
def draw_board():
"""" Function to draw playing board """
print('____... |
a42e7b7c3fd76df1335e4d44fe9eb3786cb5e456 | LW-YUNKAI/MyCode | /Python/Algorithm/SortAlgorithm/BubbleSort.py | 401 | 3.53125 | 4 | import random
a = []
for k in range(20):
a.append(random.randint(0, 100))
# 利用random.randint(0, 100)生成一个0~100的20位随机数列
print(a)
def bubble(l):
for i in range(0, len(l)):
for j in range(len(l)-1, i, -1):
if l[j] < l[j-1]:
temp = l[j]
l[j] = l[j-1]
... |
e1f229ed27f3ce625e7237d1562f601788e4992c | lorenzovngl/word-sense-disambiguation | /reducebykey.py | 1,006 | 3.640625 | 4 | # From https://gist.github.com/Juanlu001/562d1ec55be970403442
from functools import reduce
from itertools import groupby
def reduceByKey(func, iterable):
"""Reduce by key.
Equivalent to the Spark counterpart
Inspired by http://stackoverflow.com/q/33648581/554319
1. Sort by key
2. Group by key y... |
32988bcdb4e35391d6f6c6f5adecffd2cc7d7b6b | kausthub/Python-Sessions | /Day2/lists.py | 526 | 3.515625 | 4 | #Lists
os = ["windows","ubuntu","fedora","Mountain Lion","openSUSE","linux mint","Debian"]
android = ["Cupcake","Donut","Eclair","Froyo","Gingerbread","Honeycomb","Ice Cream Sandwich","Jelly Bean","Key Lime Pie"]
numbers = [27,198,88,57,9,22,5]
#Elements
a = os[3]
b = os[-4]
c = os[-1]
#Concatenation
con = os + a... |
622a3c97c2dc35501466395fb452482bea51dafe | kausthub/Python-Sessions | /Day2/classes.py | 701 | 4.1875 | 4 | #How to define a class in Python, containing certain variables and methods
#A variable can be made available to all methods in the class.
#Such a variable has to be declared as 'global' within every method that uses it
#'self' must be used as a default argument when defining a method in a class
#Eg. of usage - a=myclas... |
1e9457cf1ff8676cda43b10bb0424ed890ca7920 | Djmon07/riddled-road | /scene.py | 6,678 | 4.09375 | 4 | from sys import exit
import textwrap
class StartScene(object):
def enter(self):
print(dedent("""
You are out of the city on your first vaction in awhile.
Yet round fifty miles out you car stars to sputter.
Darn you should have gotten your car checked out on time.
... |
5c4576f2dff9c1b7b8ffe5935e44d08a518dfd58 | marcelo-r/leetcode | /easy/kids-with-the-greatest-number-of-candies/solution.py | 373 | 3.9375 | 4 | from typing import List
"""
"candies": [2, 3, 5, 1, 3],
"extraCandies": 3,
"want": [True, True, True, False, True],
"""
class Solution:
def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]:
maior = max(candies)
result = []
for i in candies:
result.app... |
937c9b4fad9ea0a1c6c6974944777b4d4a790387 | marcelo-r/leetcode | /easy/kids-with-the-greatest-number-of-candies/solution_test.py | 1,086 | 3.5625 | 4 | import unittest
from solution import Solution
class TestSolution(unittest.TestCase):
def test_1(self):
tests = [
{
"candies": [2, 3, 5, 1, 3],
"extraCandies": 3,
"want": [True, True, True, False, True],
},
{
... |
24abca4acc2c081f3868c1ecc23efd052d489dff | srikanthpragada/PYTHON_02_MAR_2021 | /demo/oop/circle.py | 739 | 3.640625 | 4 | class Circle:
# Static (class) attributes
max_radius = 100
@staticmethod
def set_max_radius(newmax):
Circle.max_radius = newmax
def __init__(self, x, y, radius):
self.x = x
self.y = y
if radius > Circle.max_radius:
raise ValueError("Invalid Radius")
... |
6938ba6c19f127282cc49fb9fe172e35ef7baf9c | srikanthpragada/PYTHON_02_MAR_2021 | /demo/libdemo/thread_demo.py | 341 | 3.5 | 4 | import threading
from threading import Thread
def print_numbers():
ct = threading.current_thread()
for n in range(1, 11):
print(f"{ct.name} - {n}")
print(threading.current_thread())
ct = Thread(target=print_numbers)
ct.name = "PrintThread"
ct.start()
print(f"No. of threads : {threading.active_count(... |
19fefdf79bb05da2e384c8c10039ae54010eea1b | srikanthpragada/PYTHON_02_MAR_2021 | /demo/oop/prime_generators.py | 285 | 3.828125 | 4 | # Generator to generate prime numbers between given range
def primes(start, end):
for n in range(start, end + 1):
for i in range(2, n//2 + 1):
if n % i == 0:
break
else:
yield n
g = primes(100,200)
for v in g:
print(v)
|
94d1f7cbdc40412e602babc9c588a74b392838cf | srikanthpragada/PYTHON_02_MAR_2021 | /demo/assignments/12-MAR/char_freq.py | 150 | 4.1875 | 4 | # Print frequency of each char in a string
st = "This is to test frequency of characters"
for c in sorted(set(st)):
print(f"{c} - {st.count(c)}") |
ece8e5dfb003e178d3513a2ad5606eee72c8d1b6 | srikanthpragada/PYTHON_02_MAR_2021 | /demo/library/number_funs.py | 405 | 3.921875 | 4 | # Number functions
def iseven(n):
"""
Returns true if the given number is even otherwise false
Usage : iseven(n)
Parameter n is the number to test
"""
return n % 2 == 0
def sign(n):
if n > 0:
return 1
elif n < 0:
return -1
else:
return 0
# WHen you run m... |
1a536b5ffe52c47ca71decf88cf7bd92ec4b2a2b | srikanthpragada/PYTHON_02_MAR_2021 | /demo/libdemo/sort_unique_names.py | 294 | 3.625 | 4 | # Take names from allnames.txt and sort unique names
f = open("allnames.txt","rt")
names = set()
for line in f.readlines():
for name in line.split(','):
name = name.strip()
if len(name) > 0:
names.add(name)
for name in sorted(names):
print(name)
f.close() |
bb67ecc5a564be58305307152c930dad6144d9d1 | statistics-exercises/t-tests-3 | /main.py | 1,002 | 3.65625 | 4 | import matplotlib.pyplot as plt
import numpy as np
import scipy.stats
def gen_t_variable( n ) :
# Your code to generate the variable that we introduced in the previous task goes here
# This generates the midpoints of all your histogram bins
nbins, xmin, xmax = 10, -6, 6
delx = (xmax - xmin ) / nbins
xvals, cou... |
e1a49f0217c43cf29e59968f7022b87a672afe1c | kev212/Multi-layer-Perceptron---Iris-Dataset | /MLP.py | 6,682 | 3.703125 | 4 | import csv
import random
import math
import matplotlib.pyplot as plt
#load dataset
with open('iris.csv') as file:
csvreader = csv.reader(file)
dataset = list(csvreader)
# Change string value to numeric
for row in dataset:
row[4] = ["setosa", "versicolor", "virginica"].index(row[4])
row[:4... |
c0d254cebd98fca0208a96d235ed21bd6f314b5b | lianggangscu/pylearn | /funpar.py | 159 | 3.609375 | 4 | #!/usr/bin/env python
#Filename:funwithpar.py
def maximum(a,b):
if a>b:
print("%d is maximum" %a)
else:
print("%d is maximum" %b)
a=7
b=5
maximum(a,b)
|
6a89f5c3cf2611aa534b4146b933bcfe0fd55212 | alxqiu/Scheduler | /Interface.py | 2,490 | 3.5 | 4 |
#No job instantiation, just an interface that could be implemented with a priority queue or map.
class Executor():
def __init__(self, IP, port):
self.server_info = (IP, port)
#server stores info of jobs in centralized location, so should manage encoding
def submit(self, job_name, siz... |
2802d0b87c1729be52e16ff085ba06399dd58631 | cpuyyp/CRA_network | /mybasiclib.py | 1,091 | 3.734375 | 4 | import pandas as pd
def flattenListOfLists(lis):
"""
Unpacking list of lists.
:param lis: List of lists
:type people_list: list(list())
:return: Return the flattened list
:rtype: list()
"""
return [item for sublist in lis for item in sublist]
def readEmailsFromFile(filename):
"""... |
c49c3df8e78d6ffbc651347e616868ef3fe9c95b | sureshmelvinsigera/cidei | /backend/lab1/lab1_12.py | 1,292 | 4.15625 | 4 | class AddressBook(object):
""" constructor para clases en Python """
def __init__(self):
self.data_store = []
def add_contact(self, contact):
""" Adicionando un contacto """
self.data_store.append(contact)
def all_contacts(self):
return self.data_store
def print_contacts(self):
for contact in self._da... |
f8cb6478cb6c6803dff677432e54914b0eaa6dc3 | damodardikonda/pythonNumpy | /ano.py | 690 | 3.71875 | 4 | #annonymous function
#import sys
import numpy as np
#f=lambda a:a*a
#print(f(5))
#g= lambda a,b:a+b
#print(g(10,20))
#h_letter=[letter for letter in 'human']
#print(h_letter)
#if sys.version_info.major == 3:
# print('Python3')
#else:
# print('Python2')
#arr=np.array([[1,2,3],[4,5,6],[6,7,8],[9,4,6]])
#... |
79077a9d3fa67c1c1f9529777f453c582f369bc3 | damodardikonda/pythonNumpy | /filterss.py | 514 | 3.984375 | 4 | #filter returns a sequence
#without using lambda
from functools import reduce
def ev(n):
if n%2==0:
return n;
num=[1,2,3,4,5,6,7,8,9,10]
res=list(filter(ev,num))
print(res)
#using lambda
nums=list(filter(lambda n:n%2==0,num))
print(nums)
# adding adding 2 in even numbers with using map.we can also used an... |
5e0f408acb5652a44aca4c1177c9aebbfb7b9be0 | size1995/Coding_Interviews-personal_solutions | /10_斐波那契数列.py | 255 | 3.75 | 4 | class Solution:
def Fibonacci(self,n):
a0,a1=0,1
if n==0:
return 0
if n==1:
return 1
for i in range(2,n+1):
a3=a0+a1
a0=a1
a1=a3
return a1
|
acfbf97ab6b8abb1e572db6cfc389388e799dd45 | nishantchaudhary12/Intro-to-Algorithms-3rd-edition-CLRS | /Chapter 8/bucketSort.py | 694 | 3.828125 | 4 | #bucket sort
def insertionSort(arr):
for i in range(1, len(arr)):
j = i - 1
key = arr[i]
while j > -1 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
def bucketSort(arr):
newArr = [[] for i in range(10)]
for each in arr:
indx =... |
1743b7f34e26e8e608030f01094f70fe7293b417 | SelyanKab/FormationPython | /Fonctions/fonctions.py | 3,730 | 3.640625 | 4 | # Ce finchier contient la définition de différentes fonctions
import random
import datetime
# fonction qui affiche bonjour avec des paramètres
def afficherBonjour(a, b):
print("Bonjour", a, b)
return 1
# Fonction qui calcule la longueur d'une liste en utilisant une boucle
def longueur(a):
# trouver la lo... |
dba28c231b51e4deeb15cda2f7b6be94649f6f19 | club-Programacion-UAEM-Ecatepec/Fundamentos-de-Python | /Practicas/10-Listas.py | 1,027 | 3.84375 | 4 | listaPersonas = ["Pedro","Mary", "Luis", "Erick", "Carol"];
listaEdades = [20,31,19,27,22];
def promEdad(listaEdades):
longitudArray = len(listaEdades);
totalEdades = 0;
for edad in listaEdades:
totalEdades += edad;
return totalEdades / longitudArray;
print("La edad promedio es de: " +... |
1fbd6ab18c1bb523b616fc54bb38c96e8d99af45 | club-Programacion-UAEM-Ecatepec/Fundamentos-de-Python | /Ejercicios/Ejer_Codificador.py | 2,059 | 3.53125 | 4 | # Ejercicio 3: Codificador/Decodificador
#
# Crea un programa que codifique un texto ingresado para que suelte
# un codigo secreto que puedas guardar y despues reingresar ese mismo codigo
# para descodificar el codigo y desifrar el texto
#
# Consejo: utiliza los diccionarios para cambiar los caracteres del texto ingr... |
c0be52a235e42e0c999e9acd51f9e748cc772de9 | Zsglatz/Code_Challenges | /code_challenge1.py | 146 | 3.765625 | 4 | # Make a function that adds two numbers and returns the binary code of that number
def add_binary(a,b):
c = a + b
return format(c, "b") |
b5ff29deea12e346eaa120abd02dc4c4137d3bb0 | OnlyLang/dev-kit | /leetcode/2、两数相加.py | 1,891 | 4.15625 | 4 | """
给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/add-two-numbers
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
... |
65a4cf290398c145f1f6a850c5dcf876200095e6 | OnlyLang/dev-kit | /sort/bubble_sort.py | 412 | 3.828125 | 4 | """
冒泡排序
"""
def bubble_sort(l):
for i in range(len(l) - 1): # 比较的轮数控制
for j in range(0, len(l) - (i + 1)): # 实际比较,将大数放到最后
if l[j] > l[j + 1]:
temp = l[j + 1]
l[j + 1] = l[j]
l[j] = temp
return l
if __name__ == '__main__':
arr = [7, 3... |
0ca3d9aecdc11eed4557a83d00d3f41cf567f4e6 | OnlyLang/dev-kit | /sort/insert_sort.py | 383 | 3.78125 | 4 | """
直接插入排序
"""
def insert_sort(l):
for i in range(1, len(l)):
for j in range(i - 1, -1, -1):
if l[j + 1] > l[j]:
break
else:
temp = l[j]
l[j] = l[j + 1]
l[j + 1] = temp
return l
if __name__ == '__main__':
arr... |
7511da720b761ace477c5bc0f15bd18f771ae327 | 1buraknegis/Python-Tkinter-examples | /kullanici_giris_uygulaması.py | 1,497 | 3.65625 | 4 | # KULLANICI GİRİŞİ UYGULAMASI
import tkinter as tk
form = tk.Tk()
form.title("UYGULAMA")
form.geometry("500x300")
mail = tk.Label(form, text="Mail: ", fg="black",
bg="blue", font="Times 10 bold")
mail.place(x=10, y=30)
sifre = tk.Label(form, text="Şifre: ", fg="black",
... |
408022982b778acc252101be0f116f831c4d7e37 | lisaaaaag18/Average-Auto-Ownership-Code | /test_code.py | 3,993 | 3.59375 | 4 | import csv
import math
import zipfile
def Conversions(file1, file2):
'''
file, file --> dict, dict
This function reads a file in order to convert a zone to the appropriate planning
district. It then reads the second file to convert the planning districts to spatial
categories. The funct... |
3e2c7770fbb45b0496a9e186c6ed8ae4bc33ca0f | gitdxj/Blocked-Sort-Based-Indexing | /language.py | 1,067 | 3.609375 | 4 | import nltk
from nltk.stem import WordNetLemmatizer
english_punctuations = [',', '.', ':', ';', '?', '(', ')', '[', ']', '&', '!', '*', '@', '#', '$', '%']
def text_process(text):
sens = nltk.sent_tokenize(text) # 首先对文本进行分句
words = []
for sent in sens:
word_in_sent = nltk.word_tokenize(sent) # ... |
54264fe5f6a6606f5060459b66c6e205740a13f9 | machinaut/old-icfp-2014 | /py/gamestate.py | 5,543 | 3.765625 | 4 |
'''
The status of the fruit is a number which is a countdown to the expiry of
the current fruit, if any.
'''
import json
class GameState:
# The Ghosts' vitality is an enumeration:
gVital = {'standard': 0,
'fright mode': 1,
'invisible': 2,
}
# The Ghosts' and Lam... |
5a66379af070046ae26647a33c3818e7a826f30c | JeanCurti/Easyprog | /loginesenhasimples.py | 492 | 3.65625 | 4 | #TELA DE LOGIN E SENHA SIMPLES
from tkinter import *
telalogin = Tk()
telalogin.title("Login do Sistema")
lb1 = Label(telalogin, text="Usuário: ")
lb2 = Label(telalogin, text="senha: ")
entrada1 = Entry(telalogin,)
entrada2 = Entry(telalogin,)
botao = Button(telalogin, text="Login")
lb1.grid(row=0, column=0)
lb2.g... |
67300301f26e258ce8dce67114c51c13660cb39f | ssabhlok/Sem1 | /5801 - CL1/cleanTweets.py | 1,535 | 3.9375 | 4 | # Read in a text file that contains a tweet on each line
# Remove urls from tweets, and print every cleaned tweet on a newline
# The script takes one argument at the command line: the file that you want to process
# If you are in a directory where the code as well as the tweets_buckeyes.txt file is, you can run the cod... |
e7412c9f26655c42bee79470f014c949294d33c4 | SEK7I0N/Python-WorkSpace | /Data Structure/hash_tbl/Q-1.py | 405 | 3.828125 | 4 | # return the first ṛepeating number in an array
inputA = [1, 2, 3, 4, 123, 5, 32, 3]
inputB = [1, 1, 2, 3, 4, 1, 5, 2, 3]
inputC = [1, 2, 3, 4, 5]
def return_first_repeating_number(arr):
dict = {}
for number in arr:
if dict[number] == number:
return number
dict[number] = number
... |
2c60e1d479399dfa18147ae08011dcba197d330f | kevinquinnw/Everyday-Python-Problems | /Largest-prime-factor.py | 379 | 3.53125 | 4 | def PrimeFactorization(k):
primeFactor = 1
q = 2
while q <= k / q:
if k % q == 0:
primeFactor = q
k /= q
else:
q += 1
if primeFactor < k:
primeFactor = k
return primeFactor
print(PrimeFactorization(300))
print(PrimeFact... |
23876f142b1e867711e878a11b9b50e293ff358e | Lubelisa/LBTokenizer-UDPipe | /Tokenizador/tokenizador.py | 9,385 | 3.53125 | 4 | # -*- coding: utf-8 -*
from nltk.tokenize import word_tokenize
from nltk.tokenize import regexp_tokenize
import unidecode
import re
def ord(k):
return int(k.replace('_',''))
# Obtendo abreviaturas e pronomes de tratamento contendo pontos e espacos
list_1 = open('lexicos/abreviaturas_com_pontos_e_espacos_ord.txt', '... |
68b99d1bc065710fa81cd3e8d072da97bfe26702 | shahin-fotowat/AI-Self-Driving-car | /finding_lanes/lanes.py | 5,853 | 3.65625 | 4 | import cv2
import numpy as np
#import matplotlib.pyplot as plt
#-------------------------------------------------------------------------------
def make_coordinates(image, line_parameters):
slope, intercept = line_parameters
y1 = image.shape[0]
y2 = int(y1*(3/5))
x1 = int((y1 - intercept)/slope)
x2... |
06d7a5b1a54e3944a7d2b60bf549d6f1db6c0811 | lobsterkatie/interview-cake | /problem_3.py | 2,970 | 4.5 | 4 | """
Given a list of integers, find the highest product you can get from three of
the integers.
The input list_of_ints will always have at least three integers.
"""
def highest_product_of_3(nums):
"""Given a list of integers, find the largest product of three
of them.
>>> highest_product_of_3([1, 1... |
2d275b0dc2231a38bfa918cdf2d0ee8e7ac66bd1 | nd9dy/Algorithmic-Toolbox | /Algorithm Toolbox/Week 2 Code/Small Fibonacci.py | 250 | 3.859375 | 4 | # Uses python3
def calc_fib(n):
list = [1,1]
if n < 2:
return n
else:
for i in range(2,n):
new = list[i-1] + list[i-2]
list.append(new)
return list[-1]
n = int(input())
print(calc_fib(n))
|
655e607af9fa82814685e157b66beea3de92c96e | AntHudovich/Repo-kraken | /Hudovich_Antanina_dz_1/task_1_1.py | 1,338 | 4.34375 | 4 | # Реализовать вывод информации о промежутке времени в зависимости от его продолжительности duration в секундах:
# до минуты: <s> сек;
# до часа: <m> мин <s> сек;
# до суток: <h> час <m> мин <s> сек;
# * в остальных случаях: <d> дн <h> час <m> мин <s> сек.
duration = int(input("Введите длительность в секундах "))
minut... |
da439687d8eafe74f2b103ac40bd95610463089b | Liliputech/Oulipo | /eodermdrome.py | 2,991 | 3.703125 | 4 | #!/usr/bin/python
#
# Usage : eodermdrome.py [dictfile]
# - dictfile is a textfile (ascii encoding) containing one word per line.
# - a test "dictfile" is provided
#
# This work wouldn't have been possible without the help of my dear friends:
# Arthur Bourcigaux : Mathematician and brilliant algorithm designer
... |
70b7e733a938850965db34b316788be0a2946afc | Theplayer592/EasierPuthonTurtle | /EasierPythonTurtle.py | 1,823 | 3.734375 | 4 | import turtle #Import turtle
t = turtle.Turtle() #Declare turtle variable
def fd(i):
t.forward(i)
def bk(i):
t.back(i)
def rt(i):
t.right(i)
def lt(i):
t.left(i)
def drawShape(sides = 4, size = 10, increaseSize = 0, reps = 1, Hex = "#000000"):
t.pencolor(Hex)
for timesDrawn in range(reps):... |
1a551a1612c6706d49e3e19b7d8457fbb4a9ca37 | crjcrj/pythonaaa | /排序/链表插入排序.py | 780 | 3.59375 | 4 | from typing import List
def insertsort(ilist:List):
if len(ilist)<2:
return ilist
for right in range(1,len(ilist)):
targar=ilist[right]
for left in range(0,right):
if ilist[left]>targar:
ilist[left+1:right+1]=ilist[left:right]
ilist[left]=targa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.