blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
14d2b15bfb28a34f05f1187d7125b41b7e4a149a | saishmohare/Loan_Predictor | /DecisionTreeLibrary.py | 820 | 3.5625 | 4 | import pandas as pd
import numpy as np
from DataLoader import DataLoader
from DataLoader import TestDataLoader
from sklearn import tree
'''Load the Dataset'''
[X,Y,df] = DataLoader.getDataSet()
'''Classify using the scikit Decision Tree Classifier'''
clf = tree.DecisionTreeClassifier()
clf = clf.fit(X,Y)
'''Feed the... |
68fdd39478c29f0ea9480dfd73bce6a60362099a | dReXntriK/py_FP_Encrypt | /py_Encrypt_Decrypt.py | 1,154 | 3.765625 | 4 | import pyffx
#Copyright Rajath Shetty
#enter the 'e = pyffx.String(b'secret-key', alphabet='abc', length=6)' here
##################################
"""Encryption Function"""
##################################
def encrypt(test):
to_list = list(test) #Sends each character of the string to a list(array)
li... |
b318e7e1032633ca4a18c238664d80b954decfc1 | marijamilanovic/Search-Engine | /structs/Trie.py | 2,573 | 3.6875 | 4 |
class TrieNode(object):
def __init__(self, char=str):
self.char = char
self.children = [] # lista reci
self.leaf = False # da l je poslednji
self.counter = 0
self.recnik = {}
def add(root, word, htm... |
24f2b69109f02640ad967a40d20b724d7abe43e7 | bkn/needlebase | /test.py | 10,327 | 3.828125 | 4 | #!/usr/bin/env python
# coding: utf-8
import os
import os.path
import getpass
import urllib
import urllib2
import simplejson
def get_password(create_password_file=False):
passwordfile = ".password.txt"
USERNAME, PASSWORD = "", ""
if not os.path.isfile(passwordfile):
print "A username and pass... |
a8883c34954cb4f651b17ff9beafc75ffdf1f3ec | cmoresid/yeg-traffic-scrape | /yeg_traffic_downloader/downloader.py | 3,670 | 3.515625 | 4 | """Utility class to download traffic data spreadsheets
from City of Edmonton's Google Drive account.
"""
from pydrive.drive import GoogleDrive
from pydrive.auth import GoogleAuth
from pydrive.files import ApiRequestError, FileNotDownloadableError
import tempfile
import os
class TrafficSpreadsheetDownloader(object)... |
7bcc79f031d33e4f670be33c322412bf80f0db69 | MarinaDaumas/mat_comp | /atividades assincronas/AA2.py | 5,715 | 3.890625 | 4 | def test():
result_1 = 0.3-0.2-0.1
result_2 = 0.3-(0.2+0.1)
return result_1, result_2
class TooComplexCalculator():
def __init__(self, num_1, num_2):
self.num_1 = num_1
self.num_2 = num_2
def is_zero(self):
"""
Procura valores iguais a zero nos vetores 1 e 2... |
1ef484520312dbe0860b5a22eda25e93a0c64481 | MarinaDaumas/mat_comp | /atividades assincronas/AA6_1.py | 2,895 | 3.65625 | 4 | # Decomposição LU
# Feito em Grupo com Júlia Xexéo e Ney Guindane.
def id_matrix(size):
m = []
for i in range(size):
temp = []
for j in range(size):
temp.append(0)
m.append(temp)
m[i][i] = 1
return m
def zero_matrix(size):
m = []
for i in range(size... |
2e0ef4eb90720ee378bdb3e9b79d387f5bb6f1c6 | katherinesullivan/CMI | /practica0/ej7.py | 391 | 3.59375 | 4 | def es_primo(a):
if (a < 2):
return 0
else:
x = 2
while (x*x <= a):
if (a%x == 0):
return 0
x+=1
return 1
def nros_primos_hasta (n):
for i in range(1, n):
if (es_primo(i) == 1):
print(i)
return 0
nros_primos_hasta(10000)
print(es_primo(169))
# https://www.... |
36203004c32b4dfbe509a3d02002164612bf517b | katherinesullivan/CMI | /practica0/ej6.py | 476 | 3.75 | 4 | # la función toma dos nros y devuelve la cantidad de nros que son múltiplos del primero
# y menores que el segundo
def dos_numeros_for(a, b):
cant = 0
if (a >= b):
return 0
for i in range(1, b+1):
if (a*i > b):
return cant
else:
cant+=1
return cant
def dos_numeros_whil... |
138b87533a8e70b1a4fa68452a326ab030ea45a0 | nikhilkajrekar31/Python-Programming | /Homework_1_Kajrekar/Kajrekar_HW1_Ques_7.py | 872 | 3.734375 | 4 | # Name: Nikhil Kajrekar
# UTA ID: 1001552488
vegetarian = "No"
vegan = "No"
gluten_free = "No"
vegetarian_ques = input("Is anyone in your party a vegetarian? ")
vegan_ques = input("Is anyone in your party a vegan? ")
gluten_free_ques = input("Is anyone in your party gluten free? ")
if vegetarian_ques == "... |
1fb2143be7d47e445d2154aea0a590ad4e5b17e8 | nikhilkajrekar31/Python-Programming | /Homework_3_Kajrekar/Kajrekar_HW3.py | 3,095 | 4.03125 | 4 | import sqlite3
conn = sqlite3.connect('players_Data.db')
conn.execute(''' CREATE TABLE if not exists Player( name TEXT NOT NULL, wins INT NOT NULL, losses INT NOT NULL, ties INT NOT NULL)''')
conn.commit()
def main():
command = ""
print("COMMAND MENU\nview - View players\nadd - Add a player\ndel - Delet... |
cf92e44bd24e6cfdc2e18619ce11dba184d87e1b | aslehv/digifab | /prosjektfiler/Oppgave 4 - Rpi/oving4.py | 915 | 3.5 | 4 | #!/usr/bin/python
from gpiozero import LED, Button
from time import sleep
from signal import pause
import os
import threading
wait = 8
led = LED(4)
btn = Button(21)
btnspeedup = Button(16)
btnspeeddown = Button(20)
def take_pic():
led.on()
print("taking pic")
os.system('fswebcam --no-banner /var/www/html/... |
79ff4446a276fcb2261e5cfe6d1c046c0d593fc5 | lizkarimi/day-2 | /data type latest.py | 392 | 3.796875 | 4 | def data_type(n):
if type(n)==int:
if n>100:
return n,"more than 100"
elif n<100:
return n,"less than 100"
else:
return n,"equal to 100"
elif type(n) == str:
return len(n)
elif n==None:
return "no value"
elif type(n)==bool:
return n
elif type(n)==list:
try:
return n[2]
except Exception... |
6b99234a2f2c0ab4bb7b4c6addea7b7e763206f6 | shivanshsen7/goeduhub | /assignment-1/assignment-1-q6.py | 413 | 3.9375 | 4 | """
Write a Python program to print alphabet pattern 'A'
"""
my_str=""
for row in range(0,7):
for col in range(0,7):
cnd1 = ((col == 1 or col == 5) and row != 0)
cnd2 = (row == 0 or row == 3)
cnd3 = (col > 1 and col < 5)
if (cnd1 or (cnd2 and cnd3)):
my_str=my_s... |
304e38dc1d8482a6a92410239c5636b6268db14d | shivanshsen7/goeduhub | /assignment-1/assignment-1-q2.py | 293 | 3.953125 | 4 | """
Write a Python program to construct the following pattern,
using a nested for loop.
*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*
"""
# i = int(input().rstrip())
for x in range(1,i+1):
print(x*"*")
for x in range(i-1,0,-1):
print(x*"*")
|
c58ba2fdf902276ab65708025656e5dde8b1b4f1 | sHalnes/Algorithms_And_DataStructs | /selection_sort.py | 558 | 3.703125 | 4 | from random import randint
from linked_list_1 import *
def unsorted_list(n):
unsorted = LinkedList()
for i in range(n):
unsorted.add_node(randint(1, 100))
return unsorted
def selection_sort(unsorted_l):
sorted_list = LinkedList()
for i in range(unsorted_l.length):
min = unsorted_l.... |
4cd7a4c3d62d42572e5c71795a37bcd15133e6c4 | sHalnes/Algorithms_And_DataStructs | /stack.py | 488 | 3.78125 | 4 | # abstract data types - ADT
# stack is ADT.
class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def is_empty(self):
return (self.items == [])
# stack = Stack()
# stack.push('cow')
# s... |
93f2c4f2c62cf0c09b6b904951aaf5d8149022a7 | sHalnes/Algorithms_And_DataStructs | /insertion_sort_arrays.py | 272 | 3.828125 | 4 | from random import randint
# O(N^2)
def insertion_sort(l):
for i in range(len(l)-1):
for j in range(i, len(l)):
if l[j] < l[i]:
l[j], l[i] = l[i], l[j]
return l
l = [randint(0,100) for x in range(20)]
print(insertion_sort(l)) |
f3e8f4c5ac94c76398e98cfa935c7e2186f7511e | almacro/snippets | /python/turtle/blue_flowers.py | 484 | 3.671875 | 4 | from turtle import *
import random
for n in range(60):
penup()
goto(random.randint(-400,400), random.randint(-400,400))
pendown()
red_amount = random.randint(0,30) / 100.0
blue_amount = random.randint(50,100) / 100.0
green_amount = random.randint(0,30) / 100.0
pencolor((red_amount, green_a... |
669ba267370c15d456ed4affd079948afc40c2b2 | almacro/snippets | /python/libvirt/basic/using_close_with_refcount.py | 979 | 3.5 | 4 | '''
Example 4. Uaing close with additional references
This example demonstrates how connection reference counting works.
The reference count is explicitly increased by an initial call to
open(), openAuth(), and similar calls. It is also temporarily increased
by other methods that depend on the keeping the connection ... |
bb42454688bd28c53b564272d073cb9fd31384a3 | almacro/snippets | /python/learning/block_crypto/utility/hash_util.py | 610 | 3.703125 | 4 | """
This module contains helper functions for generating cryptographic hashes.
"""
import hashlib
import json
def hash_string_256(string):
"""Generates a SHA-256 hash digest of the input"""
return hashlib.sha256(string).hexdigest()
def hash_block(block):
"""Combine the block elements into a single hash ... |
8e16aebf403570874b7c817c1c79ca1a900cd46e | vale314/Seminario-Algoritmia | /Actividad 9/grafo.py | 832 | 3.703125 | 4 | import pprint
grafo = dict() #{}
while True:
print('1 Crear Conexión')
print('2 Mostrar Grafo')
print('0 Salir')
op = input(': ')
if op == '1':
origen= input('origen: ').upper()
destino = input('Destino: ').upper()
peso = int(input('Peso: '))
if origen in grafo:
... |
4b807753b3de0b67bc75c90f6064c452f0e09346 | JairBernal/Practica_de-_Python | /Calendario.py | 301 | 3.78125 | 4 | import calendar
año = int(input("Ingrese el año "))
print("Calendario de {años}")
print(calendar.calendar(año))
#Para imprimir un mes
y = 2000
m = 2
print(calendar.month(y, m))
#Ingresar el mes que deseamos solicitar
y = int(input("Año: "))
m = int(input("Mes: "))
print(calendar.month(y, m)) |
fc501a2ef88d55d54505fb4e0abbc89520f0bd61 | JairBernal/Practica_de-_Python | /vocales.py | 241 | 4.09375 | 4 | """Hallar vocal"""
vocal = input("Escribe una letra: ").lower()
if vocal == 'a' or vocal == 'e' or vocal == 'i' or vocal == 'o' or vocal == 'u':
print(f"La letra {vocal} es una vocal")
else:
print (f"La letra es una consonante")
|
75e611edaa240fb88a7a7f58804d333834098673 | JairBernal/Practica_de-_Python | /Funciones/Funciones.4.py | 535 | 4.125 | 4 | """ Realiza una funcions llamada area_rectangulo (base, altura)que devuelva el area
del rectangulo a partir de una base y una altura. Calcula el área de un rectangulo
de 15 de base y 10 de altura: """
base = int(input("Base: "))
altura = int(input("Altura: "))
def area (x, y):
return x * y
resultado = area (base... |
a01cc813551c3e4f650a3fabd9fe071f90828057 | Theo-Ing/completed-projects | /theoi_labb-1/kubsumma.py | 277 | 4.03125 | 4 | while(1 < 2): #Vi kommer låta loopen gå tills man tvingar programmet att stängas. 1<2 är alltid sant
a = int(input("Heltal a : "))
b = int(input("Heltal b : "))
print("a^3 + b^3 =", a**3 + b**3)
print() #Skriver en blank rad för att separera varje omgång
|
0567316b959f9e124e825afbc3b858da6925c8bc | Theo-Ing/completed-projects | /ÖvningarFörTentan/rekursion.py | 4,655 | 3.578125 | 4 | import math
import random
import pygame
from pygame import gfxdraw
pygame.init()
SIZE = 700
def lnFact(n, counter = 0):
if counter > 0:
if n < 0:
print("Value given is less than 0, calculating for absolute value:")
n -= 1
if n == 0: return 1
if n == 1: return 1
... |
cb2957e3ead46027da02c5cff7c9f86f5e071cf8 | Theo-Ing/completed-projects | /theoi_labb-2/extra.py | 3,244 | 3.703125 | 4 | from tkinter import *
import math
SIZE = int(input("Canvas size: "))
#Doesn't require user input, this is used in createFrame()
def createRectForFrame(img, a, b, color):
for y in range(min(a[1], b[1]), max(a[1], b[1])):
for x in range(min(a[0], b[0]), max(a[0], b[0])):
img.put(color, (x, y))
... |
b343a1164b77285c9fd832adee520598f4190b51 | NeoChithu/python_tictactoe | /tic.py | 6,365 | 4.15625 | 4 | import random
import sys
sore_o = 0
sore_x = 0
computer_score = 0
user_score = 0
def drawBoard(board):
# This function prints out the board that it was passed.
# "board" is a list of 10 strings representing the board (ignore index 0)
print(' | |')
print(' ' + board[7] + ' | ' + board[8] + ' |... |
277a87287aad3d303ba34d26e3a8aff43a84b8ce | xxxmian/CodingTime | /jiuzhang-reinforcement/minwindow.py | 1,229 | 3.546875 | 4 | class Solution:
"""
@param source : A string
@param target: A string
@return: A string denote the minimum window, return "" if there is no such a string
"""
def minWindow(self, source, target):
# write your code here
if not source or not target:
return ""
ta... |
e10949a3057a208549c30e652975a064439bb2ae | xxxmian/CodingTime | /jiuzhang-reinforcement/threeSum_closest.py | 895 | 3.78125 | 4 | class Solution:
"""
@param numbers: Give an array numbers of n integer
@param target: An integer
@return: return the sum of the three integers, the sum closest target.
"""
def threeSumClosest(self, numbers, target):
# write your code here
list.sort(numbers)
diff = float(... |
20977bb02d6679ae14e702463cda6183062a822d | xxxmian/CodingTime | /jiuzhang-reinforcement/validTree.py | 584 | 3.625 | 4 | def validTree(n, edges):
# write your code here
if not edges or len(edges) != n - 1:
return False
def find(uf, a):
while a != uf[a]:
a = uf[a]
return a
def union(uf, a, b):
fa = find(a)
fb = find(b)
if fa != fb:
uf[fa] = fb
u... |
81eddc6568f5e10b0230d177f46654ffed86adf2 | chchwy/leetcode | /leetcode/0151-reverse-words-in-a-string.py | 384 | 3.515625 | 4 | class Solution:
# @param s, a string
# @return a string
def reverseWords(self, s):
s = s.strip()
if not s:
return ''
tokens = s.split()
tokens = tokens[::-1]
tokens2 = []
for t in tokens:
tokens2.append( t )
tokens2.append(... |
c244c2faf8fe9ca41a23e5b7f053d455ef4d4853 | S-samira2020/New-python-code3 | /program1.py | 256 | 3.984375 | 4 | is_hot = False
is_cold = True
if is_hot:
print('it is a hot day')
print('drink plenty of water\n')
elif is_cold:
print('it is a cold day')
print('wear your clothes\n')
else:
print('it is a lovely day')
print('enjoy your day') |
11063a4719a08da2ff86d58d3017cd424fac5edd | DevvinK/lambdata_dspt5 | /test/rectangles_test.py | 627 | 3.703125 | 4 | #
import unittest
# assume this function exists in my_lambdata/rectangles.py
def calc_area(l, w):
"""
Params: l and w are both real positive numbers representing the length and width of a rectangle.
"""
if l <= 0 or w<=0:
raise ValueError
return l * w
class TestRectangles(unittest.Tes... |
75807512894d7f67c8fdd323568e57cb3722e9d1 | michal-kloc/Weather | /weather_app.py | 1,770 | 3.546875 | 4 | import sys
import tkinter as tk
import weather as Weather
w = Weather()
avg_temp = lambda: w.query("SELECT AVG(temp) FROM weather")[0][0]
min_temp = lambda: w.query("SELECT MIN(temp) FROM weather")[0][0]
max_temp = lambda: w.query("SELECT MAX(temp) FROM weather")[0][0]
all_temp = lambda: w.query("SELECT temp FROM we... |
862856660380f1d7de53e4fe2c376711e7739681 | seekpinky/python_fundamental_2 | /03_more_datatypes/2_lists/03_06_product_largest.py | 703 | 4.40625 | 4 | '''
Take in 10 numbers from the user. Place the numbers in a list.
Find the largest number in the list.
Print the results.
CHALLENGE: Calculate the product of all of the numbers in the list.
(you will need to use "looping" - a concept common to list operations
that we haven't looked at yet. See if you can figure it ou... |
25c8073396fe8cbd33b4c86858a7eaabca080176 | seekpinky/python_fundamental_2 | /03_more_datatypes/2_lists/03_10_unique.py | 471 | 4.125 | 4 | '''
Write a script that creates a list of all unique values in a list. For example:
list_ = [1, 2, 6, 55, 2, 'hi', 4, 6, 1, 13]
unique_list = [55, 'hi', 4, 13]
'''
list_ = [1, 2, 6, 55, 2, 'hi', 4, 6, 1, 13]
'''
input_list = input("please enter a list: ")
list_ = input_list.split()
'''
unique_list = []
dup_list = ... |
24966433e4f236fad2180737d6195d9be95e300c | seekpinky/python_fundamental_2 | /06_functions/06_01_tasks.py | 1,154 | 4.15625 | 4 | '''
Write a script that completes the following tasks.
'''
# define a function that determines whether the number is divisible by 4 or 7 and returns a boolean
# define a function that determines whether a number is divisible by both 4 and 7 and returns a boolean
# take in a number from the user between 1 and 1,000... |
46785395c46d9845e4afea8d1254c84e62bc9731 | omegamotor/testowanieOprogramowania | /Zadanie 8 - Liczba pierwsza/Zadanie/dodawanie/dod.py | 672 | 3.625 | 4 |
class dodaj:
def dodaj(self, a, b):
return a+b
class LiczbaPierwsza:
def pierwsza(self, liczba):
if liczba > 1:
for i in range(2, liczba):
if (liczba % i) == 0:
#print(liczba, "to nie jest liczba pierwsza")
return False
... |
28a8eb43c268f4cc0c7e6980dfc8e2572dab46ed | omegamotor/testowanieOprogramowania | /Zadanie 5 - adressy i kręgle/test.py | 805 | 3.8125 | 4 | import unittest
from address_main import format_addresses
class AddressTestCase(unittest.TestCase):
def setUp(self):
self.addresses = ['34-Czerwona', '23-Biala', '85 Pogodna']
def test_address_in_list(self):
first_address = format_addresses(self.addresses)[0]
self.assertEqual(first_ad... |
0e2aae2694b6dd448ad2d56383e4d7e674194314 | Sidd-Shanmuhavel/Python-Practice | /a1.py | 726 | 3.984375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Oct 2 13:53:08 2019
@author: Siddhartha Shanmuhavel (119220393)
"""
# Calculate the e power of any given value
def expo():
# Getting the real number as input from user
a=int(input("Enter a real number :"))
sum = 1
f=1
term=1
# iterating ... |
2161b0e6fa21aa687ccedc3a824ce437bf0fa20f | paul841029/KnowledgeLog | /src/example/example.py | 2,261 | 4.25 | 4 | """
This file illustrates algorithms that can be used with graphs, trees, hierarchies, ...
* which nodes can be reached from another node
* what are the possible paths between 2 nodes
* give me one path between 2 nodes (more efficient)
* what is the shortest path between 2 nodes, given a cost function
... |
083f66129bcd297a876c7edd1cfb7e153e0dd714 | bashrootshell/simple-guess-numbers | /guess-3-improved.py | 1,460 | 4.375 | 4 | #!/usr/bin/env python3
from random import randint
""" v3 - código mais limpo
Jogo de adivinhação com números de 1 a 30.
Máximo de 8 tentativas.
Executa validação de entrada.
PEP8 compliant
“Readability counts."
“Beautiful is better than ugly.”
— The Zen of Python
"""
numero_aleatorio = r... |
e2a0ae6bab4e0bb16dbc324731319afc573b17b3 | lazavgeridis/Deep-Learning-Review | /linear_regr.py | 6,540 | 3.921875 | 4 | import numpy as np
import matplotlib.pyplot as plt
# Load the training dataset
train_features = np.load("train_features.npy")
train_labels = np.load("train_labels.npy").astype("int8")
n_train = train_labels.shape[0]
def visualize_digit(features, label):
# Digits are stored as a vector of 400 pixel values. Here w... |
a88427e86b78f3f9e9b48e56deb940fffa57ee72 | isabellagmz/ECE143HW4 | /bit_strings2.py | 1,726 | 4.09375 | 4 | # Isabella Gomez A15305555
# ECE143 HW4
# Instructions:
# Write a function map_bitstring that takes a list of bitstrings
# (i.e., 0101) and maps each bitstring to 0 if the number of 0s
# in the bitstring strictly exceeds the number of 1s. Otherwise,
# map that bitstring to 1. The output of your function is a
# diction... |
9a6d3f814d8dafc7ac083c72abcc521c0d424c0b | Viswanadhulaswapna/tic-toc-toe | /main.py | 3,739 | 4.09375 | 4 | # This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
#def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
# print(f'Hi, {name}')... |
9f47afdd6c5b3e78001e7f109e1c39b07030d8ff | missasd/python_project | /recursion.py | 113 | 3.59375 | 4 | def countdown(i):
print(i)
if i < 1:
return
else:
countdown(i-1)
i = 10
countdown(i) |
cd96ad5fee340ed6d64f61a545f2c903a25c8368 | Donny97/CoffeeMachine | /coffee_machine/tasks/beverage_maker.py | 1,083 | 3.84375 | 4 | """This class represents an atomic task to make any Beverage. Uses Runnable interface to support multithreading."""
from threading import Thread
from coffee_machine.stock.stock_manager import StockManager
from coffee_machine.entities.beverage import Beverage
class BeverageMakerTask(Thread):
"""Beverage Maker Ta... |
492579ecdc22478cdd2f46fecd177b2b639f1f5d | alextanhongpin/mastering-machine-learning-with-scikit-learn | /02-linear-regression/04-regularization.py | 815 | 3.65625 | 4 | import pandas as pd
import matplotlib.pylab as plt
from sklearn.linear_model import LinearRegression
from sklearn.cross_validation import train_test_split
from sklearn.cross_validation import cross_val_score
df = pd.read_csv('data/winequality-red.csv', sep=';')
print df.describe()
# plt.scatter(df['alcohol'], df['qu... |
2af8e0c7abe36d9113ba0569bb2c36230eaa5bc7 | Volodymyr-SV/Python_367 | /ClassWork4.py | 2,231 | 4.0625 | 4 | def rectangle ():
a = float(input("a= "))
b = float(input("b= "))
print("area=", a*b)
def trangle ():
a = float(input("a= "))
h = float(input("h= "))
print("area=", 0.5*a*h)
def circle ():
r = float(input("n= "))
print("area=", 3.14*r**2)
... |
36f7ed993e917482348c747f5fa054c17a416660 | mikegwyn17/ANN | /ANN/NeuralNet.py | 4,180 | 3.609375 | 4 | from __future__ import print_function
import numpy as np # used for matrix multiplication and math operations
import pdb
# A class representing a multi-layered feed-forward back-propagation artificial neural network
class NeuralNet(object):
# initialize the Hyperparameters
def __init__(self, hidden_layers=[32... |
a98204623b53d93373fcbf8616f786eb76339a8c | anshuljindal876/Sorting-Algorithms | /Sorting Algorithms/SelectionSort.py | 1,516 | 3.90625 | 4 | arr = [12, 77, 88, 55, 9, 3, 7, 8, 46, 1] ## Input unsorted array
temp = 1000 ## Temporary Variable
min_i = 0 ## Counter which stores the index of (min_i + 1)th smallest element of the array.
## For example, if min_i = 7, then, arr[min_i] would store the 8th smallest el... |
6832726ee1e2b8fcf95b93121de558194dfce4fa | charwick/helipad | /helipad/utility.py | 5,617 | 4 | 4 | """
Classes to give agents utility functions, and a base `Utility` class to subclass new utility functions. Built-in utility functions include `CES`, `Leontief`, and `CobbDouglas`.
"""
from abc import ABC, abstractmethod
from helipad.helpers import ï
class Utility(ABC):
"""A base class defining the methods a utility... |
42a84db17d4a2b3fac3a1a93c818b000087c8bc9 | arnavshroff/100_101. | /creatingClass/Student.py | 426 | 3.65625 | 4 | class Student(object):
def __init__(self,name,age,level,grades=None):
self.name = name
self.age = age
self.level = level
self.grades = {}
def setGrade(self,course,grades):
self.grades[course]=grades
def getGrade(self,course):
return self.grade... |
8ab6e830b0590ac5e710a004c969b2e14869275c | mistahangeior/hiitexams | /main.py | 1,439 | 3.578125 | 4 | """...................................Python Examination................................................
My Name is Hangeior David Hangeior
"""
import user_crud
#this is the path for the json file
db_path = "db/user.json"
def init():
# this is a constructor
print("\n**********WELCOME TO HIIT TECH MINDS****... |
e90f08fa70232c2b7fa850c1fffca7dd657d403b | samanthainneo99/Team-4-Code | /test_siblingsShouldNotMarry.py | 1,317 | 3.5 | 4 | import unittest
import siblingsShouldNotMarry
class TestSiblingsShouldNotMarry(unittest.TestCase):
'''gedcom file with one sibling marriage'''
def test1(self):
s = "The following individuals are marrying their siblings, which is not allowed: Sam Smith, Alexa Smith"
self.assertEqual(s, siblings... |
113635591b902dbe30f0785d65655020f4aeab7e | skyplane1/pythonscripts | /Fact using recursion.py | 108 | 3.59375 | 4 | def fact (n):
if n == 0 :
return 1
return n * fact(n-1)
result = fact(5)
print(result)
|
f05cf4bb1f75b0bf523940334931a802288c674b | hansejosh/pdsnd_github | /bikeshare.py | 16,332 | 4.375 | 4 | import time
import datetime
import pandas as pd
import numpy as np
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(st... |
0360198c9f6e7c17b417602a182c0c145c7962b8 | alvin1279/Oop_programes | /tree_with_itterative_traversal.py | 1,800 | 3.84375 | 4 | from collections import defaultdict
class Root:
def __init__(self, data=None):
self.Children = []
self.Data = data
self.Depth = 0
def set_attribute(self, attribute, data):
self.__dict__[attribute] = data
def find_depth(self, initial):
self.Depth = initial + 1
... |
4c575e2e9f6f3a3823555b18f9518380f89683c8 | RitamDey/Algorithms-and-Data-Structres | /Python/The New Edge Algorithms and DS/LinkedList/Node.py | 343 | 3.578125 | 4 | class Node:
def __init__(self, name):
self.data = name
self.nextnode = None
def remove(self, data, previous):
if self.data == data:
previous.nextnode = self.nextnode
del self.data
else:
if self.nextnode is not None:
self.nextno... |
5d4a3151f5fe35e47470084a1be1479061e23b3c | RitamDey/Algorithms-and-Data-Structres | /Python/BST-1.py | 2,162 | 3.875 | 4 | class Node:
def __init__(self, key: int, name: str):
self.key = key
self.name = name
self.left = None
self.right= None
def __str__(self):
return "%s has a key %d" %(self.name, self.key)
class BinaryTree:
def __init__(self):
self.root = None
def addNod... |
8a27127bc46c20f6f4bc16ba3362e723acc436e7 | AlexNaupay/dev-learn | /python/learn-decorators/a6_my_decorator_2.py | 278 | 3.59375 | 4 | # example with arguments
def decorator(some_function):
def wrapper(*args):
print "somethin is happening before some_function is caller"
res = some_function(args[0])
print "some_function is called"
return 1 + res**2 + 3
return wrapper
|
67f05ac3d7bc47a9d407651de4046e4543088ec4 | JiggsUK/ImapLib-email-retreival-example | /Basic_Retrieval.py | 5,393 | 3.75 | 4 | #!/usr/bin/env python
"""
Created by Jiggs
Basic python script to connect to an IMAP mailbox, retrieve a specific line of text from an email body and write it to a
csv file.
Includes various functions for cleaning up the returned email body if necessary.
Intended as a base code to assist with building an email checkin... |
99ac018d909a4c54f6d47afc05853cfef2315cc1 | arashhaji/Sprint-Challenge--Data-Structures-Python | /ring_buffer/ring_buffer.py | 1,223 | 3.546875 | 4 | class RingBuffer: # a buffer with a dynamic size, so that when it fills up, adding another element must overwrite the first (oldest) one its useful for storing log and history info
def __init__(self, capacity): # sets the capacity to an empty list
self.capacity = capacity
self.storage = []
... |
6ecf0e8a5c648ca07393163f72393011d5f8c43f | Sehor97/Metodo | /Project Python/EJERCICIO1.py | 2,021 | 3.78125 | 4 | import math
class ejercicio1:
def __init__(self):
self.euler=math.e
self.funcion = 0
self.derivada = 0
self.x = 0
self.xk = 0
self.a = 0
self.b = 0
def infuncion(self,x):
self.funcion = self.euler**float(x) + float(x)
return self.funcion... |
c2144760fd7a86dd950c0167f4340f64e37625a2 | jduysen/py_mosaic | /main.py | 3,625 | 3.53125 | 4 | from PIL import Image
import os
import random
large_image_path = input("Enter the path to the large image: ")
small_image_folder = input("Enter the path to the small images folder(folder should contain between 400-1,000 images for best results: ")
final_size = int(input("Enter target height of final image (pixel value... |
97bca21c91591d4c8ebffdded9d8affc65427312 | jiyouliang/PythonCodeAndDoc | /code/basic/day07/01.python引用说明.py | 466 | 4.03125 | 4 | # Python万物皆对象,一切参数的传递都是对象的引用
# 操作的是同一个列表对象,id 相同,值相同,同时操作也同步
list1 = ["张三", "李四"]
list2 = list1
print("list1=%s, list2=%s" % (list1, list2))
print("list1 id=%d, list2 id=%d" % (id(list1), id(list2)))
print("----------------------------")
list2.append("王五")
print("list1=%s, list2=%s" % (list1, list2))
print("list1 id=%... |
275ce4643183c794afd08cfdbeedfce728f79961 | jiyouliang/PythonCodeAndDoc | /code/basic/day06/04.拆包.py | 192 | 3.890625 | 4 | def getsize():
width = 320
height = 480
return width, height
size = getsize()
print(size)
# 拆包
width, height = getsize()
print("拆包width=%d,height=%d" % (width, height))
|
d25da0214d6c8e2df7cd319b801b6ab4fb4117ce | jiyouliang/PythonCodeAndDoc | /code/basic/day07/04.带参数的lambda表达式.py | 555 | 4.15625 | 4 | ## 函数
def add(a, b):
return a + b
# 调用函数
print(add(1, 2))
# -----------------------------------------------------------
## 使用lambda表达式改写
f = lambda a, b: a + b
print(f(1, 2))
# -----------------------------------------------------------
## 简写
print((lambda a, b: a + b)(1, 2))
# 带参数lambda例子2
def max1(a, b):... |
62d6143c52ca796425bca0188a008f5e3d3ebc91 | jiyouliang/PythonCodeAndDoc | /code/basic/day10/01.继承.py | 331 | 3.9375 | 4 | class Human(object):
def __init__(self):
print("Human _init_")
self.name = "Human"
class Father(Human):
def __init__(self):
super().__init__()
print("Father _init_")
self.name = "Father"
human = Human()
father = Father()
print("human=%s,father=%s" % (human.name, fat... |
5ea2127f10c59153127fab68c7ce598b419976db | jiyouliang/PythonCodeAndDoc | /code/basic/day03/g_字符串查找和检查.py | 1,336 | 4.15625 | 4 | """
字符串查找和检查
"""
## index() 查找子串是否在整个字符串中,返回子串起始下标,否则报错
mystr = "hello world itcast Python itcast hello"
"""
print(mystr.index("world")) # 6
print(mystr.index("itcast", 13)) # 从起始位置13开始查找,
print(mystr.index("itcast", 13, 28)) # 从起始位置13到结束卫视28查找,
"""
## find()和index功能一样,但是查询不到返回-1,不会报错
"""
print(mystr.find("itcast... |
1bd251fb473569ab07653a7d5a6364f66e45737f | jiyouliang/PythonCodeAndDoc | /code/basic/day07/12.文件读写操作.py | 600 | 3.671875 | 4 | filename = "python.md"
################### 读操作 ###################
# 从文件指针位置开始,向后读取所有的内容,并返回字符串,如果有参数,参数是一个数字,表示向后读取的字节数
f = open(filename, "r", encoding='utf-8')
print(f.read())
f = open(filename, "r", encoding='utf-8')
print(f.read(3)) # 读取3个字节
f = open(filename, "r", encoding='utf-8')
print(f.readline()) # 读取一行
... |
2afd14c1d96bf56e6fe32fad54ed301c0aaf886e | TanjillaTina/Basic-Python-Practices | /14ObjectOrientedProgramming/OOP2Inheritance.py | 1,713 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Oct 21 03:50:21 2017
In The Name of Allah, The Beneficent and The Merciful
@author: TINA
"""
class PartyAnimal: ##Prent Class
x = 0
name = ""
def __init__(self, nam):
self.name = nam
print(self.name,"constructed")
def party(self) :
self.x = self.x ... |
7d6fbacbd764c3f531489c82de728b84178a8575 | TanjillaTina/Basic-Python-Practices | /4Conditional Execution/ConditionalExecution.py | 360 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Oct 19 20:36:40 2017
@author: TINA
"""
print("In The Name of Allah,The Beneficent and The Merciful") #colon at the of line is not lways necessary
#conditional if
a=12;
if a>20:
print("a is bigger than 20");
print("a is not bigger than 20");
#Conditional Operators
if a>... |
ecb697ba0dbad43671ceb7376427ce482f89c1c8 | TanjillaTina/Basic-Python-Practices | /9Lists/ListBasics.py | 1,099 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Oct 20 18:00:58 2017
@author: TINA
"""
print("In The Name of Allah, The Beneficent and The Merciful");
#in python lists can save various typs of data,and alist can contain another list
names=["Tanjilla","Sarkar","Tina"]
for i in names:
print(i);
print(names[2]);
####... |
3573d399d4a4e0df0a05f88a11c4f281f2c93666 | t8213437/Multiplication-Table | /table_1.py | 173 | 3.75 | 4 | #coding:utf-8
for x in range(10):
if x == 0:
continue
for y in range(10):
if y == 0:
continue
print(x * y, end="\t")
print()
|
aa9ff8768db88a7859626d48f21d49bba91d0a66 | vivekascoder/DumpingGround | /Cryptography/main.py | 1,863 | 3.640625 | 4 | """
Name: main.py
Description: A interface or connector for all algorithm.
Date: 22-Mar-2020
Author: vivekascoder
"""
import sys
import rot13
import rot47
import reverse
import md5
"""
First argument denotes the algorithm: --rot13, --rot47
Second argument denotes the function: --encrypt, --decrypt, -... |
32d685f9a76afe21f347a07d8f4a8b242c728aa4 | 00280398/Programming-for-IT-Final-Project | /final project.py | 1,211 | 3.875 | 4 | #Nick Wunderlich
#Programming for IT Final Project
#Multiplication Test and Study Guide
import random
import time
import re
score = 0
currenttime = time.asctime( time.localtime(time.time()) )
doc = open('grades.txt','w+')
def test():
global score
rand1 = random.randint(1, 20)
rand2 = random.... |
71d5a8732044c888b1f73dffbf9805e98ad9372b | imyourghost/python | /hw7/hw7_1.py | 457 | 4.0625 | 4 | #реализовать две функции: write_to_file(data) и read_file_data().
# Которые соотвественно: пишут данные в файл и читают данные из файла.
def write_to_file(data):
file = open('read.txt', 'w')
file.write(data)
file.close()
def read_file_data():
file = open('read.txt','r')
print(file.read())
file... |
17346e04da14bb195b82794b8a3b256070f5185b | imyourghost/python | /hw3/home_work3_4.py | 393 | 4.4375 | 4 | #Написать функцию, которая принимает список чисел и возвращает их произвидение
### Переделать под задачу функционального программирования!
def list_multiply (*args):
my_var = 1
for arg in args:
my_var = my_var * arg
print(my_var)
list_multiply(1,2,3,4,5,6) |
9950e2726aaf1d10a3424eaec786733bf92ee1e3 | imyourghost/python | /hw3/home_work3_2.py | 516 | 3.5 | 4 | #Написать функцию, которая принимает на вход список,
#если в списке все объекты - int. сортирует его. Иначе выбрасывает ValueError
def list_err (*args):
try:
for i in args:
if not isinstance(i,int):
raise ValueError()
sort_lis = sorted(args)
print(*sort_lis)
... |
fc8c47c11af8cd93e15c2341f3ffe42439072917 | brookemac/COSC264-SocketAssignment | /client.py | 5,704 | 3.765625 | 4 | import socket
import sys
import select
def check_input(request_type, ip_address, port):
"""This function checks the validity of the request type, ip address
and port number. If any of the test cases fail the and error message is
printed and a system exit"""
if request_type != 'date' and request_... |
b4fb8d6fdd5e49ffa0fe8f4b8483f74e0b0a4bda | Academia-MagicKode/bases_git | /auth/validador.py | 840 | 3.671875 | 4 | import random,string
import rapid_email_validator as rv
usarios=["mati7","mati","matt"]
def agregar_numeros(n):
dig=string.digits
return "".join(random.choice(dig) for i in range(n))
def verifica_usuario(username):
orig=username
if orig not in usarios:
return (True,orig)
while usernam... |
3f13d8898b13c3ba5959ac54bc353e26ec98e448 | 2dvodcast/Data-Science-1 | /PythonEuler/spiral_primes.py | 1,194 | 3.796875 | 4 | '''Project Euler Problem 58
Find the side length of the square spiral for which the ratio of primes along both diagonals first falls below 10%'''
from math import sqrt
class Primes():
def __init__(self, Limit):
factors=[0]*Limit # number of prime factors.
count=0
for i in xrange(2,Limit):
if facto... |
ef7f9186d88e398b92badceb72d1b45c5978be02 | 2dvodcast/Data-Science-1 | /PythonEuler/circular_primes.py | 1,369 | 3.5 | 4 | '''Project Euler Problem 35
Find how many circular primes there are below one million.'''
from math import sqrt
def isPrime(primeList, num):
for prime in primeList:
if(prime > sqrt(num)):
break
elif(num%prime==0):
return False
return True
def alreadyChecked(numString):
if(numString[0] == ... |
9fb6d3383ad227df6bedd416638a0ae72f02e76e | 2dvodcast/Data-Science-1 | /PythonEuler/digit_factorials.py | 721 | 4.25 | 4 | '''Project Euler Problem 34
Find the sum of all numbers which are equal to the sum of the factorial of their digits.'''
from math import factorial
def isFactSumEqual(num):
numString = str(num)
factSum = 0
for digit in numString:
factSum += factorial(int(digit))
return factSum == num
def main():
#... |
45fcdf2011d09cfbda529a000a5fa7942cfbb6f1 | 2dvodcast/Data-Science-1 | /PythonEuler/powerful_digit_sum.py | 854 | 3.96875 | 4 | '''Project Euler Problem 56
Considering natural numbers of the form, a**b, where a, b < 100, find the maximum digital sum.'''
def findDigitSum(num):
numString = str(num)
digitList = [int(x) for x in numString]
return sum(digitList)
def main():
maxSum = 0
# the greatest digit sum of 1**b will be 1
#... |
b4d83a68ffbc6eafc5a7a636ad14b2e5e2fbe19b | 2dvodcast/Data-Science-1 | /PythonEuler/truncatable_prime.py | 1,077 | 3.84375 | 4 | '''Project Euler Problem 37
Find the sum of the only eleven primes that are both truncatable from left to right and
right to left.'''
from math import sqrt
def isPrime(primeList, num):
for prime in primeList:
if(prime > sqrt(num)):
break
elif(num%prime==0):
return False
return True
def is... |
727129f8272749f63e104aedf6bbe229ca1abcf8 | whenyd/dsa_python | /4_sort/merge_sort.py | 828 | 4.15625 | 4 | def merge_sort(arr):
"""O(nlogn)"""
size = len(arr)
if size < 2:
return arr
middle = size // 2
left = merge_sort(arr[:middle])
right = merge_sort(arr[middle:])
together = merge(left, right)
return together
def merge(left, right):
size_left = len(left)
size_right = len... |
0ce69cb255be4a18b4ffea120335f6e841362d97 | whenyd/dsa_python | /4_sort/quick_sort.py | 1,394 | 4.03125 | 4 | def _quick_sort(array):
if len(array) < 2:
return array
else:
pivot = array[0]
less_than_pivot = [x for x in array if x < pivot]
more_than_pivot = [x for x in array if x > pivot]
return _quick_sort(less_than_pivot)+[pivot]+_quick_sort(more_than_pivot)
def quick_sort(ar... |
8ab2859c82165addeef61745ab0a426408214717 | dmheisel/AdventOfCode2020 | /2020/Day15/elvish_numbers.py | 599 | 3.578125 | 4 | from collections import defaultdict
def numbers_game(end, *starting_nums):
print(starting_nums)
turn = 0
encountered = defaultdict(int)
last_said = 0
for num in starting_nums:
turn += 1
encountered[num] = turn
last_said = num
while turn < end:
if last_said in ... |
bad5eb5d3399de6ebc34b8498ca82049b3e4112d | dmheisel/AdventOfCode2020 | /2020/Day12/Ship.py | 3,253 | 3.71875 | 4 | class Ship:
def __init__(self, path=None):
self.heading = "E"
self.position = (0, 0)
self.nav_code = self.parse_nav_code(path) if path else None
self.compass = {"N": 0, "E": 90, "S": 180, "W": 270}
self.waypoint = (10, 1)
def parse_nav_code(self, path):
with open... |
a56cbc35e340c74f6ad903b810d3360fc53a98c0 | jchap136/qbb2018-answers | /day3-lunch/day3-lunch-#1.py | 413 | 3.703125 | 4 | #!/usr/bin/env python3
# run this python command followed by file
import sys
if len(sys.argv) > 1:
f = open(sys.argv[1])
else:
f = sys.stdin
count = 0
for line in f:
fields = line.rstrip("\r\n").split()
if line.startswith("#"):
continue
if fields[2] == "gene" and "protein_codin... |
8f8a87e967f2bee0520894c50433a510a4343362 | bobthecow/ManipulateCoda | /src/Support/Scripts/Capitalize.py | 1,462 | 3.796875 | 4 | '''A capitalization action for the Manipulate plugin for Coda'''
import cp_actions as cp
from titlecase import titlecase
from sentencecase import sentencecase
def act(controller, bundle, options):
'''
Required action method
Set desired capitalization with 'to_case' option
'''
context = c... |
15202b8c6bf0e944d2ecd36ace25ad3a20969e1b | bfedoronchuk/windows-10-malware | /exercise_files/1. Python Overview/1.6. Dictionaries.py | 274 | 3.9375 | 4 | myDict = {}
my_2nd_dic = dict()
myDict = {'Elliot Alderson' : 'network engineer', 'Darlene Alderson' : 'hacker', 'Angela Moss' : 'PR manager @ E Corp'}
# print (myDict)
# print (myDict['Elliot Alderson'])
# myDict['Philip Price'] = 'CEO @ E Corp'
# print (myDict)
print (myDict.keys())
print (myDict.values()) |
1d6ae062351fba4ce9fe1136f8f4fcf2beed5151 | luissantaanna/PythonForEverybody | /payforwork.py | 135 | 3.9375 | 4 | #Pay for work
hrs = input("Enter your hours")
rate = input("Enter rate per hour")
pay = float(hrs)*float(rate)
print("Pay:", pay)
|
967f1e9b3e16a6d29a6354057bc16f1c15c2f2a6 | hongbo-sun/python_basic_usage | /some_easy_program.py | 2,489 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Oct 10 16:58:00 2017
@author: lenovo
"""
import numpy as np
import copy
def double_first(k):
n=k
n[0] = n[0] * 2
numbers = [1, 2, 3, 4]
double_first(numbers)
print (numbers)
print'\n'
list0=[[2,3],[32222,4]]
print'\n'
print 'b',"a"
list1=copy.deepco... |
afcabad9b6925c823333caf211a07cca57ae5e58 | mallikarjun3739/tandemloop-test-2 | /2.py | 342 | 3.84375 | 4 | a = int(input())
for i in range(1,a+1):
if i % 2 == 0:
for k in range(i, 0, -1):
if k == 1:
print(k)
else:
print(k,' * ',end="")
else:
for k in range(1,i+1):
if k == i:
print(k)
else:
... |
338d627c02421ba2b95c82fce3bed32a124dbde3 | niki4/algorithms | /sort/radix_sort.py | 1,276 | 4.28125 | 4 | """
Radix Sort is kind of algorithm that works only to integers.
It's more powerful than Counting sort.
The idea is to sort nums by their place, from least significant digit first toward most significant one.
Assuming each integer in base b
=⇒ d = logb k digits ∈ {0, 1, . . . , b − 1}
E.g., having [329, 457, 657, 83... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.