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 |
|---|---|---|---|---|---|---|
8124f901f1650f94c89bdae1eaf3f837925effde | ravalrupalj/BrainTeasers | /Edabit/Balancing_Scales.py | 944 | 4.5 | 4 | #Balancing Scales
#Given a list with an odd number of elements, return whether the scale will tip "left" or "right" based on the sum of the numbers. The scale will tip on the direction of the largest total. If both sides are equal, return "balanced".
#The middle element will always be "I" so you can just ignore it.
#As... |
05209aa3f4105d4265090e6928e919d40186dc7d | j-scull/Python_Data_Structures | /priority_queue.py | 7,890 | 4 | 4 | from empty import Empty
from positional_list import PositionalList
class PriorityQueue:
"""
Abstract base class for priority queue implementations
"""
#-------------------------------------------------------------------
class _Item:
"""
Composite design pattern - lightweight class ... |
d183ee49cc90ee2ede5a0d6383404edd9f08a4a8 | nicolaespinu/LightHouse_Python | /spinic/Day14.py | 1,572 | 4.15625 | 4 | # Challenge
# Dot's neighbour said that he only likes wine from Stellenbosch, Bordeaux, and the Okanagan Valley,
# and that the sulfates can't be that high. The problem is, Dot can't really afford to spend tons
# of money on the wine. Dot's conditions for searching for wine are:
#
# Sulfates cannot be higher than 0.6.
... |
61a217a71284900e86f9453b52db9474189f4649 | nicolaespinu/LightHouse_Python | /spinic/Day3.py | 2,399 | 3.96875 | 4 | # Challenge
# Dot has some specific rules for what they want to change in the shopping list:
#
# They hate oak wood, and prefer maple.
# They want to paint all the rooms blue except the kitchen, which they want to paint white.
old_blueprint = {
"Kitchen": ['Dirty', 'Oak', "Damaged", "Green"],
"Dining Room": ['D... |
3779b5ef15b56a4fb9df314e93335786abb5743e | xylo99/tic-tac-toe-program | /server/game/tttg.py | 4,484 | 3.5 | 4 | from game.tttg_menu_printer import mp_print_menu
class TTTGame:
def __init__(self):
self.N = 3
self.CIRCLE = 1
self.EMPTY = 0
self.CROSS = 2
self.board = [[self.EMPTY for i in range(self.N)] for i in range(self.N)]
self.AI_row = 0
self.AI_col = 0
def cl... |
c6fe659f4f5f7b6e01ef90ce5443eeed3e8d8ccb | Anagabsoares/AdaPrecourse | /variableIO.py | 416 | 3.703125 | 4 | # Variable and IO (input/ooutput)
car = "lexus"
# input
anotherCar = input("What is your car name?")
print(f"cool! My favorite car is {car} and yours is {anotherCar}")
#CONSTANTS - a type of variable whose CANNOT be changed. - containers values that cannot be reassigned.
#it is nor reinforced by Python.It is mo... |
166402e70525f0ab90d8fbef840293868153f8d2 | Anagabsoares/AdaPrecourse | /snowman.py | 2,731 | 4.0625 | 4 | import random
from wonderwords import RandomWord
SNOWMAN_WRONG_GUESSES = 7
SNOWMAN_MAX_WORD_LENGTH = 8
SNOWMAN_MIN_WORD_LENGTH = 5
SNOWMAN_GRAPHIC = ['* * * ',
' * _ * ',
' _[_]_ * ',
' * (") ',
' \( : )/ *',
'* (_ : _) ',
'-----... |
b7361409d72262f39071be3b831fe41185e38683 | VictorMateu/practica2algoritmia | /dp_rec.py | 4,260 | 3.75 | 4 | '''
Dynamic Programing recursivo
'''
import sys
import math
import resource
resource.setrlimit(resource.RLIMIT_STACK, (2**29,-1))
sys.setrecursionlimit(10**6)
class Punto:
'''
Clase para almacenar los puntos sobre la tierra
'''
def __init__(self, n_points, height, alfa, beta):
self.... |
3a419523fb1fc6bbef5cf3da4ad3d07cc3d77b34 | PranavDev/Sorting-Techniques | /RadixSort.py | 803 | 4.15625 | 4 | # Implementing Radix Sort using Python
# Date: 01/04/2021
# Author: Pranav H. Deo
import numpy as np
def RadixSort(L, ord):
Reloader_List = []
temp = []
for i in range(0, 10):
Reloader_List.append([])
for i in range(0, ord):
print('Iteration ', i, ' : ', L)
for ele in L:
... |
9a9e006411084d4e94f543e174788fec07664a3d | Diegox777/MAT156 | /trapecio.py | 968 | 3.796875 | 4 | import matplotlib.pyplot as plt
import numpy as np
from sympy import symbols # importamos la libreria sympy
from sympy import lambdify
from sympy import sympify
x = symbols('x') # establecemos a x como variable simbolica
a = int(input('Introduzca a = '))
b = int(input('Introduzca b = '))
n = int(input('Introduzca n ... |
07452465afd7fee553f055e810405fdeac934940 | aki-nlp/AtCoder | /atcoder.jp/abc111/abc111_a/Main.py | 123 | 3.6875 | 4 | n = list(input())
for i in n:
if i == '1':
print(9, end='')
elif i == '9':
print(1, end='')
print() |
0eeedfe72aeac8b1571fdc5bb38f5b31124e4ddc | aki-nlp/AtCoder | /atcoder.jp/abc018/abc018_1/Main.py | 139 | 3.53125 | 4 | a = [int(input()) for _ in range(3)]
l = sorted(a, reverse=True)
print(l.index(a[0]) + 1)
print(l.index(a[1]) + 1)
print(l.index(a[2]) + 1) |
9e71cb471cce4502135a3158848aa6b92d10657e | aki-nlp/AtCoder | /atcoder.jp/abc165/abc165_b/Main.py | 136 | 3.5625 | 4 | x = int(input())
money = 100
ans = 0
while True:
money += int(money*0.01)
ans += 1
if money >= x:
break
print(ans) |
5bfa675cdca9c76ca073225a40e653093dc92d4d | fergusjproctor/Hangman | /Problems/The mean/task.py | 178 | 3.671875 | 4 | numberList = []
while True:
newInt = input()
if newInt == '.':
break
else:
numberList.append(int(newInt))
print(sum(numberList) / len(numberList))
|
31fdb185e264674aff42c8cce47c2417cd69d6fe | pc-kong/Algorithms | /Python/Data Structures/Stacks and Queues/RestrictedList.py | 3,501 | 3.75 | 4 | """ Linear structures with restricted insertion, peeking and deletion operations """
from abc import ABCMeta, abstractmethod
class RestrictedList:
"""
Implements the generic list that will later on serve for the Stack and Queue implementation.
Attributes
----------
head: Node
Head Node
... |
b1c37e2364ec168e559ffdead2245b86d8fb6a4b | pc-kong/Algorithms | /Python/Data Structures/Lists/skip_list.py | 5,440 | 3.90625 | 4 | import random
class SkipNode:
"""
elem : value contained in the node.
next : level where the node appears (list of pointers to the next nodes).
"""
def __init__(self, height=0, elem=None):
self.elem = elem
self.next = [None]*height
def __str__(self):
string = "[" + str(... |
10f8dd868a9fae5feba391c56955f823dfe807ad | pc-kong/Algorithms | /Python/Data Structures/Stacks and Queues/Stack.py | 794 | 4 | 4 | """ Stack (LIFO) """
from RestrictedList import RestrictedList
class Stack(RestrictedList):
"""
In stacks, the last element that was added is the first
one to be removed.
This class inherits from the RestrictedList class
which already implements the removal method.
"""
def insert(self, element):
"""
... |
4a6f9ab97e98503908cde26c203ae490eb74ac7b | Srikrishnarajan/Fibonacci-Series.py | /Fibonacci_Series.py | 190 | 4.09375 | 4 | n = int(input("Enter the value of n: "))
a = 0
b = 1
c = 0
count = 1
print("Fibonacci Series: ", end = " ")
while(count <= n):
print(c, end = " ")
count += 1
a = b
b = c
c = a + b
|
cf2cea50bae7be4d823e14763f3515184077a9f6 | KrysVal/projetM2 | /etc/duplicate_remover.py | 1,169 | 3.5 | 4 | from Bio import SeqIO, SeqRecord
import argparse
def duplicate_remover(file):
d = {}
duplicate = []
for record in SeqIO.parse(file, "fasta"):
if record.seq in d.keys():
print("duplicate found : \n" + record.id)
duplicate.append(record.id)
d[record.seq] = record.desc... |
cc550fea7bbdbf89ec7ec4ae96c84d7831864518 | RonKand14/Python-War-card-game | /client.py | 5,800 | 3.78125 | 4 | import socket
import time
class Client:
"""
Client class:
Fields: client's socket as s, host - server's Ip, port - server's port
"""
def __init__(self, host, port):
self.host = host
self.port = port
self.s = None
def read_input(self):
"""
... |
9ce619cdfb7e082cd269c7349a538f13573e01ca | haffarmohammed/Aloha-async | /plot.py | 371 | 3.859375 | 4 | from matplotlib import pyplot as plt
def generateGraphe():
# naming the x axis
plt.xlabel('K')
# naming the y axis
plt.ylabel('paquets transmis')
# giving a title to my graph
plt.title('Asynchrone Aloha Statistics')
# show a legend on the plot
plt.legend()
plt.savefig('graphe.pn... |
c5d5962687dba55ef6c7ea97b7ba1d499f152013 | FranzTseng/practice | /python/OOP_bank_Project.py | 942 | 3.78125 | 4 |
class Account():
def __init__(self, owner, balance):
Account.owner = owner
Account.balance = balance
def __repr__(self):
return f"owner:{self.owner}, balance:{self.balance}"
def deposit(self, deposit):
self.balance = self.balance + deposit
print('Succeed')
... |
08f465020fda54f2161da24bc821125b5c6e9daa | Jack64ru/python | /while.py | 78 | 3.75 | 4 | i = int(input('number: '))
p = 1
while i >= p:
print('*' * p)
p = p+1
|
cf8cf0191e831307a5d78b27ae47cbc20c63db4d | KarthikeyanS27/Turtlebot-Navigation | /MPC Path Planning/devel/test.py | 7,635 | 3.765625 | 4 | import numpy as np
import itertools
from functions import *
import matplotlib.pyplot as plt
from matplotlib import animation
# Inputs
H_p = 2 # number of steps in prediction horizon
H_c = 1 # number of steps in control horizon
dt = 1 # seconds in one time step
# positional coordinates
x = [0]
y = [0]
v = [0]
phi = [... |
b79bb17bced0ae466ecf3821624e9273f6cbac6a | SewonShin/BLOCKCHAINSCHOOL | /Python Code 2/FastCampusPythonBasic/code04/main.py | 722 | 3.875 | 4 | # num_dict = {"m":"Moon", "s":"Seong"}
# print(num_dict["m"]) # 가져오기
# keys(), values()
# for k, v in num_dict.items():
# print(k,v)
# num_dict["j"] = "Jae" # 키의 존재 유무 -> 추가, 수정
# del num_dict["m"] # 삭제
# print(num_dict.get("k"))
# x = 10
# y = 10.1
# z = "문자열"
# isBool = True # False
# isNone =... |
8ccdc8d69acc0f784dbebdfe3c5618b268a01889 | stevenwaldron/Sprint-Challenge--Data-Structures-Python | /reverse/reverse.py | 1,522 | 4 | 4 | class Node:
def __init__(self, value=None, next_node=None):
self.value = value
self.next_node = next_node
def get_value(self):
return self.value
def get_next(self):
return self.next_node
def set_next(self, new_next):
self.next_node = new_next
class LinkedList:... |
d5a781cebe422e3b777ee772c1dbf79764664b23 | humanwings/learngit | /python/basic/testStringFormat.py | 957 | 3.75 | 4 | import string
# print(str("wujian"))
# print(str("呉剣"))
# print(ascii("wujian"))
# print(ascii("呉剣"))
# print(repr("wujian"))
# print(repr("呉剣"))
# str.format()
print("============ str.format() ===============")
print()
s0 = "{} 's age is {}"
s1 = "{0} 's age is {1}"
s2 = "{0!a} 's age is {1}"
print(s0)
print(" --... |
493be0686bb1d6a9bf2aae7a22372d5f61b1373c | humanwings/learngit | /python/coroutine/testCoroutine_yieldfrom02.py | 3,405 | 3.84375 | 4 | '''
yield from 结构最简单的用法
委派生成器相当于管道,所以可以把任意数量的委派生成器连接在一起---
一个委派生成器使用yield from 调用一个子生成器,而那个子生成器本身也是委派生成器,使用yield from调用另一个生成器。
最终以一个只是用yield表达式的生成器(或者任意可迭代对象)结束。
'''
#! -*- coding: utf-8 -*-
from collections import namedtuple
Result = namedtuple('Result', 'count average')
# 子生成器
def aver... |
dc34b77a678caff2ce7b611f21ed210d55321225 | humanwings/learngit | /python/coroutine/testCoroutine_01.py | 894 | 4.25 | 4 | '''
协程(Coroutine)测试 - 生产者和消费者模型
'''
def consumer():
r = ''
# print('*' * 10, '1', '*' * 10)
while True:
# print('*' * 10, '2', '*' * 10)
n = yield r
if not n:
# print('*' * 10, '3', '*' * 10)
return
# print('[CONSUMER] Consuming %s...' % n)
... |
64310b064ce3a0e2cc14f6e238ae8da215b44a83 | Davidigbokwe/desktopapp | /Pythonapptkinter/script.py | 475 | 3.859375 | 4 | #python classes and object oriented programming
#corey schafer
#methods are functions associated with class
class Employee:
def __init__(self,first, last, pay):
self.first =first
self.last =last
self.pay =pay
self.email = first[0] + '.'+ last +"@hackmanmfb.com"
def fullname(self):
return '{} {}'.format(... |
f52b38bb4315682d54c1cd5b6062197f7a431c64 | knksknsy/facial-reenactment | /utils/transforms.py | 162 | 3.5 | 4 | def normalize(data, mean, std):
data = (data - mean) / std
return data
def denormalize(data, mean, std):
data = (data * std) + mean
return data
|
a58e7283130ce6309de6c28fcd5accdc55f96f88 | janmachowski/breast_cancer_prediction | /main.py | 4,483 | 3.546875 | 4 | import pandas as pd
import seaborn as sn
import matplotlib.pyplot as plt
from sklearn.metrics import accuracy_score
# importing the dataset
dataset = pd.read_csv('data.csv')
X = dataset.iloc[:, 2:].values
Y = dataset.iloc[:, 1].values
print("Dataset dimensions : {}".format(dataset.shape))
# Visualization of data
dat... |
13a66d537cddee11a8d927b15fb363d983d147a0 | MengSunS/daily-leetcode | /sweeping_line/452.py | 1,075 | 3.515625 | 4 | # official solution, sort by ending points:
class Solution:
def findMinArrowShots(self, points: List[List[int]]) -> int:
if not points:
return 0
# sort by x_end
points.sort(key = lambda x : x[1])
arrows = 1
first_end = points[0][1]
for x... |
df4204941cbe8c6b45705ea839225afb9177bd11 | MengSunS/daily-leetcode | /fb高频/92.py | 748 | 3.875 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseBetween(self, head: ListNode, l: int, r: int) -> ListNode:
if not head or l == r: return head
dummy = prev = ListNode(0)
... |
4c71882a32a10c8157d62309ba2a25f537f63f03 | MengSunS/daily-leetcode | /bfs/690.py | 1,758 | 3.71875 | 4 | # 第二遍做:recursion
"""
# Definition for Employee.
class Employee:
def __init__(self, id: int, importance: int, subordinates: List[int]):
self.id = id
self.importance = importance
self.subordinates = subordinates
"""
class Solution:
def getImportance(self, employees: List['Employee'], id:... |
018c7f1ba42e50c46da8dd7112c56089af479027 | MengSunS/daily-leetcode | /design/146.py | 1,956 | 3.59375 | 4 | # hashmap: {key: node}
# doubleLinkedList: <->node<->
# node.val, node.key, node.before, node.after
# two dummy nodes: self.head, self.tail
class DLinkNode:
def __init__(self):
self.key = None
self.val = None
self.before = None
self.after = None
class LRUCache:
def __i... |
3eee307938420f7cc3a58ff6ebbd295652d134ed | MengSunS/daily-leetcode | /snap/342.py | 647 | 3.609375 | 4 | class Solution:
def isPowerOfFour(self, num: int) -> bool:
return num > 0 and num & (num-1) == 0 and 0b1010101010101010101010101010101 & num == num
def isPowerOfFour(self, num: int) -> bool:
if num < 0 : return False
def helper(num):
if num < 4:
if num ==... |
437d0d9178abdbcf89042c35f1f94ebdc0912294 | MengSunS/daily-leetcode | /binary_tree/tree/333.py | 784 | 3.65625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def largestBSTSubtree(self, root: TreeNode) -> int:
def dfs(root):
if not root:
... |
86d20bc245deb7217a657286c19df842bab15d0d | MengSunS/daily-leetcode | /binary_tree/1644.py | 864 | 3.71875 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
self.p_find, self.q_find= False, Fa... |
c31c3e68fa40c14a7d943ffccbe98228a6d99c9a | MengSunS/daily-leetcode | /snap/146.py | 1,556 | 3.765625 | 4 | class Node:
def __init__(self, key=None, val=None, before=None, after=None):
self.key = key
self.val = val
self.before = before
self.after = after
class LRUCache:
def __init__(self, capacity: int):
self.cache = {}
self.maxi = capacity
self.head = Node()... |
61b424ca8f98794de4d0b80f99a2e89bc587390e | ProProgrammer/udacity-cs253-L2andPSet2 | /rot13_implementation.py | 1,399 | 3.890625 | 4 | ASCII_a = ord('a') # equals 97
ASCII_A = ord('A') # equals 65
ROTNum = 13 # requiredShift
def rot13(user_input):
outputList = []
if user_input:
for i in user_input:
if isLowerCaseChar(i):
outputList.append(rotLowerCase(i, ROTNum))
elif isUpperCaseChar(i):
outputList.append(rotUpperCase(i, ROTNum))
... |
75a9d2a6c2d318f11c3257771c7c5ebd4ff8320e | sigmaticsMUC/neuralCar | /neuronalApp/netCar/simCar/Car.py | 968 | 3.625 | 4 | from neuronalApp.netCar.abstractNetCar.abstractVehicle import abstractVehicle
class Car(abstractVehicle):
color = (255, 0, 0)
def __init__(self, xpos, ypos, velocity):
self.velocity = velocity
self.position = (xpos, ypos) # instance variable unique to each instance
self.direction ... |
bb735795b57903276b4cf8f9418d09e76f85a635 | mateuszstompor/Rosalind | /AlgorithmicHeights/2sum/2sum.py | 1,400 | 3.78125 | 4 | import sys
def two_sum(sequence):
result = None
for i in range(len(sequence)):
for j in range(1, len(sequence)):
if i != j and sequence[i] == -sequence[j]:
result = i+1, j+1
if result is not None:
return (result[0], result[1]) if result[0] < result[1] else (resu... |
37886241a038e7e967bbe9b7d043f9b6f1d1773b | mateuszstompor/Rosalind | /PythonVillage/ini6/ini6.py | 507 | 4 | 4 | import sys
def count_word_occurence(words):
count = {}
for word in words:
count[word] = count.get(word, 0) + 1
return count
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Invoke the program passing a path to a file as an argument")
else:
with open(sys.argv[1]) a... |
ba2848ac2f71d60860dec842aa0356940112a583 | mateuszstompor/Rosalind | /BioinformaticsStronghold/subs/subs.py | 576 | 3.578125 | 4 | import sys
def motif_occurrence(dna, motif):
result = []
for i in range(0, len(dna)):
stripped = dna[i:i+len(motif)]
index = stripped.find(motif)
if index >= 0:
result.append(index + i + 1)
return result
if __name__ == "__main__":
if len(sys.argv) != 2:
pr... |
bdc289b3b5677c987a35aac212afdf63b4b94ac5 | mateuszstompor/Rosalind | /AlgorithmicHeights/fibo/fibo.py | 411 | 4.09375 | 4 | import sys
def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Invoke the program passing a path to a file as an argument")
else:
with open(sys.ar... |
489f07ddb56ccd352f2b13b39c9e47355ac1a650 | Sanyab001/ProjectEuler | /task_6.py | 1,034 | 3.828125 | 4 | # Сумма квадратов первых десяти натуральных чисел равна
#
# 1**2 + 2**2 + ... + 10**2 = 385
# Квадрат суммы первых десяти натуральных чисел равен
#
# (1 + 2 + ... + 10)**2 = 55**2 = 3025
# Следовательно, разность между суммой квадратов и квадратом суммы первых десяти натуральных чисел составляет 3025 − 385 = 2640.
#
# ... |
2d19f0e057fe87daae6821150999017903b7613d | Lixmna/wikidocs | /4.자료형/4.3_Tuple.py | 169 | 3.625 | 4 | p = (1,2,3)
q = p[:1] + (5,) + p[2:]
print(q)
r = p[:1], 5, p[2:]
print(r)
# 튜플은 리스트와 달리 원소값을 직접 바꿀수 없기때문에 오려붙이기 |
0d9271a4ef2e01231c56ce2a52185d490841c041 | DMWillie/AlgorithmAndDataStruct | /Sort/BubbleSort.py | 208 | 3.828125 | 4 | """冒泡排序"""
def bubbleSort(arr):
for i in range(1,len(arr)):
for j in range(0,len(arr)-i):
if(arr[j]>arr[j+1]):
arr[j],arr[j+1] = arr[j+1],arr[j]
return arr |
e00165de1a5665174275b66e5c8471e71a247a1b | kayev1/set05-1 | /weather.py | 1,689 | 3.984375 | 4 | def get_weather_icon(pct_rain):
""" Given the percent chance of rain as an integer (e.g. 75 is 75%), return the name of the icon to be displayed."""
if int(pct_rain) <= 10:
return 'fullsun.ico'
elif int(pct_rain) <= 20:
return 'suncloud.ico'
elif int(pct_rain) <= 85:
return 'twodrops.ico'
el... |
1b94be4ea421568eddcf9e2b0cf76448ac6409ae | PzanettiD/practice | /accum.py | 222 | 3.546875 | 4 | def accum(s):
# your code
text = []
for i in range(len(s)):
temp = s[i] * (i + 1)
text.append(temp.capitalize())
new_s = '-'.join(text)
return new_s
b = accum('abcd')
print(b) |
b577fd989558130c2c9a14161af9a049545bec91 | PzanettiD/practice | /timeformat.py | 615 | 3.609375 | 4 | def timeformat(seconds):
minutes = 0
hours = 0
if seconds / 60 >= 1:
for i in range(0, seconds, 60):
if seconds - 60 < 0:
break
else:
minutes += 1
seconds -= 60
if minutes == 60:
hours += 1... |
94b9dea1cff4fa563dcf1701fb14b05e3f9ad7da | 595849292/econometrics | /optimization/gradient_descent.py | 1,693 | 3.640625 | 4 | # it solve for unconstrained optimization problem
# example f=x**2+Y**2
import time
import numpy as np
import sympy
class GD():
def __init__(self):
self.variant='x y z'
self.inivalue=[1,2,3]
self.fvalue=0
self.f=sympy.simplify('x**2+y**3+z')
def fun1(self,x):
variant=s... |
3df0972f9d6da16a68009240f911454c25d1ed32 | amnsr17/py_torch_lrn | /8-RNN.py | 8,720 | 3.6875 | 4 | # -------------- Text generation ----------------
# ---------- Character Level Encoding -----------
# -------------- Vanilla RNN -------------
# hidden(t) = tanh ( Weight(t) * hidden(t-1) + Weight(input) * Input(t) )
# output(t) = Weight(output) * hidden(t)
# ------------ Implementation Steps -----------
# 1 c... |
1d909e4aa9e2c5fe73738292b640b34abb1f45a7 | AnnaLara/smartninjacourse | /Homework_lesson_7/Guess the secret number.py | 358 | 3.890625 | 4 | #!/usr/local/bin/python
# -*- coding: utf-8 -*-
def main():
import random
secret = random.randint(1,10)
guess = int(raw_input("Guess a number from 1 to 10: "))
print "The secret numer was " + str(secret)
if guess == secret:
print "You won!"
else:
print "You lost... Try again!"
... |
0d185cc97d007f7a5651615bfe254f646bdefa43 | AnnaLara/smartninjacourse | /Lesson_11_homework/Vehicle_manager_program/vehicle_manager.py | 3,362 | 4.15625 | 4 | #!/usr/local/bin/python
# -*- coding: utf-8 -*-
class Car:
def __init__(self, brand, model, km, service_date):
self.brand = brand
self.model = model
self.km = km
self.service_date = service_date
def see_vehicles(list):
for x in list:
print list.index(x)+1
print ... |
afdf0666b5d24b145a7fee65bf489fd01c4baa8c | OaklandPeters/til | /til/python/copy_semantics.py | 1,348 | 4.21875 | 4 | # Copy Semantics
# -------------------------
# Copy vs deep-copy, and what they do
# In short: copy is a pointer, and deep-copy is an entirely seperate data structure.
# BUT.... this behavior is inconsistent, because of the way that attribute
# setters work in Python.
# Thus, mutations of attributes is not shared... |
4a92290522b34d30c72a22c4060770cadee3b300 | jebutton/flysimchk | /src/model.py | 6,888 | 3.734375 | 4 | """Module containing classes that represent data objects.
Copyright 2019 Jacqueline Button.
"""
from typing import List
from typing import Dict
class ChecklistStep():
"""Contains the data used in each step.
Right now it is limited to just the text of the step title and text.
Attributes:
step_n... |
1f6ef830d9b8da66932e33af5275fcfe7b12dde4 | andrewmaltezthomas/rosalind | /3.Reverse_Complement/Reverse_Complement.py | 1,313 | 4.09375 | 4 | """
What this script does:
Input: A DNA string s of length at most 1000 bp.
Return: The reverse complement s**c of s.
"""
#Import Sequence File
import os
print
user_path = raw_input("Enter sequence file location: ")
path = os.chdir(user_path)
print
sequence_file_location = raw_input("Enter sequence file name: ")
print
... |
60d6bc5574a943948baae691e33f18103de719d3 | andrewmaltezthomas/rosalind | /7.Mendels_First_Law/mendel.py | 1,815 | 3.96875 | 4 | homozygous_dominant = raw_input("Enter number of homozygous dominant organisms:")
homozygous_dominant = float(homozygous_dominant)
heterozygous = raw_input("Enter number of heterozygous organisms:")
heterozygous = float(heterozygous)
homozygous_recessive = raw_input("Enter number of homozygous recessive organisms:")
ho... |
a5c715a92c166274f665a37557c98f73e5caef2b | ottomattas/py | /class-example-geometry.py | 3,948 | 4.5625 | 5 | #!/usr/bin/env python
"""This is a simple class with some attributes
to calculate area and circumference for a circle."""
__author__ = "Otto Mättas"
__copyright__ = "Copyright 2021, The Python Problems"
__license__ = "MIT"
__version__ = "0.1"
__maintainer__ = "Otto Mättas"
__email__ = "otto.mattas@eesti.ee"
__statu... |
454f068d4b88865db55d1a8ea9d9b72954d82026 | rhlklwr/flappy_bird_game | /flappy_bird.py | 8,242 | 3.515625 | 4 | import pygame
from pygame.locals import *
import sys
import random
# Global variable for game
FPS = 32
SCREENWIDTH = 289
SCREENHEIGHT = 511
SCREEN = pygame.display.set_mode((SCREENWIDTH, SCREENHEIGHT)) # initialising display for game
GROUND_Y = SCREENHEIGHT * 0.8
GAME_SPRITES = {} # this is use to store i... |
4cbfb6c04bb9f888fb684b599d30c8a95dcbdfaf | parth2651/PythonLearningSample | /preprocessingdata.py | 1,248 | 3.84375 | 4 | import pandas as pd
from sklearn.preprocessing import MinMaxScaler
# Load training data set from CSV file
training_data_df = pd.read_csv("Training.csv")
# Load testing data set from CSV file
test_data_df = pd.read_csv("Testing.csv")
# Data needs to be scaled to a small range like 0 to 1 for the neural
# network to w... |
1030aacf43ea48c97a7f4f407a829429f4171929 | wdfnst/StochasticGradientDescentNeuralNetwork | /two_layer_neural_network.py | 1,126 | 4.09375 | 4 | import sys
import numpy as np
# compute sigmoid nonlinearity
def sigmoid(x):
output = 1/(1+np.exp(-x))
return output
# convert output of sigmoid function to its derivative
def sigmoid_output_to_derivative(output):
return output*(1-output)
# input dataset
X = np.array([ [0,1],
[0,1],
... |
902623aa65a95e273af213f5144f40f50b96c1d9 | hetzz/30DaysChallenge | /April/Day19/solution.py | 587 | 3.75 | 4 | def search(nums, target):
low = 0
high = len(nums) - 1
while low <= high:
mid = low + (high - low) // 2
if target == nums[mid]:
return mid
elif nums[mid] <= nums[high]:
if( target > nums[mid]) & (target <= nums[high]):
low = mid + 1
... |
162086004a87d73de9ea916be83dcb64d8551efb | hetzz/30DaysChallenge | /April/Day13/solution.py | 791 | 3.625 | 4 | def findMaxLength(nums):
hash_map = {}
curr_sum = 0
max_len = 0
ending_index = -1
n = len(nums)
for i in range (0, n):
if(nums[i] == 0):
nums[i] = -1
for i in range (0, n):
curr_sum = curr_sum + nums[i]
if (curr_sum == 0):
... |
a383876dd585215aa178a9d4c3b5ec9aee6c9494 | omegadefender/Python-Exercises-and-Unit-Testing-Practice | /exercises/name_exercise.py | 752 | 3.75 | 4 | from itertools import dropwhile
def id_consonants(x):
return x not in 'aeiouy'
def vowel(name):
schop = ''.join(dropwhile(id_consonants, name))
if len(schop) > 1 and schop[0] == 'y' and schop[1] in 'aeiou':
return schop[1:]
elif len(name) > 0 and schop == '':
return name
elif... |
8faaf7e90939099218fe30068e6dd0f87970d0ea | jeanbcaron/course-material | /exercices/210/solution.py | 305 | 3.640625 | 4 | def is_prime(a):
b = 0
for i in range(int(pow(a, 0.5))):
if a % (i+2) == 0:
if a != (i+2):
b = 1
if b == 1 or a == 1:
return False
if b != 1:
return True
sol = 0
for j in range(1000):
if is_prime(j):
sol = sol + j
print(sol)
|
63882b27e6281cf19c5c09307166dc8976eb3947 | jeanbcaron/course-material | /exercices/200/solution.py | 212 | 3.671875 | 4 | def is_prime(a):
b = 0
for i in range(int(pow(a, 0.5))):
if a % (i+2) == 0:
if a != (i+2):
b = 1
if b == 1:
return False
if b != 1:
return True
|
9e71ea1ce5ac93f533969630e9586799065740b1 | SfundoMhlungu/Suicide-Checkers-py | /helpers.py | 3,781 | 3.8125 | 4 | # the functions below are helpers, the howmany left is for the minimax hearistic value
# the nbo possible moves checks which player has won
# virtual move original created for minimax to make a fake move on a board, until it minimax finds the most optimal one
#####################attempt translation to cpp############... |
3af51321a5e8cfa7f75ff8898713152e13fb660d | bootphon/word-count-estimator | /wce/word_count_estimation/rttm_processing.py | 4,803 | 3.53125 | 4 | """Rttm processing
Module to extract segments of speech from the original wavs by reading its
related .rttm file and gather the results of the WCE on the segments that come
from the same audio.
The module contains the following functions:
* extract_speech - extract speech for one file.
* extract_speech_from... |
7e68241f8b3d58f5cd910f472dc9349080c5ab73 | koukic/perceptron | /perceptron.py | 3,244 | 3.578125 | 4 | import numpy as np
import matplotlib.pylab as plt
# パーセプトロンクラス
class PerceptronClassifier:
def __init__(self, alpha, t , x):
self.alpha = alpha
self.weight = np.random.uniform(-1.0, 1.0, 3) # -1.0~1.0の乱数を3つ
self.x = x
self.t = t
# 点を描画
self.plot_pixels()
# 点を描... |
6289c503c8bcb4f018b0246ca7701e33e69b73f8 | oorion/exercism | /python/word-count/wordcount.py | 339 | 3.8125 | 4 | import re
def word_count(sentence):
split_sentence = re.split(' +| *\n *|\t', sentence)
output = {}
for x in split_sentence:
output[x] = count_word(x, split_sentence)
return output
def count_word(word, iterable):
count = 0
for x in iterable:
if x == word:
count += 1... |
d4d24193ecd8d87635579b434a0f36469de8a147 | Keyurchaniyara/CompetitiveProgramming | /Interview Questions/04_Valid_Anagram.py | 342 | 3.5 | 4 | class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if sorted(s) == sorted(t):
if 1<=len(s)<=(5*pow(10,4)):
return True
else:
if 1<=len(s)<=(5*pow(10,4)):
return False
s = Solution()
s.isAnagra... |
429abba14b7125c258e394db7f1d27a6cde567dc | hmakinde/Python-Challenge-HM | /PyPoll/PyPoll_main.py | 2,878 | 3.734375 | 4 | import csv
import os
import numpy as np
electionfile = os.path.join("Resources", "election_data.csv")
candidates = []
votes = []
filetype = "main"
#Creates dictionary to be used for candidate name and vote count.
poll = {}
#Sets variable, total votes, to zero for count.
total_votes = 0
with open(electionfile, newl... |
2c90b90bc91309e327def9cd93abe87e177a8626 | WisdomDaPhoenix/Python | /Curse Words Program.py | 791 | 3.84375 | 4 | #Change all curse words to '****' within a string, simulating parental controls
s = input('Enter a string: ')
L = ['darn','dang','freakin','heck','shoot','Darn','Dang','Freakin','Heck','Shoot']
for i in range(len(s)):
for t in L:
if t in s:
s = s.replace(t,len(t)*'*',-1)
print(s)
#O... |
e12b92bd3b8ba18d92db758aacfbae6a4c6abce0 | Aparecida-Silva/Funcao-Split-e-len | /Média.py | 467 | 3.9375 | 4 | nota1 = eval(input("Digite a sua primeira nota: "))
nota2 = eval(input("Digite a sua segunda nota: "))
print("")
if (nota1 <= 60 and nota2 <= 60):
valor1 = nota1 * (100 / 100)
print("O valor da sua primeira nota: ")
print(valor1)
valor2 = nota2 * (80 / 100)
print("O valor da sua segunda nota: ")
print(valo... |
d2cc6c889ff35b1baba911fe72bb842af86d6d58 | Cyvid7-Darus10/Codecademy | /Learn Complex Data Structures/HashMapsPython.py | 2,025 | 3.5 | 4 | class HashMap:
def __init__(self, array_size: int):
self.array_size = array_size
self.array = [None for item in range(array_size)]
def hashFunc(self, key, count_collisions: int = 0) -> int
key_bytes = key.encode()
hash_code = sum(key_bytes)
return (hash_code + count_collisions) % self.array_siz... |
4929c3e42fb811f577c1151575655f4da7a70294 | aakankshamudgal/ML | /class.py | 305 | 3.71875 | 4 | class Calculator:
def add(a,b):
return a+b
def sub(a,b):
if(a>b):
return a-b
else:
return b-a
def mul(a,b):
return a*b
def div(a,b):
return a/b
def mod(a,b):
return a%b
x=add(4,5)
print(x)
y=sub(6,7)
print(y)
z=mul(3,2)
print(z)
c=div(4,2)
print(c)
d=mod(4,2)
print(d)
|
aa0ab44c8775e6173887aad4251acf933ceaf4fc | Mitchellsuiter/Coding-projects-Junior-year | /Port_scanner.py | 1,094 | 3.53125 | 4 | import socket
ip_address_list = ['31.13.74.36', '172.217.14.174', '40.97.142.194']
for ip in ip_address_list:
print("Begin IP Scan on: " + ip + ".")
try:
for port in range(1,1000):
#Create the Socket
aSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
... |
edb9dccf04443ff5c38694de85b8d63d5277cabd | NathanaelLeclercq/VSA-literate-waddlee | /scratches/scratch_2.py | 305 | 3.8125 | 4 | def myfunction():
print "I called My function"
myfunction()
def largest(x,y):
ans = x
if y > x:
return ans
largenum = largest(2,5)
print largenum
def getnum(prompt):
ans = int(raw_input(prompt))
age = getnum("what is you age?")
grade = getnum("what is your grade?")
|
6fd152a4821d311a934af8f894430e0775157083 | Broges/brogesBrewApp | /core/menuSelect.py | 2,265 | 3.734375 | 4 | '''This file handles the menus; it prints out the users options and
calls the methods required when the relevant option is chose.
Essentially this is the 'control tower'. '''
from core.roundClass import user_round
from core.dbManager import db
from core.preferenceClass import pref
from core.utils import clearScre... |
f04517f886ac4216950a25cb0fa3ace817c4924d | Varobinson/python101 | /print-a-square.py | 102 | 3.71875 | 4 | #Print a 5x5 square of * characters.
square = 1
while square <= 5:
print('*' * 5)
square += 1 |
761768971347ca71abb29fcbbaccf6ef92d4df86 | Varobinson/python101 | /tip-calculator.py | 998 | 4.28125 | 4 | #Prompt the user for two things:
#The total bill amount
#The level of service, which can be one of the following:
# good, fair, or bad
#Calculate the tip amount and the total amount(bill amount + tip amount).
# The tip percentage based on the level of service is based on:
#good -> 20%
#fair -> 15%
# bad -> 10%
try:
... |
54fdcaea2dd283b21c319e22f23530b961161eee | Ryanj-code/Python-1-and-2 | /Assignment/peer-programming.py | 783 | 4.09375 | 4 | #Ryan, Briana
#Shipping Cost
weight = float(input("what is the weight of the package in pounds?"))
if weight <= 2:
newWeight = weight * 1.50
print("you pay $ " + str(newWeight))
elif weight >2 and weight <=6:
newWeight = weight * 3
print("you pay $ " + str(newWeight))
elif weight >6 and weight <=10:
newWei... |
94bdd2d96de22c8911e7c22e46405558785fc25e | chhikara0007/intro-to-programming | /s2-code-your-own-quiz/my_code.py | 1,211 | 4.46875 | 4 | # Investigating adding and appending to lists
# If you run the following four lines of codes, what are list1 and list2?
list1 = [1,2,3,4]
list2 = [1,2,3,4]
list1 = list1 + [5]
list2.append(5)
# to check, you can print them out using the print statements below.
print list1
print list2
# What is the difference betw... |
1e710775997e19734be2cb46470f80d70c8bf8e1 | StefanKaeser/pybites | /157/accents.py | 300 | 3.859375 | 4 | import unicodedata
def filter_accents(text):
"""Return a sequence of accented characters found in
the passed in lowercased text string
"""
accents = []
for char in text:
if "WITH" in unicodedata.name(char):
accents.append(char.lower())
return accents
|
852fc5577d995bc8b08cd8f094362b7790c28949 | StefanKaeser/pybites | /53/text2cols.py | 921 | 3.875 | 4 | import textwrap
import itertools
COL_WIDTH = 20
def _pad(string, width=COL_WIDTH):
length = len(string)
if length > width:
raise ValueError
return string + " " * (width - length)
def _pad_list(lst, width=COL_WIDTH):
return [_pad(line) for line in lst]
def text_to_columns(text):
"""Spl... |
24373fa1a842ccab6ed11851f7cb9ac19167b246 | StefanKaeser/pybites | /170/mcdonalds.py | 1,235 | 3.671875 | 4 | import pandas as pd
data = "https://s3.us-east-2.amazonaws.com/bites-data/menu.csv"
# load the data in once, functions will use this module object
df = pd.read_csv(data)
pd.options.mode.chained_assignment = None # ignore warnings
def get_food_most_calories(df=df):
"""Return the food "Item" string with most cal... |
8f0491dde7bb67ae7e44ba31e7444fe8524d4bd4 | StefanKaeser/pybites | /208/combos.py | 142 | 3.6875 | 4 | import itertools
def find_number_pairs(numbers, N=10):
return [pair for pair in itertools.combinations(numbers, r=2) if sum(pair) == N]
|
549105f9a1329ae66e62f2130fae97545e1051fc | StefanKaeser/pybites | /7/logtimes.py | 1,190 | 3.53125 | 4 | from datetime import datetime
import os
import urllib.request
SHUTDOWN_EVENT = "Shutdown initiated"
# prep: read in the logfile
logfile = os.path.join(os.getcwd(), "log")
urllib.request.urlretrieve(
"https://bites-data.s3.us-east-2.amazonaws.com/messages.log", logfile
)
with open(logfile) as f:
loglines = f.... |
cfc7b9509d76c84061e8f77e4c0e37ff44c1c6f7 | StefanKaeser/pybites | /79/community.py | 792 | 3.546875 | 4 | import csv
import requests
from collections import Counter
CSV_URL = "https://bites-data.s3.us-east-2.amazonaws.com/community.csv"
def get_csv():
"""Use requests to download the csv and return the
decoded content"""
with requests.get(CSV_URL) as r:
content = (line.decode("utf-8") for line in ... |
3616c18c64f87459c4219d8512aa24b7f80ea3cd | StefanKaeser/pybites | /51/miller.py | 883 | 3.5625 | 4 | from datetime import datetime, timedelta
# https://pythonclock.org/
PY2_DEATH_DT = datetime(year=2020, month=1, day=1)
BITE_CREATED_DT = datetime.strptime('2018-02-26 23:24:04', '%Y-%m-%d %H:%M:%S')
def py2_earth_hours_left(start_date=BITE_CREATED_DT):
"""Return how many hours, rounded to 2 decimals, Python 2 ha... |
592e186d9725f23f98eaf990116de6c572757063 | Lobo2008/LeetCode | /581_Shortest_Unsorted_ContinuousSubarray.py | 1,749 | 4.25 | 4 | """
Given an integer array, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order, too.
You need to find the shortest such subarray and output its length.
Example 1:
Input: [2, 6, 4, 8, 10, 9, 15]
Output: 5
Explanation:... |
ee897f18008dc3589302522ed41601a88c158c27 | Lobo2008/LeetCode | /35_Search_Insert_Position.py | 1,605 | 4 | 4 | """
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
Input: [1,3,5,6], 5
Output: 2
Input: [1,3,5,6], 7
Output: 4
Input: [1,3,5,6], 0
Output: 0
Input: [1,3,5,6], 7
Out... |
efe54b9bf0d0a67475c24c0f15d02af1cc90192c | Lobo2008/LeetCode | /test14.py | 99 | 3.75 | 4 |
dic = {}
#f = "f"
#dic[f] = 10
if dic[f]:
print ('it is true')
else:
print ('it is false')
|
391adea82bbde9668280bfefc17c093da87a21c0 | Lobo2008/LeetCode | /128_Longest_Consecutive_Sequence.py | 2,734 | 3.890625 | 4 | """
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
Your algorithm should run in O(n) complexity.
Example:
Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
"""
class Solutio... |
ea2c7f0edc20071d14c98f3ac9fe25a888fc44f5 | Lobo2008/LeetCode | /102_Binary_Tree_Level_Order_Traversal.py | 2,191 | 4.03125 | 4 | """
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]
"""
# Definition for a binary... |
47a80668234357c9a895b6e1cafb240e5d2558db | Lobo2008/LeetCode | /210_Course_Schedule_II.py | 4,310 | 4.34375 | 4 | """
There are a total of n courses you have to take, labeled from 0 to n-1.
Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]
Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you shou... |
b2ba355049335f52c4304acf09b436bb471a97cb | Lobo2008/LeetCode | /213_House_Robber_II.py | 4,827 | 3.8125 | 4 | """
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have security system connected and it will automatically co... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.