blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
5cd0d40cd1470249bdbb5e7b13632cee67515c74 | cenuno/random_python | /python/02_distance_function.py | 739 | 4.125 | 4 | import numpy as np
def calculate_distance(a, b, c=2, verbose=True):
"""
Calculates the distance of two arrays. Returns a float.
"""
if verbose and c==1:
print("Calculating the Manhattan distance:")
elif verbose and c==2:
print("Calculating the Euclidean distance:")
elif verbos... |
91e70d2b7cc2975b3c8fe4839c5d5f6e85f39779 | sazad44/holbertonschool-machine_learning | /math/0x00-linear_algebra/3-flip_me_over.py | 317 | 4.125 | 4 | #!/usr/bin/env python3
"""task 3 python script to transpose a matrix"""
def matrix_transpose(mat):
"""transpose given matrix assume never empty"""
newMat = []
col = len(mat[0])
for i in range(col):
newMat.append([])
for r in mat:
newMat[i].append(r[i])
return newMat
|
7fe3c0a982b66f9d2a3a922b9be0cdbb4a3b6e6c | XiaoxuanXia/Project | /Name_Boxoffice_Url.py | 4,115 | 3.640625 | 4 |
# coding: utf-8
# In[1]:
# get the url for a specific movie
# coding: utf-8
# In[1]:
# get the url for a specific movie
def get_movie_url(keyword):
import pandas as pd
import requests
import re
from bs4 import BeautifulSoup
url = "https://www.rottentomatoes.com/search/?search=%s" % (keyword)
... |
69a4791a92c365c8dedde47dd634836350cddab9 | nick-cash/spellcheck | /error_generator.py | 862 | 3.9375 | 4 | # Nick Cash, Oct 2013
import random
DICTIONARY_PATH = "american-english-large"
def mutate_word(word):
final_word = ''
isvowel = lambda c: True if c in 'aeiou' else False
for c in word:
addc = 1
if c.isalpha():
# Chance to mess up vowels
if isvowel(c) and... |
c4fa577d20efaa3429009de54cdd164d9f8ec24f | ianaquino47/Daily-Coding-Problems | /Problem_1.py | 384 | 3.875 | 4 | # This problem was recently asked by Google.
#
# Given a list of numbers and a number k, return whether any two numbers from the list add up to k.
#
# For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.
#
def two_sum(lst, k):
seen = set()
for num in lst:
if k - num in seen:
... |
1de573cc0e0d7a370d05f4f5a9d2b4956be38b62 | PaLaMuNDeR/algorithms | /Coding Interview Bootcamp/06_max_char.py | 812 | 4.3125 | 4 | import timeit
import operator
""" Given a string, return the character that is most commonly used in the string.
Examples:
maxChar("abcccccccdef") -> "c"
maxChar("apple 12311111") -> "1"
"""
# === Solution ===
def maxChar(str):
"""
Store the characters in a dictionary.
Then we use the operator library t... |
7a485abe328a5ee7c2a113ea470efb8dd4989247 | cslaf/projectEuler | /problem21.py | 461 | 3.78125 | 4 | import math
def isAmicable(x):
if x == divisors(x):
return False
return x == divisors(divisors(x))
def divisors(x):
divisors = []
for num in range(2,int(math.sqrt(x)+2)):
if x % num == 0 :
divisors.append(num)
divisors.append(int(x/num))
return sum(diviso... |
7fc9c7cbaa9adc6b8f2a18bc5540386dfd26822b | 2468513H/OSH | /Code/Ch1-memory-centric-system-model/advanced-model/abstract_system_model.py | 3,975 | 3.625 | 4 | #!/usr/bin/env python
"""
A model for a processor-based system. The main difference from the code in the book is that it uses NumPy arrays for performance.
Furthermore, the model for loading high-level code is different as well.
"""
from abstract_system_constants import *
from abstract_system_peripherals import *
fr... |
b9aa2f23c80a4c86b7c09ece3ce650cc3ef3010d | Algorant/HackerRank | /Python/complex_numbers/complex.py | 1,395 | 3.953125 | 4 | '''
Given two complex numbers, find the result of their addition, subtraction,
multiplication, division, and modulus operations.
'''
import math
class Complex(object):
def __init__(self, real, imag):
self.real = real
self.imag = imag
def __add__(self, n):
comp = n + complex(self.real,... |
347de74e8618cd0bf423d5d9d2ab3df9b545baad | bellaxin2010/PythonPraticeDemo | /pythonBasicDemo/Day1Pratice.py | 341 | 3.9375 | 4 | import random
num = random.randint(0,10)
count =0
while count <5:
user_guess = int(input("pls input value: "))
if user_guess == '':
print("input value pls")
elif user_guess > num:
print("larger ")
elif user_guess < num:
print("smaller")
else:
print("collect")
... |
523ad5b69ee00e36c44aa4c5cf8460b6a0a10002 | Krystiano8686/python_studia | /Zad_cw5/zad11.py | 207 | 3.859375 | 4 | # ZADANIE11
def fibb(n):
a, b = 0, 1
for _ in range(int(n)):
a, b = b, a + b
yield a
ile = input("Ile chcesz wyrazow ciagu Fibonacciego: ")
n = fibb(ile)
for x in n:
print(x)
|
7efe83d7aedf4a20e819abf210f55d8be5a2d4a0 | GeVhoo/python-project-lvl1 | /brain_games/games/progression.py | 578 | 3.625 | 4 | from random import randint
DESCRIPTION = 'What number is missing in the progression?'
def get_conditions():
number1 = randint(1, 10)
step = randint(1, 10)
index = 0
random_index = randint(1, 8)
result = ''
while index < 10:
next_number = str(number1 + (index * step))
if resul... |
920f4916c8b944d033f9941f2963fd9dbcc1c926 | AvishekVerma/Python_Learning | /Python S-6_Flow Control P-1.py | 8,104 | 3.984375 | 4 | # -*- coding: utf-8 -*-
#------------------------------ Section - 6 -------------------------------------#
#(7th-Aug-2021)
#---------------------------- Python Flow Control: Part -1 -----------------------#
#Selection Statement
# if if-else if-elif-else if-elif
#Iterative Statement
# for w... |
5b5a425595b130faa32727edc623f15997e73482 | lydiahecker/exercises | /chapter-2/ex-2-4.py | 1,604 | 4.375 | 4 | # Programming Exercise 2-4
#
# Program to compute a final price for five items with tax.
# This program will prompt a user for a set of five prices,
# sum them to a subtotal and calculate sales tax with tax rate stored in a constant,
# then display the results on the screen.
# Variables to hold the prices of fi... |
68e74b7889994385c5cc76b02e68d6f07d26dc72 | shopnilsazal/validus | /validus/isbn.py | 2,592 | 3.796875 | 4 | from .utils import validate_str
import re
@validate_str
def sanitize_isbn(isbn):
sanitized = re.sub(r'[\s-]+', '', isbn)
return sanitized
def get_isbn_10_checksum(isbn):
sanitized = sanitize_isbn(isbn)
checksum = sum([(i+1) * int(sanitized[i]) for i in range(9)])
if sanitized[9] == 'X':
... |
c12efd9978439ccce6823baae6d76a208dffd90e | rafaelperazzo/programacao-web | /moodledata/vpl_data/411/usersdata/341/79694/submittedfiles/av1_programa2.py | 292 | 3.75 | 4 | # -*- coding: utf-8 -*-
preconormal = float(input('Digite um valor: '))
opcao1 = input('À vista em dinheiro ou cheque, recebe 15% de desconto')
opcao2 = input('À vista no cartão de crédito, recebe 10% de desconto')
opcao3 = input('Em duas vezes, preço normal de etiqueta sem juros')
|
b6f64aa5ec416c5abdb3ac2cb30e60db5d8fc887 | Liiura/Python-codes | /Bisection-and-fake-position-method's.py | 17,620 | 4 | 4 | import math as m
import numpy as np
from matplotlib import pyplot as plt
#nota si se quiere agregar una función debe ingresarse de la misma manera en la que están ingresadas las demás funciones, al lado de los vectores o diccionarios se explica a qué corresponde esa estructura de datos
#2nota Los diccionarios de difere... |
88aabcf35ccd068ad9cdc425699b6bf7748eee88 | Nadiia2002/Hillel | /main.py | 941 | 3.6875 | 4 | def get_denominator(file_name):
try:
with open(file_name, 'r') as f:
denominator = int(f.read())
try:
5 % denominator
except ZeroDivisionError:
print('Ha-ha, we can`t divide by zero')
return denominator
except FileNotFoundError:
pri... |
cd3518971f0a309cd2fb9dcce556e565d05a7c5b | e-liyai/python_algorithms | /implementations/graph.py | 1,277 | 3.90625 | 4 | from .LinkedList import LinkedList
from .queue import Queue
class Graph:
def __init__(self):
self.linkedListDict = dict()
def add_vertice(self, vertex, values):
linked_list = LinkedList()
for value in values:
linked_list.add_last(value)
self.linkedListDict[vertex]... |
84b35616269331e84e15fb0ad6132ed793902d72 | cry999/AtCoder | /beginner/056/C.py | 184 | 3.515625 | 4 | def go_home(X: int) -> int:
t = 1
while t * (t + 1) // 2 < X:
t += 1
return t
if __name__ == "__main__":
X = int(input())
ans = go_home(X)
print(ans)
|
4126bbf971f4189eda918cf331e205716eb4a489 | dongming2016/python_study | /base/examples/example-3-function&variable.py | 2,530 | 4.46875 | 4 | '''
函数,其英文名function已经表示了其意义,函数便是实现某一功能的一段代码。
它分为函数的定义和调用。
'''
# 函数定义, def 函数名(参数1, 参数2, 参数3……)
# 函数名需做到见名知意
def m_subtract(a, b):
return a - b # return 是返回结果的意思
# 输入时一定要做类型检查
def m_subtract1(a, b):
if not (isinstance(a, (int, float)) & isinstance(b, (int, float))):
raise TypeError('input should be... |
0840a5057e97b1ce7a9f333ba5205c1846138890 | AlexisAuriac/104intersection_2017 | /solve.py | 907 | 3.703125 | 4 | #!/usr/bin/python3
from math import *
import utilities
import show
def sphere(p, v, R):
a = v[0]**2 + v[1]**2 + v[2]**2
b = 2*(p[0]*v[0] + p[1]*v[1] + p[2]*v[2])
c = p[0]**2 + p[1]**2 + p[2]**2 - R**2
sol = utilities.secdegree(a, b, c)
show.nb_sol(sol)
show.points(sol, p, v)
def cylindre(p, ... |
87556ca274cfeef708a9a6db371da6d184f365e0 | mzaidi59/Data_Mining_Census_2011 | /Assignment_1/Misc/ass1a2_ed.py | 4,353 | 3.515625 | 4 | from pandas import read_csv
import csv
import operator
from math import isnan
import numpy as np
import copy
import os
def filter_word(a):
if a[0:3] == 'A &' or a[0:4] == 'Anda':
b = 'ANI'
elif a[0:3] == 'D &':
b = 'Dadra & Nagar Haveli'
elif a == 'Uttar Pradesh':
b = 'UPA'
elif a[0:3] == 'NCT':
b = 'Del... |
97980a1e934ccc76584cf980676b21e9301f1c3a | dwagon/pydominion | /dominion/cards/Card_Storyteller.py | 2,251 | 4.03125 | 4 | #!/usr/bin/env python
""" http://wiki.dominionstrategy.com/index.php/Storyteller """
import unittest
from dominion import Card, Game, Piles
###############################################################################
class Card_Storyteller(Card.Card):
"""Storyteller"""
def __init__(self):
Card.Ca... |
e3d55038067d2c6431f62873e890765ad04bf8f3 | shezadaibara/general | /leetcode/ans_009.py | 241 | 3.8125 | 4 | """
Determine whether an integer is a palindrome. Do this without extra space.
"""
class Solution:
# @param {integer} x
# @return {boolean}
def isPalindrome(self, x):
string = str(x)
return string == string[::-1] |
95be7f375b52614a03b490a7e746a103ff1f2a91 | 96no3/PythonStudy | /Python/201911/191121/2019112109.py | 940 | 3.671875 | 4 | import turtle
def leaf(n, pencolor, brushcolor):
def cir():
for i in range(9):
turtle.forward(n)
turtle.right(10)
a = turtle.heading()
turtle.color(brushcolor)
turtle.begin_fill()
cir()
turtle.right(90)
cir()
turtle.end_fill()
turtle.setheading(a)
turtle.color(pencolor)
cir()
... |
6fb8fe6ba75cff9908dcafb063da05b352065126 | yangxiufengsia/optimistic-optimization | /2-D-array-test.py | 400 | 4.3125 | 4 | # Create a list.
elements = []
# Append empty lists in first two indexes.
elements.append([])
elements.append([])
# Add elements to empty lists.
elements[0].append([1, 2])
elements[0].append(2)
elements[1].append(3)
print elements[0]
elements[1].append(4)
# Display top-left element.
print(elements[0][0][0])
# Disp... |
7117dbecf77a561c960c179311fc4a8924865893 | Taoge123/OptimizedLeetcode | /LeetcodeNew/Tree/LC_098_Validate_Binary_Search_Tree.py | 3,324 | 3.890625 | 4 | """
Two elements of a binary search tree (BST) are swapped by mistake.
Recover the tree without changing its structure.
Example 1:
Input: [1,3,null,null,2]
1
/
3
\
2
Output: [3,1,null,null,2]
3
/
1
\
2
Example 2:
Input: [3,1,4,null,null,2]
3
/ \
1 4
/
2
Output: [2,1,4,null,null... |
a1f151574c0884f83ede9e89a5242c5e388a1b63 | ashish3x3/competitive-programming-python | /Hackerrank/Maths/nCr_with_base_N_conversion.py | 1,516 | 3.6875 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
from collections import defaultdict
from math import factorial
def calculate_combinations(n, r):
return factorial(n) // factorial(r) // factorial(n-r)
def baseN(num,b,numerals="0123456789"):
return ((num == 0) and numerals[0]) or (baseN(num... |
f8605c47eed45ff1cff1ec16f1aac22cbaa70fd5 | csidz/related-people | /get_related_persons.py | 3,680 | 3.5625 | 4 | from utils.customLogger import custom_logger as cl
import logging
from filter_fields import FilterFields
# Applies the Search criteria for finding related persons and returns related persons data
class GetRelatedPersons:
"""
RelatedPersons class finds whether a person is related to any another person based o... |
c4411d6d95073d365d345e7d17095eb96b5c7da8 | ollyimanishimwe/alx-higher_level_programming | /0x07-python-test_driven_development/100-matrix_mul.py | 2,225 | 4.125 | 4 | #!/usr/bin/python3
"""
Multiplies two matrices
"""
def matrix_mul(m_a, m_b):
"""multiplies two matrices
Args:
m_a (:obj:`list` of :obj:`list` of :obj:`int` or :obj:`float`):
list of lists of integers or floats
m_b (:obj:`list` of :obj:`list` of :obj:`int` or :obj:`float`):
... |
76488d187722de4e6cbae3031adde1de2ec64f11 | zahessi/unileaks | /mine/eratosphen.py | 305 | 3.734375 | 4 | def eratosphen(n):
primes = [2]
divisable = None
for i in range(3, n):
divisable = False
for n in primes:
if i % n == 0:
divisable = True
break
if not divisable: primes.append(i)
return primes
print(eratosphen(100000))
|
3a6eb76a1d435ec74a80f0df7e8bad0f31617b0d | Syntetik008/NitroGen | /NitroGen.py | 572 | 3.515625 | 4 | #imports
import random
import sys
loopnum = 0
many = input("How many to generate: ") # asks for how many links to generate
f= open("output.txt","w+") # creating output.txt
while loopnum < int(many): # loop
result_str = ''.join((random.choice('AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz123... |
dc8867ea18d8e2be74d561344a416c7cf0b9648f | FRC1076/ContinuingEducation | /permutation/permute.py | 1,878 | 4.3125 | 4 | def permutor(text, permutation):
"""
The permutor function has two arguements.
It takes the text and scrambles it according to
the permutation argument.
"""
scrambled = ""
for x in permutation:
scrambled = scrambled + text[x]
return scrambled
def decoder(permutation):
"""
... |
a0b23be661d6d40540a1b0d3bc84c06be7eb9bd7 | Priyanka0502/The_Python_Bible | /while_loops.py | 800 | 4.0625 | 4 | '''
while loops repeats itself over and over while some conditions is true!!
while condition:
do what you wnat!!
'''
print('-------Even Numbers----')
number=1
while number<=20:
if number%2==0:
print(number)
number=number+1
print('------Add Name To List----------')
L=[]
while len(L)<3:
new_nam... |
0f980862aebe0965c0bb0e7773e0c7b123fbe5ad | flerdacodeu/CodeU-2018-Group7 | /nfadeeva/assignment3/tests.py | 1,146 | 3.75 | 4 | from assignment3.dictionary import Dictionary
from assignment3.search_words import search_words, Grid
import unittest
class Test(unittest.TestCase):
def setUp(self):
self.d = Dictionary(['CAR', 'CAT', 'CARD', 'CART'])
# tests for the Dictionary class
def test_word_is_in_dictionary(self):
... |
c4e914140185c024b01b0ecacf178ae763c6af04 | newton1057/PuntosGraficos | /Puntos.py | 2,225 | 3.75 | 4 | def potencia(base,exponente):
resultado = 1
if exponente == 0:
resultado = 1
else:
for i in range(exponente):
resultado = resultado * base
return resultado
def raiz(valor):
aux = 2.0
cociente = valor/aux
promedio = (aux + cociente)/2.0
while abs(cociente - pr... |
70d45a07e01662c4bb99591ffbfa787f5f573100 | Harishkumar18/data_structures | /cracking_the_coding_interview/medium/english_int.py | 1,464 | 4.25 | 4 | """
Given any integer, print an English phrase that describes the integer (e.g., "One Thousand,
Two Hundred Thirty Four").
#TODO: need to complete
"""
def convert_to_words(num):
# Get number of digits
# in given number
l = len(num)
# Base cases
if l == 0:
print("empty string")
re... |
04211cd9da0a127994212155dc69d50312f3186e | evan886/python | /python开发技术详解/源文件/05/5.3/5.3.3/return.py | 1,194 | 4.125 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
# return
from __future__ import division
def arithmetic(x, y, operator):
result = {
"+" : x + y,
"-" : x - y,
"*" : x * y,
"/" : x / y
}
return result.get(operator) # ؼ
# ûreturnĺNone
def func():
pass
pri... |
097a33b2e66a96e2ec3e2091f0ef36fbd61c71e5 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/leap/a2997e9ac0a1470c814d0dc15f2f0c71.py | 393 | 4.0625 | 4 | ''' Returns True/False if given year n is a leap year
'''
def is_leap_year(n):
if n % 4 == 0:
# If evenly divisible by 100, but not 400 (not a leap year)
if n % 100 == 0 and n % 400 != 0:
return False
# Is divisible by 4
return True
else:
# n is not ... |
2fbb549e55a3e60e2b40bffacba6890a7c51376a | ajonaed/Problem-Solving | /Graph/ownPractice.py | 1,099 | 3.640625 | 4 | def main():
aMatrix = [[0,1,0,0,1], [1,0,1,1,1],[0,1,0,1,0],[0,1,1,0,1],[1,1,0,1,0]]
# for vertex in range(len(aMatrix)):
# for edge in range(len(aMatrix[vertex])):
# if aMatrix[vertex][edge] == 1:
# print(vertex, ' Has Connection with ', edge)
# print()
print('... |
23149a260ef3039932da2fab080550817b764536 | Willmore976/Python_Projects | /Python 2.7/Banking_Project/Project_2_AW.py | 5,394 | 3.796875 | 4 | '''-------------------------------------------------------------------------
Anthony Willmore
IS 340
Austin Phillip
11/4/2014
---------------------------------------------------------------------------'''
import sys
import math
state_interest = 18.5
Project_Loop = True
# Displays Menu to choose financial ... |
1211f07d6cf1cc41d65c63a9b8abe2562acc5e91 | kenisak/txray | /machineLearning/partitionTrainingDataset.py | 1,448 | 3.640625 | 4 | import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
df_wine = pd.read_csv('https://archive.ics.uci.edu/'
'ml/machine-learning-databases/'
'wine/wine.data', header=None)
df_wine.columns = ['Class label', 'Alcohol',
... |
42f97136c04e22e70f6f490c07a86301485555e3 | stefmolin/Hands-On-Data-Analysis-with-Pandas | /ch_04/window_calc.py | 773 | 4 | 4 | def window_calc(df, func, agg_dict, *args, **kwargs):
"""
Run a window calculation of your choice on a DataFrame.
Parameters:
- df: The DataFrame to run the calculation on.
- func: The window calculation method that takes df
as the first argument.
- agg_dict: In... |
1f819303147f3ab2d543ddad60f73961735f63b9 | Hemaravishankar/Bill_Tip_Calculator | /main.py | 412 | 4 | 4 | bill = float(input("Enter your Bill amount: "))
tip = int(input("Enter your tip percentange on bill like 10, 12 or 15: "))
person = int(input("How many would u want share: "))
tip_percentage = tip / 100
total_bill_amount = bill * tip_percentage
total_bill = bill + total_bill_amount
each_person_bill = total_bill / pers... |
c6c45fd523f41b69ee0985afea23175681f63696 | PlysDecompiler/JustTetris | /src/vector.py | 1,755 | 3.703125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import math
def get_vector(a, b):
if isinstance(a, Vector2D):
return a
elif isinstance(b, Vector2D):
return b
else:
raise ValueError("both not a vector")
def get_scalar(a, b):
if not isinstance(a, Vector2D): # TODO test for ... |
263d816c494050be9e20dc9abc07676971c62862 | bayan79/AlgoPythonLabs | /lab2.py | 1,053 | 4.03125 | 4 | def fuzzy_compare_string(s1: str, s2: str) -> float:
count = 0
for i in range(len(s1)):
count += s2.count(s1[i:i + 3])
return count / max(len(s1), len(s2))
def fuzzy_compare_int(n1: int, n2: int) -> float:
DELTA = 3
if abs(n1 - n2) > DELTA:
return 0.0
return 1 - abs(n1 - n2) / ... |
9498109eb00e181d94a9c13307ef9346571f547b | Kvazar78/Skillbox | /8_algoritm_for/task_84_3.py | 581 | 4.375 | 4 | # Пока все прятались, “голя” решил схитрить и считать секунды быстрее,
# чем нужно.
#
# Напишите программу, которая выводит только чётные числа в порядке
# убывания от N до 1 включительно, используя цикл for. Нельзя использовать
# условный оператор.
n = int(input('Введи количество секунд: '))
for i in range(n, 0 , -2):... |
aedefd0c33dd5f249170dd2a6f9d353fa93941ca | vvakrilov/python_basics | /08. Pre_Exam/05. Puppy Care.py | 389 | 3.84375 | 4 | target_food = int(input()) * 1000
command = int(input())
food_eaten = 0
while command != "Adopted":
current_food = int(command)
food_eaten += current_food
command = input()
if food_eaten <= target_food:
print(f"Food is enough! Leftovers: {abs(food_eaten - target_food)} grams.")
else:
print(f"Food i... |
1bd7e31ca6cba7bb56792a984486d51b5f62738e | AxelOrdonez98/Universidad_Proyectos_All | /Archivos_Python/Practicas/Calculadora_Login.py | 2,579 | 3.78125 | 4 | import tkinter as tk
import math
class Aplicacion:
def __init__(self):
self.valor=0 #valor a incrementar o decrementar
self.ventana1=tk.Tk() #clase que representa una nueva ventana
self.ventana1.title("Calculadora") #titulo de la ventana
self.dato1 = tk.StringVar()
self.ent... |
2f59a07de3168565635a029c8177364af2fbca08 | Archer-git3/python-hard-work | /hangman-fun_version/hangman.py | 11,534 | 3.9375 | 4 | # Problem Set 2, hangman.py
# Name: Oleksandr Ponomaryv,KM-03
# Collaborators:Anton Mitchenko
# Time spent:2 night
# Hangman Game
# -----------------------------------
# Helper code
# You don't need to understand this helper code,
# but you will have to know how to use the functions
# (so be sure to read the docstring... |
5bdff0ae701e1bd2814cd508de7493ec07713789 | ccny-mystery-machine/the-mystery-machine | /story_generator/state.py | 2,203 | 3.703125 | 4 | from random import random, randint
from copy import deepcopy
from setup import OUT_PLACES, NAME_BANK, ACTOR_TEMPLATE, PLACE_TEMPLATE, ITEMS
class State:
"""
State of the Story - Nodes in the tree """
def __init__(self, actors, places, items):
self.actors = deepcopy(actors)
self.pla... |
eb8a3e0393306114553e8dec3e42780c1805047c | yonatan1988eisenberg/Metacritic-games-scrapper | /check_input.py | 698 | 3.875 | 4 | from configparser import ConfigParser
config_object = ConfigParser()
config_object.read("config.ini")
def check_input(max_opt):
"""
This functions asks for the user for input which should be between 0 and max_opt.
while the input is invalid the user will be asked to reenter a value
:return:
"""
... |
1188c4eefe1d9093d1d428b08c0531d801541f90 | Raspberriduino/PythonBeginnerProjects | /FAQ Questions Program - Dictionary Data Structure Practice/FAQ Data Entry Program.py | 2,449 | 4.21875 | 4 | #
#
# David Pierre-Louis
# August 11, 2019
# SEC 290 32784.201930 SUMMER 2019 - Block II
# Programming Assignment 5
#
# Create a Python program that will serve as a
# menu-driven interface that manages a dictionary
# of Frequently Asked Questions (FAQ's)
#
# Questions serve as the keys and answers serve as
# the value... |
4de00c6e9674928bcbdada588f899aa299d51332 | jonathan-vidal/daily-questions | /2019/07/29-EASY-Word-count/Solutions/malcolm-smith/solution.py | 272 | 3.84375 | 4 | string = str.lower('Blue hair, blue tie, hiding in your wi-fi')
search = ('blue', 'red', 'wi-fi')
def wordCount(string, search):
output = {}
for word in search:
output[word] = str.count(string, word)
return output
print(wordCount(string, search))
|
969ea576189c6306c90a19aaf4a5b9b2241bce5d | Anil314/HackerEarth-Solutions | /Implementation/Little Jhool and psychic powers.py | 2,125 | 3.6875 | 4 | '''
Little Jhool always wanted to have some psychic powers so that he could showoff his skills,
and magic to people and impress them. (Specially, his girlfriend Big Jhool!)
But, in spite all his efforts, hardwork, dedication, Googling, watching youtube videos he couldn't garner any psychic abilities!
He knew everyon... |
45436fe6032a7f2ddcbbf33139452cf9d393c91d | mdhummel076/99-CapstoneProject-201920 | /src/m2_shared_gui_delegate_on_robot.py | 13,329 | 3.546875 | 4 | """
Capstone Project. Code to run on the EV3 robot (NOT on a laptop).
This code is the delegate for handling messages from the shared GUI.
Author: Your professors (for the framework)
and James Werne, Matt Hummel, Luke Spannan.
Winter term, 2018-2019.
"""
import rosebot
import time
class Delegate(objec... |
2cbd019f3ec5f3fbc6af0ce4bf4334f8cfdbf0d6 | NakulK48/Project-Euler-Solutions | /25.py | 273 | 3.5 | 4 | #PROBLEM 25
result = {1:1, 2:1}
def fib(num):
if num not in result:
result[num] = fib(num-1) + fib(num-2)
return result[num]
def solution():
i = 3
while True:
i += 1
a = fib(i)
if len(str(a)) >= 1000:
return i
|
600d2caee533f9824ef3ea129f424019a1722562 | EternalCode24/invisible_cloak | /background.py | 476 | 3.5 | 4 | import cv2
cap = cv2.VideoCapture(0) #capturing from webcam
while cap.isOpened():
ret, back = cap.read() #this is what the webcam is reading. ret is basically a bool variable used for testing truth
if ret:
cv2.imshow("image",back)
if cv2.waitK... |
ce59d296b4dfeb9d69d6727e2f30b279a9b7dc16 | Yuliya-N/MyScripts | /Scripts/OOP_call.py | 215 | 3.625 | 4 | class MyClass:
def __init__(self):
self.calls = []
def __call__(self, number):
self.calls.append(number)
return sum(self.calls) / len(self.calls)
avg = MyClass()
print(avg(3))
print(avg(5))
print(avg(1))
|
74ec535394e5b38aafeb6ec422906a11421ec04e | rizwan2000rm/interview-prep | /Python/bit_manipulation.py | 275 | 3.96875 | 4 | # Convert decimal number to binary
decNo = 4
binaryNo = bin(decNo)
print(binaryNo)
# Convert decimal number to specified bits (eg:- 32bit)
binary32 = "{:032b}".format(decNo)
print(binary32)
# Convert binary string to decimal
decimalNo = int(binary32, 2)
print(decimalNo)
|
edcc1e6189a581d90cdc918e1e168e282b8406a6 | ArchitectNate/pyCalculator | /calculator.py | 4,165 | 3.78125 | 4 | from typing import Union
import re
runningTotal = 0
run = True
def intro_message():
print("Our Magical Calculator")
print("Supported operations: ** + - * /")
print("SPACES ARE NOT ALLOWED")
print("Please use expressions such as 2*3 to get a result")
print("To continue using the previous total you... |
a951c5a7c83fe6de5efa6f0518bc74b5c6599491 | atjason/Python | /practice/py_ex1.py | 445 | 3.5625 | 4 | # -*- coding: utf8 -*-
"""
有四个数字:1、2、3、4,
能组成多少个互不相同且无重复数字的三位数?各是多少?
"""
result_list = []
nums = [1, 2, 3, 4]
for n1 in nums:
sub_nums = nums[:]
sub_nums.remove(n1)
for n2 in sub_nums:
sub_sub_nums = sub_nums[:]
sub_sub_nums.remove(n2)
for n3 in sub_sub_nums:
str = "%d%d%d" % (n1, n2, n3)
... |
bb084835daf4861fd9c5f7a0e7cbed3fc22ea865 | sathayas/PythonClassFall2019 | /ifExamples/IfExample1.py | 215 | 3.640625 | 4 | age = 23
hand = 'right'
# evaluating the age requirement
if age>=18:
print('The age requirement is met')
# evaluating the handedness requirement
if hand=='right':
print('The handedness requirement is met')
|
4c3b4ad820382293f242836397bfc3447cec9b78 | sushmeetha31/BESTENLIST-Internship | /Day 5 task.py | 902 | 4.40625 | 4 | #DAY 5 TASK
#Create a function getting two integer inputs from user & print the following:
#Addition of two numbers is +value
#Subtraction of two numbers is +value
#Division of two numbers is +value
#Multiplication of two numbers is +value
#Here the value represents math function associated
def f(a,b):
... |
8282aeb786191a36cf93814b506eb1294c752c39 | Rajmirukula/programming | /StuffIWrote/Kaggle/titanic/my_logit.py | 3,249 | 3.546875 | 4 | """
Modified from AstroDave's Random Forest, based in-part on agconti's Logistic Regression,
Here, I use Logistic Regression as provided by sklearn.
Because agconti's whole `statsmodels` library usage is just confusing me:
How do you run it on the test data? Why don't they show it in any of the
eg's in the doc... |
00225b53d13b8b5ddf5eb0137ee985b05bdcf11a | dineshchandvarre/practice-python-random-questions | /class Customer.py | 416 | 3.65625 | 4 | class Customer:
def __init__(self,name,account_no,balance):
self.name=name
self.account=account_no
self.balance=balance
def withdraw(self,amount):
if(amount>self.balance):
raise runtimeerror("Insufficient funds")
else:
self.balance-=amount
return self.balance
def deposit(self,amount):
self.balan... |
d5b573720a5d5a81bd1d2e9f724c1b3507b5f17d | mirinrimi/submarine | /for_one/for_one.py | 2,540 | 3.828125 | 4 | Alfabet = ["A", "B", "C", "D", "E"]
Number = ["1", "2", "3", "4", "5"]
# A1座標から[1, 0, 0, 0, 0]座標への変換
def coord_chg(str):
pt = [0, 0, 0, 0, 0]
pt[Alfabet.index(str[0])] = int(str[1])
return pt
# 逆変換
def inverse_chg(list):
for i in range(1, 6):
try:
box = Alfabet[list.i... |
faf0a7d2454d59882a9cc13d24e4a9f8357776be | MotiAzran/self.py | /5-4-1.py | 291 | 3.921875 | 4 | def func(num1, num2):
"""Calculate the sum of the numbers
:param num1: First number
:type num1: int
:param num2: Second number
:type num2: int
:return: The sum of the numbers
:rtype: int
"""
return num1 + num2
def main():
print(func.__doc__)
if __name__ == '__main__':
main()
|
02b807d0ba7dcf2d991ea31aff9865ccd55ae902 | shanedoc/python3 | /factory.py | 1,142 | 3.953125 | 4 | #code=utf-8
#简单工厂模式
class MathBase(object):
def Calc(self,x,y):
return 0
class MathAdd(MathBase):
def Calc(self,x,y):
return x+y
class MathSub(MathBase):
def Calc(self,x,y):
return x-y
class MathMult(MathBase):
def Calc(self,x,y):
return x*y
class MathDiv(MathBase):
... |
84cfa1064c4602ac20689db5a4f5ff59841a0ee2 | elk1o/starting_pyhton | /test2_objetos/test2.2_clases2.py | 832 | 3.609375 | 4 | # -*- coding: utf-8 -*-
class Coche:
"""Constructor del objeto coche"""
def __init__(self,neumaticos,numero_puertas,caballos,combustible):
self.neumaticos = neumaticos
self.numero_puertas = numero_puertas
self.caballos = caballos
self.combustible = combustible
def repostar(s... |
253862277ae19898ea209eb2520b73630c2d3c06 | ugaldedr/Digital-Signal-Processing | /Homework 8/dru8068-hw08/notchFilter.py | 1,475 | 3.59375 | 4 | """
Name: Dario Ugalde
MavID: 1001268068
Course: CSE 3313 Digital Signal Processing
"""
import numpy as np
import matplotlib.pyplot as plt
def applyNotch(fs, dataFile) :
f = 17
w = 2 * np.pi * f / fs
data = np.genfromtxt(dataFile, delimiter=",")
y = np.array([])
print(len(data))
... |
1a353a78efc97c4cf04e2135d5066f18b05ef87f | nararodriguess/programacaoempython1 | /ex014.py | 113 | 3.6875 | 4 | c = float(input('Digite a temteratura em °C: '))
f = 9 * c / 5 + 32
print(f'{c:.2f}°C equivale(m) a {f:.2f}F')
|
cebefe3b8fd1a8446ce0a3376ada5796408df14a | ZumTheZazaKing/Python-Rolling-Dice-Simulator | /rolling_dice_simulator.py | 1,140 | 3.953125 | 4 | import random
import time
import sys
print("-"*70)
print(' Rolling Dice Simulator')
print('-'*70)
time.sleep(2)
def main():
print('-'*70)
ans = str(input('Would you like to roll a dice? (Y/N)'))
print('-'*70)
if (ans.strip().upper() == 'Y'):
... |
f0eaebcc2d64daf1e4f56589caab31eb4023caaa | StormInside/OOP-labs | /lab-2.py | 15,855 | 3.875 | 4 | import math
class Game():
def __init__(self, location = {"x":[-1000,1000], "y":[-1000,1000]}, money = 0):
self.money = money
self.location = location
def set_money(self, count):
self.money = count
def print_money_amount(self):
print(f"You have {self.money} left")
d... |
dc1a701b3c129a9420e89db0c2b48281a4507585 | ajulyav/Implementing-a-Neural-Network-from-scratch | /lab2_skeleton.py | 5,961 | 3.5625 | 4 | from __future__ import print_function
import numpy as np
from matplotlib import pyplot as plt
#In this first part, we just prepare our data (mnist)
#for training and testing
#import keras
from tensorflow.keras.datasets import mnist
(X_train, y_train), (X_test, y_test) = mnist.load_data()
num_pixels = X_train.shape[... |
6ff7bc94391f2568f5ba6deb4cf1da35e88c1f78 | asidlare/ardtest | /models/fizzbuzz.py | 1,556 | 4.15625 | 4 | import typing
from typing import List
def valid_params(n: int, m: int) -> bool:
"""
Functions checks if inserted params are correct.
:param n: start value
:param m: stop value
:return: bool
"""
if isinstance(n, int) and isinstance(m, int):
if 1 <= n < m <= 10000:
return... |
cd2fa1f0844c0f2634f263ffc667edb1b28ec11e | gvdevi/vanipy | /first.py | 706 | 4.03125 | 4 | for i in range(0, 5):
print(i)
print("\n")
a = 3
A = 4
print(a)
print(A)
print("\n")
a=12
b=3
print(a+b)
print(a/b)
print(a-b)
print(a*b)
a=10
b=5
if a==b:
print("a is equal to b")
else:
print(" a is not equal to b")
print("\n")
def add(a,b):
c = a+b
print(c)
add(2,3)
def div(a,b):
i... |
c5600189b3833fae63050e8aab092d47d23f1dfb | decei/image | /crypt.py | 9,651 | 3.9375 | 4 | # decei - Encryption / decryption of a message by changing the pixels.
# Version 3.1 - imageio, objects, processed pixels to landscape
# 14.5.2020
# Encrypting quite time consuming due to high quality
# Set a quality limit for the image?
import string
import os
import imageio
import numpy
from PIL import Image
# Cr... |
b42c1b11a37dcb76ca685483620038bc2484bcf1 | Lathie/HackerTravel | /extract_hackers_1.py | 2,401 | 3.578125 | 4 |
import csv
import sys
import pprint
def extract():
try:
csv_raw = open("hackerdata.csv", "rt")
csv_input = csv.reader(csv_raw)
csv_input.next() #Skip column names
global school_dict
global school_dict_total
global school_bus_requests
school_dict = {} #co... |
c51c2bbba24b7f504da3a9f2de45dcf94bd9ba01 | anash234/aoc-2020 | /puzzles and inputs/day3.py | 2,770 | 3.515625 | 4 | input3 = open('input3.txt')
map = [i[0:-1] for i in input3.readlines()]
def tree_count_3_1(slope):
current_pos = [0, 0]
trees_hit = 0
while current_pos[1] < len(slope) - 1:
while current_pos[0] + 3 > len(slope[current_pos[1] + 1]):
slope[current_pos[1] + 1] = slope[current_pos[1] + 1] ... |
bbde2c53d4655d99e004cca6f2af2dc23a284e48 | eunjungchoi/algorithm | /leetcode/most_liked/24_swap_nodes_in_pairs.py | 847 | 4.03125 | 4 | # Given a linked list, swap every two adjacent nodes and return its head.
#
# You may not modify the values in the list's nodes, only nodes itself may be changed.
#
#
#
# Example:
#
# Given 1->2->3->4, you should return the list as 2->1->4->3.
# Definition for singly-linked list.
class ListNode:
def __init__(self... |
e2410a35d7e285dcd87e7c49199ff1b4bbbe4f27 | matheusscheu/AED2 | /Lista duplamente encadeada/LinkedDoubleList.py | 2,982 | 3.828125 | 4 | class Node:
def __init__(self, valor, anterior = None, proximo = None):
self.valor = valor #o dado a ser utilizado
self.prox = proximo #o proximo nó
self.ant = anterior # o nó anterior
class LinkedDoubleList():
def __init__(self):
self.head = None
self._size = ... |
78a1be7aaefdd04084cc106ac164e29be1a6c79a | victorrrp/python-avancado | /python 3/aula13_poo/app.py | 618 | 4.21875 | 4 | '''
Polimorfismo de sobreposição: é o principio que permite que classes derivadas de uma mesma
superclasse tenham métodos iguais (de mesma assinatura) mas comportamentos
diferentes.
Mesma assinatura = Mesma quatidade e tipo de parâmetros
'''
#exemplo de polimorfismo
from abc import ABC, abstractmethod
cla... |
5f5d3147595dfbc460477e6f8be5a8ea76ed9477 | PetroUsername/MentorshipPython | /mentorship_task_03_regex.py | 2,628 | 3.796875 | 4 | import re
import csv
import argparse
parser = argparse.ArgumentParser(description='Find phone numbers corresponding to entered provider')
parser.add_argument('-i', '--input_file', default='input.txt',
help='input text file to search numbers in (default: input.txt)')
parser.add_argument('-c', '--cod... |
fe2f930a6509b51295cdcb97964f97035242203a | aawelg/flotpython | /modules/corrections/w4s8_fun_args.py | 6,016 | 3.609375 | 4 | # -*- coding: utf-8 -*-
from nbautoeval.exercise_function import ExerciseFunction
from nbautoeval.args import Args
##############################
# @BEG@ name=distance
import math
def distance(*args):
"la racine de la somme des carrés des arguments"
# avec une compréhension on calcule la liste des carrés des ... |
8d3975b5994e2d81cdeb5f1a2d12df3050987632 | vskarinov/algorithm_cource | /algorithm_cource/task5_algo.py | 3,162 | 3.78125 | 4 | u"""
Максимум в скользящем окне
Найти максимум в каждом окне размера m данного массива чисел A[1...n].
Вход.
Массив чисел A[1...n] и число 1 ≤ m ≤ n.
Выход.
Максимум подмассива A[i . . . i + m − 1] для всех 1 ≤ i ≤ n − m + 1.
Форматвхода.
Первая строка входа содержит число n,вторая — масив A[1...n], т... |
e0961541a6a6f3556208a94bcd79946aaf80adc4 | arorarohanx/Age-Calculator | /Age-Calculator.py | 568 | 4.125 | 4 | import time
print("Welcome to my another Programme Age Calculator")
time.sleep(3)
print("In this programme you will be able to calculate your Age..")
time.sleep(3)
print("Loading..")
time.sleep(2)
name = input("Enter your Name :-")
yea = int(input("Enter the Year in which you were born :- "))
future_year = int... |
4b3f23601236d40ead41905b24eed808b960bac9 | talidemestre/open-source-home-speaker | /reset.py | 1,543 | 3.890625 | 4 | import time
#Generating a blank calendar
currentYear = int(time.strftime("%Y"))
years=[]
#creates intial year array
for i in range(currentYear, currentYear+10):
years.append([])
year = currentYear
#populates the years with days and months
for x in years:
for i in range(0,12):
if (i != 8... |
981ea2644ce2f51801d9ffd8ce0368b4c3f6c65d | AttilaAV/szkriptnyelvek | /otodik_o/happy_new_year.py | 244 | 3.59375 | 4 | #!/usr/bin/env python3
def main():
"""A függvény unicode karakterek segítségével generál számot
, = 44
U = 85
44*44+85 = 2021
"""
print(ord(',')*ord(',')+ord('U'))
if __name__ == "__main__":
main() |
ff16a993373314e155d7d8d7d8e0cbf050c372d7 | maulia-c/Python-Project-Protek | /Chapter 8/Langkah Kerja chap 8.py | 1,594 | 4.21875 | 4 | #list
print("1. List")
a=[1,5,6,3,6,9,11,20,12]
b=[7,4,5,6,7,1,12,5,9]
print(a)
print(b)
#sisipkan indeks
print("2. Sisipan indeks")
a.insert(2,10)
b.insert(1,15)
print(a)
print(b)
#sisipkan ke indeks terakhir
print("3. Sisipan ke indeks terakhir")
a.append(4)
b.append(8)
print(a)
print(b)
#sorting secara ascending
... |
2b2e3d5fff55582afa719589ae82b792d67d212a | joytsay/Machine-Learning | /PolynomialRegression/Models.py | 1,157 | 3.578125 | 4 | from sklearn.metrics import mean_squared_error, r2_score
class LinearModel:
""" Trains a Linear Model model and computes the metrics
Parameters
----------
model : linear model on which the data will be trained
Attributes
----------
intercept_ : intercept of the linear line
coeffs_ ... |
acdb1b0c32198be78f1f32cfa0fcb7000421a6e3 | tedye/leetcode | /tools/leetcode.074.Search a 2D Matrix/leetcode.074.Search a 2D Matrix.submission8.py | 483 | 3.71875 | 4 | class Solution:
# @param matrix, a list of lists of integers
# @param target, an integer
# @return a boolean
def searchMatrix(self, matrix, target):
if not matrix:
return False
if target < matrix[0][0] or target > matrix[len(matrix)-1][len(matrix[0])-1]:
return Fa... |
adad9c7cbf3a36e586450fb66e7eb3fc01d8be29 | lucasdanielgeo/exercicios | /java/app_submarino.py | 1,840 | 3.640625 | 4 | class Submarino:
def __init__(self, x=0, y=0, z=0, direction='NORTE'):
self.x = x
self.y = y
self.z = z
self.direction = direction
self.direction_list = ['NORTE','LESTE','SUL','OESTE']
def get_current_position(self):
print(f'Current submarine position: {self.x} {... |
8db0e074ed7032a3fbc1292182d7f8fd93e5386d | youjiajia/learn-leetcode | /solution/142/solution.py | 618 | 3.78125 | 4 | class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def printval(self):
print self.val
class Solution(object):
def hasCycle(self, head):
nodeset = set()
while head:
if head in nodeset:
return head
node... |
f06d280ac5ea4cb242e75f0c876f67beb5607590 | suwonraison900206/TIL | /수업 코드 예제/부분집합 loop 이용.py | 276 | 4 | 4 | bit = [0, 1, 2, 3]
list = []
for i in range(2):
bit[0] = i
for j in range(2) :
bit[1] = j
for k in range(2) :
bit[2] = k
for l in range(2):
bit[3] = l
print(bit)
list.append(bit)
|
6b05b506359cfa7cef92ca7e9705b187904c7d22 | RiverHendriksen/cs-361 | /assignment 1/testKwic1.py | 1,821 | 3.9375 | 4 | #River Hendriksen 2016
#CS-361 Assignment 1
#Kwic1test.py
#The test will see if the various conditions applied will still allow to the program to work
#this test runs under the assumption that we are not in a list of lists at this point
#eg the example ("hello \n bucko that ") does prouduces ["hello" , "bucko", "that"... |
ae96e26f530ad26c23f86de762f94277220df80f | cjwood032/CSC1570 | /CSC1570/average_numbers_Wood.py | 1,580 | 4.46875 | 4 | # average_numbers_Wood
# This program will open a file, and average the values in it
# Programmer: Christopher Wood
# date 2/28/18
# file name average_numbers_Wood.py
# pseudocode
#1. Prompt the user to give the file name
#2. open the file
#3. Read through the file, checking for any non-numeric data
#4. If the... |
7a21217d7078cf2a8b8ca9aa668a4625e27a54d2 | InventosRodriguez/Curso-Python | /01_Basicos/07_utilidades.py | 257 | 3.578125 | 4 | import sys
print("\n# ---------- UTILIDADES --------------------------------\n")
data = sys.stdin.read().strip() # lee algo del sistema # el estrip es como el trim
#if data:
# if input("do you want to save? Yn:").lower().strip() |= 'n':
|
5fcb556fb80bab9ef9c98baf1452df5c69b4354e | CongoCash/Rocket | /Updated/intro-algorithms/solutions/garrett_quicksort.py | 592 | 3.890625 | 4 | def quick_sort(items):
less = []
equal = []
greater = []
if len(items) > 1:
pivot_index = len(items) / 2
pivot = items[pivot_index]
for item in items:
# Put each item in their appropriate bin
if item < pivot:
less.append(item)
if item == pivot:
equal.append(item)
if item > pivot:
grea... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.