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
13f771a2518e8cd135c71b2005978eb2dbe1eebe
cyy0523xc/ml-learning
/L00-algo/binary_tree.py
5,396
3.53125
4
''' 二叉树 Author: alex Created Time: 2020年07月31日 星期五 18时54分34秒 ''' from graphviz import Digraph from IPython.display import display class Node: """节点""" def __init__(self, val): self.val = val self.left = None self.right = None self.parent = None def __str__(self): ...
bc60a2c690b7f7e51f086f92258a7e9bc14ff466
raoliver/Self-Taught-Python
/Part II/Chapter 14.py
997
4.21875
4
##More OOP class Rectangle(): recs = []#class variable def __init__(self, w, l): self.width = w#Instance variable self.len = l self.recs.append((self.width, self.len))#Appends the object to the list recs def print_size(self): print("""{} by {}""".format(self.width, self.le...
42a450050398c08f05a86b73b269371cdd79b4be
raoliver/Self-Taught-Python
/Part II/Chapter 12 Challenges.py
1,128
3.8125
4
import math #Challenge 1 class Apple(): def __init__(self, c, w, t, s): """weight is in oz.""" self.color = c self.weight = w self.type = t self.size = s apple = Apple('Green', 4, 'Granny Smith', 'Small') print('Color: {}\n Weight(oz.): {}\n Type: {}\n Size: {}\n'.format(app...
7633a1fedf0957e1577ffcae5d1b35fc894a3b34
knmarvel/backend-katas-functions-loops
/main.py
2,253
4.25
4
#!/usr/bin/env python import sys import math """Implements math functions without using operators except for '+' and '-' """ __author__ = "github.com/knmavel" def add(x, y): added = x + y return added def multiply(x, y): multiplied = 0 if x >= 0 and y >= 0: for counter in range(y): ...
4c72f95bd1d2c044e49ae1c26d89387501fce0c7
paulomachadof/Lista-de-Exericios-1-Python
/Projeto_python/com/paulomachado/q5.py
161
3.765625
4
''' Created on 21 de jul de 2017 @author: Paulo-PC ''' print("Metro: ") metro = int(input()) centimetro = metro*100 print("Em centimetros %s cm" % centimetro)
01d6c3a71e8d57c9dced42b6abc4fd9a753eec80
paulomachadof/Lista-de-Exericios-1-Python
/Projeto_python/com/paulomachado/q9.py
198
3.625
4
''' Created on 22 de jul de 2017 @author: Paulo-PC ''' print("Qual a temperatura em Farenheit: ") temp_f = float(input()) temp_c = (5*(temp_f-32)/9) print("A temperatura em Celsius eh: ", temp_c)
e76a46e996c4c10ca32021952fd6ec120d073d2b
Suyash906/DataStructures
/Python3/LeetCode/690_Employee_Importance.py
926
3.875
4
""" # Definition for Employee. class Employee: def __init__(self, id: int, importance: int, subordinates: List[int]): self.id = id self.importance = importance self.subordinates = subordinates """ from collections import deque class Solution: def getImportance(self, employees: List['Empl...
be7df67b5bc6beb4a4a22c56ecc73d44bc95ccbd
Suyash906/DataStructures
/Python3/LeetCode/105_Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal_Two_Pointers.py
1,017
3.875
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode: def helper(preorder, inord...
97ebc93fd2aaa8442bac5ec6ac4f821455d4640b
bipinbipin/python-helloworld
/functions.py
2,075
3.71875
4
import json students = [] def get_students_titlecase(): students_titlecase = [] for student in students: students_titlecase.append(student["name"].title()) return students_titlecase def print_students_titlecase(): students_titlecase = get_students_titlecase() print(students_titlecase) ...
e2755d36a518efc21f5c479c4c3f32a54408eade
behind-the-data/ccp
/chap2/name.py
534
4.3125
4
name = "ada lovelace" print(name.title()) # the title() method returns titlecased STRING. # All below are optional # Only Capital letters print(name.upper()) # Only Lower letters print(name.lower()) ## Concatenation ## first_name = "ada" last_name = "lovelace" full_name = first_name + " " + last_name print(full_n...
ffaa0462f1bf3dc252136528ba9acf9ba2455669
fpdotmonkey/ME179P
/breadthFirstSearch.py
3,573
4.0625
4
# # breadthFirstSearch.py # # Fletcher Porter 2019 # import math def computeBFSTree(adjacencyTable, startNode): assert startNode < len(adjacencyTable), "computeBFSTree: startNode must be the index of a node in adjacencyTable" parents = [ None for _ in range(len(adjacencyTable)) ] parents[startNode] =...
0b057cc75e3698e2c8c1029d3ecbbc537af79a1a
unixcs/python_study
/基础/案例/99乘法表.py
369
3.5
4
for i in range(1, 10): #i 是竖向1-9 print(i) for j in range(1, i+1): #j 是横向 1-(1,9) # 打印语句中,大括号及其里面的字符 (称作格式化字段) 将会被 .format() 中的参数替换,注意有个点的 print('{}x{}={}\t'.format(i, j, i*j), end='') print() # 打印完一个i 换行
f290ab899cae21b926a10f0086c40d658f458551
unixcs/python_study
/基础/类/子类.py
225
3.875
4
""" 函数 调用 类 """ class A(object): def __init__(self): self.name = "feng" print(self.name) @property def b(self): print(" i'm b") def f(): # A() a = A() a.b() f()
9d0381a130b1cf8fe44543140e91bb3c4c21bf9e
GenericGiraffe/ConnectFour
/proj1.py
11,503
4.09375
4
# File: proj1.py # Author: Blake Lewis # Date: 11/16/16 # Description: This program is a simple connect four game EMPTY = "_" PLAYER_1 = "x" PLAYER_2 = "o" # emptyBoard() creates a blank connect four board # input: dimensions of board # output: the board def emptyBoard(): board = [] # asks for the rows of the...
2d29f47c7b91c33feac52f38bf0168ac6918d821
jcol27/project-euler
/41.py
1,674
4.3125
4
import math import itertools ''' We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once. For example, 2143 is a 4-digit pandigital and is also prime. What is the largest n-digit pandigital prime that exists? Can use itertools similar to previous problem. We can use t...
b55839a6a82c0df898aa62b612c3911b36d7e6e9
durvesh1992/hackerrank
/Algorithms/Implementation/bon_appetit.py
437
3.671875
4
# Enter your code here. Read input from STDIN. Print output to STDOUT n = map(int,raw_input().strip().split(' ')) #print n costList = map(int,raw_input().strip().split(' ')) #print costList amountCharged = int(raw_input()) #print amountCharged dinnerCost = sum(costList)- costList[n[1]] #print dinnerCost perPerson =...
0abf91d4446a4ca65fa5bec846a3b45b3de6554e
durvesh1992/hackerrank
/Algorithms/regex/greedy_nonGreedy_matching.py
409
3.921875
4
import re #greedy match haVal = re.compile(r'(ha){3,5}') haobj = haVal.search("hahahaha") print haobj.group() haobj = haVal.search("hahaha") print haobj.group() haobj = haVal.search("hahahahaha") print haobj.group() #Non greedy match haVal = re.compile(r'(ha){3,5}?') haObj = haVal.search("hahahaha") #will print on...
589685f2d4dabed36e468a003c1eb7ccf57427ec
tphoran/projecteuler
/projecteuler/ten_code.py
973
3.875
4
class Ten(object): """ The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million. """ def __init__(self, primes_below_number): self.primes_below_number = primes_below_number def sieve_for_primes_to(self, n): """ http://stac...
6241ab04295925257f882e661acd82739ffed623
tphoran/projecteuler
/projecteuler/eleven_code.py
4,884
3.640625
4
import numpy as np class Eleven(object): """ In the 20 by 20 grid below, four numbers along a diagonal line have been marked in red. The product of these numbers is 26 * 63 * 78 * 14 = 1788696. What is the greatest product of four adjacent numbers in the same direction (up, down, left, right...
b5d510696e545fcf7825b20ceee6aa29afc1fa5f
tphoran/projecteuler
/projecteuler/twenty_three_code.py
3,122
4.0625
4
class TwentyThree(object): """ A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number. A number n is called deficient if the...
3497b8f4b8a8e7759f22b7a7fdb77ab7908003e2
tphoran/projecteuler
/projecteuler/twenty_four_code.py
1,296
4
4
from itertools import permutations class TwentyFour(object): """ A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically, we call it lexicographic order. The l...
d892b7888ba29ba8ba480ec533184c669bfe3585
MohamedEl1/LeetCode
/SquaresOfSortedArray/SquaresOfSortedArray.py
283
4
4
# 977. Squares of a Sorted Array # Given an integer array nums sorted in non-decreasing order, # return an array of the squares of each number sorted in non-decreasing order. nums = [-4, -1, 0, 3, 10] for i in range(len(nums)): nums[i] = nums[i] ** 2 nums.sort() print(nums)
089dc6d300f0df779fbd9ed5695c3ee8fc5fcee5
MohamedEl1/LeetCode
/consecutivecharacters.py
1,072
4.09375
4
def maxsubstringchars(): s = "aabbbbbccccdddddddeffffffggghhhhhiiiiijjjkkkkkllllmmmmmnnnnnoopppqrrrrsssttttuuuuvvvvwwwwwwwxxxxxyyyzzzzzzzz" count = 1 maximum = 0 # iterate through the string and check if the first characters equals the second character # if it does then increase count by 1 till the...
200b1d19c0523128b8b0203cbdba75122d16c02c
codemee/blynk-library-python
/examples/hardware/PyCom_WiPy.py
1,276
3.71875
4
""" Blynk is a platform with iOS and Android apps to control Arduino, Raspberry Pi and the likes over the Internet. You can easily build graphic interfaces for all your projects by simply dragging and dropping widgets. Downloads, docs, tutorials: http://www.blynk.cc Sketch generator: http://examples.blyn...
b34c7a9aa3fb9d8d0832dd452d9ddb4000c54fb1
sarthakpant772/login_notetaking
/login_and_notetaking/password/password.py
317
3.578125
4
userName=open("user_Name.txt",'a') userPass=open("user_password.txt",'a') class password: def __init__(self,user_name,passw): self.user_name=user_name self.passw=passw def save(self): userName.write("username "+self.user_name+" ") userName.write("password "+self.passw+" ")
28a0dca8c9fac69130535f7d4baf21fda8bc2857
Longtailneighbor/ml
/ml/6/prime.py
1,216
3.578125
4
#!/usr/bin/python # -*- coding:utf-8 -*- import math from time import time def is_prime(x): return 0 not in [x % i for i in range(2, int(math.sqrt(x)) + 1)] def is_prime2(x): if x <= 1: return False elif x < 4: return True else: r = int(math.sqrt(x)) for i in range(2...
22a63c2af82386b713852c0abfd515a319b337f3
PugnaHAN/Python
/Chapter_5/is_balanced.py
618
3.78125
4
def is_balanced(text, brackets = "()[]{}<>"): counts = {} left_or_right = {} for left, right in zip(brackets[::2], brackets[1::2]): assert left != right, "the bracket characters must differ" counts[left] = 0 left_or_right[right] = left # print(counts) # print(left_or_right) ...
92d7e9dcf39245ed81b86bc03e5597fc292f4be8
PugnaHAN/Python
/Chapter_1/getNumbers.py
1,756
3.84375
4
def swapNumbers(numbers, index1, index2): swappedList = [] if index1 < index2: if index1 > 0 and index2 < (len(numbers) - 1): swappedList = numbers[ : index1] +\ [numbers[index2]] +\ numbers[index1 + 1 : index2] +\ ...
ea9b2beb697ee4247407a5f2e36dda87549275f8
rafoonehjafarian/voiceAssitant
/models.py
4,007
3.703125
4
""" In this module, the functions for speech recognition are provided; """ import speech_recognition as sr import pyaudio import wave import yaml import win32com.client import config r = None p = None config_file = './config/config.yaml' def fetch_audio(): """ using PyAudio class from pyaudio package, Thi...
5305c54d3e5b108bd9eff241e1634c8b9b5ac29e
kun888/Programs
/Python/dictionary.py
648
3.8125
4
a={} a['one']='uno' print(a) b={} b['two']=2,'a','z' print(b) c={} c['three']='t',1,'a' print(c) d={} d['4']='kartik' print(d) eng={'happy':'sad','joy':'sadness','class':'turing','sub':'python'} print(eng['class']) fruits={'apples':430,'bananas':312,'oranges':512,'pears':217} print(fruits) del fruits['pears'] print(fru...
8ec02039e87fdb510ae9f896658a03d0fa810832
chashkov-ms/InMotion
/KalmanFilter/Kalman/__init__.py
4,426
3.984375
4
import numpy as np import pandas as pd from abc import ABC, abstractmethod class KalmanFilter_EKF: def __init__(self, dim_x, dim_z, dim_u=0): """ Create a Kalman filter. You are responsible for setting the various state variables to reasonable values; the defaults below will not gi...
4c421cfd69c7c36ea03e5f632050db30491653a0
francoAlonso/ReversiTP2
/ingresoYchequeo.py
2,241
3.9375
4
# -*- coding: cp1252 -*- #El archivo Usuarios.csv tiene 6 datos, los cuales se encuentran en este orden: Nombre,Puntaje,PJ,PG,PP,PE #Esta funcion lee el archivo y si encuentra al final, devuelte una clave que indica el EoF def leer (archivo,default): linea = usuarios.readline() if linea: return linea.s...
c70c0c57662d5f93e30583603051ddf40cb8519c
sapkos/ultimate-tictactoe
/environment/env.py
2,111
3.953125
4
# https://deeplearningcourses.com/c/artificial-intelligence-reinforcement-learning-in-python # https://www.udemy.com/artificial-intelligence-reinforcement-learning-in-python # Simple reinforcement learning algorithm for learning tic-tac-toe # Use the update rule: V(s) = V(s) + alpha*(V(s') - V(s)) # Use the epsilon-gre...
1318536bd5e17ebeeb48e8fe28e1823e5d8ac812
ashish-hacker/Art-Ideas
/bot.py
5,396
3.59375
4
""" This program is for building a twitter bot . Which can retweet and fav the tweets and suggest you something pretty awesome things to draw or paint. Which will inturn make you creative ;). HAPPY DRAWING """ # Import the necessary modules... Don't forget to import our sweet tweepy ;) import tweepy import time ...
f6f217ea78e0a225b3e2332a3c9f293139fac767
A01746742/Mision_02
/extraDistanciaPuntos.py
225
3.5625
4
#Alondra Miranda Aguilera | A01746742 #Extra: Galletas x1=int(input("Teclea X1")) y1=int(input("Teclea y1")) x2=int(input("Teclea X2")) y2=int(input("Teclea y2")) distancia= (((x2-x1)**2)+((y2-y1)**2))**0.5 print("La distancia es: ",distancia)
d1a2631418fac8cab591111088a0eaa0ddc528ba
samilyil/Phyton_Assignments
/Pandas.py
1,574
3.921875
4
#!/usr/bin/env python # coding: utf-8 # In[7]: #PANDAS 1. SORU ÇÖZÜMÜ import pandas as pd import numpy as np import warnings import string warnings.filterwarnings('ignore') # Defining a function which returns a list of first 10 prime number def prime(x): primeNumbers= [] for val in range(x): if val...
5c4fc548e88cada634ce1e2c84bf0fa494d6b6a8
mparkash22/learning
/pythonfordatascience/raise.py
538
4.1875
4
#raise the value1 to value2 def raise_both(value1, value2): #function header """Raise value1 to the power of value 2 and vice versa""" #docstring new_value1= value1 ** value2 #function body new_value2= value2 ** value1 new_tuple = (new_value1, new_value2) return new_tuple #we c...
501118bb0ef89071831f9878eec8e2132ea1c340
mparkash22/learning
/university.py
795
3.75
4
class University: # Hello anoop, ,this is just a test def __init__(self, name, role, holidays): print('Constructor called') self.name = name self.role = role self.holiday_var = 0 def print_details(self): print("{} : {}".format(self.name, self.role)) ...
f9dbc54c6b2cf46b0f879bce94908ff944045eb2
leemyoungwoo/pybasic
/python/활용자료/예제/04/ex4-4.py
218
4.1875
4
for i in range(10) : print(i, end =' ') print() for i in range(1, 11) : print(i, end =' ') print() for i in range(1, 10, 2) : print(i, end =' ') print() for i in range(20, 0, -2) : print(i, end =' ')
4e95f4ca415a14a5a449c80c84cf5c62284d308b
leemyoungwoo/pybasic
/python/활용자료/예제/03/Q3-4.py
256
3.921875
4
char = input('영어 알파벳을 입력하세요 : ') char2 = char.upper() if char2 == 'A' or char2 == 'E' or char2 == 'I' or char2 == 'O' or char2 == 'U' : print('%s은(는) 모음이다.' % char) else : print('%s은(는) 자음이다.' % char)
5db0b96d671238932420c23cb4f66e8c2b20928e
leemyoungwoo/pybasic
/python/활용자료/예제/07/ex7-4.py
259
3.5
4
def average(*scores) : sum = 0 for i in range(len(scores)) : sum += scores[i] avg = sum/len(scores) print('%d과목의 평균 : %.2f' % (len(scores), avg)) average(80, 90, 100) average(75, 80, 94, 78) average(80, 73, 76, 86, 82)
e707463f07d8c8c44e64e44df187a32e3fcbf0de
leemyoungwoo/pybasic
/python/활용자료/예제/04/ex4-6.py
83
3.828125
4
word = input('영어 문장을 입력하세요 : ') for x in word : print(x)
2f35e2cf38f75424de3c5809324e5c95e158b3eb
leemyoungwoo/pybasic
/python/활용자료/예제/04/ex4-12.py
413
3.828125
4
s = input('영어 문장을 입력하세요 :') i = 0 count = 0 print('모음 : ', end = '') while i <= len(s) - 1 : if (s[i] == 'a' or s[i] == 'A' or s[i] == 'e' or s[i] == 'E' \ or s[i] == 'i' or s[i] == 'I' or s[i] == 'o' or s[i] == 'O' \ or s[i] == 'u' or s[i] == 'U') : count += 1 print(s[i], end='...
a99b236a5b20794bfe332ab3cad9d4b4fde48eb9
leemyoungwoo/pybasic
/python/활용자료/예제/12/Q12-3.py
503
3.71875
4
import matplotlib.pyplot as plt from matplotlib import rc import random rc('font', family='Malgun Gothic') def make_random_list(num): result = [] for i in range(num): result.append(random.randrange(1,7)) return result count = 10 # 주사위 던진 회수 y = make_random_list(count) x = list(range(1,11...
2b7ed7d2bb937ed9ec396285bbae5578ae2e1451
leemyoungwoo/pybasic
/python/활용자료/예제/03/ex3-1.py
116
3.625
4
x = int(input('숫자를 입력하세요 : ')) if x > 0 : print('양수!') else : print('0 또는 음수!')
e5b158aece7ea21c2ce6c737eac451c4892d2ad6
leemyoungwoo/pybasic
/python/활용자료/예제/05/ex5-2.py
153
3.5625
4
a = ['red', 'green', 'blue'] a.append('yellow') print(a) a.insert(1, 'black') print(a) b = ['purple', 'white'] a.extend(b) print(a) c = a + b print(c)
a9525ab654e1668d87d997d8885445aedbc7ecab
leemyoungwoo/pybasic
/python/활용자료/예제/06/ex6-2.py
199
4.375
4
tuple1 = ("apple", "banana", "cherry") tuple2 = ("orange", "melon", "strawberry") tuple3 = tuple1 + tuple2 print(tuple3) print(len(tuple3)) for x in tuple1 : print(x) del tuple1 print(tuple1)
b640e2f99599e2a4f2d5352fd85b9075bf516005
Alvin8212/intro-data-capstone-musclehub
/Alvin Lo - MuscleHub Project/Alvin Lo - musclehub.py
16,265
4.15625
4
# coding: utf-8 # # Capstone Project 1: MuscleHub AB Test # ## Step 1: Get started with SQL # Like most businesses, Janet keeps her data in a SQL database. Normally, you'd download the data from her database to a csv file, and then load it into a Jupyter Notebook using Pandas. # # For this project, you'll have to...
d96080e7b30a12d1132abdbdd8d522ffc1ece804
RookieLinLucy666/Codewar
/Ones and Zeros.py
235
3.890625
4
def binary_array_to_number(arr): result = 0 length = len(arr) for index in range(length): result += pow(2, index) * arr[length - 1] length -= 1 return result print(binary_array_to_number([1,1,1,1]))#15
fe2958f15fb8c63bdc0e150c25b072a4a9ce0dca
sirwin4/planets
/planets.py
525
3.8125
4
planet_list = ["Mercury", "Mars"] planet_list.append("jupiter") planet_list.append("saturn") planet_list.insert(1, "Earth") planet_list.insert(1, "Venus") planet_list.append("Pluto") rocky_planets = planet_list[0:4] print(planet_list) print(rocky_planets) planet_list.remove("Pluto") print(planet_list) visited_list = pl...
d8581cc6b52f6732abcfdc5ba4b0ea9a02e5ced8
B-Benja/Little_Games
/Snake/snake.py
1,617
4.09375
4
from turtle import Turtle MOVE_DISTANCE = 20 UP = 90 DOWN = 270 LEFT = 180 RIGHT = 0 STARTING_POSITIONS = [(0, 0), (-20, 0), (-40, 0)] # create snake body class Snake: def __init__(self): self.snake_body = [] self.create_snake() # define the head of the snake self.head = self.snak...
03fd78bb81c978ff5e9ac24c05f925295dd6974b
grayondream/perceptron
/code/perceptron_classifier.py
3,536
3.65625
4
#通过感知机分类半月数据 import numpy as np import matplotlib.pyplot as plt def sgn(y): y[y > 0] = 1 y[y < 0] = -1 return y class Perceptron(object): '''单层感知机 ''' def __init__(self, shape): super(Perceptron, self).__init__() self.w = np.ones(shape) #weigth self.b = 1.5 ...
af29db2886b1c28bbc9ec437a23b8f6bae49cd59
TusharSharma16/Tsukuyomi
/models.py
572
3.53125
4
import sqlite3 as sql def insert(username,email,password): con = sql.connect("database.db") cur = con.cursor() cur.execute("INSERT INTO register (username,email,password) VALUES (?,?,?)", (username,email,password)) cur.execute("INSERT INTO users (username,password) VALUES (?,?)", (username,password)) ...
2a971401660ac322a1cb45ebf79f2f3a8d53e172
kanglicheng/little_codewars
/python/dog_recommendation_system.py
613
3.84375
4
# 6 kyu Dog recommendation system """ return a set of the dog breeds that are most similar in temper to the given breed. """ def find_similar_dogs(breed): # dogs is a dictionary with key as breed and values as adjectives results =[] scores ={} for dog in dogs: #go through each breed name if dog != breed: #if n...
4aea56a6afd1b94f55366b0b4b2187ae6adb2763
xiaomengxiangjia/Python
/practice_10_3.py
158
3.75
4
a = input("Please input your name: ") print(a.title()) filename = 'guest.txt' with open (filename, 'w') as file_project: file_project.write(a.title())
856ea8f0efef73fba334f00caa090b9a2697c0a8
xiaomengxiangjia/Python
/foods.py
580
4.34375
4
my_foods = ['pizza', 'falafel', 'carrot cake', 'beer', 'chicken'] friend_foods = my_foods[:] my_foods.append('cannoli') friend_foods.append('icecream') print("My favorite foods are:") print(my_foods) print("\nMy friends's favorite foods are:") print(friend_foods) print("The first three items in the list are:" ) pri...
93b998361a1c522919c2bfa78a1cc4590d429fd0
xiaomengxiangjia/Python
/practice_3_4.py
1,813
3.84375
4
names = ['steve jobs', 'kristen stuwart', 'mom', 'dad', 'tuling'] print(names) message0 = "\n Hello " + names[0] + ", can you have dinner with me?\n" message1 = "Hello " + names[1] + ", can you have dinner with me?\n" message2 = "Hello " + names[2] + ", can you have dinner with me?\n" message3 = "Hello " + names[3] + ...
c894f690f17886589a430ccde5d82edf5fb6ae44
xiaomengxiangjia/Python
/practice_9_7.py
1,250
3.90625
4
class User(): def __init__(self, first_name, last_name,user_info): self.first_name = first_name self.last_name = last_name self.user_info = user_info def describe_user(self): print("The " + self.first_name.title() + self.last_name.title() + "'s address is " ...
acc3b49b3fc09191c0943d73d1b44a54eb711d09
xiaomengxiangjia/Python
/practice.5.13.py
156
3.90625
4
dress = 'T-shirt' print("Is dress == 'T-shirt'? I guess so.") print(dress == 'T-shirt') print("\nIs dress == 'jean'? I guess not.") print(dress == 'jean')
b86653b27a02f7905c16caa94e06d8bda1aa0a9b
xiaomengxiangjia/Python
/test_cities.py
411
3.546875
4
import unittest from city_functions import get_name class NameTestCase(unittest.TestCase): def test_city_country(self): name = get_name('santiago', 'chile') self.assertEqual(name, 'Santiago,Chile') def test_city_country_population(self): name = get_name('santiago', 'chile', 500...
31d4c19d8c982177f3b2b0a9f3ae9d784fbaa33e
xiaomengxiangjia/Python
/sorted.py
278
3.953125
4
cars = ['bmw', 'audi', 'toyota', 'subaru'] print("Here is the original list:") print(cars) print("\nHere is the sorted list:") print(cars) print("\nHere is the origin list again:") print(sorted(cars)) print("\nHere is the reverse list:") print(sorted(cars,reverse = True))
bf3a24aac552e88891666e14714978af4f329d39
abrahamsk/ml_naive-bayes-classification
/src/probabilistic_model.py
1,249
3.71875
4
#!/usr/bin/env python # coding=utf-8 # Machine Learning 445 # HW 4: Naive Bayes Classification # Katie Abrahams, abrahake@pdx.edu # 2/25/16 from __future__ import division from input import * """ 2. A) Compute the prior probability for each class, 1 (spam) and 0 (not-spam) in the training data. As described in part ...
32aa15eecf200d3c1efb2ba4dd13ed3451b1e4a5
ai2cm/pace
/util/pace/util/_corners.py
6,205
3.828125
4
""" fill_scalar_corners The fill_corners routines put data into tile corners to make stencil operations more convenient. The corners themselves do not map on to anything meaningful. At, say, the southwest corner of a tile, the south edge and west edge correspond to different cube faces. However, there is no cube face...
f6bc1371cbb9a597b5b3a88e0d6141638172e775
saaruuna/ot-harjoitustyo
/src/ui/lab_size_menu.py
4,916
3.609375
4
from ui.menu import Menu from ui.lab_designer import LabDesigner class LabSizeMenu(Menu): """A class which creates a Lab Size menu to be displayed before designing a labyrinth. The player navigates between size options (2--9) by using the left and right buttons. Attributes inherited from super...
805a7597e4da65cd7f5cc3d567251e65b9cbd6d5
saaruuna/ot-harjoitustyo
/src/components/cheese.py
845
4.03125
4
import pygame from load_image import load_image class Cheese(pygame.sprite.Sprite): """A class which creates a cheese to display in the game. Attributes: image: The image to be displayed as a cheese. rect: The shape pygame will display as a cheese. rect.x: The x-coordinate of the chees...
9ede6aece473b6ce865a8a05acde5e9f28c720ec
drylynch/garfieldtextadventure
/garfield.py
29,242
4
4
# why am i doing this """ TODO maybe do * make in pygame ? """ import os import platform import collections """ text based clone of garfield, released pc and ps2, 2004 by hip games garfield has to clean the house up cause odie fucked it or something move garfield around the house with his trusty vacuum cleaner a...
98b7128829f1d22bcd267eba53a490bc98c98253
pwilthew/Brainiax
/Entrega 2/funciones.py~
584
3.859375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # Funcion que imprime un arbol sintactico abstracto def print_arbol(arb): str_ = "" str_ = str(arb) str_ = str_[:len(str_)-1] return str_ # Funcion que halla la columna donde se encuentra un token dado def hallar_columna(input, t): ...
56dec2031489c62443c5ef1d54f05fb1edac14a0
Jqden/Ultimate-Frisbee-Plays-Simulator
/venv/Include/defender.py
1,236
3.671875
4
from Include.player import Player # A defender is a type of player who is assigned to "guard" an offender. Once assigned to an offender, # the defender remains glued to them, exactly matching the offenders movements. The user chooses the # initial relative positioning of the defender and offender, and this relative p...
ad076b53de3f41e1a40ce4a2d984b381908555b0
ToobaKhanam321/Game-Tower-Defence
/core/explosion.py
1,259
3.59375
4
import math import random import pygame from core.prefab import Prefab class Explosion(Prefab): """ Represents an explosion in the level. Contains an animated graphic. """ def __init__(self, game, position, radius, damage): """ Constructor. Args: game (Game): T...
aec15d1708777d5cccc103aa309fab48491fb53c
jesuarezt/datacamp_learning
/python_career_machine_learning_scientist/04_tree_based_models_in_python/classification_and_regression_tree/02_entropy.py
1,607
4.125
4
#Using entropy as a criterion # #In this exercise, you'll train a classification tree on the Wisconsin Breast Cancer dataset using entropy as an information criterion. #You'll do so using all the 30 features in the dataset, which is split into 80% train and 20% test. ## ##X_train as well as the array of labels y_tr...
2d8b6253cdc95f774940590ec0842613f130d14d
jesuarezt/datacamp_learning
/python_career_machine_learning_scientist/08_preprocessing_for_machine_learning/05_union_all_information/02_standarizing_exercise.py
1,481
3.90625
4
#Extracting numbers from strings # #The length_of_time field in the UFO dataset is a text field that has the number of minutes within the string. Here, you'll extract that number from that text field using regular expressions. def return_minutes(time_string): # Use \d+ to grab digits pattern = re.compi...
bc983e640bd972dbee887446f8be478d78325059
jesuarezt/datacamp_learning
/python_career_machine_learning_scientist/08_preprocessing_for_machine_learning/01_introduction/02_datatypes.py
877
3.78125
4
#Exploring data types # #Taking another look at the dataset comprised of volunteer information from New York City, we want to know what types we'll be working with as we start to do more preprocessing. # #Which data types are present in the volunteer dataset? # # The dataset volunteer has been provided. # ...
5672d830ff6b548d3d83142031146d1945f00ec3
jesuarezt/datacamp_learning
/python_career_machine_learning_scientist/14_introduction_tensor_flow/chapter2.py
9,951
4.5625
5
#Load data using pandas # #Before you can train a machine learning model, you must first import data. There are several valid ways to do this, but for now, we will use a simple one-liner from pandas: pd.read_csv(). Recall from the video that the first argument specifies the path or URL. All other arguments are optional...
3d375393f0e9ad8f1bb5f81d8ac9e66d167a5e86
jesuarezt/datacamp_learning
/python_career_machine_learning_scientist/04_tree_based_models_in_python/classification_and_regression_tree/01_regression_tree.py
2,976
4.09375
4
#Train your first classification tree# #In this exercise you'll work with the Wisconsin Breast Cancer Dataset from the UCI machine learning repository. You'll predict whether a tumor is malignant or benign based on two features: the mean radius of the tumor (radius_mean) and its mean number of concave points (concav...
a5b6035fb3d38ef3459cfd842e230bbfb2148583
jesuarezt/datacamp_learning
/python_career_machine_learning_scientist/06_clustering_analysis_in_python/03_kmeans_clustering/01_example_kmeans.py
1,881
4.1875
4
#K-means clustering: first exercise # #This exercise will familiarize you with the usage of k-means clustering on a dataset. Let us use the Comic Con dataset and check how k-means clustering works on it. # #Recall the two steps of k-means clustering: # # Define cluster centers through kmeans() function. It has...
7c1c08698b64bc27a27f296d3f887fcfb842eb2e
jesuarezt/datacamp_learning
/python_career_machine_learning_scientist/15_Introduction_to Deep_Learning_in_Python/chapter2.py
7,100
4.40625
4
#Coding how weight changes affect accuracy # #Now you'll get to change weights in a real network and see how they affect model accuracy! # #Have a look at the following neural network: Ch2Ex4 # #Its weights have been pre-loaded as weights_0. Your task in this exercise is to update a single weight in weights_0 to create...
2a87d0a176e31ccb80f662271690fc4f8609d173
jesuarezt/datacamp_learning
/python_career_machine_learning_scientist/13_feature_Engineering_for_NLP_in_Python/chapter4.py
8,081
4.1875
4
# #tf-idf vectors for TED talks # #In this exercise, you have been given a corpus ted which contains the transcripts of 500 TED Talks. Your task is to generate the tf-idf vectors for these talks. # #In a later lesson, we will use these vectors to generate recommendations of similar talks based on the transcript. ...
6fb9bce717d2a04531dcf99f389c8ee661bf212b
jesuarezt/datacamp_learning
/python_career_machine_learning_scientist/14_introduction_tensor_flow/chapter3.py
14,303
4.40625
4
#The linear algebra of dense layers # #There are two ways to define a dense layer in tensorflow. The first involves the use of low-level, linear algebraic operations. The second makes use of high-level keras operations. In this exercise, we will use the first method to construct the network shown in the image below. # ...
f63f5d928da6e77161920a019543b82d333bfc99
jesuarezt/datacamp_learning
/python_career_machine_learning_scientist/15_Introduction_to Deep_Learning_in_Python/chapter1.py
6,041
4.6875
5
#Coding the forward propagation algorithm # #In this exercise, you'll write code to do forward propagation (prediction) for your first neural network: # #Ch1Ex4 # #Each data point is a customer. The first input is how many accounts they have, and the second input is how many children they have. The model will predict h...
11c53adb00dd9eb69a86639896726bc8a5543af9
jesuarezt/datacamp_learning
/python_career_machine_learning_scientist/05_XGBoots/02_regression/02_regularization_in_xgboots.py
3,307
3.953125
4
#Using regularization in XGBoost # #Having seen an example of l1 regularization in the video, you'll now vary the l2 regularization penalty - also known as "lambda" - and see its effect on overall model performance on the Ames housing dataset. # Create the DMatrix: housing_dmatrix housing_dmatrix = xgb.DMatrix(da...
3dce641b6ee86c7c5a2a903a173354d8b2ce257b
jesuarezt/datacamp_learning
/python_career_machine_learning_scientist/02_unsupervised_learning_in_python/discovering_interpretable_features/04_NFM_cosine_similar_metric_with_articles.py
508
3.5625
4
# Perform the necessary imports import pandas as pd from sklearn.preprocessing import normalize # Normalize the NMF features: norm_features norm_features = normalize(nmf_features) # Create a DataFrame: df df = pd.DataFrame(norm_features, index = titles) # Select the row corresponding to 'Cristiano Ronaldo'...
0cea5de9a5a43ff0377506c0a725de19b98b8550
bbriano/cs50
/introduction/6-python/floats.py
75
3.75
4
a = float(input("a: ")) b = float(input("b: ")) print(f"a + b = {a + b}")
d51f0a33aa1ca8827576ab51179ca5c5b3ed0eeb
jleng7987/python-cookbook
/工业大数据竞赛/test.py
501
3.703125
4
import numpy as np import pandas as pd # 定义df1 df1 = pd.DataFrame({'alpha':['A','B','B','C','D','E'],'feature1':[1,1,2,3,3,1], 'feature2':['low','medium','medium','high','low','high']}) # 定义df2 df2 = pd.DataFrame({'alpha':['A','A','B','F'],'pazham':['apple','orange','pine','pear'], 'kilo':[...
5ca2cf2b0365dd45d8f5ff5dc17b8e21d6ab751f
remichartier/002_CodingPractice
/001_Python/20210829_1659_UdacityBSTPractice/BinarySearchTreePractice_v00.py
1,210
4.25
4
"""BST Practice Now try implementing a BST on your own. You'll use the same Node class as before: class Node(object): def __init__(self, value): self.value = value self.left = None self.right = None This time, you'll implement search() and insert(). You should rewrite search() and not use yo...
c7f1a592ba1dc81f24bc3097fbde5f0784eecd35
remichartier/002_CodingPractice
/001_Python/20210818_2350_UdacityQuickSortAlgo/QuickSorAlgoPivotLast_v01.py
1,305
4.1875
4
"""Implement quick sort in Python. Input a list. Output a sorted list.""" # Note : method always starting with last element as pivot def quicksort(array): # quick sort with pivot # Then quick sort left_side of pivot and quick_sort right side of pivot # Then combine left_array + Pivot + Right Array # b...
0461e672a89b7a8ce478010f61d087cdb12699ec
remichartier/002_CodingPractice
/001_Python/20211127_2311_HackerrankTheFullCountingSortMedium/theFullCountingSort_v01.py
1,052
3.953125
4
#!/bin/python3 import math import os import random import re import sys # # Complete the 'countSort' function below. # # The function accepts 2D_STRING_ARRAY arr as parameter. # def countSort(arr): # Write your code here result = [[]] for i in range(len(arr)): if i < int(len(arr)/2): ...
3ef4cd00430e276739fb17449e2ed50dfdb6a513
remichartier/002_CodingPractice
/001_Python/20220108_2240_HackerrankTheBombermanGameMedium/solutionOtherProgrammersNb02.py
2,692
4.0625
4
#!/bin/python3 import math import os import random import re import sys # # Complete the 'bomberMan' function below. # # The function is expected to return a STRING_ARRAY. # The function accepts following parameters: # 1. INTEGER n # 2. STRING_ARRAY grid # # Solutions found by other programmers (https://www.hacker...
9c54cff39e2548b4b86cdeeaf9c96266643b0daa
remichartier/002_CodingPractice
/001_Python/20211004_2150_HackerRank_TimeConversion/time_conversion_01.py
771
3.96875
4
!/bin/python3 import math import os import random import re import sys # # Complete the 'timeConversion' function below. # # The function is expected to return a STRING. # The function accepts STRING s as parameter. # def timeConversion(s): # Write your code here """ Sample Input 07:05:45PM Sample Ou...
2e83840558020fae6e89164792e92cdfa4069c35
ZeroDestru/aula-1-semestre
/aulas/ex3.py
1,193
4.03125
4
''' a. "Telefonou para a vítima?" b. "Esteve no local do crime?" c. "Mora perto da vítima?" d. "Devia para a vítima?" e. "Já trabalhou com a vítima?" O programa deve no final emitir uma classificação sobre a participação da pessoa no crime. Se a pessoa responder positivamente a 2 questões ela deve ser classi...
d975dee37afc80c487f6ff0b1723697f340b2448
ZeroDestru/aula-1-semestre
/aulas/oitavo3.py
1,764
4.125
4
import turtle myPen = turtle.Turtle() myPen.tracer(5) myPen.speed(5) myPen.color("blue") # This function draws a box by drawing each side of the square and using the fill function def box(intDim): myPen.begin_fill() # 0 deg. myPen.forward(intDim) myPen.left(90) # 90 deg. myPen....
32b87b1c954b4768bcd2c73918ac6a51e05c13b8
king4arabs/WSNSIMS2
/wsnsims/core/linalg.py
877
3.6875
4
import numpy as np def centroid(points): """ Calculate the center of mass over a collection of points :param points: The points, expressed as numpy.array :type points: numpy.array :return: The center of mass for the given points :rtype: numpy.array """ com = np.mean(points, 0) re...
54ed18de06f2630976066d7cee0d681e85ef4ff7
shireen-nazneen/loops
/factorial_num_loop.py
187
3.890625
4
num=int(input("enter number: ")) copy=num i=1 m=0 sum1=1 while i<=num: if num%i==0: m=num print(i,"is a factror of ",num) sum1=sum1*i i=i+1 print(sum1)
8f2de109a57a13f88cfd4780723a37c2d3e5cc8c
shireen-nazneen/loops
/perfect_num_loop.py
236
3.84375
4
num=int(input("enter your number---")) i=1 copy=num sum_num=0 while i<num: if num%i==0: sum_num=sum_num+i i=i+1 if sum_num==num: print(num,"this is perfect number") else: print(num,"this is not perfect number")
3e42878dd4b25deb50e122891f8faf693506892c
armando-rocha/POO-Java-Python-Php-Javascript
/Python/car.py
854
3.5625
4
from account import Account class Car (Account): __id= int __license = str __driver = Account("","","","") __passenger = int def __init__(self, id, driver ,license,passenger): if passenger == 4 or passenger == 6: self.__id =id self.__license=license ...
6c235db9f230303767182fd2e4eb71b8463fbab9
mtn/advent19
/day01/part2.py
293
3.84375
4
#!/usr/bin/env python3 def calculate_fuel(mass): t = 0 mass = mass // 3 - 2 while mass > 0: t += mass mass = mass // 3 - 2 return t total = 0 with open("input.txt") as f: for line in f: total += calculate_fuel(int(line.strip())) print(total)
89ed53bc8e2aed0c22180ed27f20294991eb122c
frdnamalia/List_Spinner
/ujian2.py
614
3.53125
4
print("="*50) print("---List Spinner---\n") print("by Fardhina Amalia") print("="*50) print("===SEBELUM===") Matrix1=[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] print(Matrix1) # [[4, 8, 12, 16] [0][3] [1][3] [2][3] [3][3] # [3, 7, 11, 15], [0][2] [1][2] [2][2] [3][2] # [2, 6, 10, 14]...
92f0837d2b94b72d013e7cb41d72ef7f5c78fdf8
HYnam/MyPyTutor
/W2_Input.py
1,110
4.375
4
""" Input and Output Variables are used to store data for later use in a program. For example, the statement word = 'cats' assigns the string 'cats' to the variable word. We can then use the value stored in the variable in an expression. For example, sentence = 'I like ' + word + '!' will assign the string 'I like cat...
c21a9037c094373b18800d86a8a5c64ea1beb0f7
HYnam/MyPyTutor
/W6_range.py
711
4.53125
5
""" Using Range The built-in function range returns an iterable sequence of numbers. Write a function sum_range(start, end) which uses range to return the sum of the numbers from start up to, but not including, end. (Including start but excluding end is the default behaviour of range.) Write a fun...
0fbe09ab6841a44123707d905ee14be14e03fc53
HYnam/MyPyTutor
/W12_recursive_base2dec.py
354
4.125
4
""" Recursively Converting a List of Digits to a Number Write a recursive function base2dec(digits, base) that takes the list of digits in the given base and returns the corresponding base 10 number. """ def base2dec(digits, base): if len(digits) == 1: return digits[0] else: return digits[-1] + ...
8dc081fad4227c0456266c0eab5ae3fcf5ed4d36
HYnam/MyPyTutor
/W7_except_raise.py
1,736
4.5625
5
""" Raising an Exception In the previous problem, you used a try/except statement to catch an exception. This problem deals with the opposite situation: raising an exception in the first place. One common situation in which you will want to raise an exception is where you need to indicate that some precond...