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 |
|---|---|---|---|---|---|---|
abaf40acd562a020872f0d10b77779696bd2575f | ZahraNaddaf/class-1 | /session_03/guess.py | 282 | 3.96875 | 4 |
secret = 7
while True:
answer = input("guess:",)
answer = int(answer)
if answer > secret:
print("secret is lesser than your number")
elif answer < secret:
print("secret is greater than your number")
elif answer == secret:
print("True") |
5e8b91d07a324ddd18512e5a6ded6314898c693d | Aperocky/leetcode_python | /010-RegularExpressionMatching.py | 3,869 | 4.375 | 4 | """
Given an input string (s) and a pattern (p), implement regular expression matching with support for '.' and '*'.
'.' Matches any single character.
'*' Matches zero or more of the preceding element.
The matching should cover the entire input string (not partial).
Note:
s could be empty and contains only low... |
a9a263f4b3a58c22a57d5f06ba4b17d98707e0c4 | Aperocky/leetcode_python | /007-ReverseInteger.py | 945 | 4.21875 | 4 | """
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For th... |
b21d00c049ae28637c6919637741e1bbbab1a035 | idada13/project_test | /ida/ida.py | 2,673 | 3.671875 | 4 | def sum_all_even(test_in):
result = 0
for i in test_in:
if i % 2 == 0:
result += i
return result
def count_characters(test_senc, characters):
result = {}
for i in characters:
result[i] = 0
for j in test_senc:
if i == j:
result[i] +=... |
fb10ddd2cc365360340a9a5fc17f1ef9c9f4a4ff | JSchatzman/code-katas | /longest.py | 162 | 3.875 | 4 | """longest."""
def longest(s1, s2):
"""Return the sorted string of unique elements in s1 or s2."""
return ''.join(sorted(list(set(s1).union(set(s2)))))
|
1c37419134ed8105cacc15a43a8dd4bfd57834b7 | stanford-ccb/ccb-id | /ccbid/outliers.py | 1,146 | 3.5625 | 4 | """Methods for outlier identification in refl data
"""
import numpy as _np
from sklearn.decomposition import PCA as _PCA
def with_pca(features, n_pcs=20, thresh=3):
"""PCA-based outlier removal function
Args:
features - the input feature data for finding outliers
n_pcs - the number of ... |
8255b9c9adbd89119728a20f0da586b7ee886cee | Jhingerkid/Week16 | /dogs.py | 2,770 | 3.65625 | 4 | import random
firstNames = ["Bucko", "Flippy", "Zigso",
"Marco", "Raddoci", "Doggo", "Floofer", "Doge"]
lastNames = ["Flomfer", "Chungo", "McFloof", "Ryklo",
"Cronk", "Floochung"]
breeds = ["Corgi", "Terrier", "Lab", "Poodle",
"Border Collie", "Pug", "Bulldog", "Pitbull"]
colors = ... |
169259ac3929065e8a9171eb3422648e8ddf317f | Metallizer95/contact_wire_application | /testing2.py | 3,645 | 3.796875 | 4 | from math import sqrt
import tkinter as tk
height = 1000
width = 800
def check_line_in_circle(circle, kLine, bLine):
a = circle[0]
b = circle[1]
k = kLine
d = bLine
r = circle[2]
xq = 1 + k**2
x = -2*a + 2*k*d - 2*k*b
fx = a**2 + d**2 + b**2 - 2*b*d - r**2
solve = solve_square_equ... |
f858562f3107dff9c768528d1b8df15afcc68248 | soleilxie/calculator | /calculator.py | 1,902 | 4.09375 | 4 | #Addition
def add(a, b):
return (a + b)
#Subtraction
def sub(a, b):
return (a - b)
#Multiplication
def mul(a, b):
return (a * b)
#Division
def div(a, b):
return (a / b)
#Exponent
def exp(a, b):
result = 1
if b == 0:
return 1
while b > 0:
result = res... |
af0e6075e97fb53ec0513a0f7fdbbf6eb62b9544 | nitzjain/practice | /Stacks, Queues and Dequeue/implement_queue_using_2_stacks.py | 826 | 3.890625 | 4 | class Queue2stacks(object):
def __init__(self):
self.stack1 = []
self.stack2 = []
def enqueue(self,element):
self.stack1.append(element)
return self.stack1
def dequeue(self):
if len(self.stack1) == len(self.stack2) == 0:
return "Queue is empty"
e... |
f481a25733269c39d82eb807e0c549550b19dfdf | nitzjain/practice | /array/create_own_dynamic_array.py | 1,843 | 4.3125 | 4 | '''
the aim is to create your own dynamic array.
If the array gets filled up, then double the size of the array.
So we create a new array with double the size and rename it to the first array.
We use ctypes library to create an array object.
'''
import ctypes
class DynamicArray(object):
#init method. Has 3 compon... |
f2bd5ebaec5b04deb9fbfbe846a7aa8ab0555623 | cakeandturtles/junkyard-of-junkyard | /textGame/etc/commandChecker.py | 1,012 | 3.796875 | 4 | import os, sys
import charVar
import action
import random
def commandChecker():
commandList=raw_input().lower().split(' ')
print
if commandList[0] == "a" or commandList[0] == "action" or commandList[0] == "actions":
Lex()
elif commandList[0] == "look":
if len(commandList)==3:
if commandList[1] ... |
9cdc73cf147d3f7c1a2d966410b7612701d7afc2 | ahsankhan530/python-practice | /assignment#6.6.py | 218 | 3.921875 | 4 | names={'Ahsan':'python','Furqan':'java','nabeel':'c#','Ali':'c'}
list=['Ahsan','JAwad','nabeel','Ali']
for name in names:
if name in names.keys():
print('Thanks',name,'\n','You voted for',names[name])
|
67823c999f91cf7e447947fd10c2ac282a298c20 | ahsankhan530/python-practice | /Assignment#9.6.py | 1,538 | 3.890625 | 4 |
class Resturant():
def __init__(self,name,cuisine_type):
self.name=name
self.cuisine=cuisine_type
def descirbe_resturant(self):
print(self.name,' serves wonderfull',self.cuisine)
def open(self):
print(self.name,' is open come on in')
class IceCreamStand (Res... |
a62015d9de162a95778e731f64eb251382b100b4 | sindhugudivada/Coursera_algo_toolbox | /largest_number.py | 474 | 4.0625 | 4 | #Uses python3
import sys
from functools import cmp_to_key
def largest_number(a):
a = [str(digit) for digit in a]
a.sort(key = cmp_to_key(compare_string), reverse = True)
res = ''.join(a)
return res
def compare_string(x,y):
if x + y > y + x:
return 1
elif x == y:
return 0
els... |
4482f2a0cf59f804ae3a604d2a7ad2c7a1663347 | ben-whitten/ICS3U-Unit-4-03-Python | /square_to_be_fair.py | 2,257 | 4.21875 | 4 | #!/usr/bin/env python3
# Created by: Ben Whitten
# Created on: October 2019
# This is a program which tells you the total value of a number.
# This allows me to do things with the text.
class color:
PURPLE = '\033[95m'
CYAN = '\033[96m'
DARKCYAN = '\033[36m'
BLUE = '\033[94m'
GREEN = '\033[92m'
... |
543a1937e2a336202d49d1a24eb24eda990f6346 | Ramshiv7/Python-Codes | /Range_check.py | 393 | 4.03125 | 4 | #Write a function that checks whether a number is in a given range (inclusive of high and low)
def ran_check(num,low,high):
if num in range(low,high+1):
print(f'{num} is in the range between {low} and {high}')
else:
print(f'{num} is NOT the range between {low} and {high}')
ran_check(5,2,7)
... |
ea76bb800fb75050700f066e2e4c7b0b68e879a4 | Ramshiv7/Python-Codes | /Timer.py | 302 | 4.28125 | 4 | # Write a Python function which display timer(in Seconds)
import time
def timer(i):
while i>0:
print(i)
time.sleep(1)
i-= 1
try:
i = int(input('Set the Timer for (Seconds): '))
int(i)
timer(i)
except ValueError:
print('Input is not an INTEGER !')
|
87822abf5a5a44a407f78348d918a42848b165b0 | Ramshiv7/Python-Codes | /Summer_of_69.py | 809 | 3.8125 | 4 | '''SUMMER OF '69: Return the sum of the numbers in the array, except ignore sections of numbers starting with a 6
and extending to the next 9 (every 6 will be followed by at least one 9). Return 0 for no numbers.'''
def summer_69(nums):
def su_69():
output = 0
for i in nums:
output+= ... |
509860da579fb7bff8b82bb326efaa49e16c7206 | Ramshiv7/Python-Codes | /Slope_Dist_of_Line.py | 537 | 4.03125 | 4 | # Slope and Distance of an co-ordinates using class function on python
import math
class Coordinate:
def __init__(self,coor1,coor2):
self.coor1 = coor1
self.coor2 = coor2
def slope(self):
#y2 - y1 / x2 -x1
x1 = self.coor1[0]
y1 = self.coor1[1]
x2 = self.coor2[0]
y2 = self.coor2[1]
out = (y2 - y1) ... |
bf5cbfbd7ca6d9ba344a926dd3bfa0d7c5fd2a13 | kakamissyou/crossinright | /weather.py | 805 | 3.65625 | 4 | # -*- coding: utf-8 -*-
#两个问题,第一个是城市名称不支持中文,奇怪 ,第二个是urlopen后面竟然不支持read方法
from city import city
import urllib2
import json
cityname = raw_input(u'您想查询哪个城市的天气?\n')
citycode= city.get(cityname)
if citycode:
url = ('http://www.weather.com.cn/data/cityinfo/%s.html' % citycode)
content = urllib2.urlope... |
93f8b457654cdb052cbe41f95c003e7f203716b7 | 7minus2/Python | /Excercises/tesla_input_excercise.py | 533 | 3.921875 | 4 | #!/usr/local/bin/python3
def checkDriverAge(age=0):
# if not age:
# age = int(input('What is your age?: '))
if int(age) < 18:
print('Sorry, you are too young to drive this car '
'Powering off!')
elif int(age) > 18:
print('Powering On. Enjoy the ride!')
elif int(ag... |
d9d45ba89127f5703db72deae8b44add3ed03919 | 7minus2/Python | /Excercises/highest_even.py | 404 | 4.46875 | 4 | #!/usr/local/bin/python3
def highest_even(my_list):
'''
Info: Get the highest even number from a list of numbers \n
Example: highest_even([10,2,3,4,8,11]) # returns 10
'''
even_list = [num for num in my_list if num % 2 == 0]
highest_number = sorted(even_list, reverse=True)
return highest_n... |
1b10d8dfb6eb45c75dd65bc05f5527812e56fc49 | 7minus2/Python | /Excercises/useful_modules.py | 1,053 | 4 | 4 | #!/usr/local/bin/python3
from collections import Counter, defaultdict, OrderedDict
import datetime
import time
from array import array
# creates a dict of how many times number occurs in a iterable
li = [1, 2, 3, 4, 5, 6, 7, 7]
sentence = "Something jumped over the sheet"
# this helps count like dup emails or users fo... |
c6ef5a601652aac40ba158e52cac3f6353323326 | 7minus2/Python | /Excercises/error_catch.py | 829 | 3.828125 | 4 | #!/usr/local/bin/python3
from time import time
def func_timer(fn):
def wrapper(*args, **kwargs):
timer1 = time()
result = fn(*args, **kwargs)
timer2 = time()
print(f'(It took {timer2-timer1} seconds to run')
return result
return wrapper
@func_timer
def func_error():
... |
b8085aa57eb1ff89579d9116892bb06ef3e21875 | AiltireNacht/Where-s-Hoid | /Wheres-Hoid.py | 1,819 | 3.75 | 4 | import time
import os
def Intro():
print(''' _ _ _ _ ____ ____ ____ / ___ _ _ _____ ____ ____ ___
( \/\/ )( )_( )( ___)( _ \( ___) / __) ( )_( )( _ )(_ _)( _ \ (__ )
) ( ) _ ( )__) ) / )__) \__ \ ) _ ( )(_)( _)(_ )(_) ) (_/
(__/\__)(_) (_)(____)(_)\_)(____) (___/ (_) (_)... |
8aa8a6be17fb6a0c7a42064555cfe92648090804 | cbsc228/rsa_encryption | /decryption.py | 928 | 3.84375 | 4 | #this module serves to decrpty ciphertext in the RSA algorithm
from keysetup import modExp
#decrypt the message stored in ciphertext.txt
#input: n from public key pair (n, e)
#sends calculated plaintext to decrypted_message.txt
def decryptMsg(n):
#retrieve the private key from file for decryption
fin =... |
405ff7bdad7fac0f894bb570203dba2235a40cb7 | Lemito66/Python | /CambioDeMoneda.py | 150 | 3.546875 | 4 | libras=int(input("Ingresa tus libras"))
cambio=float(1.35)
cambioTotal=libras*cambio
print("El total de dolares que has gastando es: " +cambioTotal)
|
93fdf41bfe452b6a82d8683df202919f24bf802c | Lemito66/Python | /SobreCargaOperadores.py | 1,029 | 4.21875 | 4 | class Vector(object):
def __init__ (self, x, y,z):
self.x = x
self.y = y
self.z=z
def __repr__ (self):
return '(%f, %f,%f)' % (self.x, self.y,self.z)
def __mul__ (self, v): #sobrecarga de multiplicacion
return Vector (self.x *v.x, self.y *v.y,... |
f83e5af1bd5eb55b882e5e02d5c46e3698a17a2f | jcarstenson/parallel_final | /dataStructure.py | 1,656 | 3.875 | 4 | """
AUTHORS: Joon Sung Park, Jacob Carstenson
DATE: 2016-4-08
"""
class DataStructure(object):
def __init__(self):
self.root = None
self.size = 0
# __str__ supports print operation for printing out.
def __str__(self):
raise NotImplementedError
def length(self):
retur... |
4b76e72c13c18c8ad42c50cb41ec49f1ad468648 | tarokiritani/torchex | /torchex/nn/modules/lazy/linear.py | 1,621 | 3.515625 | 4 | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class Linear(nn.Module):
'''
Examples::
import torch
import torchex.nn as exnn
net = exnn.Linear(10)
# You don't need to give the size of input for this module.
# This network is equi... |
3491871a5650693d2aaf807300665a70809a5aef | gowthamdongari/fsdse-python-assignment-5 | /count_word.py | 176 | 3.875 | 4 | def countWord(input_file,word):
word_count = 0
doc = open(input_file,'r')
for line in doc:
if word in line:
word_count+=1
return word_count
|
a977c0fb3f3c170700b70a773a22f2a9b5544288 | mayelbaz/Elevator | /Elevator.py | 8,724 | 3.984375 | 4 | import time
import threading
M =10
UP=1
DOWN=-1
class Elevator():
"""An elevator class. Elevator has its position- floor number, direction- -1 is down and 1 is up ,
and an array of floors pressed from inside the elevator"""
def __init__(self):
self.current_floor = 0
self.directi... |
9787c525e089d6aac97d7279a37b84ee7428ba88 | Philstrae/001-projet | /san_antonio.py | 1,431 | 4.15625 | 4 | import random
import json
# -*- coding: utf8 -*-
quotes= [
"Ecoutez-moi, Monsieur Shakespeare, nous avons beau être ou ne pas être, nous sommes !",
"On doit pouvoir choisir entre s'écouter parler et se faire entendre."
]
#characters = [
# "alvin et les Chipmunks",
# "Babar",
# "betty boop",
# "cal... |
02bde541cb9fac492db28cc4d9cdec72918afeaf | pranali04/practice | /inheritance.py | 1,112 | 4.25 | 4 | # Online Python compiler (interpreter) to run Python online.
# Write Python 3 code in this online editor and run it.
#print("Hello world")
class math:
def __init__(self,a,b):
print("math class")
class divide(math):
def __init__(self,a,b):
self.a = a
self.c = b
print("divide initi... |
338c0154922a0ee8f80741fe0c4e0db1f33d39b4 | Magda-Ski/Git | /Zadanie_2.py | 166 | 3.890625 | 4 | for i in range(1,100):
if i % 5 == 0:
print(i)
for i in range(1,100):
if i % 5 == 0:
print(i*i*i)
print("Branch Branch Branch Branch") |
203c5360475ea04d7195ec22ecf0f7a4d6fd6d65 | danieljobvaladezelguera/CYPDANIELJVE | /libro/Problemas_resueltos/Capitulo3/Problema3_3.py | 499 | 3.78125 | 4 | #Problema 3.3
print("Programa para una sucesion de numeros")
#Variables a declarar
N = int(input("Dame el numero final denominador de la serie: "))
SERIE = 0
BAND = 'T'
I = 1
if I <= N:
for I in range (1,N,1):
if BAND == 'T':
SERIE = SERIE + 1/I
... |
efb178c0c33969141b621926862feaf5da43c92b | danieljobvaladezelguera/CYPDANIELJVE | /libro/Problemas_resueltos/Capitulo3/Problema3_2.py | 533 | 3.65625 | 4 | #Programa 3.1
#Programa que sume una serie que tiene un aumento de 2 y 3
print("Programa que sume una serie que tiene un aumento de 2 y 3")
#Variables a declarar
BAND = 'T'
SUMSER = 0
I = 2
#Inicia el programa
for i in range (1,1800,1):
if I <= 1800:
print("imprime el valor de i =", I)
... |
4f97c1d2e994f53c4fa9d6cb20b463790f1f6d45 | danieljobvaladezelguera/CYPDANIELJVE | /libro/Problemas_resueltos/Capitulo3/Problema3_13.py | 981 | 3.84375 | 4 | #Programa 3.13
print("Promedios mensuales del clima en Argentina")
#Variables a declarar
ARSU = 0
ARNO = 0
MERSU = 50000
ARCE = 0
I = 1
MES = 0
PRORCE = 0
for i in range (1,3):
RNO = int(input("Dame el # de lluvia en el norte: "))
RCE = int(input("Dame el # de lluvia en el centro: "))
RSU = int(input("... |
0e0d2d95a66ffdd6a0e08cb3c98d8467a0bb1902 | danieljobvaladezelguera/CYPDANIELJVE | /if.py | 222 | 3.78125 | 4 | edad = int(input("Dame tu edad: "))
INE = bool(int(input("Tienes INE (0 NO/1 SI): ")))
if edad >= 18 and INE == True:
print("Es mayor de edad")
print("Aun puedes entrar al bar")
print("Fin del programa")
|
5ab3210bcfbc9304429343edeef8f1ae9c49e0fc | danieljobvaladezelguera/CYPDANIELJVE | /libro/Problemas_resueltos/Capitulo3/Problema3_9.py | 256 | 3.859375 | 4 | #Programa 3.9
print("Diagrama de flujo que lea un numero entero N y calcule la suma de una serie")
SERIE = 0
N = int(input("Dame un numero"))
I = 1
for i in range (1,N + 1):
if I <= N:
SERIE = SERIE + I**I
I = I + 1
print(SERIE)
|
d2bfc5e779a9a7f493f990ab092856dd6bbee7c8 | danieljobvaladezelguera/CYPDANIELJVE | /for3.py | 208 | 4.15625 | 4 | for v in range(3,31,3):
print("Hola",v)
for v in range(20,-1,-1):
print("Hola",v)
print('------------------------')
n = int(input("Dame un numero: "))
for x in range(0,n,1):
print("+",end="")
|
4a7ba22c431cb61001dad9d7d1656e8bcc257b03 | Sagar-1807/Python-Projects | /Algorithms/Selection Sort.py | 500 | 4.28125 | 4 | # MULTIPLE SWAPPING CONSUME MUCH CPU POWER,OR MEMORY POWER
# SORT FROM START TO END
def bubblesort(list):
for i in range(5): # UPPER INDEX :7, INITIAL i=0
min=i
for j in range(i, 6):
if list[j] < list[min]:
min = j
temp = list[i]
list... |
4cfbd5c415b36b0eb76f5f968b9a417c7a4b380e | Sagar-1807/Python-Projects | /Algorithms/LinearSearch.py | 474 | 3.921875 | 4 | #USING FUN & FOR LOOP
choice_position=0
def search(list,choice):
i=0
while i < len(list):
if list[i]==choice:
global choice_position
choice_position=i
return True
i=i+1
return False
list=[12,5,6,7,8,9]
choice=int(input("Enter:"))
if sear... |
91279fa10277381cb4da372d305fcd3a3326149f | CrystalShrestha/Tkinter | /TextEntry.py | 320 | 3.765625 | 4 | from tkinter import *
root = Tk()
e1 = Entry(root, width = 50, fg = "blue", bg = "white", borderwidth=5)
e1.pack()
def myClick():
textoutput="Hey " + e1.get()
myButt1 = Button(root, text=textoutput)
myButt1.pack()
myButton = Button(root, text="Press!", command=myClick)
myButton.pack()
root.mainloop() |
2ac1f1c1a3fac55ad545e2e75047e6d7d570f2e2 | gxgarciat/Playground-GUI-Tkinter | /8_frame.py | 412 | 3.6875 | 4 | from tkinter import *
from PIL import ImageTk,Image
# This code will insert a frame and it will include buttons
root = Tk()
root.title("Frame testing")
frame = LabelFrame(root,text="This is a frame",padx=5,pady=5)
frame.pack(padx=100,pady=100)
b = Button(frame,text="Click here!")
b2 = Button(frame,text="...Not he... |
66b879bfcd0da5e749ecd1373bbf6cb7b9614137 | gxgarciat/Playground-GUI-Tkinter | /5_calculator.py | 3,587 | 4.40625 | 4 | from tkinter import *
# This will display a calculator on the screen
# This calculator only carries out SUM
root = Tk()
root.title("Simplified calculator")
# For this, an entry widget will be required
e = Entry(root,width=40,borderwidth=5)
# e.pack()
e.grid(row=0,column=0,columnspan=3)
# This will get the event fr... |
f9649f0473bc7900d653fd0e216a35d95b6412a3 | gxgarciat/Playground-GUI-Tkinter | /4_entry.py | 738 | 4.375 | 4 | from tkinter import *
# Everything on tkinter is based using widgets
# The program will expand depending on the content
root = Tk()
# For this, an entry widget will be required
e = Entry(root,width=50,borderwidth=5)
e.pack()
# This will get the event from clicking the Button. It needs to be inside of the function
#... |
e1939bd8f6cd2d311fe340c69bb94a529744cb6a | guyBy/PythonWEB | /Lesson1/zip.py | 190 | 3.8125 | 4 | a = ("John", "Charles", "Mike")
b = ("Jenny", "Christy", "Monica")
print(f'a: {a}')
print(f'b: {b}')
x = zip(a, b)
print(f'note that zip is generator {x}')
xt = tuple(x)
print(f'tup {xt}')
|
77a6191bd70457a56db2fba1bda8e2aaf8414024 | erelsgl/auctions | /mcafee_protocol.py | 8,899 | 3.625 | 4 | #!python3
"""
The direct implementation of the McAfee (1992) trade-reduction protocol for a bi-lateral market.
This protocol may have a budget surplus.
Author: Erel Segal-Halevi
Since: 2019-11
"""
from agents import AgentCategory
from markets import Market
from trade import TradeWithSinglePrice
import logging, sy... |
cefa735082da108a90e1235b24f1f92df1661516 | sumon-dey/MachineLearning | /LogisticRegression.py | 2,936 | 3.703125 | 4 | # Logistic Regression
# Import the required libraries and the collected dataset
import numpy as np
import pandas as pd
import matplotlib.pyplot as plotter
collectedDataset=pd.read_csv('Car_Purchase.csv')
X=collectedDataset.iloc[:,[2,3]].values
Y=collectedDataset.iloc[:,4].values
# Split the Dataset into the Training ... |
21d4ee9ef3dabe751dd44a97a0c8feae75e999e5 | mhaeussermann/Programming-Foundations-With-Python | /mindstorms.py | 836 | 3.859375 | 4 | import turtle as t
def draw_square(some_t):
iteration = 0
while iteration < 4:
some_t.forward(100)
some_t.right(90)
iteration +=1
def draw_art():
window = t.Screen()
window.bgcolor("blue")
#Square
hedgehog = t.Turtle()
hedgehog.shape("turtle")
hedgehog.color("w... |
0a939491348d36f67ae8ab544b444d1a18a8729a | Sulagna-Chowdhury/DataStructures_and_Algorithms | /tree.py | 3,422 | 3.703125 | 4 |
class BinaryTreeNode:
def __init__(self,left = None, right = None, data = None, parent = None):
self.left = left
self.right = right
self.data = data
self.parent = parent
def tree_example1():
e = BinaryTreeNode(data='e')
f = BinaryTreeNode(data='f')
d = Binary... |
18cef094a6f6dba8bce64d615968a6d1e19c626f | matsu7874/geister | /montecarloplayer.py | 5,352 | 3.5 | 4 | import random
import player
# Monte Carlo method
class MonteCarloPlayer(player.Player):
def __init__(self, name='PrimevalMonteCarlo'):
self.name = name
def decide_initial_placement(self):
placement = ''
for i in range(8):
if placement.count('g') >= 4:
pla... |
16bd2745c8dcd86d4a5fb793df42809e85f1c40e | DamoM73/tkinterbyexample | /To Do v1s.py | 1,677 | 3.765625 | 4 | # To Do List v1 simple complete
# make a list of To Do items
from tkinter import *
class Todo(Tk):
def __init__(self):
super().__init__()
# Object vairables
self.tasks = []
# Window details
self.title("To-Do App v1")
self.geometry("300x400")
# Adding inst... |
009c418ac68f7e2ee83804359ec70e0a15de216f | gargigupta1507/Security | /1_Password bruteforce.py | 776 | 3.921875 | 4 | #!/usr/bin/python2.7
#character set English albhabet say 26 A-Z (n)
#write a program to bruteforce a password of length 8 (k)
#number of combinations = n^k = 26^8
#print all passwords in a file: password.txt
#write passwords in file
file = open("1_password.txt", "w")
#Recursion logic
def generatePass(charset, n, k,... |
69d1baeaab55466c3d11e6f408986101a31fd658 | vwood/pymantics | /bayes.py | 6,015 | 3.609375 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Naïve Bayesian Classifier
#
class Bayes():
"""Data should be a set of terms."""
def __init__(self):
self.total_count = 0
# labels = {label: count}
self.labels = {}
# data = {labels: {data : count}}
self.label_dat... |
1b9668cb2684df43b939b6a8bfa94dbcc93942aa | daorejuela1/mastermind | /codemaker.py | 4,070 | 3.546875 | 4 | #!/usr/bin/python3
"""
Screen for the player to select actions
"""
from tkinter import *
import tkinter as tk
from tkinter import messagebox
import subprocess
colors = ['blue', 'red', 'yellow', 'green', 'orange', 'cyan', 'purple', 'pink']
class MakerApplication(Frame):
"""Class for the player to make the code
"... |
abd73f67f3950a694e1922c90b307cc98550b07c | konradzicho/Codility | /Brackets.py | 650 | 3.78125 | 4 | def solution(S):
stack_of_brackets = [] * len(S)
for character in S:
if character == "(" or character == "{" or character == "[":
stack_of_brackets.append(character)
elif character == "]" or character == "}" or character == ")":
if len(stack_of_brackets) <= 0:
... |
b55cf105eb52cf9222dfc8c4a3ef0a66fec7cf3e | AtomicTalkShow/lunch-break-rl | /utils.py | 1,404 | 3.5 | 4 | from math import sqrt
def cp437(string):
"""Converts utf8 to codepage 437"""
return ''.join([chr(ord(c.encode('cp437'))) for c in string])
def rect(x, y, width, height):
result = []
for i in range(width):
for j in range(height):
result.append((i + x, j + y))
return result
... |
2acec236729eaf645462396ca2437abe9731d5ae | lien-Gu/Crawler_learning | /03_day/pythontest01.py | 1,469 | 3.734375 | 4 | # t1=()# 创建空元组
# t2=(11,22,'abc')
# # print(t2[1])
# t2[1]
# s1={} # <class 'dict'>空字典
# print(type(s1))
# s2=set() #<class 'set'>空集合
# print(type(s2))
# s3={'a','b','a','c','b'}
# print(s3) # {'a', 'b', 'c'}自动去重
# 运算
# s4={'a','b','c','d'}
# s5={'b','d','e','f'}
# print(s4-s5) # {'c', 'a'}
# ... |
2325991f2ebee880420dda3e75b334b42e9f145f | lien-Gu/Crawler_learning | /01_day/homework.py | 1,286 | 3.8125 | 4 | '''
作业:
1、摄氏度和华氏度相互转化,华氏度=摄氏度*1.8+32
摄氏度转为华氏度请按1
华氏度转化为摄氏度请按2
1
请输入摄氏度:23
23.0 摄氏度转化为华氏度为:73.4
2、计算三角形的面积
三个格式化输出结果:三条边分别为X,X,面积为X
'''
# import math
# print("请输入三角形的三条边长度:")
# a=float(input("a:"))
# b=float(input("b:"))
# c=float(input("b:"))
# if a+b>c and m... |
2316df57e2da04011c79f10c14642c744f46d9bc | mozilla/pyjexl | /pyjexl/operators.py | 1,745 | 3.75 | 4 | import operator
class Operator(object):
__slots__ = ('symbol', 'precedence', 'evaluate', '_evaluate_lazy')
def __init__(self, symbol, precedence, evaluate, evaluate_lazy=False):
"""Operator definition.
If evaluate_lazy is set to True, the `evaluate()` method will receive
it's paramet... |
907cbf889187c38a4408f2b7f709916adc59000d | enakilci/TUHH-Project-Work | /utils.py | 3,829 | 3.890625 | 4 | import csv
import os
import pandas as pd
import errno
import sqlite3
def load_n_debug(csv_files_path,drop_percent=0.985):
"""Creates a dataset as a pandas.DataFrame object from the csv_files in given 'csv_files_path' and debugs the data in the datasets
Arguments:
csv_files_path: os path of the csv fi... |
f5bf94d674a20714c684b4ec5b3c744c88d33a31 | kevinyu/furry-guacamole | /lib/spikes/filters/util.py | 2,025 | 3.625 | 4 | from __future__ import division
import numpy as np
def gaussian_convolver(std, n=3.0):
"""Create gaussian in an array form extending n std on either side
Input:
std (float): std of gaussian distribution
n (float, default=3.0): number of stds to extend gaussian in each direction
Output:
conv... |
ad167b90e85f9b620b1206ed6520d8af6f3e4d7c | hkakran/ud_fswdnd | /programming_foundation_with_python/secret_message.py | 375 | 3.703125 | 4 | import os
import re
def remove_numbers(name):
return re.sub('[0-9]','',name)
def rename_files():
# 1. get all the photos
files = os.listdir(os.getcwd()+'/prank')
# 2. rename the files
for fileName in files:
print fileName
print remove_numbers(fileName)
os.rename(os.getcwd()+'/prank/'+fileName, os.getcwd(... |
d203d9dd6649f422ffa0ea9bd411cbb614fd899a | beinganuvesh/Cheatsheet-DS-ALGO | /Second Attempt.py | 27,260 | 3.515625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
#ARRAYS
#Next Permuation in O(1) Space
def next_Permutation(arr):
n=len(nums)
for i in range(n-1, 0, -1):
if arr[i-1]<arr[i]:
break
else:
return arr.sort()
i=i-1
for j in range(n-1, 0, -1):
if arr[i]<... |
5a4a9d2af6957142142f90de2004268026590771 | ubriela/cracking_coding | /graph.py | 9,119 | 3.859375 | 4 | """
Gray Code
https://leetcode.com/problems/gray-code/
The gray code is a binary numeral system where two successive values differ in only one bit.
Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0.
For example, gi... |
582f49d65aa88914b68b464559a4c6a17b86c00f | ubriela/cracking_coding | /data_structure_design.py | 15,085 | 3.59375 | 4 | """
Insert Delete Search GetRandom O(1)
https://leetcode.com/problems/insert-delete-getrandom-o1/
http://www.geeksforgeeks.org/design-a-data-structure-that-supports-insert-delete-search-and-getrandom-in-constant-time/
Design a data structure that supports all following operations in average O(1) time.
insert(val): In... |
74c583a30f01e2e7536cac1d87479651c161345e | shunni9949768377/gitbasics-mstp-level1-162T1A0591 | /01-10-19/packages/operations.py | 387 | 3.890625 | 4 | def add(x,y):
z=x+y
print(z)
def isprime(n):
fact=0
for i in range(1,n+1):
if(n%i==0):
fact=fact+1
if(fact==2):
return True
else:
return False
isprime(6)
def primefactors(n):
if isprime(n)==True:
for i in range(1,n+1):
if n%i==... |
d5414ff5403d0d2da654d14c2b5fb132f5c5f974 | Yacine-Saoudi/hackathonRepo | /calcpage.py | 1,258 | 3.671875 | 4 | import tkinter as tk
import page as p
class CalcPage(p.Page):
def __init__(self, *args, **kwargs):
p.Page.__init__(self, *args, **kwargs)
self.labelTotal = tk.Label(self, text ="Calories: 0")
self.labelTotal.pack(side="top", fill="both")
self.labelGoal = tk.Label(self, tex... |
21fd13a55218a849652de9afed00c965dc5296e2 | pdmxdd/tutoring | /week_two/true_false.py | 629 | 4.0625 | 4 |
'''
first_name = "Sam"
last_name = "Drummond"
first_name_two = "Chris"
last_name_two = "White"
if first_name == "Paul" and last_name == "Matthews":
print("Welcome Paul")
elif first_name_two == "Chris" and last_name_two == "White":
print("Welcome Chris")
elif first_name == "Julia" and last_name == "Drummond":
... |
0d3e07b3196babe68fc60e9236b07cfcb403e8ad | Jeremyy55/AO_TP1 | /generate_solution/julie.py | 2,196 | 3.53125 | 4 | import random
# Fonction pour trouver des voisins
# X est un vecteur représentant la position des 1
# nbNeighbour est le nombre de voisins qu'on veut créer
# Return une list de nouveaux voisins (sans doublon et ne comprenant pas le X de départ)
def find_neighbour(x):
new_neighbour = x.copy()
possible_element... |
788e7bc7c2f5deb6d74be18e4f92cf72fc1bad31 | Idowuolaidemoshood/DSN-AI-INVASION-OSUN | /programm class.py | 1,102 | 3.578125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[11]:
import numpy;
import numpy as np;
a = np.array([1,2,3,4,5]);
b = np.array([9,10]);
print(a);
print(b);
# In[10]:
print ('the shape of a is:', a.shape)
# In[13]:
print("the shape of b is:",b.shape)
# In[17]:
x = np.array([[1,2], [3,4]]);
print(x);
# In[19... |
b7e1f322b21869f69c2284b5ed23c0cc23017c83 | manicmaniac/Project_Euler | /python/Problem25.py | 801 | 3.890625 | 4 | # coding:utf-8
"""
The Fibonacci sequence is defined by the recurrence relation:
F[n] = F[n−1] + F[n−2], where F[1] = 1 and F[2] = 1.
Hence the first 12 terms will be:
F[1] = 1
F[2] = 1
F[3] = 2
F[4] = 3
F[5] = 5
F[6] = 8
F[7] = 13
F[8] = 21
F[9] = 34
F[10] = 55
F[11] ... |
226eb21253e420af566eeaec40eaacf0042d4c0e | manicmaniac/Project_Euler | /python/Problem22.py | 851 | 3.953125 | 4 | # coding:utf-8
"""
Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name scor... |
10ced900f96289c8b049586defb49db9039e14b1 | manicmaniac/Project_Euler | /python/Problem40.py | 500 | 3.84375 | 4 | # coding:utf-8
"""
An irrational decimal fraction is created by concatenating the positive integers:
0.123456789101112131415161718192021...
It can be seen that the 12th digit of the fractional part is 1.
If dn represents the nth digit of the fractional part, find the value of the following expression.
d1 d10 d100... |
50fc37faeb1db5b2343fae033968ea6acff48737 | manicmaniac/Project_Euler | /python/Problem10.py | 519 | 3.6875 | 4 | # coding:utf-8
r"""
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
"""
import itertools
def sieve(limit):
search = bytearray([1] * limit)
search[0] = 0
search[1] = 0
sqrt_limit = int(limit ** 0.5)
for i in range(2, sqrt_limit):
if ... |
964e696f63f6315758e91f5e621afcba86fe1b3d | manicmaniac/Project_Euler | /python/Problem36.py | 512 | 3.90625 | 4 | # coding:utf-8
"""
The decimal number, 585 = 10010010012 (binary), is palindromic in both bases.
Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2.
(Please note that the palindromic number, in either base, may not include leading zeros.)
"""
def is_palindromic(n):
re... |
c9bf13d58b798a203ed36497863598fd16693bd7 | manicmaniac/Project_Euler | /python/Problem46.py | 1,433 | 3.8125 | 4 | # coding:utf-8
"""
It was proposed by Christian Goldbach that every odd composite number can be written as the sum of a prime and twice a square.
9 = 7 + 212
15 = 7 + 222
21 = 3 + 232
25 = 7 + 232
27 = 19 + 222
33 = 31 + 212
It turns out that the conjecture was false.
What is the smallest odd composite that cannot b... |
52d739156ca3df5615782a791ebe497ddcbfabd5 | manicmaniac/Project_Euler | /python/Problem99.py | 866 | 3.703125 | 4 | # coding:utf-8
"""
Comparing two numbers written in index form like 2^11 and 3^7 is not difficult,
as any calculator would confirm that 2^11 = 2048 < 3^7 = 2187.
However, confirming that 632382^518061 > 519432^525806 would be much more
difficult, as both numbers contain over three million digits.
Using base_exp.txt (... |
b539aa1b21567d467b4443d94a3b45c884f8f1f6 | aditi002/Tkinter_Project | /New folder/Tkinter_One.py | 375 | 3.9375 | 4 | from tkinter import *
root=Tk()
e1= Entry(root, width=50, fg="blue", bg="white", borderwidth=5)
e1.pack()
def myClick():
textoutput = "Hello " + e1.get()
myLabel = Label(root, text=textoutput)
myLabel.pack()
myButton = Button(root, text=textoutput)
myButton.pack()
myButton = Button(root, text="Click... |
dc557b764ba7e2bacf978872247772ac0a222a8d | HALF-MAN/pythonlearn | /learning/oop/InstanceAndClassaAttributes.py | 1,307 | 4.71875 | 5 | """
直接在class中定义属性,这种属性是类属性,归Student类所有:
class Student(object):
name = 'Student'
当我们定义了一个类属性后,这个属性虽然归类所有,但类的所有实例都可以访问到。
>>> class Student(object):
... name = 'Student'
...
>>> s = Student() # 创建实例s
>>> print(s.name) # 打印name属性,因为实例并没有name属性,所以会继续查找class的name属性
Student
>>> print(Student.name) # 打印类的name属性
Studen... |
7dd3273d1069016229a18a38848502aa7a263fec | HALF-MAN/pythonlearn | /learning/oop/ClassAndInstance.py | 3,295 | 4.25 | 4 | """
以Student类为例,在Python中,定义类是通过class关键字:
class Student(object):
pass
class后面紧接着是类名,即Student,类名通常是大写开头的单词,紧接着是(object),
表示该类是从哪个类继承下来的,继承的概念我们后面再讲,通常,如果没有合适的继承类,
就使用object类,这是所有类最终都会继承的类
定义完类就给类创建实例
>>> bart = Student()
>>> bart
<__main__.Student object at 0x10a67a590>
>>> Student
<class '__main__.Student'>
可以看到,变量... |
bd4b01a4f57c749e711c7bce1cbcd2fefaf9ba2a | HALF-MAN/pythonlearn | /learning/oop_advanced_features/binding.py | 2,716 | 4.1875 | 4 | """
正常情况下,当我们定义了一个class,创建了一个class的实例后,
我们可以给该实例绑定任何属性和方法,这就是动态语言的灵活性。先定义class:
class Student(object):
pass
给实例绑定一个方法:
>>> def set_age(self, age): # 定义一个函数作为实例方法
... self.age = age
...
>>> from types import MethodType
>>> s.set_age = MethodType(set_age, s) # 给实例绑定一个方法
>>> s.set_age(25) # 调用实例方法
>>> s.age # 测试结... |
73b8018ce662ca4b68220e091a3cfa9bc546c507 | HALF-MAN/pythonlearn | /learning/functional_programming/higher_order_function/Filter.py | 1,222 | 4.375 | 4 | """
Python内建的filter()函数用于过滤序列。
和map()类似,filter()也接收一个函数和一个序列。和map()不同的是,filter()把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素。
例如,在一个list中,删掉偶数,只保留奇数,可以这么写:
def is_odd(n):
return n % 2 == 1
list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]))
# 结果: [1, 5, 9, 15]
filter()这个高阶函数,关键在于正确实现... |
a60d67e3b4281f7bc6ddce2343218b952fd9bc51 | alduf1972/Excercispython | /Exercices C1C Ennoncés/C1C3.py | 1,635 | 3.8125 | 4 | # Enoncé : Votre programme demande à l'utilisateur d'entrer un chiffre, ce chiffre représentera le sexe la personne (1:femme 2:homme 3:autre)
# En fonction de l'entrée donnée, le programme donnera un résultat différent, le programme saluera la personne en prenant en compte son sexe,
# (Boujour Madame/Boujour Monsieur/... |
4236a00fc82ac2bed48764a68e3bb8f4be2791b5 | webfudge95/codenation | /DayTwo/challenge6.py | 444 | 4.3125 | 4 |
def is_even(num):
if (num % 2) == 0:
return True
else:
return False
def addition(num1, num2):
num3 = num1 + num2
return num3
num1 = int(input("What's the first number: "))
num2 = int(input("What's the second number: "))
num3 = addition(num1, num2)
print("The sum of {} and {} is {}".f... |
b83bba009e6e982bc75af1503329a627babef0dd | webfudge95/codenation | /DayTwo/challenge2.py | 278 | 4.46875 | 4 | num = int(input("Please type a number: "))
if (num % 3) != 0:
print("Your number is not dividasable by 3")
else:
print("Your number is divisable by 3")
if (num % 5) != 0:
print("Your number is not dividasable by 5")
else:
print("Your number is divisable by 5") |
a0d9da050e64516b2af70711379c4d6266b4386b | vuthyruos/Python-Complete-Foundation | /14_whileloop_continue.py | 138 | 3.625 | 4 | # Initiate new variables
a = 1
# While block with continue keyword
while a < 10:
a += 1
print(a)
if a == 7:
continue |
d4beb52faafda9d2cf7e386a07624563c5dd895c | vuthyruos/Python-Complete-Foundation | /29_writefile.py | 177 | 3.703125 | 4 | # Use open() function to open a file
f = open("29_message.txt", "w")
# Use write() function to write the file
f.write("I love learning programming.")
# Close the file
f.close() |
2199fcc443470f761b2c26e4819a9033a5308221 | vuthyruos/Python-Complete-Foundation | /35_regex.py | 159 | 3.5625 | 4 | # Import module
import re
# Initiate new variable
text = "That cost around 20 bucks"
# Using \d special character
regex = re.findall("\d", text)
print(regex) |
3f4fc07173c471eec61ae2bcf9128ba72b685c66 | vuthyruos/Python-Complete-Foundation | /18_input.py | 111 | 4.21875 | 4 | # Initiate new variable
# Assign input function to the variable
name = input("Enter your name:\n")
print(name) |
31d56c14702ad034a88257f9af5607731482094b | vuthyruos/Python-Complete-Foundation | /03_variable_datatype.py | 343 | 3.671875 | 4 | # Initiate new variables
var_str = "Hello world! I am Cambodian."
var_int = 2022
var_float = 3.14
var_cmp = 1j
# String data type
print(var_str)
print(type(var_str))
# Integer data type
print(var_int)
print(type(var_int))
# Float data type
print(var_float)
print(type(var_float))
# Complex data type
print(var_cm... |
ee81e67cae5adee38fd9267b220d09d414ffe398 | ryerh/leetcode | /solutions/lru-cache.py | 4,475 | 3.859375 | 4 | import unittest
class Node:
def __init__(self, key, value):
self.key = key
self.value = value
self.prev = None
self.next = None
class LinkedList:
def __init__(self):
self.begin = None
self.end = None
self.size = 0
# tail insertion
def add_no... |
13bbd1eddbe2d3fa2a4ace78152528ce76d0e0b6 | mqtlam/osu-cs531 | /project1/Agent.py | 383 | 3.609375 | 4 | #!/usr/bin/env python
class Agent:
"""The Agent class is an abstract class with useful constants."""
FORWARD = 1
RIGHT = 2
LEFT = 3
SUCK = 4
OFF = 5
NORTH = 0
EAST = 1
SOUTH = 2
WEST = 3
def takeStep(self, percept):
"""Given a percept, determine and return an action."""
[wall, dirt, home] = percept
... |
ae6b39bf461f69f0dd0e01b562925c852693e15a | JPB-CHTR/mycode | /challenge_labs/sleepytime.py | 975 | 4.1875 | 4 | #!/usr/bin/env python3
def toddler():
diaper = input("Is the diaper wet? (Y or N)")
if diaper == "Y":
print("Change Diaper")
elif diaper == "N":
print("Give milk")
else:
print("You should have answered Y or N")
def teen():
wakestate = input("Is the kid sleep walking (Y or N... |
95c15919e6c237ed8e79e5d9cc9184334792ff66 | ankur0493/Random-Python-Exercises | /integer_columns_to_letters.py | 1,716 | 3.6875 | 4 | def length_three(number_in):
letter = ''
letter = length_one(((number_in-26)/676)-1)+length_two(((number_in-26)%676)+26)
return letter
def length_two(number_in):
letter = ''
letter = length_one(number_in/26-1)+length_one(number_in%26)
return letter
def length_one(number_in):
letter = ''
if number_in =... |
5375c2de10a4317b965ad7b7604b25fa4810b6c9 | Cidney688/python200817 | /Aug17/M+Eng.py | 407 | 3.953125 | 4 | math=int(input("whats's your math score?"))
Eng=int(input("what's your eng score?"))
if (math>=0 and math<=100) and (Eng>=0 and Eng<=100):
if (math>=90) and (Eng>=90):
print("有獎品!")
elif(math<60) and (Eng<60):
print("接受處罰")
elif math<60 or Eng<60:
print("加油!")
else:
p... |
071ba547f9f6d08f1c14fdecf5fe9114d1963893 | socialite-lang/socialite | /test/test_recur.py | 1,665 | 3.65625 | 4 | """
Testing recursive rules.
"""
import unittest
class TesetRecursion(unittest.TestCase):
def __init__(self, methodName='runTest'):
unittest.TestCase.__init__(self, methodName)
def test_recur1(self):
`Edge(int s, (int t)) indexby s.
Edge(s,t) :- s=1, t=2.
Edge(s,t) :-... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.