blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
c2ca9dfe9e0b1056931fe992e987daa7cc689d10 | nat-sharpe/Python-Exercises | /Day_3/strings_reverse.py | 162 | 3.71875 | 4 | message = "storm the castle!"
message_reverse = ""
for i in range(len(message)):
letter = message[-i-1]
message_reverse += letter
print message_reverse |
e669fe212b5780d4db0e9e085e7bfe559759821d | nat-sharpe/Python-Exercises | /Day_5/dict.py | 141 | 3.734375 | 4 | height = 4
character = '*'
space = height * ' '
for i in range(height):
print space * + character
character += '**'
height -= 1 |
ce4321fb63f8aaec7d187fb11161fc3dc5edfbf7 | michaelsvanbeek/mvb_py | /mvb/plotlyh.py | 1,315 | 3.53125 | 4 | import pandas as pd
import plotly
import plotly.plotly as py
import plotly.figure_factory as ff
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
import plotly.graph_objs as go
#from plotly import tools
init_notebook_mode(connected=True)
def top_n_pie_chart(df,val_col,n=50,title=None):
... |
4880bb4f725977a94fa7364d20fc57bbb063e84a | AlexWufan/StockPrediction | /fetchdata.py | 628 | 3.671875 | 4 | import sqlite3
import numpy as np
def get_data(stock_name='YHOO'):
conn = sqlite3.connect('stockHistory.db')
cursor = conn.cursor()
stock_name = tuple([stock_name])
N = 100
# find the max date of the records in DB
cursor.execute('SELECT ClosePrice FROM HistoryValue '
'WHERE ... |
d61d378c7de2d678ebcfb585d2ccdb327d5b300b | mathewsnamanda/python_projects | /day 2/age_challange.py | 234 | 3.828125 | 4 | age=input("enter your age in years:\n")#all inputs is usually floats therefore casting is required
years=90-int(age)
months=years*12
weeks=52*years
days=365*years
print(f"you have got {months} months,{weeks} weeks and {days} days \n") |
802baa4d293f6ab26ece51eb84ab4106311d5516 | YADRO-KNS/py-timeout | /tests/test_timeout.py | 1,455 | 3.8125 | 4 | """
Unit tests for "timeout.timeout" decorator function
"""
import time
import unittest
from timeout import timeout, TimeoutException
class TestTimeout(unittest.TestCase):
@timeout(duration=0.5)
def blocking_function(self):
while True:
time.sleep(1)
@timeout(duration=0.5)
def no... |
c426a2b21b293cd43fcc573c56194f0def1e83d7 | blueriver212/Sanition_hub | /Python/Classes/OrganisationAndUser.py | 9,867 | 3.671875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 27 14:27:10 2019
@author: gather3
"""
#from User import User, SuperUser
from datetime import datetime as dt
import re
# =============================================================================
# ---------------------------- Organis... |
c0094570cea993b229dae7647ca53c1799dec816 | celona/brush_up | /py-basics/dictionary1.py | 652 | 4.03125 | 4 | myDictionary = {'Key-1': 'Element-1', 'Key-2': 'Element-2', 'Key-3': 'Element-3', 'Key-4': 'Element-4'}
print( myDictionary['Key-3'])
integerDictionary = {10: "C++", 20: "Java", 30: "Python", 40: "Ruby", 50: "C#", 60: "Perl"}
print (integerDictionary[30])
identity = {"name": "Sal", "age": "23", "username": "celona"... |
187fad68aee84d130022135fd0f67880208eb503 | RahatIbnRafiq/leetcodeProblems | /Hash Table Problems/204. Count Primes.py | 420 | 3.578125 | 4 | class Solution(object):
def countPrimes(self, n):
if n < 2:return 0
isPrime = [1]*(n)
isPrime[0],isPrime[1] = 0,0
i = 2
while i*i < n:
if isPrime[i] == 0:
i+=1
continue
j = i*i
while j < n:
is... |
654f589541a9affc108470ae6d9da623b227bd1a | RahatIbnRafiq/leetcodeProblems | /Linked List Problems/203. Remove Linked List Elements.py | 890 | 3.671875 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def removeElements(self, head, val):
if not head: return None
d1,d2 = ListNode(0),ListNode(0)
d1.next = head
current ... |
7f0d6faf428c7f61ac3b7363355639213d4833fa | RahatIbnRafiq/leetcodeProblems | /Linked List Problems/82. Remove Duplicates from Sorted List II.py | 764 | 3.640625 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def deleteDuplicates(self, head):
d1,d2 = ListNode(0),ListNode(0)
d1.next = head
cur2 = d2
while d1.next:
... |
00b1bd571657f364e9322e5f027f42ccf117c271 | RahatIbnRafiq/leetcodeProblems | /Linked List Problems/147. Insertion Sort List.py | 1,410 | 3.921875 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def insertionSortList(self, head):
if not head or not head.next: return head
d1,d2 = ListNode(0),ListNode(0)
d1.next = head
w... |
5c2e50afa9c5447740a937b187b266bad5e9209a | RahatIbnRafiq/leetcodeProblems | /Trie/676. Implement Magic Dictionary.py | 794 | 3.6875 | 4 | class MagicDictionary(object):
def __init__(self):
self.dict = dict()
def buildDict(self, dict):
for word in dict:
self.dict[len(word)] = self.dict.get(len(word),[])+[word]
def search(self, word):
if len(word) not in self.dict:
... |
98befeca3a8b485cd2b9531a87ca206887c8bd1a | RahatIbnRafiq/leetcodeProblems | /Tree/117. Populating Next Right Pointers in Each Node II.py | 826 | 3.65625 | 4 |
class TreeLinkNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
self.next = None
class Solution:
def connect(self, node):
tail = dummy = TreeLinkNode(0)
while node:
tail.next = node.left
if tail.next:
... |
43e7f689d23d1f62d66b9e8b56ac167b701b3f57 | RahatIbnRafiq/leetcodeProblems | /Heap/355. Design Twitter.py | 1,205 | 3.515625 | 4 | import heapq
class Twitter(object):
def __init__(self):
self.followmap = dict()
self.tweetmap = dict()
self.time = -1
def postTweet(self, userId, tweetId):
self.time+=1
self.tweetmap[userId] = self.tweetmap.get(userId,[])+[(self.time,tweetId)]
def ge... |
5ec2cefcdc822f5cd6bb891a2ba7e1d0a46902c3 | RahatIbnRafiq/leetcodeProblems | /Tree/637. Average of Levels in Binary Tree.py | 855 | 3.640625 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def averageOfLevels(self, root):
if not root:
return [0]
result = []
stack = [[root]]... |
5fff370ffe4cec5254400cd2586dbb7bc958e4e4 | RahatIbnRafiq/leetcodeProblems | /Tree/563. Binary Tree Tilt.py | 834 | 3.78125 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
res = 0
def helper(self,root):
if not root:return 0
else:
if root.left and root.right:
... |
d631143c34c49a7a7f1765f4d08d610419d1e7f4 | RahatIbnRafiq/leetcodeProblems | /Hash Table Problems/290. Word Pattern.py | 514 | 3.578125 | 4 | class Solution(object):
def wordPattern(self, pattern, str):
map1,map2 = {},{}
strs = str.strip().split(" ")
pattern = list(pattern)
if len(pattern) != len(strs):return False
for s,c in zip(strs,pattern):
if s not in map1 and c not in map2:
map1[s]... |
3a93be009f482e884c8e99d6b97dc4d8974df367 | JohnathanLP/minecraftpython | /Intermediate 2016/function.py | 824 | 4.0625 | 4 | import time
def scaryMathThing(a):
"This is the scary math function"
print "Hold on a second, I will do the math"
time.sleep(1)
print "."
time.sleep(1)
print "."
time.sleep(1)
print "."
return (((a+4)/5)+19%(8+a))
def anotherScaryMathThing(a,b,c):
"This is another scary math th... |
c7f69ed355eee737c19b6baabf2f32a1c1d6eae6 | GCatSword/m02_boot_0 | /funciones1nivel.py | 411 | 3.65625 | 4 | def normal(x):
return x
def cuadrado(y):
return y * y
def cubo(x):
return x**3
#Admite funciones como parametros de entrada
def sumaTodos(limitTo, f):
resultado = 0
for i in range(limitTo +1):
resultado += f(i)
return resultado
if __name__ == '__main__':
print(su... |
fb971ad16bda2bb5b3b8bff76105a45510bcc24c | fyupanquia/idat001 | /a.py | 469 | 4.125 | 4 | name = input("Enter your name: ")
worked_hours = float(input("How many hours did you work?: "))
price_x_hour = float(input("Enter your price per hour (S./): "))
discount_perc = 0.15;
gross_salary = worked_hours*price_x_hour
discount = gross_salary*discount_perc
salary=gross_salary-discount
print("")
print("*"*10)
print... |
f366cde2b71a43c63c11c903bbce646f4a14b811 | FernandoPZ/oop | /example06(clases).py | 3,134 | 3.609375 | 4 | class Operations:
def __init__(self):
pass
#Areas
#Cuadrado
def area_cuadrado (self,lado):
return lado*lado
#Circulo
def area_circulo (self,radio):
return 3.1415926535897932384626433832795028841971694*(radio*radio)
#Triangulo
def area_triangulo (self,base,altura):
return (base*altura)/2
... |
ccc59ee295963667b4eb4f4a9bd60b9555d3aac3 | mcc-sw-eng-course/python-programs-AnMontes | /L4/Problem14.py | 2,872 | 3.8125 | 4 |
class MyPowerClass:
def __init__(self):
self.classList = []
def add_item(self, item):
if type(item) in [int, float]:
self.classList.append(item)
else:
raise TypeError("The type of the argument is not a float or integer.")
def remove_item(self, pos):
... |
cab81f2879b797eaa20ade77b082c8d62e8abd1f | mkjmkumar/PythonCheatSheet_SampleCode | /FileHandleRead.py | 525 | 3.765625 | 4 | newfile=open("text1.txt",'r')
print(type(newfile))
contents=newfile.read()
print(contents)
print(type(contents))
print("to get the contents as a list")
contents1=newfile.readlines()
print(contents1)
print("it prints an empty list, as the cursor is at the end of all lines. pointer should be moved back")
n... |
78950eee5553e796b9f7130143984bf4b7a9e524 | lrazovic/exercism | /python/perfect-numbers/perfect_numbers.py | 563 | 3.640625 | 4 | def divisorGenerator(n: int):
large_divisors = []
for i in range(1, int(n ** 0.5 + 1)): # From 1 to sqrt(n) + 1
if n % i == 0:
yield i
if i * i != n:
large_divisors.append(n / i)
for divisor in reversed(large_divisors):
yield int(divisor)
def classi... |
53c03c6cc11ca27d6b2663b28c7f6d04a62cf31b | lrazovic/exercism | /python/armstrong-numbers/armstrong_numbers.py | 176 | 3.734375 | 4 | def is_armstrong_number(number):
numbers = str(number)
exp = len(numbers)
sum = 0
for elem in numbers:
sum += int(elem) ** exp
return sum == number
|
b431c5d78b5a3eb9dd02e5cdb35abf4e5c3c2bd1 | kaushik4u1/Hackerrank_Solutions | /30 days of code(Python)/Day 2-Operators/op.py | 1,013 | 3.828125 | 4 | i = 4
d = 4.0
s = 'HackerRank '
# Declare second integer, double, and String variables.
i1 = int(input())
d1 = float(input())
s1 = input('')
# Read and save an integer, double, and String to your variables.
# Print the sum of both integer variables on a new line.
print(i+i1)
# Print the sum of the double va... |
9084441c183522dff77fdbd9de1aea55f39c1e58 | kaushik4u1/Hackerrank_Solutions | /30 days of code(Python)/Day 23-BST Level-Order Traversal/bst(lot).py | 1,387 | 3.828125 | 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)
... |
0e15c2d10d4238cb1296082e0a53fdaef4c51c49 | Saswati08/Data-Structures-and-Algorithms | /LinkedList/insert_in_sorted_list.py | 758 | 3.859375 | 4 | class node:
def __init__(self, val):
self.data = val
self.next = None
def insertInSorted(head,data):
#code here
if head == None:
return
if data < head.data:
nw = Node(data)
nw.next = head
return nw
prev = head
curr = head.next
... |
ee62e83e3e378d95e107634ffae9557ad75d036a | Saswati08/Data-Structures-and-Algorithms | /Heap/kth_largest_element_klogn.py | 470 | 3.640625 | 4 | from heapq import heappush, heappop, heapify
def kthLargest(a,n,k):
'''
:param a: given array
:param n: size of array
:param k: value of k
:return: Integer.
'''
# code here
heap = []
for i in range(n):
heappush(heap, a[i])
for i in range(n - k):
... |
5418454d1fee7ab57d064d4861146d2448f3c6f2 | Saswati08/Data-Structures-and-Algorithms | /Trees/connect_nodes_same_level.py | 1,297 | 4.03125 | 4 | class Node:
# Constructor to create a new node
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def connect(root):
'''
:param root: root of the given tree
:return: none, just connect accordingly.
{
# Node Class:
cla... |
a068a38e9ea2aabb2e77bdc3b21a96a9162257f3 | Saswati08/Data-Structures-and-Algorithms | /LinkedList/count_length_of_loop.py | 648 | 3.859375 | 4 | class node:
def __init__(self, val):
self.data = val
self.next = None
def countNodesinLoop(head):
#Your code here
if head.next == None:
return 0
slow = head
fast = head.next.next
while(fast != None and fast.next != None and slow != fast):
slow = slow.next
... |
6f1b6bb22751945bbf05b2b32222d0e2a3dd06b3 | Saswati08/Data-Structures-and-Algorithms | /Trees/check_identical.py | 1,016 | 3.8125 | 4 | class Node:
# Constructor to create a new node
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def isIdentical(root1, root2):
# Code here
if root1 == None and root2 == None:
return True
if root1 == None or root2 == None:
... |
f05113e00818364a6f7639000b238ce571170d70 | Saswati08/Data-Structures-and-Algorithms | /BST/insert_and_delete_node_in_BST.py | 1,523 | 3.8125 | 4 | class Node:
def __init__(self, data, left=None, right=None):
self.data = data
self.left = left
self.right = right
def inorder(root):
if root is None:
return
inorder(root.left)
print(root.data, end=' ')
inorder(root.right)
def insert(root, key):
# if the root is None, create a node and return it
if ro... |
a267eff041e8e97141b82ad952deee9cf83c8b5e | Saswati08/Data-Structures-and-Algorithms | /Heap/finding_median_in_a_stream.py | 1,612 | 4.125 | 4 | def balanceHeaps():
'''
use globals min_heap and max_heap, as per declared in driver code
use heapify modules , already imported by driver code
Balance the two heaps size , such that difference is not more than one.
'''
# code here
global min_heap
global max_heap
if len(max_heap) - l... |
e7e0b717d60e2b54f5aebd2a94f34afbe9e48428 | Saswati08/Data-Structures-and-Algorithms | /String/check_two_string_isomorphic.py | 1,232 | 4 | 4 | '''
Your task is to check if the given strings are
isomorphic or not.
Function Arguments: s and p (given strings)
Return Type: boolean
'''
def areIsomorphic(s,p):
hash_map1 = {}
hash_map2 = {}
if len(s) != len(p):
return False
for i in range(len(s)):
if s[i] not in hash_map1 and p... |
8e1fe44a03b1895af8ae7d5d1dd18f874ce35572 | Saswati08/Data-Structures-and-Algorithms | /Stack/infix_to_postfix.py | 978 | 3.96875 | 4 | def greater(ch, top):
precedence = {'+':1, '-':1, '*':2, '/':2, '^':3}
if top in precedence:
return precedence[top] >= precedence[ch]
else:
return False
def InfixtoPostfix(exp):
#code here
postfix = ""
stack = []
for i in range(len(exp)):
ch = exp[i]
# p... |
413317bece827257a505b7cabb9920e16843c41d | Saswati08/Data-Structures-and-Algorithms | /String/uncommon_character_in_2_strings.py | 591 | 3.765625 | 4 | t = int(input())
m = 0
while(m < t):
string1 = input()
string2 = input()
hash_map1 = {}
hash_map2 = {}
# print(string1[0])
for i in range(len(string1)):
hash_map1[string1[i]] = 1
for i in range(len(string2)):
hash_map2[string2[i]] = 1
# print(hash_map1, hash_map2)
res... |
e5e9ccac721bd2076f6249d9c3ce6f5929e8f595 | Saswati08/Data-Structures-and-Algorithms | /BST/inorder_array_to_BST.py | 809 | 3.609375 | 4 | class Node:
def __init__(self, value):
self.data = value
self.left = None
self.right = None
def construct_tree(inorder_arr, index):
if index[0] > index[1]:
return None
mid = (index[0] + index[1])//2
key = inorder_arr[mid]
nw = Node(key)
nw.left = construct_tree(in... |
941e245a5f7a260e26450cfc9aa5d7776a9efa02 | Saswati08/Data-Structures-and-Algorithms | /LinkedList/reverse_doubly_linked_list.py | 1,816 | 4.0625 | 4 | import gc
# A node of the doublly linked list
class Node:
# Constructor to create a new node
def __init__(self, data):
self.data = data
self.next = None
self.prev = None
class DoublyLinkedList:
# Constructor for empty Doubly Linked List
def __init__(self): ... |
5c477eb07b025e96e0c330a7d3a3da7200103ac8 | Saswati08/Data-Structures-and-Algorithms | /DP/print_nth_fibonacci_number.py | 392 | 3.984375 | 4 |
#Given a number N, print the first N Fibonacci numbers.
def printFibb(n):
# your code here
result = []
result.append(1)
result.append(1)
if n == 1:
return result[:1]
if n == 2:
return result[:2]
else:
for i in range(2, n):
result.append(resu... |
6b2cdaf9d7ba090a18e3f95b665758961dfb3a38 | Saswati08/Data-Structures-and-Algorithms | /Trees/postorder_from_inorde_and_preorder.py | 466 | 3.625 | 4 |
def printPostOrder(inorder, preorder, n):
# Code here
ind = inorder.index(preorder[0])
if ind != 0:
printPostOrder(inorder[:ind], preorder[1: ind + 1], len(inorder[:ind]))
if ind != n - 1:
printPostOrder(inorder[ind + 1:], preorder[ind + 1:], len(inorder[ind + 1:]))
p... |
a611825d53906bdcc026d3c3bb572b8bfdb1b3fc | Saswati08/Data-Structures-and-Algorithms | /String/permutations_of_string.py | 492 | 3.703125 | 4 | def toString(List):
return ''.join(List)
def permute(s, l, r):
if l == r:
# print(toString(s), end = " ")
out.append(toString(s))
return
for j in range(l, r + 1):
s[l], s[j] = s[j], s[l]
permute(s, l + 1, r)
s[j], s[l] = s[l], s[j]
t ... |
74ce7436f20f9b9b9922593b018a34d17b076ecb | Saswati08/Data-Structures-and-Algorithms | /String/implement_atoi.py | 627 | 3.71875 | 4 | # function should return an integer
def atoi(string):
# Code here
sign = 1
if string[0] == '-':
string = string[1:]
sign *= -1
s = 0
value = {'0' : 0, '1': 1, '2': 2, '3': 3, '4' : 4, '5': 5, '6': 6, '7' : 7, '8': 8, '9' : 9}
for i in range(len(string)):
if string[i] > '9... |
4cfb40653b2f32eaff4f9aece71df5ded74868e6 | Saswati08/Data-Structures-and-Algorithms | /BST/get_count_of_nodes_in_specific_range.py | 952 | 3.921875 | 4 | class Node:
def __init__(self, data, left=None, right=None):
self.data = data
self.left = left
self.right = right
def insert(root, key):
# if the root is None, create a node and return it
if root is None:
return Node(key)
# if given key is less than the root node, recur for left subtree
if key < root.dat... |
fd66e0908166c686971c2164cb81331045a54f49 | AniyaPayton/GWC-SIP | /gsw.py | 1,714 | 4.375 | 4 | import random
# A list of words that
word_bank = ["daisy", "rose", "lily", "sunflower", "lilac"]
word = random.choice(word_bank)
correct = word
# Use to test your code:
#print(word){key: value for key, value in variable}
# Converts the word to lowercase
word = word.lower()
# Make it a list of letters for someone ... |
b3411650a7e0d9738d68ff8395baf7187d3d7a7c | agiuse/sudoku-svn | /sudoku_1/trunk/src/sudoku_coordinate.py | 11,674 | 3.796875 | 4 | # -*- coding: utf-8 -*-
'''
Created on 27 juil. 2011
@author: eagius
'''
# -----------------------------------------------------------------------------------
class Coordinate(object):
"""
Classe gérant les coordonnées dans la grille.
Cette classe lie entre elles les differents objets de ... |
36d2dc1c69bd82adbfd41069f361ed92a143f749 | barbs-pm/Python | /ex3.py | 250 | 3.875 | 4 | # -*- coding: utf-8 -*-
min = input("Digite quantos minutos foram usados: ")
if min < 200:
conta = min * 0.20
elif min <= 400:
conta = min * 0.18
elif min <= 800:
conta = min * 0.15
else:
conta = min * 0.08
print 'Sua conta é de R$', conta |
8c97f6a324e97390fcb0979a44e2fc3546eba93d | alinabrinza95/licenta | /pollard.py | 1,521 | 3.578125 | 4 | #aflarea celui mai mare divizor comun
def gcd(a, b):
while (b != 0):
remainder = a % b
a = b
b = remainder
return a
#aflarea celuilalt element din factorizarea unui numar format din inmultirea a doua numere prime
#prin impartirea numarului initial la primul factor prin gasit in numar
def... |
771e434f032e740764dcb6d39a6768129f414041 | Mohamed-hanafy30/Airline_transportation_statistics | /ETL_helper_2.py | 1,883 | 3.6875 | 4 |
def map_airport_name(data_frame,data_frame_airport):
'''
This function take 2 data frames as argument to map origin column code into names using airport_names.csv
file
:param data_frame:
:param data_frame_airport:
:return: data frame after mapping origin code with names
'''
mydict =... |
2b1dd3fad02a68239fc79ba48391c2e7a4866c53 | DarknessRdg/estrutura_de_dados | /Grafos/arvores_geradoras_minimas/prim.py | 3,453 | 4.125 | 4 | # A implementação original utiliza uma estrutura de dados `heap`
# como fila de prioridade, mas optei por apenas utilizar uma ordenação
# comum da lista para fins didáticos e por ser mais claro e simples para todos
from typing import Callable, Any
INFINITO = float('infinity')
class Vertice(object):
def __init__(... |
927350a643f37a636c6a6da0e0108438f8c9f4d4 | NasiaHerodotou/Codility | /StacksAndQueues/closingBracketsInString.py | 675 | 3.78125 | 4 | def solution(S):
stack = [] #create a stack
if len(S) % 2 != 0: #if the string's length is odd it means that something remains unclosed
return 0
dict = {'(': ')', '{': '}', '[': ']'}
for s in S:
if s in ('(', '{', '['): #if it is opening bracket push in stack
stack.append(s)
... |
6db403826f56d6b6da0c8d982dd35266e80130cc | CardenB/pyGames | /Memory.py | 4,014 | 3.5625 | 4 | # implementation of card game - Memory
import simpleguitk as simplegui
import random
import math
#keep track of the number of turns used to discover all cards
TURN_COUNT = 0
#number range of cards
cardRange = range(8)
#global list for deck of cards
deck = []
#global list for cards that have been exposed
exposed = []
... |
fb81eefb22eb853f27da35988a73c8d4c8d628d4 | mikias21/Code-For-Algorithms- | /queue/queueExercise/queueExercise.py | 4,387 | 3.9375 | 4 | class CircularQueue(object):
def __init__(self , limit=5):
self.queue = []
self.front = None
self.rear = None
self.size = 0
self.limit = limit
def getFront(self):
if self.front is None:
raise Exception("Queue is empty")
return self.queue[self.front]
def getRear(self):
if self.rear i... |
6a5dea69a9e604b8f0bfd1221df5a757ce35381c | mikias21/Code-For-Algorithms- | /polyregression.py | 1,762 | 4.03125 | 4 | #import libs
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
#read the csv
dataset = pd.read_csv("Position_Salaries.csv")
#get the dependant and independant vars
X = dataset.iloc[: ... |
1078dc3508263a9e2b7140b3acc899dd49bcb022 | mikias21/Code-For-Algorithms- | /linkedlist/linkedlistexercise/linkedliststack.py | 1,271 | 4.09375 | 4 | class Stack(object):
#constructor
def __init__(self):
self.top = None
self.next = None
self.data = None
self.length = 0
#constructor
def setData(self , data):
self.data = data
def getData(self):
return self.data
def setNext(self , next):
self.next = next
def getNext(self):
retu... |
773f7f5697a6229346c215c18e0eb78228610995 | mikias21/Code-For-Algorithms- | /linkedlist/SingleLinkedList.py | 5,088 | 4.0625 | 4 | class LinkedList(object):
def __init__(self):
self.head = None
self.next = None
self.data = None
self.length = 0
#setters and getters
def setData(self,data):
self.data = data
def getData(self):
return self.data
def setNext(self,next):
... |
93e21495d7db02678b8e9b5febe86df702476275 | julie-oh/starbucks-flask | /menu.py | 527 | 3.609375 | 4 | from enum import Enum
class MenuKindEnum(Enum):
BEVERAGE = 1
DESSERT = 2
menu_kind_dict = {
MenuKindEnum.BEVERAGE: {'americano', 'latte', 'green tea'},
MenuKindEnum.DESSERT: {'cake', 'cookie', 'bagel'}
}
class Menu:
def __init__(self, name, price, time):
self.name = name
self.p... |
390d31ea2d3453ce78a6bf729b888fb2f26377f1 | Maferisp/Tarea2-CI3715 | /Pension.py | 2,175 | 3.5 | 4 | from datetime import datetime
from datetime import date
from datetime import timedelta
def verification (age, sex, situation, SDate):
# Fecha actual
actual = date.today()
# Semanas reglamentarias
diasCotizados = 750*7
# Edad reglamentaria
edadH = 60
edadM = 55
paid = (actual - SDate)... |
eac890bcb120c238579e6cb133cb4aaf3cb29997 | Taimoor23/C105-BBSC | /StandardDeviation.py | 587 | 3.796875 | 4 | import math
import csv
with open('C:/Users/Bajwa/Downloads/data.csv',newline='')as f:
reader=csv.reader(f)
file_data=list(reader)
new_data=file_data[0]
def mean (new_data):
n=len(new_data)
total=0
for x in new_data:
total=total+int(x)
mean=total/n
return mean
... |
fa46bd784dcfeee4f9012ffb6ab6731d2764c9fa | awesometime/learn-git | /Data Structure and Algorithm/Data Structure/Tree/BST_Tree/binary_search_tree1.py | 12,239 | 3.765625 | 4 | # 来源知乎 https://zhuanlan.zhihu.com/p/51987247
# 博客 https://www.cnblogs.com/yangecnu/p/Introduce-Binary-Search-Tree.html
"""
二叉查找树 (Binary Search Tree, BST)
特点 : left < root < right
若任意节点的左子树不空,则左子树上所有结点的 值均小于它的根结点的值;
若任意节点的右子树不空,则右子树上所有结点的值均大于它的根结点的值;
任意节点的左、右子树也分别为二叉查找树;
没有键值相等的节点(no ... |
11d0968998875136df4c263ec4f608e01c730196 | awesometime/learn-git | /Data Structure and Algorithm/Data Structure/Sorted_Search/shell_sort.py | 2,259 | 3.6875 | 4 | # 时间复杂度:O(nlogn) 2、空间复杂度:O(1) 3、非稳定排序 4、原地排序
# todo 好处
def shellSort(alist):
# len(alist) 每次除2
sublistcount = len(alist) // 2 # sublistcount分组数目
# 直到最后sublistcount=1,即gap=1 变成插入排序,步长为1,最后全部排序完毕
while sublistcount > 0:
# 对sublistcount 组中的每组进行insert_sort
for startposition in range(su... |
71262a0af88d9a1bb7a1f070f2643133d9fe44bb | awesometime/learn-git | /Data Structure and Algorithm/Data Structure/Basic/decorator.py | 2,052 | 3.84375 | 4 | # def f():
# it=0
# while it < 5:
# x = yield 100000000000000
# print(x)
# it -= 1
#
# # 怎么迭代
#
# listt = [_. for _ in f()]
# print(listt)
"""
https://www.zhihu.com/question/26930016
装饰器在Python使用如此方便都要归因于Python的函数能像普通的对象一样能作为参数传递给其他函数,
可以被赋值给其他变量,可以作为返回值,可以被定义在另外一个函数内。
"""
# import os,... |
e35af480179813669a7452c6d866a5122e638046 | awesometime/learn-git | /Data Structure and Algorithm/Data Structure/Tree/BST_Tree/binary_search_tree3.py | 11,922 | 4.125 | 4 | #!/bin/env python3.1
# Bradley N. Miller, David L. Ranum
# Introduction to Data Structures and Algorithms in Python
# Copyright 2005, 2010
#
import unittest
"""
暂时弃用此方法 python库里的方法 不太好理解
二叉查找树 BST :大小从左到右依次排
特色: 跟踪了self.parent = parent的二叉查找树实现方法
"""
class BinarySearchTree:
'''
Author: Brad Miller
Date:... |
a50ec0bb69075d06886309d4c8f95aa7e6b38ee2 | awesometime/learn-git | /Data Structure and Algorithm/Data Structure/ListNode/TreeNode.py | 1,644 | 4.34375 | 4 | ###
二叉树的产生及递归遍历
class TreeNode:
def __init__(self, value=None, left=None, right=None):
self.value = value
self.left = left # 左子树
self.right = right # 右子树
root = TreeNode('D', TreeNode('B', TreeNode('A'), TreeNode('C')), TreeNode('E', right=TreeNode('G', TreeNode('F'))))
print(root.value... |
54ca03d220d43b4d8e65190b74492e43ec218d0b | MaciejBedkowski/Hangman | /Hangman/Gallows.py | 1,412 | 3.703125 | 4 | def Gallows(wrongDecision):
if wrongDecision == 0:
print("+-----+---")
print("| | ")
print("| ")
print("| ")
print("| ")
print("|_________")
elif wrongDecision == 1:
print("+-----+---")
print("| | ")
prin... |
f873c177b269ff834f3cb930f14b17d6295c4c1c | kronicle114/codewars | /python/emoji_translator.py | 837 | 4.4375 | 4 | # create a function that takes in a sentence with ASCII emoticons and converts them into emojis
# input => output
# :) => 😁
# :( => 🙁
# <3 => ❤
ascii_to_emoji = {
':)': '😁',
':(': '🙁',
'<3': '❤️',
':mad:': '😡',
':fire:': '🔥',
':shrug:': '¯\_(ツ)_/¯'
}
def emoji_translator(input, mapper):
... |
4286cd082caae7d98aebb0fa784c2925e6f8414c | uladkasach/News-vs-Volatility | /data_analysis/regression_assessment.py | 3,430 | 3.578125 | 4 | '''
1. load data
2. split data : https://stackoverflow.com/questions/24147278/how-do-i-create-test-and-train-samples-from-one-dataframe-with-pandas/35531218
- train, test[, validate]
3. train model
- linear-regression
- svm-regression
- neural-network
'''
import argparse;
imp... |
c1eb10c031b9b5f8a91edf0f196e138452e58e63 | Jp9910/Projeto-e-Analise-de-Algoritmos | /branchAndBound.py | 1,305 | 3.703125 | 4 | class Tarefa():
def __init__(self) -> None:
self.alocada = False
class Pessoa():
def __init__(self) -> None:
self.alocada = False
class Assignment():
def __init__(self,p,t,c) -> None:
self.p = p
self.t = t
self.c = c
def branchAndBound(C,n,lb,R,p,P,T):
bestLB =... |
899aeedef65f6e506c4b0d623cb47fb286dac2b6 | Jp9910/Projeto-e-Analise-de-Algoritmos | /algoritmosProbabilisticos.py | 1,106 | 3.796875 | 4 | import random
import time
def monteCarlo(X,n,k):
#Problema: Sejam n números inteiros em ordem arbitrária.
# Encontrar um número que pertença à metade superior
# (maior ou igual à mediana), considerando a ordem dos elementos
#X é o vetor da qual será escolhido aleatoriamente um ... |
182b77e348b32ccc07c0bba4d3e0ee51583f0e9c | Jp9910/Projeto-e-Analise-de-Algoritmos | /ProgramacaoDinamica/problemaDaMochila.py | 1,460 | 3.546875 | 4 | class nodeMochila():
def __init__(self,e=0,p=0) -> None:
self.existe = e
self.pertence = p
class nodeItem():
def __init__(self,v,p) -> None:
self.valor = v
self.peso = p
def printMochila(M,n,K):
for i in range(0,n):
for j in range(0,K):
print(M[i][j].exi... |
1135af9efca5a0ba6b59a376acabbe425cbd08cd | Jp9910/Projeto-e-Analise-de-Algoritmos | /Sorting/countingSort.py | 753 | 3.703125 | 4 | def countingSort(A,B,n,k):
C = [0] * (k+1) #+1 por causa que o elemento 0 precisa ser representado pelo indice 0
for i in range(0,k+1):
C[i] = 0
for j in range(0,n):
C[A[j]] += 1
for i in range(1,k+1):
C[i] = C[i] + C[i-1]
print(C)
for j in range(n-1,-1,-1):
B[C[A... |
c99b8f4136c33a0b904206cf4f05bc8fd5e3876f | Jp9910/Projeto-e-Analise-de-Algoritmos | /segundoMenorElemento.py | 526 | 3.875 | 4 |
def segundoMenorElemento(vetor) -> int:
#O(n)
if(vetor[0] < vetor[1]):
menor=vetor[0]
segMenor=vetor[1]
else:
menor = vetor[1]
segMenor = vetor[0]
for i in range(2,len(vetor)):
if(vetor[i] < menor):
segMenor = menor
menor = vetor[i]
... |
aaa9460804922b9678055189a294fd95d992ae98 | TuanSimonetti/Treinos | /ex12.py | 300 | 3.796875 | 4 | import random
num = random.randint(0, 10)
num2 = int(input('Por favor, diga-me um número de 0 à 10 e veremos se esse número é sorteado: '))
if num2 == num:
print('Parabéns, você acertou!')
else:
print('Infelizmente, você não acertou. Mais sorte na próxima vez.')
print('')
|
85cd56fa4483ce7518d0bdf3e3198cb4eeecff0f | zepher4/School-Work | /CSE015/Lab2/Equivilance.py | 456 | 3.640625 | 4 | #Recieved help from roommate
from logic import TruthTable
prop1 = raw_input("Enter the first proposition statement: ")
prop2 = raw_input("Enter the second proposition statement: ")
myTable1 = TruthTable(['p','q'], [prop1])
myTable2 = TruthTable(['p','q'], [prop2])
print myTable1.table
print myTable2.table
... |
2c3972dc66596fb987b1ccee25256c6e1f29a522 | inesamaro/JeK-Project | /JogoPython.py | 2,765 | 3.78125 | 4 | #Jogo Python Turtle
import turtle
import random
import math
#Definir ecra
wn = turtle.Screen()
wn.bgcolor("lightblue")
#Criar jogador 1
jogador1 = turtle.Turtle()
jogador1.color("red")
jogador1.shape("triangle")
jogador1.penup()
#Criar jogador 2
jogador2 = turtle.Turtle()
jogador2.color("orange")
jogador2.shape("tri... |
5c95893072cf61f4f1570542ea08caac9c315dce | ABee2410/snel | /substitution.py | 694 | 3.515625 | 4 | alphabet = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
key = "`1234567890-=qwertyuiop[]\\asdfghjkl;'zxcvbnm,./~!@#$%^&*()_+QWERTYUIOP{}|ASDFGHJKL:\"ZXCVBNM<>? "
def decrypt(message):
result = ""
for letter in message:
loc = key.find... |
1338fc48aac6360c66fa256f079f14bbc20110b0 | Ting-Crush/platform | /180618_01.py | 763 | 3.796875 | 4 | def foo():
print("hell : everyone!")
def main():
celsius = eval(input("what is the celsius temperature?"))
fahrenheit = (9/5) * celsius +32
print("The temperature is ", fahrenheit, " degrees Fanhrenheits.")
a = input()
a*4
a1 = eval(input())
a1 * 4
number = input("숫자를 입력하세요: ")
number2 =... |
89b545d48bbd0f38108029ba0069622f55f88ba5 | pereiraj72020/Math_Quiz_Game | /1003_config().py | 910 | 3.671875 | 4 | from tkinter import *
from functools import partial # To prevent unwanted windows
import random
class Start:
def __init__(self, parent):
# GUI to get user's numbers
self.start_frame = Frame(padx=10, pady=10)
self.start_frame.grid()
# Math Heading (row 1)
self.my_label = L... |
e7712241ca3c223fd1da8cb4daf00ab1a99e9063 | craigwalkerwl/100days | /Day 5/5.2 High Score.py | 399 | 3.890625 | 4 | # 🚨 Don't change the code below 👇
student_scores = input("Input a list of student scores ").split()
for n in range(0, len(student_scores)):
student_scores[n] = int(student_scores[n])
print(student_scores)
# 🚨 Don't change the code above 👆
#Write your code below this row 👇
hs = 0
for s in student_scores:
if s... |
33b0f9cee58365f1b89e25cd0d5c3fa9ab87aeb2 | craigwalkerwl/100days | /Day 14/Higher Lower Game.py | 1,238 | 3.6875 | 4 | import random
from art import logo, vs
from game_data import data
import os
def clear():
"""Clear the screen."""
os.system('cls' if os.name=='nt' else 'clear')
def get_data(a):
choice = random.choice(data)
while choice == a:
choice = random.choice(data)
return(choice)
def compare(guess, o... |
c7a0a0a2c910a60010f665a68aa323a1e1981d25 | emuroiwa/python_introduction | /loops.py | 1,090 | 4.09375 | 4 | print('xxxx')
# while
# count = 0
# while count < 5:
# if count == 3:
# continue
# print(count)
# count = count + 1
person = {
'first_name':'Asabeneh',
'last_name':'Yetayeh',
'age':250,
'country':'Finland',
'is_marred':True,
'skills':['JavaScript', 'React', 'Node', 'MongoDB... |
f48b82aa32b159552dcbe60e99a21b74d23e74d6 | sabiut/modeling-Student | /src/process/Process.py | 900 | 3.8125 | 4 | from src.student.Students import NewStudent
class Processstudents(NewStudent):
@staticmethod
def addStudent():
name = input("Enter the student name:")
data = NewStudent(name)
return data
def studentMark(student, mark):
student.marks.append(mark)
class Average(NewStudent)... |
0f425b7b6d4c9b9ef8ac837d0acef1dba7fe940c | Munkhbat0716/Hexapawn | /blackWhiteOperators.py | 4,487 | 3.984375 | 4 |
#function to move the white down and check boundaries and return the changed board
def whiteDown(game, x, y):
board = (game.board).copy()
#check if you are on white
if(board[y][x] != "w"):
return None
#check if you are out of range
if((y+1) >= game.size):
return print("Ou... |
97fa9041dc9ea3f80b5d8dc38df43bbe7ea60f76 | gullwv/pyprojects | /henlo.py | 266 | 3.828125 | 4 | # henlo.py
# created on November 13, 2018
# by Gull
def hello():
fren = str(input("what is your name, friend? ")) #get a name for variable fren
print("hello,", fren, ", and welcome to henlo.py!") #say hello to fren
print("how you doing today?")
hello() #hello!
|
c13b9693986a01dde660c844563015e8c4fd8fb1 | gullwv/pyprojects | /challenges/1.2/challenge2.py | 233 | 3.921875 | 4 | # challenge2.py
# by gull on 12/12/18
# greet the user after they input their name
def main():
first=str(input("What is your first name? "))
last=str(input("What is your last name? "))
print("Hello,", first, last + "!")
main()
|
33b4a7b60c37cc48aa3ff6d902a9b4578f75d68a | gullwv/pyprojects | /deliverables/1.1/deliverable3.py | 343 | 3.828125 | 4 | # File: deliverable3.py
# modified on 11/19/18 by gull, original "chaos.py" module created 2/12/15 by Kevin Grimsley
# a simple program illustrating chaotic behavior.
def main():
print("This program illustrates a chaotic function")
x = eval(input("Enter a number between 0 and 1: "))
for i in range(10) :
x = 2.0 *... |
28930cd5476792bbebdbe85e3933924f82fe4917 | cameronbennett32/refactored-couscous | /QuestionMarkChallenge.py | 2,064 | 3.90625 | 4 | """ Question Marks Problem """
""" Read a string and return True if there are exactly 3 '?' between every set of numbers that add up to 10 """
#Simplest correct solution (Pass)
a = '5???5'
#Using the same number in two pairs (Pass)
b = 'a5a???a5a???a5a'
#Only require pairs that equal 10 to be ok (Pass)
c ='a5a... |
8cfc878be48ddbf6fc5a6a977075b1691b4c44c6 | IcefoxCross/python-40-challenges | /CH2/ex6.py | 778 | 4.28125 | 4 | print("Welcome to the Grade Sorter App")
grades = []
# Data Input
grades.append(int(input("\nWhat is your first grade? (0-100): ")))
grades.append(int(input("What is your second grade? (0-100): ")))
grades.append(int(input("What is your third grade? (0-100): ")))
grades.append(int(input("What is your fourth g... |
fce09c74ef59354049e4497ef6db232dd3e908b6 | yasminemortazavi/AlgorithmsPractice | /helloworld.py | 431 | 3.96875 | 4 | string1 = input()
currentstring = ""
hellocount = 0
count = 0
for char in string1:
currentstring = currentstring + char
if char is 'h':
currentstring = 'h'
elif char is 'w':
currentstring = 'w'
elif currentstring == 'hello':
hellocount = hellocount + 1
currentstring = ""
... |
b0be90fabd5a0ba727f3e8c36d79aead438e20b5 | TheOneTAR/PDXDevCampKyle | /caish_money.py | 2,961 | 4.375 | 4 | """An account file ofr our Simple bank."""
class Account:
"""An Account class that store account info"""
def __init__(self, balance, person, account_type):
self.balance = balance
self.account_type = account_type
self.owner = person
def deposit(self, money):
self.balance +=... |
0a15a183e9b05f243b252141381762784fe51ed2 | TheOneTAR/PDXDevCampKyle | /factorial.py | 440 | 4.03125 | 4 | def fact1(n):
product = 1
for x in range(1, n+1):
product *= x
print("{}! = {}".format(n, product))
def fact2(n):
if n == 0:
return 1
else:
return fact2(n-1) * n
def fib(n):
if n < 3:
return 1
else:
return fib(n-1) + fib(n-2)
if __name__ == '__main_... |
57b493e0ffe40737e5efca40e90e51d8a6233d79 | yarinbar/cryptop | /tests/strategy_test.py | 1,708 | 3.625 | 4 |
import unittest
from strategy import Strategy
from random import uniform
from data import Data
def mean_deviation(dataset):
return uniform(-1, 1)
class StrategyTest(unittest.TestCase):
def test_init(self):
# strategy name should be more than 3 char long
with self.assertRaises(ValueError):
... |
aa09cb08a8c1e3b40264a32cffa27607df255912 | wellington1-dev/webpage | /public/img/portfolio/HTML/CssCheatSheet/coding_dojo/python_two/venv/python04.py | 141 | 3.875 | 4 | def reverse_list(my_list):
for i in range(len(my_list)):
my_list=len(my_list)
return my_list
print(reverse_list([0,1,4,5] |
effb0c8ccebe91efe403888f2b362a203cc49bf9 | asherkobin/cs-module-project-iterative-sorting | /src/iterative_sorting/iterative_sorting.py | 736 | 3.90625 | 4 | # TO-DO: Complete the selection_sort() function below
def selection_sort(arr):
for i in range(len(arr)):
min_index = i
for j in range(i + 1, len(arr)):
if arr[min_index] > arr[j]:
min_index = j
arr[i], arr[min_index] = arr[min_index], arr[i]
return arr
# TO-DO: implement the Bubble Sort... |
6e7622b6cc1de5399b05d7c52fe480f832c495ba | jacobkutcka/Python-Class | /Week03/hash_pattern.py | 636 | 4.25 | 4 | ################################################################################
# Date: 02/17/2021
# Author: Jacob Kutcka
# This program takes a number from the user
# and produces a slant of '#' characters
################################################################################
# Ask user for Input
INPUT = i... |
41ed6175e175aa04254f3de4a904398ea629ccb3 | jacobkutcka/Python-Class | /Week05/19-Hex_Spiral/hex_spiral.py | 731 | 3.953125 | 4 | ################################################################################
# Author: Jacob Kutcka
# Date: Mar 12, 2021
# This program loops through 40 times to make
# a line 6 pixels longer and 60 degrees off from the last
################################################################################
# Don't c... |
4c5a6f6d8e2d5a076872f06d0484d9d5f6f85943 | jacobkutcka/Python-Class | /Week03/rainfall.py | 1,668 | 4.25 | 4 | ################################################################################
# Date: 03/01/2021
# Author: Jacob Kutcka
# This program takes a year count and monthly rainfall
# and calculates the total and monthly average rainfall during that period
###################################################################... |
966bcdfc1fb28b4f1c2fd892ab0dbac69602f1c8 | holoviz-topics/imagen | /imagen/transferfn/__init__.py | 9,379 | 3.53125 | 4 | """
TransferFns: accept and modify a 2d array
"""
import numpy
import copy
import param
class TransferFn(param.Parameterized):
"""
Function object to modify a matrix in place, e.g. for normalization.
Used for transforming an array of intermediate results into a
final version, by cropping it, normali... |
21ac424e86e189e2b409bed60e5179692559033b | lukeyzan/CodeHS-Python | /TypeConversion.py | 121 | 3.875 | 4 | x = input("Enter a number: ")
print type(x)
x = int(x)
print type(x)
print x + 3
var = "Not a number"
var = float(var) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.