blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
7a991b0cdf823b9fb912f18709b12884e0ec0852
LaurenceWarne/maplayerpy
/maplayerpy/perlin_layer.py
956
3.515625
4
""" Machinery for creating MapLayers containing Perlin noise. """ from typing import Callable, Tuple from perlin_numpy.perlin2d import generate_perlin_noise_2d, interpolant from .maplayer import BasicLayer, MapLayer def get_perlin_layer( width: int, height: int, res: Tuple[int], tileable: Tuple[bool...
f6fb5a47d321592ab9cc5562d99d849a4420db37
JanieTran/SCHOOL_ProgrammingIoT
/W03/Lecture7/menu.py
1,356
3.5625
4
from database_utils import DatabaseUtils class Menu: def main(self): with DatabaseUtils() as db: db.createPersonTable() self.runMenu() def runMenu(self): while True: print() print("1. List People") print("2. Insert Person") p...
01126ee138f4c3b954fd397bfd01774ad85fb2f2
JanieTran/SCHOOL_ProgrammingIoT
/W01/Lecture3_OOPython-Database-SenseHAT-CRON/05_mult_level.py
259
3.515625
4
class Animal: def eat(self): print ('Eating...') class Dog(Animal): def bark(self): print ('Barking...') class PuppyDog(Dog): def play(self): print ('Playing...') d=PuppyDog() d.eat() d.bark() d.play()
0505b53873a6ce606ccad71b5c070d8a7184e5c4
Isaac2/AZ_BDA_Practica
/trumpAnalyzer.py
564
3.75
4
import pandas import nltk #Natural Language Tokenizer nltk.download('stopwords') import matplotlib.pyplot as pyplot tweets = pandas.read_csv("./datasets/trump_tweets.csv") print(tweets.shape) tokenized = {} tweet_tokenizer = nltk.tokenize.casual.TweetTokenizer() filter_words = ["!", ",", ":", ".", "—", "&", "?", "\'...
8da0b1dd8e0dd6024cff4612ab35a83a3cfc95d2
Gallawander/Small_Python_Programs
/Caesar cipher.py
991
4.3125
4
rot = int(input("Input the key: ")) action = input("Do you want to [e]ncrypt or [d]ecrypt?: ") data = input("Input text: ") if action == "e" or action == "encrypt": text = "" for char in data: char_ord = ord(char) if 32 <= char_ord <= 126: char_ord -= 32 char_o...
64af9cb6529dd9024d79e3843f1eaea79e05049b
kalyan-dev/Python_Projects_01
/demo/examples/cmd_line_args_factors.py
345
3.953125
4
import sys # This function computes the factor of the argument passed def get_factors(x): factors = [] for i in range(1, x + 1): if x % i == 0: factors.append(i) return factors # num = 320 num = int(sys.argv[1]) factors = get_factors(num) print(f"The factors of {...
0c3b7a53b9dec1629b9300a33f84bd417a7e5f24
kalyan-dev/Python_Projects_01
/demo/examples/sort_stings2.py
257
4
4
# Accept names from user until END is given, and display them in sorted order; inputs = [] while True: s = input("Enter a string(enter END to stop)") if s.lower() != "end": inputs.append(s) else: break print(inputs)
2a0ffb39c845e7827d3a841c9f0475f42e8a5838
kalyan-dev/Python_Projects_01
/demo/oop/except_demo2.py
927
4.25
4
# - Accept numbers from user until zero is given and display SUM of the numbers; handle Invalid Numbers; # program should not crash, but should continue; def is_integer(n): try: return float(n).is_integer() except ValueError: return False def is_integer_num(n): if isinstance(...
4afbcf702c11cd5dee480bb13646f88d5090571f
adeshp96/AIProject
/triangle.py
2,260
3.84375
4
def show(): # Import a library of functions called 'pygame' import pygame from math import pi # Initialize the game engine pygame.init() # Define the colors we will use in RGB format BLACK = ( 0, 0, 0) WHITE = (255, 255, 255) BLUE = ( 0, 0, 255) GREEN = ( 0,...
f3977bc72ebe0d9d79c1482208cea62a6b71e1c8
aieml/MLON-Week-05
/3.0 Linear regression for a practical dataset.py
853
3.75
4
import pandas as pd import numpy as np df=pd.read_csv('cardio_dataset.csv') #read the csv into a pandas dataframe #print(df.head[5]) df=df.values #converting the dataframe object into a numpy array #print(df) data=df[:,0:7] target=df[:,7] target=np.reshape(target, (-1,1)) #normalize data,target - u...
6c490d890e02c3c7c47cda25b405657a00fac0f3
Qiangzhongxiao/hadlx
/tuoyuanyuxianbo.py
2,372
3.5
4
# -*- coding: utf-8 -*- from scipy.integrate import * # 引入积分库(全部) from sympy import * # 引入sqrt库 from decimal import * # 引入精度函数库(全部) def K(k): # 定义函数 """lambda定义一个关于t的函数,t不是定值""" return quad(lambda t: 1/sqrt((1-(k*sin(t))**2)), 0, pi/2) def EE(k): return quad(lambda t: sqrt((1-(k*sin(t))**2)), 0, pi...
9b6a117c5d2ae6e591bc31dfd1ba748b84079710
tejaboggula/gocloud
/fact.py
332
4.28125
4
def fact(num): if num == 1: return num else: return num*fact(num-1) num = int(input("enter the number to find the factorial:")) if num<0: print("factorial is not allowed for negative numbers") elif num == 0: print("factorial of the number 0 is 1") else: print("factorial of",num, "is:...
3c8195172f12a2938ac4414572c474101dad9738
Atilhan/forever-young
/tafelmanieren/rocketlaunching.py
484
3.796875
4
#print ('\033[1;32;40m'+"Rocket departing in:..") # from time import sleep # for a in range (1,31): # print (a) # sleep(1) # print ("Prepare for take off ! ") #=======Bovenste code was mijn eerste poging maar het telte af van 1 naar 30 toe, maar het moest anders om #=======Current Code Below=======# print...
92c0b021adccbe1836f3daa2a1970023eb6bd3d2
pintuux/Pintu
/Basic_of_linked_list.py
502
3.765625
4
class node: def __init__(self,data): self.data = data self.next = None def takeinput(): inputnode = [int(i) for i in input().split()] head = None for i in inputnode: node1 = node(i) if head is None: head = node1 curr = head ...
64ca57e47dc2fda105f417432ebb49a1f850ec4d
pintuux/Pintu
/palindrome_linked_list.py
1,176
3.859375
4
class Node: def __init__(self,data): self.data = data self.next = None def create_linked_list(): inputElement = [int(i) for i in input().split()] head = None for i in inputElement: node = Node(i) if head is None: head = node curr = hea...
7195da031e8916ef1cf775d3da9494e21f3571b3
JorgeJurado/TSFC3
/suma.py
173
3.875
4
#Aquí solicito un número entero al usuario numero = int(input("Escribe un número entero: ")) #Aquí imprimo la suma de los n números print(int(numero*(numero+1)/2))
4b5bacce46c70baae37b9c15381583ea22886cf3
Stanley9292/imageProcessingTool
/JPGtoPNGconverter.py
631
3.640625
4
# two arguments, the folder and the new folder that I want to create # ('Pokedex' 'new') import sys import os from PIL import Image # grab first and second argument actualFolder = sys.argv[1] newFolder = sys.argv[2] if not os.path.exists(newFolder): try: os.makedirs(newFolder) except OSError: ...
72cce730f46fa01b7870783789cae79cfcf19a07
FranklyCui/ML_in_action
/logistic_regression.py
13,415
3.5
4
#!/usr/bin/env python # -*- conding:UTF-8 -*- """ logigstic regression Model """ import numpy as np import matplotlib.pyplot as plt # 从文件加载数据,返回样本数据集及类别标签列表 def load_data_set(): """ Des: 从文件加载数据,返回样本数据集及类别标签列表 Args: None Return: data_set --> class_labels --> """ ...
e58938306eb2415072bbe2d37dbffb627f737f04
Schlagoo/sort_algorithms
/algorithms.py
4,126
4.375
4
""" Implementation of different sorting algorithms in Python3 including: InsertionSort, SelectionSort, BubbleSort, MergeSort, QuickSort. Author: https://github.com/Schlagoo Date: 2020/04/20 Python: 3.6.9 """ class SortingAlgorithms: def __init__(self, arr: list): self.arr = arr def insertion_sort(se...
0fa7e809c7f4a8c7b0815a855cbc482abf600a77
dimpy-chhabra/Artificial-Intelligence
/Python_Basics/ques1.py
254
4.34375
4
#Write a program that takes three numbers as input from command line and outputs #the largest among them. #Question 02 import sys s = 0 list = [] for arg in sys.argv[1:]: list.append(int(arg)) #arg1 = sys.argv[1] list.sort() print list[len(list)-1]
836c0d8e6932a938f4d3abab78335bacd9e1f45f
orb1225/learnpython
/str2float_v1.0.py
361
3.5
4
from functools import reduce from sys import argv script,s=argv def str2float(s): str_arr=s.split('.') dic= {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9} def str2int(x,y): return x*10+y return reduce(str2int,map(lambda x:dic[x],str_arr[0]+str_arr[1]))/float(10**len(str_arr[1])) ...
d94baeb89da4bf1f98b30a760ecbe35eebea4d7e
KingdeJosh/Cryptography-for-beginners
/Prime Tests/millers rabin test.py
1,399
4.0625
4
from random import randint def is_probably_prime(n, k=1): d = n - 1 s = 0 ifsetter = 1 print(f"1. We have that n = {n}, k-times: k = {k} and d = {n-1}") print(f"2. We then make an iteration until d is not divisible by 2") while not d % 2: s += 1 d //= 2 for ...
66aa4c4a49c97f75da650dec66e3b427f78cafe7
KingdeJosh/Cryptography-for-beginners
/Public Cryptosystem/Find_pq_from_n_phiN.py
877
3.671875
4
import math n= 221 toitent = 192 print(f"When we have n = {n} and toitent = {toitent}") print("1. We know that n = p * q and toitent = (p-1)(q-1)\n" "2. We then susbsitute to get\n" " toitent =p.q-(p+q)+1 = n-(p+q)+1\n" "3. To get p and q we have that \n" " p+q = n + 1 - toitent") s...
b9c7f156d3be3e95c5fac5767c76ccd9895a9ea9
bknopps/Public_SE_DevNet
/init_challenge.py
1,343
3.5
4
#! Python3 import csv import requests # TOKEN GOES HERE. # LAST FOR 12 hours. # reference this url: https://developer.webex.com/docs/api/v1/memberships/list-memberships # This page will give you access to how to use the membership api and how to get your token. USER_TOKEN = "Bearer XXXXXXXXXXXXXXX" # your token goes...
83a460d0f88674ac4ee2f46c89ffb286a2495d00
Wieschie/nqueens_constraint
/nqueens_constraint.py
1,209
3.84375
4
from constraint import * problem = Problem() board_size = 8 queen_list = range(board_size) # enforce different columns by restricting each queen to only move within 1 column. coord_list = [[(x,y) for y in range(board_size)] for x in range(board_size)] for q,c in zip(queen_list, coord_list): problem.addVariable(...
b08e0bc97509d4ad4a0961af96bd759553efd97d
iam3mer/mTICP472022
/Ciclo I/Unidad 3/fororwhile.py
441
4.09375
4
nombres = ['Andres', 'Derly', 'Edison', 'Edwin', 'Karla'] print('Elementos con While') nElementos = len(nombres) # 5 contador = 0 while contador < nElementos: # 0,1,2,3,4 print(nombres[contador]) contador = contador + 1 print('\nElementos con For') range(nElementos) # [0,1,2,3,4] for contador in range(nElem...
82737a375f3f7cb93ec64203c8b7a0c480a31c1c
iam3mer/mTICP472022
/Ciclo I/Unidad 4/AnyAll.py
914
3.578125
4
# Que pasa? numeros = [345,756,34,0,467,456,-94,63,64,686,543] impares = list(map(lambda num: num%2 != 0, numeros)) #print(impares) #print(all(impares)) #print(any(impares)) def esVerdadero(secuencia): numeros = [] for num in secuencia: if num: numeros.append(True) else: ...
acbbae79ade5944bbd4b83e8a92f98e0a564b7d5
eylultuncel/AI-Search-Algorithms
/maze.py
9,614
3.625
4
import datetime import random import networkx as nx import matplotlib.pyplot as plt import heapq import math from collections import deque def calculate_neighbors(vertex, n): neighbors = [] if vertex % n != 0: neighbors.append(vertex - 1) if vertex % n != n - 1: neighbors.append(vertex + 1...
ce1874c25ef19eebda51b2bc15b7125f7ebb2995
snail15/AlgorithmPractice
/LeetCode/Python/SecondRound/23_mergeKSortedLists.py
852
3.828125
4
def mergeKLists(self, lists: List[ListNode]) -> ListNode: if not lists or len(lists) == 0: return None return self.mergeLists(lists, 0, len(lists) - 1) def mergeLists(self, lists, start, end): if start == end: return lists[start] mid = start (end - start) // 2 left = sel...
87bfb462b2472475eb54b9075d6d213644dabe32
snail15/AlgorithmPractice
/LeetCode/Python/inorderTraversal.py
690
3.5
4
def inorderTraversal(self, root: TreeNode) -> List[int]: res = [] self.helper(root, res) return res def helper(self, root, res): if root is not None: if root.left is not None: self.helper(root.left, res) res.append(root.val) if root.right is not None: ...
e8e83ac29ce59ebb1051bbe6457e3d5bd8ade162
snail15/AlgorithmPractice
/Udacity/BasicAlgorithm/binarySearch.py
1,127
4.3125
4
def binary_search(array, target): '''Write a function that implements the binary search algorithm using iteration args: array: a sorted array of items of the same type target: the element you're searching for returns: int: the index of the target, if found, in the source -1: ...
3e725cae69a005cf798d5d82ebe34e010095fcdc
snail15/AlgorithmPractice
/DailyCoding/Python/Arrays/productofAllOtherElements.py
454
3.71875
4
def productOfAllOtherElements(nums): L = [1 for x in nums] R = [1 for x in nums] ans = [1 for x in nums] L[0] = 1 for i in range(1, len(nums)): L[i] = L[i - 1] * nums[i - 1] R[len(nums) - 1] = 1 for i in range(len(nums) - 2, -1, -1): R[i] = R[i + 1] * nums[i + 1] ...
48edb9390ee5072af8e7e16767917e2dd37140e6
snail15/AlgorithmPractice
/LeetCode/Python/SecondRound/92_reverseLinkedList2.py
589
3.78125
4
def reverseBetween(self, head: ListNode, left: int, right: int) -> ListNode: if not head: return head if left == right: return head prev = None cur = head while left > 1: prev = cur cur = cur.next left -= 1 right -= 1 connection = prev ...
615be3798321168dc2407d6188e824d35ca100c3
snail15/AlgorithmPractice
/LeetCode/Python/permutations.py
607
3.734375
4
class Solution: def permute(self, nums): result = [] temp = [] self.backtrack(nums, result, temp) print(result) return result def backtrack(self, nums, result, temp): if len(temp) == len(nums): # print(temp) result.append(list...
e867ad74a11224e1bdaab40093d37162ffdee6f8
snail15/AlgorithmPractice
/LeetCode/Python/SecondRound/241_differentWaysToAddParentheses.py
647
3.625
4
def diffWaysToCompute(self, expression: str) -> List[int]: res = [] for i in range(len(expression)): c = expression[i] if c in "+-*": left = self.diffWaysToCompute(expression[:i]) right = self.diffWaysToCompute(expression[i + 1:]) for l in left: ...
eb988049722c635c5ae6ce765d3cb474d786575c
snail15/AlgorithmPractice
/LeetCode/Python/climbingStairs.py
726
3.984375
4
# You are climbing a stair case. It takes n steps to reach to the top. # Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? # Note: Given n will be a positive integer. # Example 1: # Input: 2 # Output: 2 # Explanation: There are two ways to climb to the top. # 1. 1 step ...
3e0497b84476442645b9b7ff1c74bfd2a31776a9
veeteeran/holbertonschool-web_back_end
/0x03-caching/0-basic_cache.py
912
3.515625
4
#!/usr/bin/env python3 """BasicCache module""" from base_caching import BaseCaching class BasicCache(BaseCaching): """ Inherits from BaseCaching """ def put(self, key, item): """ Assign key: item to self.cache_data If key or item is None do nothing ...
65e82a4377f6d922df70c04dd68d7c68afef2c80
veeteeran/holbertonschool-web_back_end
/0x03-caching/100-lfu_cache.py
2,258
3.6875
4
#!/usr/bin/env python3 """LFU caching module""" from base_caching import BaseCaching class LFUCache(BaseCaching): """ LFU Caching algorithm """ __LFUDict = {} __bit = 0 def put(self, key, item): """ Assign key: item to self.cache_data If key or item is None...
065ebcd4e86de796e08bd6be4e96689f360b6eab
Arunscape/CMPUT291
/labs/lab6/Iterate_All.py
789
3.859375
4
from bsddb3 import db DB_File = "data.db" database = db.DB() database.set_flags(db.DB_DUP) #declare duplicates allowed before you create the database database.open(DB_File,None, db.DB_HASH, db.DB_CREATE) curs = database.cursor() #Insert key-values including duplicates … database.put(b'key1', "value1") databas...
dae99b43b13add7251e5ed4611f9f6696fe41c34
Hansolomix/List-Data-Structure
/main.py
3,651
4.59375
5
# ''' # Creating List # ''' # # List items are enclosed in square brackets # # Lists are ordered # # Lists are mutable # # Lists elements do not need to be unique # # Elements can be of different data types # # empty lists # List = [] # # list of intergers # list= [ 1,2,3 ] # # list of strings # list = [ "oran...
e877bbc77cf8e9544c5e5015c544f7aeed19409f
kacperlukawski/tensorflow-introduction
/03_Examples/03_ML_Datasets/01_face_recognition.py
4,524
3.609375
4
# This example tries to create a model able to handle face recognition. # The dataset is taken from "CMU Face Images": # http://kdd.ics.uci.edu/databases/faces/faces.html # It contains at least 28 different images for 20 people. Created model # should be able to recognize the name of the person. from helper import prep...
460d75a61550f0ae818f06ad46a9c210fe0d254e
lyderX05/DS-Graph-Algorithms
/python/BubbleSort/bubble_sort_for.py
911
4.34375
4
# Bubble Sort For Loop # @author: Shubham Heda # Email: hedashubham5@gmail.com def main(): print("**NOTE**: Elements should be less then 25 as alogrithm work best on that only") print("Enter Bubble Sort elements sepreated by (',') Comma: ") input_string = input() array = [int(each) for each in input_st...
a3fdb417a8f2824e5c271a09ff974081eb620715
rodneywells01/cmpsc483
/program_sample.py
965
3.65625
4
import substitutor import readin_real import relation_checker_utility import testing def run(verbose): # Validate integrity of data cache. relation_checker_utility.check(verbose) # Ask the user for input and substitute it into one simplified equation simplifiedequation = substitutor.Substitutor().fin...
22b6330b82b1011cad1739b9163e1f206a0bfb78
rodneywells01/cmpsc483
/readin_real.py
6,410
3.890625
4
### THIS IS THE OLD READIN FILE ### test input from the command line instead of using tests written into the code import sys import getopt ### get the options to only come up once all code has been input; until then, just read input code until first blank ### output should be a single string, each line separated ...
1d53b2f05934347b38ac937fa8138b659fd9519b
haalogen/hist_divider
/hist_divide.py
2,707
3.703125
4
""" This is a script for dividing the histogram of Grayscale image into N intervals ("shades of gray"), by the means of integral sums of the histogram. Idea: All intervals should have approximately equal integral sums. """ import sys import numpy as np import matplotlib.pyplot as plt from PIL import Image img_f...
2db313eb1c4cbe69bfb08827efc5b6dad5dfd4ce
kkwietniewski/Python
/hackerrank/day8DictMap copy.py
344
3.859375
4
n = int(input()) phoneBook = {} for i in range(n): name, phoneNumber = input().split() phoneBook[name] = phoneNumber enterName = input() while enterName: if enterName in phoneBook: print('{0}={1}'.format(enterName,phoneBook[enterName])) elif enterName not in phoneBook: print('Not found')...
a6db01b0b21bd604d700e9f48ac3879493f631b7
kkwietniewski/Python
/kursUdemy/6_serching_sequences.py
525
3.71875
4
numList = [2,3,4,5,6,8,9,5,6] name = "arek" #wyszukaj a w name print('a' in name) #true print("Ilosc elementow: ",len(numList)) print("Najwiekszy element: ", max(numList)) print("Najmniejszy element: ", min(numList)) #funkcja list dzieli stringa na tablicę charów charTab = list("metallica") print(charTab,"\n") p...
9f7349e4c4b68a17f696d9fe47c76a9317091329
conor1993/pythonDocs
/practicas/metodos diccionarios/diccionario.py
1,298
3.859375
4
#devuelbe una lista con todas las llaves del diccionario def llaves(): dic = {'1':'ola','2':'io'} yaves = dic.keys() print(yaves) #retorna una lista cobn todos los valores def valores(): dic = {'1':'ola','2':'io'} valoress = dic.values() print(valoress) #devuelbe una lista de tuplas def tuplas(...
8d7a1008bd093182a5ad8437ad6055be8bf6b314
rdiaz21129/python3_for_network_engineers
/ready/windowsMac_to_ciscoMac.py
1,513
4.09375
4
import re # By: Ricardo Diaz # Update: 20171223 # File: windowsMac_to_ciscoMac.py # Python 3.6 # Prompt the user to enter a windows format mac address | D8-FC-93-7B-67-7C | Ricardo Wireless mac address print ("\n" + "===" * 4) userWindowsMacAdd = input("Enter Windows MAC address to convert to a Cisco MAC address fo...
eb1a3b4a62c74a8d53416c6e5a5f48a2ab4c2e67
yaroslavche/python_learn
/1 week/1.12.5.py
1,034
4.15625
4
# Напишите программу, которая получает на вход три целых числа, по одному числу в строке, и выводит на консоль в три # строки сначала максимальное, потом минимальное, после чего оставшееся число. # На ввод могут подаваться и повторяющиеся числа. # Sample Input 1: # 8 # 2 # 14 # Sample Output 1: # 14 # 2 # 8 # Sample In...
208303bdec3be5362ce314eb632da444fed96f2c
yaroslavche/python_learn
/2 week/2.1.11.py
504
4.21875
4
# Напишите программу, которая считывает со стандартного ввода целые числа, по одному числу в строке, и после первого # введенного нуля выводит сумму полученных на вход чисел. # Sample Input 1: # 5 # -3 # 8 # 4 # 0 # Sample Output 1: # 14 # Sample Input 2: # 0 # Sample Output 2: # 0 s = 0 i = int(input()) while i != 0:...
f86c962844036de4cd97aca448e3b59e1fa294c1
yaroslavche/python_learn
/2 week/2.6.8.py
923
3.703125
4
# Напишите программу, которая выводит часть последовательности 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 ... (число повторяется # столько раз, чему равно). На вход программе передаётся неотрицательное целое число n — столько элементов # последовательности должна отобразить программа. На выходе ожидается последовательность чисел, з...
f5cd77591c358dbec25bc14314585e9cd229c06f
No-Way-Jose/utsc-tree-project
/UofTScrape.py
4,590
3.546875
4
import requests import urllib from SQL import * from bs4 import BeautifulSoup def ScrapeUTSC(url): """ Function which will scrape the UTSC course website and store all the needed information into a database """ # Connect to the main page response = requests.get(url) document = BeautifulSoup(re...
8674d8f7e11eae360e63b470b7b2310f7170c5cc
zeusumit/JenkinsProject
/hello.py
1,348
4.40625
4
print('Hello') print("Hello") print() print('This is an example of "Single and double"') print("This is an example of 'Single and double'") print("This is an example of \"Single and double\"") seperator='***'*5 fruit="apple" print(fruit) print(fruit[0]) print(fruit[3]) fruit_len=len(fruit) print(fruit_len) ...
f19cb40a5e8a1eca039f65fe1f96601e6a5cec73
codingclubrvce/ML_Workshop_CC
/matplotlib.py
715
3.59375
4
from matplotlib import pyplot as plt plt.plot([1,2,3],[4,5,1]) plt.show() x = [5,2,7] y = [2,16,4] plt.plot(x,y) plt.show() #Bargraph from matplotlib import pyplot as plt plt.bar([0.25,1.25,2.25],[50,40,70], label="B1",width=.5) plt.bar([.75,1.75,2.75],[80,20,20], label="B2", color='r',width=.5) plt.legend() plt.xl...
f81309928a1891a4947a62cb73a147b177463e78
francomattos/memory-paging-python
/Paging.py
4,994
3.625
4
# The list of program words requested by program wordBank = [10, 11, 104, 170, 73, 309, 185, 245, 246, 434, 458] # Make a class for the paging system because why not class PagingCounter: # Initializes variables for the program def __init__(self, _memSize, _pageSize): self.memSize = _memSize ...
6e75ff6820fd9bb69601af4b6cdc72c3f44ca3b6
dillondesilva/Ronie
/bot_code.py
3,808
3.578125
4
from microbit import * import neopixel import radio ANALOG_MAX = 1023 LIGHT_STATE = True MOTOR_STATE = True radio.on() radio.config(channel=18) # Converting values into a valid int between # 0-1023 for valid analog signals def to_analog(value): global ANALOG_MAX analog_val = int(value * ANALOG_MAX) retu...
929aa885ffb601853b6cbc8d0af7b8b66df58919
effepivi/EGUK-authorship-viz
/src/python/csv2SQLlight.py
9,090
3.890625
4
#!/usr/bin/env python3 import sys import math import pandas as pd import sqlite3 from sqlite3 import Error SQL_CREATE_CONFERENCES_TABLE = """ CREATE TABLE IF NOT EXISTS conferences ( id integer PRIMARY KEY, year integer NOT NULL, ...
991d4eebea421257574792017851c8d0948089a8
nkibbey/word2vecTemporal
/analysis/w2vTools.py
968
4.09375
4
#!/usr/bin/python import psycopg2 import sys import pprint def main(): #Define our connection string conn_string = "host='localhost' dbname='w2vdb' user='pyfun' password='fun'" # print the connection string we will use to connect print "Connecting to database\n ->%s" % (conn_string) # get a connection, if a co...
73d9618599379392ec67c264eff125ea19627767
Dhruvisha100/Work__Assignments
/Heuristics.py
419
3.953125
4
import random print("#---------------#\n|GUESS THE NUMBER|\n#---------------#\n") print("Range of random numbers.\n") start = int(input("start no:")) end = int(input("end no:")) n = random.randint(start,end) print("\n") while True: g = int(input("no:")) if g>n: print("try a lower no. ") ...
aa8a0f6810c2746d0db5ab0bd6e8c03d3dd6ceb8
ache167/lesson003
/03_division.py
830
3.96875
4
# -*- coding: utf-8 -*- # (цикл while) # даны целые положительные числа a и b (a > b) # Определить результат целочисленного деления a на b, с помощью цикла while, # __НЕ__ используя стандартную операцию целочисленного деления (// и %) # Формат вывода: # Целочисленное деление ХХХ на YYY дает ZZZ a, b = 179, 37 temp...
01f481eef5cf6005afb5651f1ee089d3500b428e
d222nguy/DSA
/week6/hw6.py
2,015
3.8125
4
from collections import Counter def getShortestSubstrOfAllChar(S, T): '''get shortest substring of all char. If there are multiple substrings with same length, return the leftmost one. Time Complexity: O(max(N, M)) where N = length of S and M = length of T (in case O(N) < O(M) the time complexity is strictly O...
4e6dac2be8094795716e7abd6866dd5ffc2c177d
Hassan-Shakeri/Face-Smile_Detector
/Smile-detector.py
1,811
3.53125
4
import cv2 #load some pre-trained data on face frontals from opencv #load some pre-trained data on smile from opencv trained_face_data = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') trained_smile_data = cv2.CascadeClassifier('haarcascade_smile.xml') #cpture video from webcame webcam = cv2.Vid...
6d39da94c8634cbbe8f1948d5163c3a83fbfd066
EderVs/hacker-rank
/algorithms/implementation/service_lane.py
236
3.703125
4
""" Service Lane """ n,t = map(int, raw_input().split()) width = raw_input().split() for x in range(t): i,j = map(int, raw_input().split()) vehicle = 3 for y in range(i, j + 1): vehicle = min(int(width[y]), vehicle) print vehicle
d9181d5a66f0b8a86efe112cb1f38e6c649ad749
EderVs/hacker-rank
/algorithms/graph_theory/breadth_first_search_shortest_reach.py
1,966
3.890625
4
""" Breadth First Search: Shortest Reach """ class Node: def __init__(self, element, level=-1): self.element = element self.neighbors = set() self.level = level def add_neighbor(self, neighbor): self.neighbors.add(neighbor) def __repr__(self): return str(self....
807ebac26abb25e82b6cc5d25dfa0fcb57265363
EderVs/hacker-rank
/30_days_of_code/day_23.py
1,406
3.71875
4
import sys class Node: def __init__(self,data): self.right=self.left=None self.data = data class Solution: def insert(self,root,data): if root==None: return Node(data) else: if data<=root.data: cur=self.insert(root.left,data) ...
33553f9506dc46c9c05101074116c5254af7d0e9
EderVs/hacker-rank
/30_days_of_code/day_8.py
311
4.125
4
""" Day 8: Dictionaries and Maps! """ n = input() phones_dict = {} for i in range(n): name = raw_input() phone = raw_input() phones_dict[name] = phone for i in range(n): name = raw_input() phone = phones_dict.get(name, "Not found") if phone != "Not found": print name + "=" + phone else: print phone
6784ec88c6088dfcd462a124bc657be9a4c51c3c
asmitaborude/21-Days-Programming-Challenge-ACES
/generator.py
1,177
4.34375
4
# A simple generator function def my_gen(): n = 1 print('This is printed first') # Generator function contains yield statements yield n n += 1 print('This is printed second') yield n n += 1 print('This is printed at last') yield n # Using for loop for item in...
46a7b9c9a436f4620dac591ed193a09c9b164478
asmitaborude/21-Days-Programming-Challenge-ACES
/python_set.py
2,244
4.65625
5
# Different types of sets in Python # set of integers my_set = {1, 2, 3} print(my_set) # set of mixed datatypes my_set = {1.0, "Hello", (1, 2, 3)} print(my_set) # set cannot have duplicates # Output: {1, 2, 3, 4} my_set = {1, 2, 3, 4, 3, 2} print(my_set) # we can make set from a list # Output: {1, 2, ...
1a87238ebb8b333148d1c2b4b094370f21fd230b
asmitaborude/21-Days-Programming-Challenge-ACES
/listsort.py
677
4.4375
4
#python list sort () #example 1:Sort a given list # vowels list vowels = ['e', 'a', 'u', 'o', 'i'] # sort the vowels vowels.sort() # print vowels print('Sorted list:', vowels) #Example 2: Sort the list in Descending order # vowels list vowels = ['e', 'a', 'u', 'o', 'i'] # sort the vowels vowels.sort...
6346a452b77b895e2e686c5846553687459798ca
asmitaborude/21-Days-Programming-Challenge-ACES
/dictionary.py
2,840
4.375
4
#Creating Python Dictionary # empty dictionary my_dict = {} # dictionary with integer keys my_dict = {1: 'apple', 2: 'ball'} # dictionary with mixed keys my_dict = {'name': 'John', 1: [2, 4, 3]} # using dict() my_dict = dict({1:'apple', 2:'ball'}) # from sequence having each item as a pair my_dict = d...
21cfa8b9d6ac84ac69fc918fd051d435761c4e1d
smeissa2019/Python-Work
/madlibs.py
334
3.5625
4
#%% import random y = 1 z=[] verbs = ["Jump","plays","run"] adj =["beautiful", "amazing","pretty"] while y >= 1: if len(z) == 0 : sentence = print("yes " + random.choice(adj) + " cats " + random.choice(verbs)) sentence.append(z) else: len(z) == 10: sentence = print("STOP") sentence.append(z) exi...
47aaf63216e1ec638a15e367002a05757115f486
jhonasiv/rl-algorithms
/src/rlalgs/utils/functions.py
536
3.640625
4
import math def constant_decay_function(variable, rate): result = variable * rate return result def exponential_function(a, x, k, b, exp): """ Exponential function where y = a * e^(-k * (x / b)^exp) """ result = a * math.exp(-k * (x / b) ** exp) return result def casted_ex...
4251f4947d792d20ea20f870c9603886e1b77703
sarahdorich/data-pipelines
/common/util/DateTimeMethods.py
3,074
4.375
4
#!/usr/bin/python """ Helper methods for manipulating dates, times and datetimes """ import datetime def get_curr_date_str(date_format="%Y-%m-%d"): """ Get the current date as a string Returns: date_str: (str) current date """ date_str = datetime.date.today().strftime(date_format) retu...
4d8330c764402d59e5d37990c90adddc1c49fa2e
sarahdorich/data-pipelines
/common/util/OSHelpers.py
2,463
3.703125
4
#!/usr/bin/python """ Helpers for operating system functions Contains methods to get directory paths and other operating system functions. """ import os from os.path import expanduser from sys import platform def get_user_home_dir(): """ Get user's home directory Returns the user's home directory. A...
4357dbcb6514fcee1cffee063b8c428099fde8d5
angelo-bento/estudo-dirigido
/patinet.py
220
3.703125
4
time = int( input ('quanto tempo de uso?')) time_ex = int (time - 10 / (5 * 0.2) ) if time <= 10: print("o valor a ser pago é de R$5,00") elif time > 10: print("o valor a ser pago é de:", 5 + time_ex)
1aa0d9c1f2fb80624e2d954ecbe203e8700db010
dkodotcom/tinker
/range_sort.py
938
3.96875
4
# partial functions from functools import partial def func(u,v,w,x): return u*4 + v*3 + w*2 + x p = partial(func,5,6,7) print(p(8)) # (5*4)+(6*3)+(7*2)+8 = 60 #range() function my_list = ['one', 'two', 'three', 'four', 'five'] my_list_len = len(my_list) for i in range(0, my_list_len): print(my_list[i]) # w...
f6e0028e7494a12f7b1074b71d397be98a8717d1
venessaliu1031/Data-structure-and-algorithm
/2. data structure/assignments/week4_binary_search_trees/find_pattern (1).py
1,117
3.5
4
# coding: utf-8 # In[34]: # python3 def read_input(): return (input().rstrip(), input().rstrip()) def print_occurrences(output): print(' '.join(map(str, output))) def pre_hash(text, P, p, x): T = len(text) S = text[T-P:] H = [0]*(T-P+1) H[T-P] = poly_hash(S, p, x) y = 1 for i ...
2498c6484f6ffc45f55d86d28de3dbcedcd44b77
venessaliu1031/Data-structure-and-algorithm
/1. algorithm toolbox/assignments/week2_algorithmic_warmup/my answers/Fibonacci number.py
168
3.8125
4
# coding: utf-8 # In[10]: #Fibonacci number a = int(input()) a1 = 0 a2 = 1 n = 0 i = 0 while(i < a-1): n = a1 + a2 a1 = a2 a2 = n i += 1 print(n)
7e51e69f780afe7149e9e2a8b3179c10ef27d254
venessaliu1031/Data-structure-and-algorithm
/2. data structure/assignments/week1_basic_data_structures/majority (2).py
1,469
3.625
4
# coding: utf-8 # In[40]: # Uses python3 import sys def get_majority_element(a, lo, hi): #if left == right: # return -1 #if left + 1 == right: # return a[left] if len(a) == 1: return a[0] if lo == hi: return -1 if lo+1 == hi: return a[lo] # recurse on ...
d3f3c62467f05f78b4fab31052c2de257d2d327f
chihuahua/egg-eating-sentiment-cfeelit-classifier
/providers/AfinnProvider.py
949
3.53125
4
# # The provider for the Afinn lexicon. Provides a dictionary # mapping from stemmed word -> 0, 1, 2 (NEG, POS, NEU) # @author Dan # Oct. 11, 2013 # import Provider class AfinnProvider(Provider.Provider): def __init__(self): ''' Creates a new provider for Subjectivity ''' Provider.Provider.__init__...
b44f99acf2ae8f902543f1bec5df4b59d764be4f
rmit-s3607407-Tony-Huang/ai1901-connectfour
/connectfour/agents/monte_carlo.py
3,068
3.671875
4
import copy import math import random class Node: """ Data structure to keep track of our search """ def __init__(self, state, parent=None): self.visits = 1 self.reward = 0.0 self.state = state self.children = [] self.children_move = [] self.parent = pa...
f1e73874c9d09a51aa7b9c4a5890fe3cb34f5622
parth-sp02911/My-Projects
/Parth Patel J2 2019 problem.py
1,161
4.125
4
#Parth Patel #797708 #ICS4UOA #J2 problem 2019 - Time to Decompress #Mr.Veera #September 6 2019 num_of_lines = int(input("Enter the number of lines: ")) #asks the user how many lines they want and turns that into an integer output_list = [] #creates a list which will hold the values of the message th...
c0ce66694cb465c7dfea14c54b0e876461eb084a
Ahmmed44/coursera-adswp
/Course5/Week3/Assignment_3.py
4,444
4.28125
4
import networkx as nx path = ('C:/Users/manma/Google Drive/GitHub/' 'Coursera-Applied-Data-Science-with-Python/Course5/Week3/') G1 = nx.read_gml(path + 'friendships.gml') def answer_one(): """ Find the degree centrality, closeness centrality, and normalized betweeness centrality (excluding endpoin...
b20b082c9401fdf1d6322f30b0d9abb4c721582b
Ahmmed44/coursera-adswp
/Course3/Week3/Assignment+3.py
7,835
4.28125
4
# coding: utf-8 # --- # # _You are currently looking at **version 1.2** of this notebook. To download notebooks and datafiles, as well as get help on Jupyter notebooks in the Coursera platform, visit the [Jupyter Notebook FAQ](https://www.coursera.org/learn/python-machine-learning/resources/bANLa) course resource._ ...
b9db06ba03fa3d7a3d5982ff10a7208d996ba4a1
spaceguy01/PythonProjects
/Tkinterkg.py
1,241
4
4
""" Using Tkinter to create a kg -> grams, US pounds,and ounces calculator """ from tkinter import * """ Open a Tkinter GUI window """ window = Tk() """ Defining Calculator program """ def kg_to(): try: grams = float(e1_value.get()) * 1000 pounds = float(e1_value.get()) * 2.20462 ounce...
77de51fd88642bda186a95dded225cace555e92e
spaceguy01/PythonProjects
/Excelopenpyxl.py
1,269
3.59375
4
""" Working with Excel Files using openpyxl """ import openpyxl """WORKING WITH ALREADY EXISTING EXCEL FILE """ """ Open excel file as workbook in same directory """ worksheet = openpyxl.load_workbook('example.xlsx') """ Getting sheetnames of workbook and set sheets to variable""" print(worksheet.sheetnames) sheet1...
4783c951d8caaf9c5c43fb57694cfb8d60d466b7
marcinosypka/learn-python-the-hard-way
/ex30.py
1,691
4.125
4
#this line assigns int value to people variable people = 30 #this line assigns int value to cars variable cars = 30 #this line assigns int value to trucks variable trucks = 30 #this line starts compound statemet, if statemets executes suite below if satement after if is true if cars > people: #this line belongs to sui...
94e322bcb05ff775e87bb66b2f5854e9866abfe0
haugstve/plotly-and-dash-with-udemy
/1-02E-ScatterplotExercises/Ex1-Scatterplot.py
978
3.640625
4
####### # Objective: Create a scatterplot of 1000 random data points. # x-axis values should come from a normal distribution using # np.random.randn(1000) # y-axis values should come from a uniform distribution over [0,1) using # np.random.rand(1000) ###### # Perform imports here: import numpy as np import pandas as p...
16a475d3b83ea0a1f8daf415e04210fcedda79a2
PaveLLodiagin/homework
/5.py
1,313
3.640625
4
'''Спортсмен занимается ежедневными пробежками. В первый день его результат составил a километров. Каждый день спортсмен увеличивал результат на 10 % относительно предыдущего. Требуется определить номер дня, на который общий результат спортсмена составить не менее b километров. Программа должна принимать значения парам...
e85ae23a40de086dbe652ff142643e4ada28546f
Ccook4Umass/Lab2
/VC_Encrypt.py
721
3.65625
4
#!/usr/bin/env python import string mykey="ECE" data = open("test.txt", "r") input_mes = data.readline() source = string.ascii_uppercase shift = 23 matrix = [ source[(i + shift) % 26] for i in range(len(source)) ] def coder(thistext): ciphertext = [] control = 0 for x,i in enumerate(input_mes.upper()): ...
1b59b6f971ce37b62f3ed7eb6cc5d94ed8b2df44
felcygrace/fy-py
/currency.py
852
4.21875
4
def convert_currency(amount_needed_inr,current_currency_name): current_currency_amount=0 Euro=0.01417 British_Pound=0.0100 Australian_Dollar=0.02140 Canadian_Dollar=0.02027 if current_currency_name=="Euro": current_currency_amount=amount_needed_inr*Euro elif current_currency_name=="B...
1612734eb81f25fe55018dcef2bb15dfe58c33a2
mbaraldi/Coppie
/lista_persone.py
1,671
3.609375
4
from persona import Persona from archiviatore import Archiviatore class ListaPersone(object): """ gestisce una lista di oggetti Persona, caricandoli e salvandoli su file """ def __init__(self): self.lista = [] #lista di persone self.archivio = Archiviatore() self.npersone = 0 def Nuovo(self, nome, cognome):...
61b6c8f82b21b8c22200af21229debd4a1a76934
majsylw/Python-3.x-examples
/150321-strings/zad4-cesar.py
1,320
3.65625
4
import string # dla caesar_encode3 def caesar_encode(message, key): res = [] for c in message: if 'A' <= c <= 'Z': idx = ord(c) - ord('A') idx = (idx + key) % 26 res.append(chr(ord('A') + idx)) else: res.append(c) return "".join(res) def ca...
461002afa84528d9fdc4f77fbfa4b57db41142d2
majsylw/Python-3.x-examples
/170521-lambda-expresions,list-comprehension,classes/excercises.py
1,663
3.859375
4
# lista składana (ang. list comprehension), podobnie wyglądaj set comprehension i tuple comprehension liczby = [1, 2, 3, 4, 5] # jeśli liczba jest parzysta wypełniamy listę 2 potęgami, inaczej 1 nowe_liczby = [] for i in liczby: if i % 2 == 0: nowe_liczby.append(i ** 2) else: nowe_liczby.appen...
9310f1a6233e5dde2142749ed9dd41f64af46eba
bohdi2/euler
/202/elegant.py
2,332
4.03125
4
#!/usr/bin/env python3 def gcd(x, y): while y != 0: (x, y) = (y, x % y) return x def isquareroot(n): return int(n ** 0.5) + 1 # Check if n is divisible by a square . def is_divisible_by_square(n): i = 2 while i ** 2 <= n: if n % (i ** 2) == 0: return 1 i += ...
010249ce07999afdd314a34f02eb8756c5bdbc48
bohdi2/euler
/1/problem1.py
1,709
3.515625
4
#!/usr/bin/env python3 import sys from common.timing import elapsed @elapsed def sum1(limit, d1, d2): sum = 0 for n in range(1, limit): if n % d1 == 0 or n % d2 == 0: sum += n return sum @elapsed def sum2(limit, d1, d2): return sum([n for n in range(1, limit) if n % d1 == 0 ...
c5d852ead39ef70ee91f26778f4a7874e38466cf
bohdi2/euler
/208/directions.py
792
4.125
4
#!/usr/bin/env python3 import collections import itertools from math import factorial import sys def choose(n, k): return factorial(n) // (factorial(k) * factorial(n-k)) def all_choices(n, step): return sum([choose(n, k) for k in range(0, n+1, step)]) def main(args): f = factorial expected = {'1'...
be1046d9aae2f8671503696ad63b836edba0b6ae
adesamthomas/python-challenge_hw
/PyBoll/main.py
1,987
3.90625
4
#PyBoll import os import csv file = 'election_data.csv' with open(file, encoding='utf-8') as csvfile: csvreader = csv.DictReader(csvfile) #declaring variables total_votes = 0 dict_candidates = {} #dictionary for candidate votes winning_vote_count = 0 csv_header = next(csvreader) for r...
6d75c8ac5465accd45c9edb6f486c17d75cc7594
MohamedEmad1998/OCR
/OCR CODE.py
1,537
3.65625
4
# import needed libraries import cv2 as my_cv import pytesseract as my_pt import os # get the image to work on img=my_cv.imread("textbook_image_3.PNG") # i had some problems with tesseract installation # so i used this line as an explicit reference to tesseract path in my PC my_pt.pytesseract.tesseract_cmd = ...