blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
940e631dfc40c24a7361f3873f22f4b57b9a24f0
kis307887597/policy_crawl
/add_quote.py
300
3.59375
4
while True: input_value=input("请输入字符串:\n") print(input_value) items=input_value.split("&") form_data={} for item in items: key=item.split("=")[0] value=item.split("=")[1] form_data[key]=value print(form_data) print(form_data.keys())
59eb728d5ea1abc5105b50e9a7c70cdee7acb79a
Angelfire/python-master-course
/homework6/main.py
786
4.125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """Homework 6 - Pirple Homework Assignment #6: Advanced Loops """ import os t_columns, t_rows = os.get_terminal_size() def playing_board(rows, columns): """ Args: rows(number): Represent the rows columns(number): Represent the columns Returns: ...
66f5e1725635cd21184da8579cb40ec00c4c5461
kaushalaneesha/100DaysOfCode
/coding_questions/randomized_set.py
2,262
3.984375
4
""" Design a data structure that supports all following operations in average O(1) time. insert(val): Inserts an item val to the set if not already present. remove(val): Removes an item val from the set if present. getRandom: Returns a random element from current set of elements (it's guaranteed that at least one el...
4b31330ced755727ec06c3a12acaa2b2f77ed5dd
adrienlagamelle/csSurvival
/css/app/forms.py
7,428
3.5625
4
""" The Flask-WTF extension uses Python classes to represent web forms. A form class simply defines the fields of the form as class variables. Classes: SearchForm - let the user search for a query LoginForm - user enters username, password, remember option and submit button RegistrationForm - user enters u...
d4c03eb9f331448bbfd75e1b08e62adb19837193
adrienlagamelle/csSurvival
/css/app/database/group.py
1,288
3.84375
4
"""Interface for the Group table of the database""" from . import sqlalchemy from .models import Group from .models import User def new(name): """Add a new group to the database Args: name (str): The name of the group Returns: obj: Instance of Group """ group = Group(name=name)...
ee906d92b2dfc12ce1dc944f844487f2d5c28d49
codesahib/Python-Notes
/sampleCodes.py
1,777
4.1875
4
#Python Funadamentals #Uncomment particular block to run #Print ''' print("Hello World") a=1 b=2 c=a+b print("c is {}".format(c) ) print("c is",c,"that's it" ) print("c is %d" % (c) ) ''' #Conditional Statements ''' a=2 b=2 if a>b: print("a>b") elif a==b: print("b=a") else: print("b>a") x="less" if a<2 else x="m...
f94e9d6f14d41dfb524a48d084299dae5a7c3280
shervinrad100/Python-Projects
/Hobby/Arithmetic game - multi-threading/QuickMafs.py
4,532
3.640625
4
# exercise to improve arithmetic maths import numpy as np import time print('Welcome to the \'quick mafs\' practice game' ) # implement negative marks def gennumber(a_large=False, start=2): """ generates four numbers: - two random integers between 2 and 100 with option to choose a > b an...
88119b99d4126b35874c554799a55e4b06bd7a7a
jvargh81/trade_stratergy
/hypothesis_testing/test.py
847
3.53125
4
import skewness import variance skew = skewness.skewness() var = variance.variance() data1 = [1,1,1,1,1,1,2,3,4,5,6,7,8] data2 = [1,2,3,4,5,6,7,8,8,8,8,8,8,8,8,8,8] data3 = [1,2,3,4,5,6,7,8,9] print("data1 : " + skew.skew_ness(data1)) print("data2 : " + skew.skew_ness(data2)) print("data3 : " + skew.skew_ness(data3)) ...
a3fd17383efeb303eda39500c31c2a3bfed98068
iamreebika/Python
/Datatypes35.py
104
3.640625
4
d = {'x': 1, 'y': 6, 'z': 9} for dict_key, dict_value in d.items(): print(dict_key,'->',dict_value)
4a9d7b0c7a314658d37d245363ae970c15e3c2ac
iamreebika/Python
/Datatypes31.py
129
3.828125
4
d = {'pizza': 1, 'momo': 2, 'Burger': 3} for food_key, value in d.items(): print(food_key, 'corresponds to ', d[food_key])
1e8476c8792ea6fcdc9edd1f34b3246bbec90823
DariaFilateva/python_course
/Task1.py
106
3.703125
4
b=int(input()); if (b<=12 and b>-12) or (b<17 and b>14) or (b>=19): print("True"); else: print("False") ;
22b1cbb3554ddf32f2810bd3507cd7c474423982
AmanMudgal2701/Second-Python-Project
/Day - 5 (Number game).py
734
4.28125
4
#The computer will think of a random number from 1 to 10 as secret number. import random random_number=random.randint(1,10) #Then ask you ( Player ) to guess the number and store as guess number. guessed_number=input('Guess any number between 1 to 10: ') guessed_number1=int(guessed_number) #Compare the guess ...
5c14d2d65ab17cdd50c5f813ad5ca461120deef4
izabelcavassim/Genome_scale_algorithms
/gsa-read-mapper-master/mappers_src/binary_search_map_src/binary_search_map
2,259
3.625
4
#!/usr/bin/env python from sys import argv from SamRow import SamRow from parsers import fasta_parser, fastq_parser, from_strings_to_cigar # Constructing the array in the naive way: (On * n log n) def build_array_naive(string): #string = string.strip('\n') zero_index = sorted(range(len(string)), key=lambda i: strin...
5e6b2ea53c0a48afe36ed40f021d40fb50a906ab
izabelcavassim/Genome_scale_algorithms
/Project5/suffix_build.py
320
3.640625
4
# Suffix array construction algorithm #from radix_sort import radix_sort # Constructing the array in the naive way: (On * n log n) def build_array_naive(string): #string = string.strip('\n') zero_index = sorted(range(len(string)), key=lambda i: string[i:]) # sorting suffixes by alphabethic order return zero_index
ed98aa7e7d81497ca7b3054e0e99cf6835699e3d
KornSiwat/unittesting-mmookptr
/fraction.py
4,356
4.3125
4
import math import fraction class Fraction: """A fraction with a numerator and denominator and arithmetic operations. Fractions are always stored in proper form, without common factors in numerator and denominator, and denominator >= 0. Since Fractions are stored in proper form, each value has a u...
108393e4d522d553743f06bfca1620e39aa86442
ejmurray/statsintro_python
/Code/C4_3_showData.py
6,248
4.09375
4
''' Show different ways to present statistical data The examples contain: - scatter plots, with 1-dimensional and higher-dimensional data - histograms - cumulative density functions - KDE-plots - boxplots - errorbars - violinplots - barplots - grouped boxplots - pieplots - scatterplots, with markersize proportional to...
b1ba5d1fe442e7af664c4afddd4999695f03076a
AlexandraMilts/Web_Crawler
/Replacement.py
578
3.734375
4
# Example 1 # marker = "AFK" #replacement = "away from keyboard" #line = "I will now go to sleep and be AFK until lunch time tomorrow." #Example 2 # uncomment this to test with different input marker = "EY" replacement = "Eyjafjallajokull" line = "The eruption of the volcano EY in 2010 disrupted air travel in ...
69e533cd09e924cbd6d3533c4cbc6d6753b12176
Dannie1G/short_projects
/guessing_game.py
1,122
4
4
#guessing_game.py def guess_number(): x = 0 # x is the lowest number in range of possible numbers y = 50 # y is the middle number in range of possible numbers z = 100 # z is the maximum number in range of possible numbers counter = 1 # counter counts the number of guesses taken input("Please ...
10b6339b5f062ecbb5d6c05f75165def476b7f5e
uxai/leetcode-challenges
/valid-mountain-array-main/mountain-array.py
635
3.546875
4
class Solution(object): def validMountainArray(self, arr): if len(arr) >= 3 and arr[0] < arr[1]: climax = False for i, item in enumerate(arr[1:], 0): if (item > arr[i] and not climax) or (item < arr[i] and climax): continue elif ite...
82563d5b69b7a4a59c2a0e0e274833585dce9b96
njc1583/Chess-Plan
/motion/planners/multiStepPlanner.py
5,119
3.59375
4
import math import time class StepResult: FAIL = 0 COMPLETE = 1 CONTINUE = 2 CHILDREN = 3 CHILDREN_AND_CONTINUE = 4 class PQNode: def __init__(self, key, value): self.key = key self.value = value def __lt__(self, other): return self.value < other.value def...
d22cd0ae98bcbdd33c33a4622a16d6dca3eb8642
ChuyX3/WTDesigner
/tools/utils.py
373
3.6875
4
from os import system, name def clrscr(): if name == 'nt': system('cls') else: system('clear') def menu(options): i = 0 for option in options: print(str(i + 1) + '. ' + option) i += 1 valid = False while not valid: op = int(input("Choose a valid option: ...
19aad56cfb27cc3872faf824cdc494662521ea92
green-fox-academy/kesu1991
/week-01/day-3/Day-03-Answers.py
10,658
3.984375
4
########################################################################## Functions ########################################################################## ###### Doubling base_num = 123 def doubling(para): double = para*2 print(double) return double doubling(base_num) ###### Greeter function al = "...
a332ce0f9271336044e818f9e2851e4a2a3b9204
shreyadixit19/yenergi
/load_template.py
1,458
3.5625
4
""" Template for creating a loading a table. Assuming you have a TAB-SEPARATED file structured with the first row as the header (the column names), and subsequent rows are the entries in the table with tab-separated values, set DATA_FILE_PATH to the path of that file Change the import statement to import db as well as...
956e5e939444987a9cdd6c519a86a55ccaff6484
CCTSAI-Tony/intern_assignment
/logic_gates/INPUT.py
613
3.546875
4
""" INPUT gate """ from logic_gates.GATE import Gate class INPUTGate(Gate): """ INPUT logic gate. """ def __init__(self, input1=None, input2=None): super().__init__(input1, input2) """ :param input1: int :param input2: int """ self._input1 = inp...
c06766a2033a9c4d9235dbf48fca5ee367172627
brendanwhit/ds1-final-project
/accumulate_stats.py
1,585
3.5625
4
#!/usr/bin/env python3 # -*- coding: utf8 -*- #------------------------------------------------------------------------------- # created on: 11-28-2018 # filename: accumulate_stats.py # author: brendan # last modified: 11-28-2018 20:59 #------------------------------------------------------------------------------- """...
081170ffa8f122b9a355ac1b68d6f7b1c5ba5e6c
icsolution/Loan-Calculator
/creditcalc.py
3,142
3.5625
4
import argparse import math # calculate differentiated payments def diff(principal, periods, interest): interest = interest / 100 / 12 total = 0 for month in range(1, periods + 1): result = math.ceil(principal / periods + interest * (principal - (principal * (month - 1)) / periods)) print(f...
4afc7f991486a10695bf4d3eff2510261b26aa91
lumalik/code-challenges
/isValidWalk.py
417
3.796875
4
def isValidWalk(walk): from collections import Counter d = Counter(walk) ns = abs(d["n"] - d["s"]) we = abs(d["w"] - d["e"]) back = int(ns + we) forward = len(walk) if (10-(forward+back))>=0: if(ns == 0 and we == 0): return(True) else: return(False) ...
cc198d4222ddbcd1c20c3d2f482360fad8077f9f
YANGYANTEST/Python-development
/stage one/day10/作业.py
2,269
3.921875
4
''' 动手完成: 1.自定义一个异常类,当list内元素长度超过10的时候抛出异常 2.思考如果对于多种不同的代码异常情况都要处理,又该如何去处理,自己写一个小例子 3.try-except和try-finally有什么不同,写例子理解区别 4.写函数,检查传入字典的每一个value的长度,如果大于2, 那么仅仅保留前两个长度的内容,并将新内容返回给调用者 dic = {“k1”: "v1v1","k2":[11,22,33}} ''' import sys class MyListError(Exception): def __init__(self,message): ...
2a2ebddadfd1a1f9b05c1f25b8e6e10fc4c1e637
cbgoodrich/Unit6
/quiz.py
1,627
4.0625
4
#Charlie Goodrich #12/13/17 #quiz.py - last quiz boi dictionary = open("engmix.txt") """def program1(): for words in dictionary: p_count = words.count("p") c_count = words.count("c") if p_count == 2 and c_count == 3: print(words.strip()) program1() """ """def program2(): r...
6409630227c48ca8d3d37ae11d80e1c28a0b6637
roadprimus/practices-of-the-python-pro
/ch03/functional.py
621
3.84375
4
# Python for loop numbers = [1, 2, 3, 4, 5] for i in numbers: print(i * i) # Functional style from functools import reduce squares = map(lambda x: x * x, [1, 2, 3, 4, 5]) should = reduce(lambda x, y: x and y, [True, True, False]) evens = filter(lambda x: x % 2 == 0, [1, 2, 3, 4, 5]) # List comprehension style ...
16a03f9477e8d6ba8e2a0b2d1244fa030b79dd39
roadprimus/practices-of-the-python-pro
/ch02/rock_paper_scissors.py
7,221
4.1875
4
# Shoddy procedural code import random options = ['rock', 'paper', 'scissors'] print('(1) Rock\n(2) Paper\n(3) Scissors') human_choice = options[int(input('Enter the number of your choice: ')) - 1] print(f'You chose {human_choice}') computer_choice = random.choice(options) print(f'The computer chose {computer_choice}'...
39801a8f5ef6cef37e4438cc5c5a96fdb8a79f20
ritvikrao/PycharmProjects
/Chatbot/test_chatbot.py
8,453
3.671875
4
import unittest import hw1_chatbot # import your solution # make sure that this file and your hw1_chatbot.py file # are in the same directory, then run this file with the # command `python test_chatbot.py` # Ritvik Rao # This is my unit test file for the chatbot class ChatbotTest(unittest.TestCase): # you may...
ee4fe13c52f5c9502c1b60bbdfabb4daca5e9abb
saritazavala/Proyecto-final
/math_fuctions.py
2,177
3.515625
4
def cross(a, b): c = [a[1]*b[2] - a[2]*b[1], a[2]*b[0] - a[0]*b[2], a[0]*b[1] - a[1]*b[0]] return c def substractV3(a, b): c = [a[0]-b[0], a[1]-b[1], a[2]-b[2]] return c def root(x,a): y = 1 / a y = float(y) z = x ** y return ...
794ed6ddf950390933e3d201fe575561be24726a
Raylively/python
/多进程/queue_connections.py
1,018
3.625
4
# -*- coding: utf-8 -*- from multiprocessing import Queue,Process from time import sleep """ Queue() # 如果没有指定数量或数量为负,表示可接受的消息数量没有上限 Queue.qsize() # 返回当前数列包含的消息数量 Queue.full() # 队列满了返回true,反之false Queue.get() # 获取队列中的一条消息,然后将其从队列移除 Queue.put() # 相对列存消息 """ def write_task(q): if not q.ful...
6dfe37bcefca609f9fb518e52e77e7de118fe809
joabim/a3c_vrep
/default/cartpole.py
7,403
3.671875
4
import numpy class CartPole: """Cart Pole environment. This implementation alows multiple poles, noisy action, and random starts. It has been checked repeatedly for 'correctness', specifically the direction of gravity. Some implementations of cart pole on the internet have the gravity constant inverted...
6df5140aebb1674b6efe8797a8353da3c6990b03
akesiraju/raspberrypi
/sensors/samples/keytest.py
171
3.609375
4
import keyboard print('hello') while True: if keyboard.is_pressed('up'): print('up') if keyboard.is_pressed('down'): print('down') break
647154d5782fdc918a5d3bed0383506d6f4c889a
Rowing0914/Interview_Prep_Python
/algorithms/data_structures/stack.py
339
3.65625
4
class Stack: def __init__(self): self.data = [] def push(self, item): self.data.append(item) def pop(self): if len(self.data) < 1: return None else: return self.data.pop() def size(self): return len(self.data) if __name__ == '__main__': stack = Stack() stack.push(1) item = stack.pop() print(...
c9318cb7826561ee33daacff77ede0a7f7553edf
Rowing0914/Interview_Prep_Python
/algorithms/search/binary_search.py
386
3.984375
4
a = [1,2,3,4,5] target = 2 def binary_search(arr, target): first = 0 last = len(arr) - 1 found = False while (first <= last and not found): mid = (first + last) // 2 if arr[mid] == target: found = True else: if arr[mid] > target: last = mid - 1 else: first = mid + 1 return found, mid if _...
20b2667869fdb264998ad15d107d19df0486300f
NikolayWTF/GraphTheory2
/D.py
5,900
4
4
from tkinter import * import math # Функция для визуализации вершин графов def vizualization (centerX, centerY, radius, angel, X, Y, nm): i = 0 while i < nm: x = centerX + radius * math.sin(i * angel) # Координата новой вершины по x y = centerY + radius * math.cos(i * angel) # И по y ...
df4eb7e0a11fab33feabac34275b8b1d3df5c690
pratikshah1701/hackerrank
/the-minion-game.py
607
4
4
#!/usr/bin/env python3 def is_vowel(letter): return letter in 'AEIOU' def compute_score(S, letter_condition): return sum(map(lambda entry: len(S) - entry[0], filter(lambda entry: letter_condition(entry[1]), enumerate(S)))) def main(): S = input() stuart_score = compute_score(S, lambda letter: no...
b4dd1cd063443185f6a0a4a0f96711eb4905a243
pratikshah1701/hackerrank
/py-set-add.py
261
3.859375
4
#!/usr/bin/env python3 def main(): N = int(input()) distinct_countries = set() for _ in range(N): country = input() distinct_countries.add(country) print(len(distinct_countries)) if __name__ == "__main__": main()
540979821efd340eceaa9a22c6529abdc524d091
pratikshah1701/hackerrank
/zipped.py
301
3.71875
4
#!/usr/bin/env python3 import statistics def main(): N, X = map(int, input().split()) subjects = [map(float, input().split()) for _ in range(X)] print(*map(lambda student: '{0:.1f}'.format(statistics.mean(student)), zip(*subjects)), sep='\n') if __name__ == "__main__": main()
c48f2d2879d95ea54f5d29f78a0ae053023f6043
pratikshah1701/hackerrank
/find-angle.py
287
3.984375
4
#!/usr/bin/env python2.7 # -*- coding: utf-8 -*- import math def main(): AB = int(input()) BC = int(input()) theta = round(math.degrees(math.asin(AB / math.sqrt(AB ** 2 + BC ** 2)))) print '{theta:.0f}°'.format(theta=theta) if __name__ == "__main__": main()
a89ec19b52ff3b6fd2351b5f696ab1976f822440
pratikshah1701/hackerrank
/find-a-string.py
344
3.90625
4
#!/usr/bin/env python3 def main(): string = input() substring = input() occurrence = 0 start = 0 while True: index = string.find(substring, start) if index < 0: break occurrence += 1 start = index + 1 print(occurrence) if __name__ =...
63c448d3c79b6f185c38365d6c310fd35d4f1c1b
pratikshah1701/hackerrank
/finding-the-percentage.py
338
3.734375
4
#!/usr/bin/env python3 def main(): N = int(input()) student2marks = {} for i in range(N): student, *marks = input().split() student2marks[student] = list(map(float, marks)) marks = student2marks[input()] print("{0:.2f}".format(sum(marks) / len(marks))) if __name__ == "__ma...
0ea4a16e30e7b37cef78c5a9462c5df79e075bec
zzuzzy/PyLadies
/06/ai.py
2,593
3.515625
4
from random import randrange from util import tah import re def tah_pocitace(pole, symbol): symbolPC = symbol if "x" == symbolPC: symbolHrace = "o" else: symbolHrace = "x" #Vyherni tah pocitace if(symbolPC*2+"-" in pole): pozice = pole.index(symbolPC*2+"-")...
b1fac1f809238a947b627a839990821efe598722
HoloTheDrunk/damalex
/src/board.py
980
3.90625
4
from typing import * class Board: def __init__(self, size: int, lines: int): if size % 2 != 0: raise ValueError("Board.__init__: argument 'size' should be even.") if lines > size / 2: raise ValueError("Board.__init__: argument 'lines' should be at most half of argument 'siz...
ea2313a82ddab2effbfbd6eea266186bb30a600f
vin-snathan/Tic-Tac-Toe-Python
/TicTacToe.py
3,124
3.71875
4
# initialize data structure gameBoard = { 'top-L': '', 'top-M': '', 'top-R': '', 'mid-L': '', 'mid-M': '', 'mid-R': '', 'low-L': '', 'low-M': '', 'low-R': '' } winningCombinations = [ ['top-L', 'top-M', 'top-R'], ['mid-L', 'mid-M', 'mid-R'], ['low-L', 'low-M', 'low-R'], ...
62028f2c6ea00dfb7ffd2a97a94140505b99b344
eb-gardito/eng.training
/recommender.py
1,651
3.765625
4
import csv import statistics # see https://docs.python.org/3/library/statistics.html import sys CATEGORY_MAP = { 'Sports': '101', } PRICES_SOURCE_FILE = 'src/ebengtraining.csv' def get_prediction(country_code, event_category): """ Returns the mean and standard deviation for purchases for the provided co...
14e432eb3820d69716b6a8fbdbda6b516b9a9ea9
0verk1ll/Algorithms-1
/graphs/eulerian_tour.py
4,374
4.125
4
#!/usr/bin/env python3 # Find Eulerian Tour # # Write a program that takes in a graph # represented as a list of tuples # and return a list of nodes that # you would follow on an Eulerian Tour # # For example, if the input graph was # [(1, 2), (2, 3), (3, 1)] # A possible Eulerian tour would be [1, 2, 3, 1] def get_a_...
1e2bc329ce2b19affe77b1647591367754b398fe
0verk1ll/Algorithms-1
/heaps/heapsort.py
261
3.625
4
from minheap import minheap import random def heapsort(nums): h = minheap(nums) return [h.heappop() for i in range(h.max_elements())] if __name__ == "__main__": a = [random.choice(range(100)) for i in range(40)] print heapsort(a) == sorted(a)
097bb9da32dcbfa3b2d3d47c5ffec65366c16ecd
0verk1ll/Algorithms-1
/trees/trie.py
3,365
3.734375
4
""" Tries in python Methods - insert_key(k, v) has_key(k) retrie_val(k) start_with_prefix(prefix) """ def _get_child_branches(trie): """ Helper method for getting branches """ return trie[1:] def _get_child_branch(trie, c): """ Get branch matching the charac...
86907545ef396f7c1e1d06d755196ada82322e7e
nataleedesotell/HPM573S18_DESOTELL_HW1
/DESOTELL_HW1_P5.py
448
3.9375
4
#PROBLEM 5 #NATALEE DESOTELL #HPM 573 HOMEWORK 1 months = {'January': 1 ,'February': 2 ,'March': 3 ,'April': 4 ,'May':5,'June':6, 'July':7,'August':8,'September':9,'October':10,'November':11,'December':12, 1:'January',2:'February',3:'March',4:'April',5:'May',6:'June',7:'July',8:'August',9:'September',10:'October',11:'...
6f5e74d14caecee0841bf45ff822fefee315d477
Siddharth0701/python-programming
/factorial.py
2,067
4.125
4
''''def recur_factorial(n): """Function to return the factorial of a number using recursion""" if n == 1: return n else: return n*recur_factorial(n-1) # Change this value for a different result #num = 7 # uncomment to take input from the user num = int(input("Enter a number: ")) # check is ...
805714f3ef37b0267c846f385b24616992083ad7
yoshuah809/RPSLS_Proj
/human.py
1,114
3.65625
4
from player import Player class Human(Player): def __init__(self): super().__init__() self.set_name() def set_name(self): self.name = input('Please enter your name: ') print(f'{self.name} has been registered as a player!') def set_gesture(self): choose_gesture = inp...
d2d340a92c96478bee7956233b9979057a29713b
KnightApu/Leetcode-30days-challenge
/week-2/backspaceString.py
629
3.59375
4
class Solution: def backspaceCompare(self, S: str, T: str) -> bool: p = [] q = [] for i in range(0, len(S)): if S[i] != '#': q.append(S[i]) elif len(q) != 0: q.pop() for i in range(0, len(T)): ...
ace3643076df5b166c9a528e9e29b33179fc75b0
craigbrennan24/CloudComputing2015-16
/Lab03/euler25.py
401
3.8125
4
#! /usr/bin/env python def DigitFibonacci(): fib1 = 0 fib2 = 1 temp = 0 found = False fibCounter = 1 while( found == False ): fibStr = str(fib2) fibCheck = len(fibStr) if( fibCheck >= 1000 ): found = True else: temp = fib2 fib2 = fib2 + fib1 fib1 = temp fibCounter += 1 print "First 1k D...
e966526ae5a66cf3a527449b8f823cc24d2543bc
JimilProgGrammer/AISCLab
/Lab 2 - Activation Functions/activation.py
3,600
3.734375
4
import numpy as np from tabulate import tabulate def perceptron(weights, inputs, bias, activation_function="tanh"): """ Builds a simple perceptron using the given input, weights, bias values and activation function. - **parameters**, **types**, **return** and **return types**:: :param weights:...
8faf20a04d6e491db64565c31b74d2a6b27249f7
tbedford/code-snippets
/python/split-strip.py
162
4.40625
4
str= ' this | is | a string ' s1, s2, s3 = str.split('|', 2) print('>%s<' % s1.strip()) print('>%s<' % s2) print('>%s<' % s3) s = str.split('|', 2) print(s)
682973190487de9ba0cf4032cfedbb91dece1e79
tbedford/code-snippets
/python/async/generator.py
274
3.875
4
def number_generator(n): for i in range(n): yield i # Using the generator gen = number_generator(5) print(gen) print(next(gen)) # Output: 0 print(next(gen)) # Output: 1 print(next(gen)) # Output: 2 print(next(gen)) # Output: 3 print(next(gen)) # Output: 4
37a6bcd29d95a04f5131165a02808177c85d50f3
tbedford/code-snippets
/python/async/test.py
576
3.515625
4
import asyncio # Simulate I/O-bound task that takes 1 second only async def rt1(): print("A") await asyncio.sleep(1) print("B") # This is a CPU-bound task that will block other # co-routines. It shouldn't really be async, as it's # CPU-bound rather than I/O bound. async def rt2(): print("CPU bound 1"...
d92e31138455a03e605eae07e04fdb1e41364fc3
tbedford/code-snippets
/python/calc_age.py
573
4.34375
4
from datetime import datetime def calculate_age(birth_date): current_date = datetime.now().date() birth_date = datetime.strptime(birth_date, "%Y-%m-%d").date() age = current_date.year - birth_date.year # Check if the birthday has occurred this year or not if current_date.month < birth_date.month: ...
9eecc66137ba8a94174325ddf2922c3ff4bb8d9a
tbedford/code-snippets
/python/dates.py
412
3.859375
4
students = [ {'name': 'fred', 'age': 29}, {'name': 'jim', 'age': 34}, {'name': 'alice', 'age': 12} ] students = sorted(students, key=lambda x: x['age']) #print(students) students = [ {'name': 'fred', 'dob': '1961-08-12'}, {'name': 'jim', 'dob': '1972-01-12'}, {'name': 'alice', 'dob': '1949-01-01'}, {'name': 'bob', '...
42097f34f2c8f7d88550bdb6fd67730eaf807364
InfantRanjanR/Letsupgrade-Python
/List.py
567
4.21875
4
Lst = ["ranjan",1,2,3,4]#declaring list print(Lst) #output ['ranjan', 1, 2, 3, 4] Lst.append("Infant")#Adding item to the last of the list print(Lst) #output ['ranjan', 1, 2, 3, 4, 'Infant'] lst = Lst.copy()#copying list items to another variable print(lst) #output ['ranjan', 1, 2, 3, 4, 'Infant'] lst.po...
68d884a23aa1e9d1ddb58eea5b5d97dd39714fe4
psmrecek/UI-Zadanie2-Problem3g-ZS20
/Starsie verzie/Smrecek-Zadanie2-Verzia1.py
11,751
3.5
4
# ----------------------------------------------------------- # UI - Zadanie 2 - Problem 3 g) # ZS 2020 # # Peter Smreček # email xsmrecek@stuba.sk # AIS ID 103130 # ----------------------------------------------------------- from Smrecek_Zadanie2_Pohyby import * def zaciatokFunkcie(funkcia, zac): ''' Pomocn...
215555e2b5aae1e44f6d37436453133fb9ccadc1
bunnany/english_words
/sample_code.py
460
4.1875
4
## # Sample code to use load_words.py import load_words as lw def load_words(): """ Load a list of words to a list. """ return lw.load_words() def check_word(words, word): """ Check if a word exists in the list of words. """ if word in words: return True else: r...
46c87774c7c88d0ad12b2d675ecdc92a2e80c062
yuchun921/CodeWars_python
/8kyu/Convert_number_to_reversed_array_of_digits.py
112
3.5625
4
def digitize(n): result = [] for i in reversed(str(n)): result.append(int(i)) return result
8b5da5ebefef0c029e581c8565670a00522da01a
bertomartin/capstone2016
/src/data_retrieval/load_data.py
1,406
3.53125
4
# converts data to csv, helpers for loading data: df = load_top_100() # iopro allows you to slice small parts of your data efficiently and then just create pandas data frame # also use iopro to load from say s3, db, local text into dataframes. import os import re import csv DELIMITER = "##########" def convert_to_cs...
af3f91774ffb21baf5bfe3e6bf140c3e29872e71
gentikosumi/python-challenge
/PyBank/main.py
2,040
3.78125
4
import os import csv path = '/Users/kevinkosumi12345/Genti/python-challenge/PyBank/Resources/budget_data.csv' budget_csv=os.path.join("../Resources", "budget_data.csv") csvfile = open(path, newline="") reader=csv.reader(csvfile, delimiter=",") header = next(reader) # print(header) # the columns we have to convert ...
2c141b76bf49b66d4698065f6e0e0f11500809f5
matsuyasu45/DejiTera01_Python_Fundamentals
/04_Graph.py
3,615
3.59375
4
""" デジタル寺子屋 第1回 Pythonの基礎 - 04 グラフ描画 by まつもと 基礎の基礎ばかりだとつまらないので、第1回の締めとして「グラフの描画」にトライします。 グラフの元となるデータを格納する型として「リスト」が出てきますが、詳しくは第2回でレクチャーします。 ここでは、[]の中に,切りでデータが並んでいるのが「リスト」だ理解しておけばOKです。 """ """ ■04-01 グラフ描画用パッケージの読込 ※グラフ内に日本語を書くと文字化けしてしまう問題は、フォントのダウンロードで解決でき ます。「matplotlib 文字化け 日本語 Windows/Mac」で検索して...
668935f07f8dff6a7c8837a8c699a5c35dbf0570
TimothyCowan/Conversions
/conversions.py
2,181
4.28125
4
# Convertsions for tempature # v1 - basic functionality - Fahrenheit, Celsius, Kelvin conversions # by -Tim Cowan #invalid_response set for while statment to loop until 'q' is entered to quit the program invalid_response = None while invalid_response != "q": #conversion_type = input("To convert temperature enter ...
fcecc461ca2a4bd99929ad5fe142fcbf176d9b54
ryanhebert31/CSI355-Project1
/IPAddressConverter.py
774
3.796875
4
# Ryan Hebert & Ben Kohler # IP Calculator # Docs consulted: https://docs.python.org/3/library/ipaddress.html from ipaddress import AddressValueError, IPv4Address, ip_network def main(): ip = str(input("Enter IP Address: ")) prefix = int(input("Enter Prefix Length: ")) ipWithPrefix = ip + "/" + str(pref...
4ec3a54595e11c291f339a0cfb27105f077b6cee
chrisfilho/python
/metodos /metodos_de_string.py
537
4.375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- print "um exemplo de como usar len()" variavel = "essa palavra e muito grande" print len(variavel) print "e sua resposta será:" print "23" print "agora vamos para lower()" variavel = "ESSA PALAVRA E MAIUSCULA" print variavel.lower() print "e sua resposta será:" print "e...
36c7bf1d55a7b31eddc4e7880190fe0041eba228
vandraghol/LexaMazyrorBoykoAntipov
/MBAL.py
814
3.921875
4
import math a = int(input('выбор действия')) if a==1: x=int(input('введите x ')) y=x**3-64*x*(x**3/x**2) print(y) elif a==2: x1=int(input("x1=")) x2=int(input("x2=")) x3=int(input("x3=")) z=pow(x1,2) x=pow(x2,2) c=pow(x3,2) v=(z+x+c)-100 print(v) elif a==3: x...
04047ac8d8a9f25d66d99cc2fac1fb7c0d56021c
22aishwaryagoyal/Python
/Python/LineGrapg.py
176
3.59375
4
import pandas as pd data={'year':[1971,1981,1991,2001,2011],'pop':[50,73,81,98,111]} df=pd.DataFrame(data,columns=['year','pop']) df.plot(x='year',y='pop',kind='line')
4031cc2c92787ec58fa07947c29a95342d34140e
22aishwaryagoyal/Python
/Python/FileHandling.py
242
3.640625
4
empno=int(input('Enter empno')) name=input('Enter Name') city=input('Enter City') fn=input('Enter Filename.') obj=open(fn,'a') obj.write(str(empno)+'\n') obj.write(name+'\n') obj.write(city+'\n') print('Data Saved..') obj.close()
8c9f3115df01629e4a06dc59f0852a00613e69d5
22aishwaryagoyal/Python
/Python/bar+Panda.py
271
3.578125
4
import pandas as pd import matplotlib.pyplot as plt d={'empno':[101,102,103],'name':['Aish','Surbhi','Aman'],'Salary':[1000,2000,3000]} df=pd.DataFrame(d) df['Tax']=df['Salary']*0.30 plt.bar(df['name'],df['Tax'],color='r') plt.title('Bar Chart..') plt.show()
909fd264cd87f25d9c3e723bb7f8033a8bc7461b
22aishwaryagoyal/Python
/Python/Inheritance.py
359
3.734375
4
# -*- coding: utf-8 -*- """ Created on Wed Aug 18 11:36:05 2021 @author: User """ class A: def hello(self): print('hello') print('parent') class B: def sum(self,a,b): print('sum',(a+b)) class C(A,B): def Hi(self): print("HI C") obj=C()...
0c78e8a46717951b35a289fe6552f7d9eea3e376
christianctq/christianctq.github.io
/python/fact.py
255
3.796875
4
#def fact(n): # if n==1: # return 1 # return n*fact(n-1) #print(fact(10)) def fact(n): return fact_iter(n,1) def fact_iter(num,product): if num == 1: return product return fact_iter(num-1,num*product) print(fact(1000))
e176ca8f98c2c0a55495180d5d5a7c226b066ed2
karljohnbeck/Learning-python-basics
/microsoftDemo.py
1,125
4.03125
4
# # name = input("whats your name?") # # print('hello') # # print(name) print("another line") print('math time', 2 / 2) print("chicken math:") print("hens", 25+ 30 / 6) print("roosters", 100-25*3%4) print("Mary had a little lamb.") print("Its fleece was white as {}.".format('snow')) print("And everywhere that Mary ...
47ddabff9bc85f38d03ce3320c2f363f9296345a
Anastasiyaglider/pythonintask
/INBa/2014/A-Bykhovskaya/task 7.py
1,099
4.125
4
# Задача 7, Вариант 7 # Разработайте систему начисления очков для задачи 6, в соответствии с которой игрок получал бы большее количество баллов за меньшее количество попыток. # Быховская А.С. # 25.04.2016 import random print ('Отгадайте имя одного из основателей компании Google') def get_random_b(): a =...
d2a9859634c7e5045a7034b44553519ac40320e5
hamza-boudouche/data-structures
/python/hashTable.py
2,232
3.96875
4
from linkedLists import linkedList class Node: def __init__(self, key, value): self.key = key self.value = value self.next = None class HashTable: def __init__(self, capacity): self.capacity = capacity self.size = 0 #keep count of the size so that we can reAllocat memor...
f9dd203044ed68bc645d706218a4692f44fce23f
hiEntropy/words
/topology.py
3,124
3.515625
4
from Utilities import trim_newline,credentials import mongodb ''' getTopology outputs the topology of any string as defined by PathWell ?u = any uppercase ?l = any lowercase ?s = any special char ?n = any number returns a string representing the topology of the given string ''' def get_topology(string): topolo...
5deb46b528a127052948ae13ebad362d17b8cd5b
cheokml/cheokles
/ctci.py
372
4.09375
4
# Chapter 6: The Big O def sum_between(x,y): """ Sums all of the values between x & y Parameters ___________ :param x: int: First variable :param y: int: Second variable Returns ___________ :return: The total between the minimum and max numbers """ high = max(x,y) low =...
8f3cfc818efcb2b72ef5357323386ae2f1e5714e
KevinCabeza/myrepo
/PycharmProjects/introduccion/estructurasdecontrol/contraseña.py
196
3.78125
4
contraseña = "programacion" clave = input("introduce una contraseña:") clave = clave.lower() if contraseña == clave: print("contraseña correcta") else: print("contraseña incorrecta")
b3b738861a904bfbee4047ccc3875c75da651e0a
KevinCabeza/myrepo
/Imágenes/fotos/fotos/producto1a5.py
96
3.578125
4
producto = 1 for i in range(1,6): producto = producto * i print("el producto es ", producto)
42e09bdb1193843505d30c22210aea62b0a7a6ed
KevinCabeza/myrepo
/Imágenes/fotos/fotos/Renta.py
351
3.9375
4
#programa que pregunte al usuario su renta anual # y muestre por pantalla el tipo impositivo que le corresponde rent1 = int(input("Introduce la renta: ")) if rent1 < 10000: imp1 = 5 elif rent1 < 20000: imp1 = 15 elif rent1 < 35000: imp = 20 elif rent1 < 60000: imp1 = 30 else: imp1 = 45 print("El t...
c9ae7e27bdb56571b447cbfdecb0ecebb012cfbd
KevinCabeza/myrepo
/Imágenes/fotos/fotos/s_o_n_v2.py
335
3.984375
4
'''Este programita valida una respuesta''' respuesta_valida = False while not respuesta_valida: respuesta = input("Desea continuar (s/n)") respuesta = respuesta.lower() respuesta_valida = respuesta == "s" or respuesta == "n" if not respuesta_valida: print("Error: Teclea una s o una n") print("Fi...
0a5d61fd01515574624eef752d88f7afff503574
KevinCabeza/myrepo
/Imágenes/fotos/fotos/contraseña_nueva.py
315
3.6875
4
contraseña = 'damdam' contraseña_input =input("Introduce la contraseña: ") while contraseña_input != contraseña: print("ERROR, La contraseña no es correcta. ") contraseña_input =input("Introduce la contraseña: ") print("Contraseña correcta.") print() print("Fin de programa, goodbye.")
d60b42ef04aedc71f7dd8d918fce15e68a3a73b7
adonley/defcon-cesear-2019
/music_convert.py
466
3.71875
4
from typing import List bin_str = """01110011 00111010 00101111 00101111 01100010 01101001 01110100 00101110 01101100 01111001 00101111 00110010 01011001 01000010 00110001 01011010 00110101 00110010""" bin_list = [] def convert(l: List): string = "" for s in l: string += str(chr(int(s, 2))) retu...
50b1e9a31572a7040d7b7c7e78820eeb187b8fbd
codie-bodie-jo-mommie/Overwatch-Accounts
/main.py
1,189
3.75
4
import os while True: option = input("Email or Account or Show: ") if option == "Email": email = input("Email (without @gmail.com): ") password = input("Password for the email: ") account = input("Account name with that email: ") with open(f"Email Info - {account}.txt", 'w')...
42c822531c82006ee91a24c602f9302e83d65598
lukedoukakis/pathfinding
/Pathfinding/graph.py
8,302
4.21875
4
class Node: def get_id(self): """ Returns a unique identifier for the node (for example, the name, the hash value of the contents, etc.), used to compare two nodes for equality. """ return "" def get_neighbors(self): """ Returns all neighbors of a node, and how ...
37eda72ca12d4adddba2cb99c92359c3bc7fc9c8
dandani-cs/tiny_python_projects_created_code
/06_wc/wc_ver2.py
1,567
3.59375
4
#!/usr/bin/env python3 """ Author : None Date : 2020-03-30 Purpose: Rock the Casbah """ import argparse import os import sys # -------------------------------------------------- def get_args(): """Get command-line arguments""" parser = argparse.ArgumentParser( description='Rock the Casbah', ...
d862eeb2c68caac7a8bfc9bc5692e41b93cb034b
dandani-cs/tiny_python_projects_created_code
/08_apples/apples_ex1.py
1,648
3.8125
4
#!/usr/bin/env python3 """ Author : None Date : 2020-04-08 Purpose: Rock the Casbah """ import argparse import os import sys # -------------------------------------------------- def get_args(): """Get command-line arguments""" parser = argparse.ArgumentParser( description='Rock the Casbah', ...
bad16532836abb58ee1e4f09e618a03511a37998
dcl-covid-19/mega-map
/web-scraping/county-scraping/CalfreshScraper.py
2,788
3.53125
4
import re import csv import time from selenium import webdriver from bs4 import BeautifulSoup from chromedriver_py import binary_path # this gets you the path variable class CalfreshScraper(object): URL = "https://calfresh.dss.ca.gov/food/officelocator/" def __init__(self): """ Initializes the...
53ce775d2a2e0b5f637011efcc8782a34ad01525
Kortekaasy/pyGPG
/src/Utils/Arithmetic.py
1,722
3.578125
4
def xgcd(b, n): """ Extended euclidean algorithm according to [https://en.wikibooks.org/wiki/Algorithm_Implementation/Mathematics/Extended_Euclidean_algorithm#Python] :return: tuple (g, x0, y0) such that g is equal to gcd(b,n) and g = b*x0 + n*y0 """ x0, x1, y0, y1 = 1, 0, 0, 1 while n != 0: ...
825a48899f4470cc246034dda9dc07949b967f04
Kortekaasy/pyGPG
/src/pygpg.py
6,061
3.859375
4
import sys, os, os.path import sqlite3 from pathlib import Path from src.NTRUCrypt.EncryptionParameters import Parameters def generateKey(keyid): from src.NTRUCrypt.NTRUCrypt import NTRUCrypt c = conn.cursor() keytable = c.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='keys';") ...
de343b0b1137bb943281e6ec763f08f3f146a553
Bozo-max/dcdl
/renardo.py
4,254
3.765625
4
from copy import deepcopy from numpy import abs from time import time def main(): nums = [] print() print() print("==========") for i in range(6): nums.append(int(input('Nombre %d? '%(i+1)))) print("==========") obj = int(input('Nombre cible ?')) print("==========") pri...
90277004d907b5f53eb7e33a28e0197f212ef5b2
mow09/movement
/motion.py
8,304
4.09375
4
# from objects.positions import Point1D # # # class motion1D(Point1D): # """Moving object in 1D.""" # # def __init__(self, ): import time from math import pi # , tan, sin import turtle def get_rad_list(n): return [(2*pi*i-2*pi)/n for i in range(1, n+1)] def get_rad_step(n): return (2*pi)/n def r...
3b4134321d4318e16600e09cad07ba1124566728
apayol/X-Serv-13.6-Calculadora
/calculadora.py
830
3.625
4
#!/usr/bin/python3 # ADRIÁN PAYOL MONTERO import sys if len(sys.argv) != 4: # han de ser 4 argumentos sys.exit("uso: python3 calculadora.py función operando1 operando2") _, funcion, op1, op2 = sys.argv # guardo los argumentos try: op1 = float(op1) op2 = float(op2) except ValueError: sys.exit("L...