blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
e126c0d4c8952613097a91a23caf08b533271374
FinnStokes/doomtower
/src/path.py
2,777
3.671875
4
import heapq class Node: def __init__(self, index): self.index = index def __cmp__(self, other): return other.index - self.index def __hash__(self): return hash(self.index) class Edge: def __init__(self, src, dest, cost): self.src = src self.dest = des...
69a240213d3338e2e8090520aa85d99f90e82b7a
loliamserious/SOEN6111-BIG-DATA
/DataPreprocessing.py
4,461
4.0625
4
from DataExploration import * import pyspark.sql.functions as F from pyspark.sql.functions import col, sum,split from sklearn.preprocessing import MinMaxScaler def drop_exception_data(dataset): """ This function is used to drop the exception of dataset. For example, some houses with extreme large square ...
7336a4cefddaa367e873cb96f0ffbaa090efc2d0
posguy99/comp660-fall2020
/src/M6_string_start_end.py
182
3.671875
4
# check if string starts and ends with a substring title = 'Monty Python and the Holy Grail' print(title.endswith('Grail')) # True print(title.startswith('Monty')) # True
5edce8e73a3ec5ea8929520dffe321bc44082fa3
posguy99/comp660-fall2020
/src/M6_assignment_3a.py
965
3.609375
4
# M6 #3a str = \ ''' inet addr :127.0.0.1 Mask:255.0.0.0 inet addr :127.0.0.2 Mask:255.0.0.0 inet addr :127.0.0.3 Mask:255.0.0.0 inet addr :127.0.0.4 Mask:255.0.0.0 ''' # print('The input string is:\n', str) # debug # create a list of strings from the input theList = str.split('\n') # print(theList) ...
b65280021b7397d9f85e81ea974600001c8908c1
posguy99/comp660-fall2020
/src/M4_future_value_calculator.py
1,229
4.34375
4
#!/usr/bin/env python3 def calculate_future_value(monthly_investment, yearly_interest_rate, years): monthly_interest_rate = yearly_interest_rate / 12 / 100 months = years * 12 future_value = 0 for i in range(0, months): future_value += monthly_investment monthly_interest_amount = futur...
1c8c6473e7fe467a4e21bb6707b54ea154764777
posguy99/comp660-fall2020
/src/Module 2 Assignment 3.py
672
4.34375
4
#!/usr/bin/env python3 kg_to_lb = 2.20462 earth_grav = 9.807 # m/s^2 moon_grav = 1.62 # m/s^2 mass = float(input("Please enter the mass in lb that you would like to convert to kg: ")) kg = mass / kg_to_lb print("The converted mass in kg is:", kg) print("Your weight on Earth is:", kg*earth_grav, "Newtons") print("...
190bbbc26dd2db956d03a7dbcf9b2edc27bd8599
posguy99/comp660-fall2020
/src/M6_Exercise.py
1,052
4.1875
4
# string traversal fruit = 'Apple' # print forwards index = 0 while index < len(fruit): letter = fruit[index] print(letter) index = index + 1 # exercise 1 - print in reverse index = len(fruit) while index: letter = fruit[index - 1] # because slice is zero-based print(letter) index = inde...
45f27c218bfdffef7bbb1f492d46bcdad30eb84e
posguy99/comp660-fall2020
/src/M5_lambda.py
417
4.03125
4
# do not assign a lambda expression, use a def flake8(E731) double = lambda x: x * 2 print(double(5)) # Program to filter out only the even items from a list my_list = [1, 5, 4, 6, 8, 11, 3, 12] new_list = list(filter(lambda x: (x % 2) == 0, my_list)) print(new_list) # Program to double each item in a list using ma...
5040e259b59e95d545761d424b0d4d134c868b08
hlucas96/Algonum-Projet-3-Team-2
/convert_picture.py
819
3.734375
4
import matplotlib.pyplot as pl import numpy as np import matplotlib.image as img def picture_to_matrix(path): ##Return 3 matrixs corresponding to the color Red Green Blue of the picture in path img_full = img.imread(path) n = len(img_full); m = len(img_full[0]) R,V,B = np.zeros((n,m)),np.zeros((n,m...
4fcff4f339780152d836153e8078492e39f5335a
jmitchellkelley/pythonclass
/chapter3/exercise3-3.py
445
3.796875
4
#Exercise 1 num = 3 while True: num = 2 * num if num > 15: break print(num) print() #Exercise 2 num = 3 while num < 15: num += 5 print(num) print() #Exercise 7 - With List list1 = ['a', 'b', 'c', 'd', 'e'] i = 0 while True: print(list1[i]) i += 1 if i == len(list1): break #prints the letter of the list c...
4f3405090651719123d3e7290b52562854e5ee16
jmitchellkelley/pythonclass
/radius.py
199
4.28125
4
# Assign a value to a radius radius = 20 # The radius is now 20 # Compute Area area = radius * radius * 3.14159 # Display Results print("The area for the circle of the radius", radius, "is", area)
f4c6d38064c2989e8affebb32529aab5440eba4a
NayanNaman/Circle-Area
/Circle Area.py
193
4.1875
4
print("Hello!, I am here to find the area of the circle.") r=float(input("Please enter the Radius here: ")) area=(22/7)*r**2 print("The area of the cicle whose radius is", r, "is", area)
9354bb8cb83dc8de41e492226c21b2573d97dd0a
nizguy/my_python_ltp
/rolodex1.py
1,393
4.0625
4
#!/usr/local/bin/python2.7 import csv print "Welcome To My Rolodex" print "Please Use The Following Menu To Enter New Contacts: " def menu(): print "To Add to Rolodex - Enter N" print "View List of Contacts - Enter V" print "To Quite Program - Enter Q" selection = raw_input("Shall We beg...
9e5f21b1a3568a053f6960452d7572f107748b6e
nizguy/my_python_ltp
/dictionaries.py
664
4
4
gpas = { "Mark Lassoff" : 3.45, "Fred Smith" : 2.99, "Mary Johnson" : 2.55, "John Johnson" : 1.95, "Louis Lane" : 3.15, "Brett Smith" : 4.0, } print "The GPA is: ", (gpas["Mark Lassoff"]) print "The GPA is: ", (gpas["Brett Smith"]) gpas["Louis ...
a9496b206cd6ced2873f84ee800cb8f6836ee2e7
gugeniubi/pythonjoker
/day002.py
4,198
3.59375
4
#1. # double a = input.nextDouble() # double b = input.nextDouble() # double c = input.nextDouble() # System.out.print("要求解的方程为:" + a + "*x*x + " + # b + "*x + " + c + " = 0") # System.out.println("\n方程的判别式为:" + equation.getDiscriminant(a,b,c)); # if(equation.getDiscrim...
262f8daf43f1eddc23f9abdcb6d648cd8727cc7b
Pavan1511/python-program-files
/python programs/data wise notes/28 april/OrderedDict.py
496
3.578125
4
# OrderedDict from collections import OrderedDict def accessing_ord_dct(): # control flow -->5 student = OrderedDict([('usn', '1ms09cs415'), ('name', 'Arjun'), ('cgpa', 8.35)]) # accessing OrderedDict values by using their keys print(student['usn']) # 1ms09cs415 print(student['name']) ...
2b2f36856823c27ee7d0f56a61d50e0e364d01fe
Pavan1511/python-program-files
/python programs/data wise notes/22 april/reverse_deque.py
341
4.09375
4
#Program: 7 # reverse() from collections import deque def reversing_deque(): d1 = deque([11,13,15,17,19]) print(f'deque before reversing:{d1}')#deque([11, 13, 15, 17, 19]) print(d1.reverse())#None print(f'deque after reversing:{d1}')#deque([19,17,15,13,11]) if __name__ == "__main__": rev...
2d52aa2d9101714688f9bbd6498c17a10e7def6d
Pavan1511/python-program-files
/python programs/data wise notes/29 april/default dict ex3.py
797
4.1875
4
#Program: 3 returning a default value if key is not present in defaultdict # creating a defaultdict # control flow --> 1 from collections import defaultdict # control flow --> 5 def creating_defaultdict(): student = defaultdict(func) # ----> invoke func() ---> 8 print(type(student)) student['...
19f2fd7f1d7c2dcd4b2f4ac8915bc3eae95c5427
Pavan1511/python-program-files
/python programs/data wise notes/29 april/default dict ex9.py
585
3.765625
4
#Program: 9 # using list as a default_factory in my defaultdict from collections import defaultdict def list_defaultdict(): aadhar_info = defaultdict(list) # default_factory lst = [('aaddar_no', 265482731827), ('name', 'Arjun'), ('address', 'Bengaluru')] # append items to aadhar_info for k...
6468a1bf78bb51a20e0a95fa1ff58343f4d06f6b
Pavan1511/python-program-files
/python programs/data wise notes/21 april/colletions starting.py
361
3.703125
4
#creating a double ended queue or deque #only list and string #colletions from collections import deque def creating_deque(): #deque of number deck1=deque([10,20,30,40,50]) print(deck1) print(type(deck1)) #deque of string deck2=deque('abc for tech') print(deck2)#deque['a','b','c','c',........] if _...
f72159d34446e902f009b3946a3698d4ed092d48
Gabriel-Kirchgraber/MadKillerAgents
/src/Map.py
3,220
4.03125
4
import random from Tile import Tile import SurroundingTiles class Map: def __init__(self, dimX, dimY): """ If instatiated this class will generate a Map object with the specified dimensions. The map is a 2D array, and every array field contains a tile object. For each tile object th...
ab2d92b7e16305d3ce343c6926e3cce6508959e2
EricWWright/PythonClassStuff
/aThing.py
1,369
4.125
4
# print("this is a string") # name = "Eric" # print(type(name)) # fact = "my favorite game is GTA 5" # print("my name is " + name + " and I like " + fact) # # or # print("my name is ", name, " and i like ", fact) # # or # message = "my name is " + name + " and I like " + fact # print(message) # # vars # num = 8 # num2...
ee7d581e3759ccf1b93614448aa937f25fbddc41
EricWWright/PythonClassStuff
/twoWayIF.py
509
4.0625
4
#two way if.exe #Eric Wright #10/18 num = int(input("Enter a number")) if num%2 == 0: print("that number is even") else: print("That number is odd") num1 = float(input("pick a number")) num2 = float(input("pick another number")) if num1 <= num2: if num1 == num2: print("The numbers you entered ar...
721ceeb936675904e4406cf14f1a88e6e0a694db
colekahkonen/Jarvis
/jarviscli/tests/test_lyrics.py
2,073
3.53125
4
import unittest from plugins.lyrics import lyrics from tests import PluginTest class Lyrics_Test(PluginTest): def setUp(self): self.song_name = "everybody dies" self.artist_name = "ayreon" self.complete_info = "everybody dies-ayreon" self.wrong_info = "everybody dies-arebon" ...
3c0333a33cd6d62a39997ac9cfb22e511973d225
williamluisan/numerical_methods
/trapezioda.py
1,000
3.875
4
class Trapezioda: def fx(self, x): return 0.2 + (25*x) - (200*x*2) + (675*x*3) - (900*x*4) + (400*x*5) if __name__ == "__main__": print(""" Diketahui f(x) = 0,2 + 25x - 200x2 + 675x3 - 900x4 + 400x5 dalam interval 0 <= x <= 0,8 dengan jumlah pembagi (n) = 5 """) trz = Trapezioda() # batas at...
1e86f0e891b4f89244bb721921ebb1ea80a24c70
KangMin-gu/Python_work
/Hello/test/Step02_DataType.py
1,233
3.578125
4
#-*- coding:utf-8 -*- # int type (정수) num1=10 # float type (실수) num2=10.1 # bool type (논리) isRun=True isWait=False isGreater=10>5 # 비교연산의 결과 isGo=True or False # 논리연산의 결과 # str type (문자) myName='kimgura' yourName="monkey" # unicode type (한글을 다룰때는 unicode type 을 써야한다) ourName=u'에이콘' ourName2=u"에이콘 아카데미" # list ty...
ff929f34bf5180a28adf60098c3c7182275b546f
KangMin-gu/Python_work
/Hello/test/Step05_tuple.py
798
3.75
4
#-*- coding:utf-8 -*- ''' - tuple 1. list type 의 read only 버전(읽기전용) 2. 수정, 삭제 불가 3. list type 보다 처리 속도가 빠르다. ''' tuple1=(10, 20, 30, 40, 50) for tmp in tuple1: print "tmp:", tmp # 수정불가 #tuple1[0]=999 # 삭제불가 #del tuple1[0] # 방 1개 짜리 tuple type 을 만들때는 주의! result=('kim',) # tuple 을 만들때...
65b4cc1c995c1435092ec830d1450668f17ad8f3
Tenagrim/L-systems_drawing
/tree2.py
2,030
3.640625
4
import turtle from random import randint from math import floor WIDTH, HEIGHT = 1200, 700 screen = turtle.Screen() screen.setup(WIDTH, HEIGHT) screen.bgcolor('black') screen.delay(0) turtle.hideturtle() turtle.tracer(0) leo = turtle.Turtle() leo.pensize(1) leo.speed(0) leo.setpos(0, -HEIGHT // 2 + 50) leo.color('gre...
e1ec02c93892e7c7b13806e96bb6cba1732b575a
Cm290/learning-day-stuff
/Python_fun/right_orbits.py
3,842
3.96875
4
import matplotlib.pyplot as plt from matplotlib.patches import Ellipse, Circle #Set axes aspect to equal as orbits are almost circular; hence square is needed ax = plt.figure(0).add_subplot(111, aspect='equal') #Setting the title, axis labels, axis values and introducing a grid underlay #Variable used so title can in...
0d5a809a8b130044211551e518c584a583711b68
gustavoallfadir/Small-tools-for-Python
/menu_clickderecho.py
744
3.625
4
import Tkinter def make_menu(w): global the_menu the_menu = Tkinter.Menu(w, tearoff=0) the_menu.add_command(label="Cut") the_menu.add_command(label="Copy") the_menu.add_command(label="Paste") def show_menu(e): w = e.widget the_menu.entryconfigure("Cut", command=lambda: w.event_generate...
df9a39d8f39c87d4700239ff06261dc683ebded3
greearb/lanforge-scripts
/py-scripts/scripts_deprecated/lf_launch_arg_util.py
3,317
3.640625
4
#!/usr/bin/env python3 ''' This module is meant to serve as a utility for converting command line arguments to VSCode launch.json formatted launch parameters. Importing the script offers functions command_to_json, which takes a command string and returns a dict structure, and prettify_json, which creates and returns a...
506070d71ca124ac0dd09d8ca13e4449b297a5b9
SHITIANYU-hue/challenge-aido_RL-IL
/tutorials/image_processing/process_image.py
6,954
3.953125
4
""" Explanation on how Canny Edge Detector works: https://www.youtube.com/watch?v=5dL7FvL-oy0 """ import cv2 from matplotlib import pyplot as plt import numpy as np # Load an RGB image on a gray scale img = cv2.imread("../images/road.png", 0) # One way to get rid of the noise on the image, is by applying Gaussian ...
1ae9eab4c62a92e2ceeb4bd21e9bd3c50d6e5aad
rawalter/School-Projects-Python01
/Python Projects/rawalter_18.4.py
806
3.9375
4
#!/usr/bin/python3.4 #Robert A. Walters #Thanks to kyle Carr from LinkedList import LinkedList from LinkedList import LinkedListIterator from LinkedList import Node def main(): list = LinkedList() list.add("USA") list.add("Canada") list.add("Antarctica") list.add...
1f22b4189bfa3a1c8910638b223a93fb1afb865a
NavTheRaj/python_codes
/mat_pie_1.py
285
3.703125
4
import matplotlib.pyplot as plt def main(): #SET THE VALUES values=[20,50,40,50,90] labels=['Math','Science','Computer','English','Nepali'] plt.legend() plt.title('Marks Obtained') #PLOT THE POINTS plt.pie(values,labels=labels) plt.show() main()
3013fa9ec8d94ad6324cd01529cabfded8c29333
NavTheRaj/python_codes
/dict_3.py
637
3.984375
4
d=dict({'abc':12,'nepal':13}) print(d) #dict([()()()]) d1=dict([('Steve',4987),('Harry',7895)]) print(d1) d2={x:x**2 for x in (2,4,6)} print(d2) d3={x:y for x in ('Hari','Ram') for y in (1,2)} print(d3) for key,value in d.items(): print(key,value) for index,key in enumerate(d): print(index,key) for key i...
89be613074ec6e331fb1fc01a7303f0b0af03379
NavTheRaj/python_codes
/reverse_name.py
152
3.953125
4
def main(): name=str(input("Enter your full name")) reverse(name) def reverse(name): name.split(' ') print(str[1],"",str[0]) main()
c3dce1096fb30c49f8256830dc529a02a70566a4
Koctr/security_py_scripts
/CTF/py27/Bacons_cipher.py
1,977
3.671875
4
import re alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] first_cipher = ["aaaaa", "aaaab", "aaaba", "aaabb", "aabaa", "aabab", "aabba", "aabbb", "aba aa", "abaab", "ababa", "ababb", "abbaa", "abb...
2e0f38da82cb68eaef5123360be920dd14c34f2c
j1angray/65O
/A3/a1.py
15,699
3.546875
4
#!/usr/bin/env python # coding:utf-8 import re import sys def split_vertex(vertex_list): vertices = [] vertex_pattern = re.compile(r'\(\-?\d+,\-?\d+\)') str_vertices = vertex_pattern.findall(vertex_list) for i in str_vertices: pattern = r'\((\-?\d+),(\-?\d+)\)' matchVer = re.match(pat...
1b4b4bf10c4d453895cb3f53baec5b40e116d1a7
davidvela/MyFirstPythonProject
/zPythonLearn/test_myFirstClass.py
671
3.71875
4
from unittest import TestCase from MyFirstFile import MyFirstClass class TestMyFirstClass(TestCase): def setUp(self): self.myClass = MyFirstClass() def test_two_roots_1(self): self.assertEqual(self.myClass.quadratic_fn(2, 5, 3), (-1.0, -1.5)) def test_two_roots_2(self): self.ass...
7f37fe9f97caea8e656c82f6838f4f2f3c0e9501
Taruni-Anand/Practice
/PM.py
2,394
3.78125
4
"""Perform either exact or approximate inference to obtain answers to part III of Assignment 4. You solved this inference problem exactly, and the answers should be P(G1=2|X2=50) = 0.1054 and p(X3=50|X2=50) = 0.1024. If you're going to use Edward, I wasn't able to get any of the sampling-based inference procedures (Met...
f465a24a25ff819d2f93f175b0b03a593d910dbd
nithin1117/PassGen
/password_generator.py
6,010
3.578125
4
import string import random from tkinter import * from tkinter import messagebox import sqlite3 with sqlite3.connect("users.db") as db: cursor = db.cursor() cursor.execute("CREATE TABLE IF NOT EXISTS users(Username TEXT NOT NULL, GeneratedPassword TEXT NOT NULL);") cursor.execute("SELECT * FROM users") db.commit()...
c9e1d7103e8633a92004a33e25b5f60aaeb9a99e
cthulahoops/RustPython
/tests/snippets/function_args.py
279
3.53125
4
def sum(x, y): return x+y # def total(a, b, c, d): # return sum(sum(a,b), sum(c,d)) # # assert total(1,1,1,1) == 4 # assert total(1,2,3,4) == 10 assert sum(1,1) == 2 assert sum(1,3) == 4 def sum2y(x, y): return x+y*2 assert sum2y(1,1) == 3 assert sum2y(1,3) == 7
31921c962f952f443cae380a26b36bdb3b5286cb
capogluuu/Machine-Learning-Algorithm-From-Scratch
/Linear Regression/linearregression.py
1,653
3.515625
4
import numpy as np import pandas as pd import random class LinearRegression(): print("LinearRegression Class") def __init__(self, learning_rate, epoch): self.learning_rate = learning_rate self.epoch = epoch self.weight = 0 self.bias = 0 d...
362394abdf87008e69007c7268050b4397e57a08
hkam0323/MIT-6.0001
/Problem set 4a - Permutations.py
1,980
4.5
4
def get_permutations(sequence): ''' Enumerate all permutations of a given string sequence (string): an arbitrary string to permute. Assume that it is a non-empty string. You MUST use recursion for this part. Non-recursive solutions will not be accepted. Returns: a list of all pe...
3be2c75ad3a59759d43bfdba06f247edf57f2f49
soumitra9/BFS-1
/right_view_DFS.py
918
3.890625
4
# Time Complexity : Add - O(n) # Space Complexity :O(h) # Did this code successfully run on Leetcode : Yes # Any problem you faced while coding this : No ''' 1. I have recursively traversing right side first and then left side 2. If len of result is less than the level+1, then I am adding that ellement to it 3. If not,...
623ced9e93e8e6a63b5987ac4a7f15ef1e014760
hemincong/MachineLearningExercise
/ex4_NN_back_propagation/prdict.py
772
3.96875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np from utils.sigmoid import sigmoid def predict(Theta1, Theta2, X): # PREDICT Predict the label of an input given a trained neural network # p = PREDICT(Theta1, Theta2, X) outputs the predicted label of X given the # trained weights of a...
8ca4604249fdc9f984b9c44ff7d93ffca559adac
hemincong/MachineLearningExercise
/ex7_K_means_Clustering_and_Principal_Component_Analysis/runkMeans.py
2,291
3.765625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np def runkMeans(X, initial_centroids, max_iters, plot_progress): # RUNKMEANS runs the K-Means algorithm on data matrix X, where each row of X # is a single example # [centroids, idx] = RUNKMEANS(X, initial_centroids, max_iters, ... # ...
98eedc0e570e8874f8b9db1338389022629c1042
hemincong/MachineLearningExercise
/ex5_regularized_linear_regressionand_bias_vs_variance/validationCurve.py
1,254
3.53125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- def validationCurve(X, y, Xval, yval): # VALIDATIONCURVE Generate the train and validation errors needed to # plot a validation curve that we can use to select lambda # [lambda_vec, error_train, error_val] = ... # VALIDATIONCURVE(X, y, Xv...
80870643ab0f9aa4cb6663af765dbd57810a1167
hemincong/MachineLearningExercise
/ex8_Anomaly_Detection_and_Recommender_Systems/multivariateGaussian.py
940
3.671875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np def multivariateGaussian(X, mu, Sigma2): # MULTIVARIATEGAUSSIAN Computes the probability density function of the # multivariate gaussian distribution. # p = MULTIVARIATEGAUSSIAN(X, mu, Sigma2) Computes the probability # density fu...
912b52732d9352aac2720272b97757106a549eff
Fongyitao/_001_python_base
/_008_字符串/_001_字符串常用方法.py
1,957
4.28125
4
name="abcdefg" print(name[0]) print(name[len(name) - 1]) print(name[-1]) str = "hello world itcast and itxxx" index = str.find("world") print(index) # 6 下标为6 index = str.find("dog") print(index) # -1 没有就返回 -1 index = str.rfind("itcast") print(index) # 12 index = str.index("w") print(index) # 6 count = str.co...
56807bf6a46d8d4316ae11d429df0f40f953729f
Fongyitao/_001_python_base
/_007_选择语句_循环语句/_008_打印等边三角形.py
230
3.859375
4
''' * * * * * * * * * * ''' a=int(input("请输入边长:")) i=0 while i<a: k=0 while k<i: print(end=" ") k+=1 j = 0 while j<a-i: print("*",end=" ") j+=1 i+=1 print()
582e9d3021b08852ec9e56d72528155992ee6298
Fongyitao/_001_python_base
/_011_递归和匿名函数/_006_seek定位光标位置.py
542
4.34375
4
''' 定位到某个位置: 在读写文件的过程中,需要从另一个位置进行操作的话,可以使用seek() seek(offset,from)有两个参数 offset:偏移量 from:方向 0:表示文件开头 1:表示当前位置 2:表示文件末尾 ''' # demo:把位置设置为:从文件开头偏移5个字节 # 打开一个已经存在的文件 f=open("test.txt","r") str=f.read(10) print("读取的数据是:%s" %str) f.seek(1,0) # 查找当前位置 position=f.tell() print("当前的位置是:%s" %position) f.close()
1b8e78001e04dfbb198ff0cb20912ef02e9b1ece
Fongyitao/_001_python_base
/_012_面向对象/_002_定义一个类.py
164
3.78125
4
# 定义一个类 class Car: def start(self): print("启动") c=Car() # 创建Car对象 c.name="Audi"# 属性 c.start() # 启动 print(c.name) # Audi
2589f6122555c557e08a147760eda92f357cefef
Fongyitao/_001_python_base
/_012_面向对象/_003_init.py
1,161
3.9375
4
class Person: def __init__(self): self.name="张三" self.age=23 print("对象初始化") def work(self): pass p1=Person() # 对象初始化 print(p1.name,p1.age) print("---------------------") class Student(): def __init__(self,name,age,height,weight): self.name=name self.age=ag...
c084acdc6c9b0cb185c197712d1b0d4f1dfa7f2e
Sonni/Who-s-Julia-
/Benchmarking/stats/euler22/euler22.py
799
3.828125
4
import sys path = sys.argv[1] file = open(path) def namesSorted(file): line = file.readline() line_new = str.replace(line, '"', "") array = line_new.split(',') file.close() names = sorted(array) return names def letterValues(): letters = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",...
4f629093a4bfadb49899942b151e2d7546bb3e74
CNakai/divvy
/divvy/assignment/cli.py
1,836
3.578125
4
import click from os import mkdir from pathlib import Path from shutil import rmtree from sys import exit from .assignment import Assignment def set_up_command_group(): global command_group __attempts.add_command(unpack) command_group = __attempts @click.group(name='attempts') def __attempts(): """...
d96852d0ca086a12065ba7ea169bdc5641b1bccc
Mjg79/reddit-backend
/reddit/accounts/utils.py
308
3.578125
4
import random import string def generate_random_username(length: int = 16) -> str: """Generate random user name Generate a random username that conforms to User model's custom username field :return: """ return ''.join(random.choices(string.ascii_lowercase + string.digits, k=length))
862403084d568180f60bf71f4afd49832d48ab4e
adamazoulay/ProjectEuler
/adam/q17_adam.py
2,631
3.5
4
# This is going to suck # Super ugly and can be made waaaayyyyy cleaner but here we are def num_2_word_ones(n): n = int(n) if n == 0: return "" if n == 1: return "one" if n == 2: return "two" if n == 3: return "three" if n == 4: return "four...
2b10100747f5ad9b8c9680b5c6ae721ce10b4a9d
adamazoulay/ProjectEuler
/adam/q4_adam.py
547
3.765625
4
# Template file for Project Euler questions def is_palindrome(num): num = str(num) half = int(len(num) / 2) p1 = num[:half] p2 = num[half:][::-1] if p1 == p2: return True return False if __name__=="__main__": prod1 = 999 palilist = [] while prod1 > 0: ...
cdbb9cfb4e254b82b1922dc8a83f6b29951c4bf0
adamazoulay/ProjectEuler
/adam/q18_adam.py
954
3.6875
4
if __name__=="__main__": triangle = """75 95 64 17 47 82 18 35 87 10 20 04 82 47 65 19 01 23 75 03 34 88 02 77 73 07 63 67 99 65 04 28 06 16 70 92 41 41 26 56 83 40 80 70 33 41 48 72 33 47 32 37 16 94 29 53 71 44 65 25 43 91 52 97 51 14 70 11 33 28 77 73 17 78 39 68 17 57 91 71 52 38 17 14 91 43 58 5...
eaa2f7234bf700d6ef6b5865a546de5341106366
adamazoulay/ProjectEuler
/jason/q3_jason.py
366
3.953125
4
import math def prime_factors(number): big_prime = 1 if number % 2 == 0: big_prime = 2 for oddNum in range(3, int(math.sqrt(number)) + 1, 2): if number % oddNum == 0: big_prime = oddNum number /= oddNum return big_prime if __name__ == "__main...
a8306be123982728f18baa2c1e3d074b64494b5d
bxwhite/p_test_function
/advanced_features/del_space.py
642
3.796875
4
# -*- coding: utf-8 -*- #方法1 def trim(s): i = 1 if s == '': return s while i : if s[:1] == ' ': s = s[1:] else: break while i: if s[-1:0] == ' ': s = s[0:-1] else: break return s stri = " ABCDEF " print(trim(stri)) #方法2 def trim_2(s): if s == '': return s else: while s[0:1] == ' ': ...
42b81d31eb2b5c0658471532a6fea9e400d13041
az-ahmad/python
/projects/BlkJack.py
4,012
3.828125
4
from random import shuffle print('Hello and welcome to Black Jack 2-Player Ultimate Edition With Bonus DLC') player1 = '' player2 = '' while player1 == '': player1 = input('Please enter the name of Player 1: ') while player2 == '': player2 = input('Please enter the name of Player 2: ') print(f'Welcome {player...
bd972aa7c74758552db121a9c2263c065774a3af
abc010804/a
/查找字符.py
704
3.84375
4
# 喜乐 4.14 3.59 file = open ("new_file.txt" , "w") file.write(input("Please enter the txt:\n\n")) file.close() with open("new_file.txt") as f: text = f.read() with open("new_file.txt") as b: text_two = b.read() a = str(input("\nPlease enter characters:\n\n")) def count_char(text,char): count = ...
51b8b8375da1d64be9b637245baa01b3d73a493e
tigerbombz/selection_sort
/scoresgrades.py
422
3.890625
4
from random import randint print "Scores and Grades" for count in range(0,10): score = randint(60,100) if score >= 90: print "Score:" + str(score)+"You got a A" elif 80 <= score <=89: print "Score:" + str(score)+"You got a B" elif 70 <= score <=79: print "Score:" + str(score)+"You got a C" elif...
cc20a524fb12871c722b5bf596744401cba24b86
Jesper-Andersson/Short-Projects
/python/snakegame/snake.py
3,423
3.625
4
#Snakegame Jesper-Andersson # TODO: # Background keyboard input DONE # Remove empty line between grid rows DONE # Impassable borders KINDA DONE # User defined grid size DONE # Apples & point display DONE # Border Generation # Game over # "Snake" part (Automatic movement, tail growing) import time import math import r...
83efe7d3a28021e43d5219adf2086bcc5cbc5fd9
mfilipav/genome-tools
/get-codons.py
475
3.71875
4
# Reads first cmd line argument as DNA sequence, second argument as the readframe (0, 1 or 2) # Returns a codon sequence in triplet characters at a given frame import sys sequence = (sys.argv[1]).upper() frame = int(sys.argv[2]) #for i in range(len(sequence)-2): for i in range(frame, len(sequence) - 2, 3): # from 0 ...
c6889027b4dbbd363086d8a1226b0c85ec4a3525
alexland/levenshtein-in-cython
/levpy/hamming.py
214
3.796875
4
def hamming_dist(s1, s2): ''' returns: pass in: ''' if len(s1) != len(s2): raise ValueError("Hamming dist undefined for two strings of unequal length") return sum(ch1 != ch2 for ch1, ch2 in zip(s1, s2))
c60830da7f0a77e1e231d9c6e2a846ca99a04b9b
MaciejPel/complex-data-structures
/bst.py
5,188
3.734375
4
from data_generator import randomSubset class Node: def __init__(self, value = None): self.value = value self.left = None self.right = None self.parent=None class binary_search_tree: def __init__(self): self.root=None def insert(self, value): if self...
6622eac7764bcb216b2fbddf622feeffd40be9ae
birromer/neural-network-p
/denseLayer.py
562
3.546875
4
from neuron import * from random import uniform import numpy as np class DenseLayer: def __init__(self, num_of_inputs, num_of_neurons): self.neurons = [] for i in range(num_of_neurons): weights = np.random.uniform(-1, 1, num_of_inputs) bias = np.random.uniform(0,1,1) ...
e43adfef9c3cd9907156a6959bdfa5eecbca2d54
ruslangrimov/opencl-conv3d
/naive_conv3d/conv3d.py
5,234
4
4
import numpy as np import math as m def calc_out_shape(in_shape, k_shape, pads=[0, 0, 0], strides=[1, 1, 1]): """ Calculates the output shape based on the input shape, kernel size, paddings and strides. Input: - in_shape: A list with input size for each dimensions. - k_shape: A list wi...
ea2d601450dbcc91a76e379be42020bf9c3247bf
Joyounger/HeadFirstProgramming
/ch5/scores_hash_sorted.py
508
3.65625
4
result_f = open("results.txt") score_hash = {} score_array = [] for line in result_f: (name, score) = line.split() #集合 score_hash[score] = name score_array.append(float(score)) result_f.close() #score_array.sort().reverse()--false #score_array.sort() #score_array.reverse() score_array.sort(revers...
4dd880f4f2423a147bbeb86ff4d7ad545d0b6513
baksoy/WebpageScraper
/WebpageScraper.py
1,155
4.15625
4
import urllib2 from bs4 import BeautifulSoup website = urllib2.urlopen('https://en.wikipedia.org/wiki/List_of_countries_by_population_(United_Nations)').read() # print website # html_doc = """ # <html><head><title>The Dormouse's story</title></head> # <body> # <p class="title"><b>The Dormouse's story</b></p> # # <p c...
eed5db1335b1cefb166c4b8d8c08d3fe552be025
xjcarter/hannibal
/DataQueues.py
3,825
3.65625
4
import collections from threading import Lock from Queue import Queue import copy class DQueue(object): def __init__(self): self.items = collections.deque() self.lock = Lock() def put(self,item): with self.lock: self.items.append(item) def get(self): with self.lock: return self.items.popleft() d...
70174b36455e2c1175287cc3bdc98447a0c418b7
bijuta128/testyty
/test/repeatednumber.py
99
3.875
4
a=10 b=20 if not a>b: print(f"{a}is less than{b}") else: print(f"{b}is less than {a}")
5dfe2987c1d8a3535bce08313e28dcb208f9e421
bijuta128/testyty
/lab/lab ex 3/prime.py
239
3.890625
4
def prime(a): count=0 for i in range(1,a+1,1): p=a%i if(p==0): count=count+1 if count==2: print("prime") else: print("composit") a=int(input("enter a number")) prime(a)
e4eaa6791f0555207f60d6d8474c0c52da7713aa
bijuta128/testyty
/test/bijj.py
158
4.0625
4
x=int(input("enter a number")) y=int(input("enter a number")) if (x>7): print(x ,"is greater then" ) else (x<7) : print(x," is smaller then")
af42b91efbcd69171f653f88e2ea5918e56b7d81
bijuta128/testyty
/lab/lab ex 2/smallest.py
242
4.0625
4
a=int(input("enter 1st number")) b=int(input("enter 2nd number")) c=int(input("enter 3rd number")) if (a<b and a<c): print(a,"is the smallest") elif(b<a and b<c): print(b,"is the smallest") else: print(c,"is the smallest")
b8b413f187d0055b3c726f2a7925bc7e82d0f612
bijuta128/testyty
/test/fact.py
96
4.09375
4
x=int(input("Enter the number: ")) fact=1 for b in range(1,x+1): fact=fact*b print(fact)
ca6570e6d0edb86bf149340ec962fa745d7fb25e
chaitanya472/cs50x
/pset6/readability/readability.py
1,489
3.96875
4
from cs50 import get_string def main(): # Gets text from user text = get_string("Text: ") # Sets counter for letters l, word w, and sentences s l = 0 w = 1 s = 0 count = 0 for char in text: # if char is a letter add 1 to l if (char.isalpha()): ...
dede7287d9325b6e60a88939cf9197a7202f6fd4
TeskaLabs/asab
/asab/timer.py
2,534
3.65625
4
import asyncio import typing class Timer(object): """ The relative and optionally repeating timer for asyncio. This class is simple relative timer that generate an event after a given time, and optionally repeating in regular intervals after that. The timer object is initialized as stopped. Attributes: App ...
3652fc5411c75588d37319f9776dbaee6e5044d4
Viktoriya-Pilipeyko/books
/dousonP2.py
1,504
4.3125
4
# Бесполезные факты # # Узнает у пользователя его / ее личные данные и выдает несколько фактов #о нем / ней. Эти факты истинны. но совершенно бесполезны. name = input( "Привет. Как тебя зовут? ") age = input("Сколько тебе лет? ") age = int(age) weight = int(input("Xopoшo. и последний вопрос. Сколько в тебе килограммов...
44ad837a03b617202d6417f71b911cd4ab5f9add
dpkenna/PracticePython
/Exercise 6.py
254
4.1875
4
# http://www.practicepython.org/exercise/2014/03/12/06-string-lists.html maypal = input('Enter a string: ') backwise = maypal[::-1] if maypal == backwise: print('{} is a palindrome'.format(maypal)) else: print('{} is not a palindrome'.format(maypal))
00a12ee0d9c7b95583e1a43a3143d8f2df2bb9a6
va-syl1/Beshlei_lab
/Lab_2a/modules/common.py
528
3.59375
4
import datetime import sys def get_current_date(): """ :return: DateTime object """ return datetime.datetime def get_current_platform(): """ :return: current platform """ return sys.platform def parity(value): if (value == "True"): for number in range(100): if numbe...
54cbd8559c9106cca85fe8b504e73b52700c9735
amisha-tamang/function
/factorial.py
254
4.1875
4
def factorial(inputValue): if inputValue==0: return inputValue elif inputValue==1: return inputValue else: return inputValue*factorial(inputValue-1) Number = 6 print("factorial of number") print(factorial(Number))
9cca4fa75fd8e21396243303d47bdc911fb0b772
amisha-tamang/function
/QUESTION 2.py
285
3.609375
4
def ek_perfect(): i=1 sum=0 n=int(input("enter the number")) while i<n: if n%i==0: sum=sum+i i=i+1 if n==sum: print("it is prefect number") else: print("it is not prefect number") ek_perfect()
0c56bdd6fff73ded84befae2bf975f7910ce62dc
milton-dias/Fatec-Mecatronica-0791721011-Rogerio
/LTP2-2020-2/Pratica03/elife.py
320
4.125
4
numero_secreto = 32 numero_secreto2 = 42 numero_secreto3 = 23 palpite = int(input("Informe um Palpite: ")) if palpite == numero_secreto: print("Acertou") elif palpite > numero_secreto: print("Chute um numero menor") elif palpite < numero_secreto: print("Chute um numero maior") else: print("Caso padrão")
962252eedb82b5b86a039e6081ac92d5a264cf50
milton-dias/Fatec-Mecatronica-0791721011-Rogerio
/LTP2-2020-2/Pratica01/converter-cm-m.py
145
3.75
4
valor_cm = int (input("Informe um valor em CM: ")) valor_m = valor_cm / 100 print("O valor",valor_cm,"cm", "em metros é igual a: ",valor_m,"m")
7147f9ddac28af4a1faeec6ff3eb5c01d8353e78
rmccorm4/BHSDemo.github.io
/rand.py
246
4.1875
4
#Game to guess a number between 1-10, or any range you choose import random number = str(random.randint(1, 10)) guess = input("Guess a number between 1 and 10: ") print(number) if guess == number: print("You won!") else: print("You lost!")
e611e16e29e22d0e91bf686d0eeb0362717d1843
wortelstoemp/Scientific_Python
/tut_numpy.py
5,920
4.28125
4
# ------------------------------------------------------------------------------ # Numpy cheatsheet # ------------------------------------------------------------------------------ # USE NUMPY INSTEAD OF LISTS (FASTER)!!! # For linear algebra use scipy.linalg instead of np.linalg! # Numpy array = grid of values of SAM...
8c69d1f97d59c1a3c53150e9ed2485fba91a8fb9
Jueee/PythonStandardLibrary
/lib07.07-urlparse.py
1,282
3.578125
4
''' urlparse 模块 urlparse 模块包含用于处理 URL 的函数, 可以在 URL 和平台特定的文件名间相互转换. ''' # 使用 urlparse 模块 from urllib.parse import urlparse print(dir(urlparse)) print(urlparse('http://www.baidu.com?ca=123#12313')) # 使用 urlparse 模块处理 HTTP 定位器( HTTP Locators ) import urllib.parse scheme, host, path, params, query, fragment = urlli...
765f891152bcfac717c60ffe1afaccb2981b0dd2
Jueee/PythonStandardLibrary
/lib12.11-msvcrt.py
717
3.65625
4
''' msvcrt 模块 (只用于 Windows/DOS ) msvcrt 模块用于访问 Microsoft Visual C/C++ Runtime Library (MSVCRT) 中函数的方法. ''' ''' # 使用 msvcrt 模块获得按键值 import msvcrt print("press 'escape' to quit...") while 1: char = msvcrt.getch() if char == chr(27): break print(char, end = '') if char == chr(13): print() ''' # 使用 msvcrt 模...
8ec77ebfb0083525c3ad4e39ffcc1430826d6d61
Jueee/PythonStandardLibrary
/lib03.02-threading.py
1,257
4.125
4
''' threading 模块 (可选) threading 模块为线程提供了一个高级接口 它源自 Java 的线程实现. 和低级的 thread 模块相同, 只有你在编译解释器时打开了线程支持才可以使用它. 你只需要继承 Thread 类, 定义好 run 方法, 就可以创建一个新的线程. 使用时首先创建该类的一个或多个实例, 然后调用 start 方法. 这样每个实例的 run 方法都会运行在它自己的线程里. ''' # 使用 threading 模块 import threading import time, random class Counter(object): """docstring for C...
f281bdf903db4b4164f6f2a1bef430ec7c7f3626
Jueee/PythonStandardLibrary
/lib01.05-os.path.py
5,475
3.6875
4
''' os.path 模块 os.path 模块包含了各种处理长文件名(路径名)的函数. 先导入 (import) os模块, 然后就可以以 os.path 访问该模块. ''' ''' 处理文件名 os.path 模块包含了许多与平台无关的处理长文件名的函数. 也就是说, 你不需要处理前后斜杠, 冒号等. ''' # 使用 os.path 模块处理文件名 import os filename = "E:\\360\\Python\\PythonCode\\01Study\\03-StandardLibrary" print('using',os.name,'...') print('split','=>',os.pat...
ba3d1c382e0683183a698bfaa0a3e8a3e5214e19
Jueee/PythonStandardLibrary
/lib02.10-UserString.py
905
3.734375
4
''' UserString 模块 UserString 模块包含两个类, UserString 和 MutableString . 前 者是对标准字符串类型的封装, 后者是一个变种, 允许你修改特定位置的字符 (联想下列表就知道了). 关于UserString类 对于2.X版本:Python文档中提到,如果不涉及到2.2以前的版本,请考虑直接使用str类型来代替UserString类型。 对于3.X版本:该模块已经移到collection模块中。 ''' from collections import UserString class myString(UserString): """docstring for...
092360be23e1b8b4afbdb17980d1e7bdd122ad7c
Jueee/PythonStandardLibrary
/lib01.16-types.py
2,156
3.625
4
''' types 模块 types 模块包含了标准解释器定义的所有类型的类型对象 同一类型的所有对象共享一个类型对象. 可以使用 is 来检查一个对象是不是属于某个给定类型. ''' ''' types模块中的常量# types模块里各种各样的常量能帮助你决定一个对象的类型。 在Python 2里,它包含了代表所有基本数据类型的常量,如dict和int。 在Python 3里,这些常量被已经取消了。只需要使用基础类型的名字来替代。 Python 2 Python 3 types.UnicodeType str types.StringType bytes types.DictType d...
311d7b4e7a3c32c340bbd72b113cb28a2ac3ae35
Jueee/PythonStandardLibrary
/lib13.20-token.py
245
4.03125
4
''' token 模块 token 模块包含标准 Python tokenizer 所使用的 token 标记. ''' import token print('NUMBER', token.NUMBER) print('PLUS', token.PLUS) print('STRING', token.STRING) ''' NUMBER 2 PLUS 14 STRING 3 [Finished in 0.3s] '''
b17ba65b61cb496bf4c6aae84811dfac7647e274
Jueee/PythonStandardLibrary
/lib13.03-ntpath.py
631
3.71875
4
''' ntpath 模块 ntpath 模块( 参见 Example 13-3 )提供了 Windows 平台下的 os.path 功能. 你也可以使用它在其他平台处理 Windows 路径. ''' import ntpath file = "/my/little/pony" print("isabs", "=>", ntpath.isabs(file)) print("dirname", "=>", ntpath.dirname(file)) print("basename", "=>", ntpath.basename(file)) print("normpath", "=>", ntpath.normpath(fil...
e1cb4f4825a8fd3b775db79563958b3198398cbd
Liverworks/Python_dz
/8.io_modules/some_functs.py
686
3.515625
4
def maximum(l): """ :param l: list of numbers :return: maximum value from the list """ m = l[0] for i in l: if i > m: m = i return m def mean(l): """ :param l: list of numbers :return: mean of the list """ length = 0 m = int() for i in l: ...
60f5d46b2edbf66531b04a1dfc47601f8fcf9878
Muguett/Scoring-and-machine-learning-PYTHON
/OLS and PCR 09112020.py
4,098
3.796875
4
#!/usr/bin/env python # coding: utf-8 # In[1]: import statsmodels.api as sm from sklearn import datasets data = datasets.load_boston() # In[2]: print(data.DESCR) # In[4]: import numpy as np import pandas as pd #define the data/predictors as the pre-set feature nammes df = pd.DataFrame(data.data, columns=d...