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 |
|---|---|---|---|---|---|---|
4aaec95dc4331dfb4b56a4aba4f487bb2fa25c3b | cedoradog/datasci_course_materials | /assignment2/matrix_multiplication.py | 1,285 | 3.546875 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#Required packages
import sqlite3 as lite
import sys
#Dimension of the product AB
rowsA = 5
colsB = 5
#Every possible (duplicated) tuple for of product
dimAB = [(i, j, i, j) for i in range(rowsA) for j in range(colsB)]
#Open the database and create a cursor for it
connectio... |
1b9ad9ec6f44752c5ed963714cff446dbb74bd8a | mattmoniz/PythonToDoList | /functional_tests.py | 595 | 3.625 | 4 | from selenium import webdriver
browser = webdriver.Firefox()
# Johnny starts using this brand new To-Do List App
browser.get('http://localhost:8000')
#John sees the name of the new app in the header
assert 'To-Do' in browser.title
#He types in his first to-do item name.
#He hits enter and the page updates.
#There wi... |
be4795ece4f68ccb6b1da83b0560bcb23bec592d | danfujii/python-challenge | /py_bank-main.py | 1,760 | 3.78125 | 4 | import os
import csv
csvpath = os.path.join("Resources", "budget_data.csv")
with open(csvpath, newline="") as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
csv_header = next(csvfile)
months = []
profit_loss = []
differences = []
greatest_increase_date = ""
greatest_decreas... |
40770930cd15ca52499609283d0336f4b2760829 | energyscope/EnergyScope_multi_cells | /esmc/utils/df_utils.py | 440 | 3.796875 | 4 | import pandas as pd
def clean_indices(df):
"""Cleans the leading and trailing spaces in the index and columns names
Parameters
----------
df: pd.DataFrame
DataFrame to clean
Returns
-------
df: pd.DataFrame
Cleaned dataframe
"""
if type(df.index[0]) == str:
df.ind... |
ac2f4599d94cc421a6db41e97be5b4f58f5b86e4 | necromuralist/algorithmic-toolbox | /week-2/4_lcm.py | 680 | 3.921875 | 4 | # Uses python3
import sys
def lcm_naive(a, b):
for l in range(1, a*b + 1):
if l % a == 0 and l % b == 0:
return l
return a*b
def greatest_common_divisor(a, b):
"""finds the GCD of a and b
Args:
a, b: non-negative integers
Returns:
int: the GCD of a and b
"""
... |
33ff6f49d83e3889c5b1655c0182b918286cd1e6 | necromuralist/algorithmic-toolbox | /posts/memories/joblib/__main__--home-brunhilde-projects-necromuralist_repositories-algorithmic-toolbox-posts-__ipython-input__/reference_implementation/func_code.py | 368 | 3.859375 | 4 | # first line: 1
@memory.cache
def reference_implementation(n):
"""Calculates the nth fibonacci number
Args:
n (int): the fibonacci number to get (e.g. 3 means third)
Returns:
int: nth fibonacci number
"""
if (n <= 1):
return n
return (calculate_fibonacci_recursive(n - 1)
... |
45bdb7e668b4c1d76f805c4a424852ad9d0494a6 | heojungeun/codingtestPractice | /level1&2/42585.py | 342 | 3.546875 | 4 | def solution(arrangement):
answer = 0
st = []
arr1 = arrangement.replace("()","*")
for x in arr1:
if x == "*":
answer += len(st)
elif x == "(":
st.append(x)
else:
st.pop()
answer += 1
return answer
arr = "()(((()())(())()))(())... |
cc161f5c4ecba07eb2f00a320b20a33413012f44 | heojungeun/codingtestPractice | /level1&2/42747.py | 430 | 3.640625 | 4 | def solution(citations):
citations.sort()
print(citations)
lenc = len(citations)
answer = 0
for i in range(lenc):
if citations[i]>= lenc-i:
return lenc-i
return answer
def solution1(citations):
citations.sort(reverse=True)
lenc = len(citations)
for i in range(len... |
38395c17ce5d1912e4e9d8c5d2cc8e086d8aacb1 | heojungeun/codingtestPractice | /codingtest/201802.py | 648 | 3.5625 | 4 | import re
def solution(dartResult):
answer = 0
expdic = {'S':1, 'D':2, 'T':3}
numarr = [1,1,1]
starr =[1,1,1,1]
darr = [1,1,1]
str = re.findall('\d{1,2}[SDT][*#]?',dartResult)
for i, x in enumerate(str):
if x[-1] in '*#':
if x[-1]== '*':
starr[i] = 2
... |
fc64a6a807ed40a35000cccbb0695ba287335fc5 | heojungeun/codingtestPractice | /level1&2/12973.py | 246 | 3.78125 | 4 | def solution(s):
answer = 0
st = []
for x in s:
if not st or st[-1] != x:
st.append(x)
elif st[-1]==x:
st.pop()
if s:
return 0
return 1
string = "baabaa"
print(solution(string)) |
e6654eb358bab63755a157bcd56278e0af6f3a07 | heojungeun/codingtestPractice | /level1&2/12985.py | 486 | 3.890625 | 4 | def solution(n,a,b):
import math
answer = 3
if a > b:
a, b = b, a
while n>1:
half = n//2
if a<= half and half < b:
return int(math.log2(n))
elif half<= a and half <= b:
n = n//2
a, b = a%half, b%half
b = half if b==0 else b
... |
22449b384f9ec21dad9fd55ac96799a8496169a7 | kamaljohnson/calender.py | /months.py | 1,300 | 3.75 | 4 | import time
class Month():
def __init__(self):
now = time.asctime().split()
self.now_date = now[2]
self.now_day = now[0]
self.now_month = now[1]
self.now_year = now[4]
self.starting_day = self.get_day_of_this_month(1)
self.leap = self.cheak_leap_year(int(self.... |
104df48126c81aaade444844a5c67c501a98126a | Lumiras/Treehouse-Python-Scripts | /Beginning_python/general_exercises/shopping_list_4.py | 2,236 | 4.125 | 4 | shopping_list = []
def clear_list():
confirm = input("Are you sure you want to completely clear the list?\nThere is no way to undo this!\nType YES to confirm ")
if confirm == 'YES':
del shopping_list[:]
def move_item(idx, mov):
index = idx - 1
item = shopping_list.pop(index - 1)
shopping_l... |
b2a6070dafabaeb436bff41ea479f4e6f2c9caae | Lumiras/Treehouse-Python-Scripts | /Beginning_python/math_quiz/quiz.py | 1,965 | 3.953125 | 4 | import datetime
import random
from questions import Add, Multiply
class Quiz:
questions = []
answers = []
def __init__(self):
#generate 10 rand questions with numbers from 1 to 10
question_types = (Add, Multiply)
for _ in range(10):
num1 = random.randint(1, 10)
... |
900a780a0f882e79b80b4803287d796a7342124a | clarencekwong/CSCA20-B20 | /banking.py | 9,187 | 3.703125 | 4 | import sqlite3
def run_query(db, query, args=None):
'''(str, str, [tuple]) -> list of tuple
Return the results of running the given query on database db.'''
con = sqlite3.connect(db)
cur = con.cursor()
if args == None:
cur.execute(query)
else:
cur.execute(query, args)
d... |
04f1caf80aaf3699dfe4e525c7f69909c5a33476 | clarencekwong/CSCA20-B20 | /e4.py | 1,672 | 4.15625 | 4 | import doctest
def average_list(M):
'''(list of list of int) -> list of float
Return a list of floats where each float is the average of the
corresponding list in the given list of lists.
>>> M = [[0,2,1],[4,4],[10,20,40,50]]
>>> average_list(M)
[1.0, 4.0, 30.0]
>>> M = []
>>> average_... |
45b7be5573512204fe438ad9827e1f2d52edc515 | clarencekwong/CSCA20-B20 | /lab9.py | 2,068 | 4.09375 | 4 | import doctest
def open_temperature_file(filename):
'''(str) -> file
Open filename, which must be a file, read past its three-line header, and
return the open file.
'''
count = 0
myfile = open(filename, 'r')
while count < 3:
myfile.readline()
count += 1
return myfile
... |
27ff7f866f125b4930facd5f7f28d04e151b0f79 | pinardy/Digital-World | /Week 3/wk3_hw4.py | 622 | 4.21875 | 4 | def isPrime(x):
if x==2:
return True
elif x<2 or x % 2 == 0:
return False
elif x==2:
return True
else:
return all(x % i for i in xrange(2, x))
#all function: Return True if all elements of the iterable are true
#(or if the iterable is empty).
#range returns a Python li... |
b8882305984ea9a78efef36659fd635ba7078c3e | pinardy/Digital-World | /Week 5/Cohort Problems/wk5_cohort2_suggested.py | 3,112 | 3.953125 | 4 | import math
def leapYear(year):
if year%4!=0:
return False
elif year%100!=0:
return True
elif year%400!=0:
return False
else:
return True
def dayOfWeekJan1(year): # 0-Sunday,1-Monday,...,6-Saturday
return (1+(5*((year-1)%4))+(4*((year-1)%100))+(6*((year-1)%400)))%7
... |
b075f9a6b1d98719010358098c07aa591ffb7637 | pinardy/Digital-World | /Week 6/strings.py | 158 | 3.578125 | 4 | a=' abcdabcde '
#print a.index('b',5)
#'dab' in a
#print list(a)
#for i in a:
#print i
for i in range(len(a)): #good for matrices
print a[i] |
abd0ce77a02278c494ece50ef7ff1b25e454dfcf | pinardy/Digital-World | /Week 5/Cohort Problems/wk5_cohort1.py | 1,259 | 4.03125 | 4 | import random
import time
random.seed(round(time.time()/3,-1)) #do not seed elsewhere in your code
#################################
# SMALLER FUNCTIONS #
#################################
craps=set([2,3,12])
naturals=set([7,11])
def rollTwoDices():
n1=random.randint(1,6)
n2=random.randint(1,6)... |
dd48ab76896763914a5f7c3990ff4f75a5d2a4e5 | pinardy/Digital-World | /Week 6/Cohort Problems/wk6_cohort3_commonPrefix.py | 269 | 3.65625 | 4 | def prefix(s1,s2):
output = ''
length = min(len(s1),len(s2))
for i in range(length):
if s1[i] == s2[i]:
output += s1[i]
else:
break
return output
print prefix('drinking','drinker')
#prefix('drinking','drinker') |
ed19b8cede12de20cf9d55b17e2297d1af0504da | allicsander/python | /func.py | 273 | 3.609375 | 4 | #!/usr/bin/python3
def get_summ(one, two, delimeter = '@'):
return str(one) + delimeter + str(two)
# my_summ = get_summ(12, 18)
# print(my_summ)
# my_summ = get_summ("Hello", " World")
# print(my_summ)
my_summ = get_summ("Hello", 25, delimeter ='+')
print(my_summ)
|
fd693faa3016303f595143f10c6edd2500c439e3 | KaidenAura/HackerRankAnswers | /HackerRank/Bonetrousle.py | 2,202 | 3.75 | 4 | #Written by EXPYH(or DublinerYH)
#dublineryh@gmail.com
#YounghwanShin.com
import sys
trip = int(input().strip())
#read problems as many as skeleton trips
for eachTrip in range(trip):
#read lines
n = input().strip()
#parameters of the problem
parameters = n.split()
#numberOfSticksToBuy = n in problem
#sales... |
71ed1a072842753e5f1f601a79106ffbb8334fcb | mrzhaisp/ZHIYINXIAOSHI-REQUEST | /test-copy/pq.py | 149 | 3.546875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from pyquery import PyQuery as pq
a = [2,3,10,11,12,13,14,9]
d = [x for x in a if x>10]
print(d)
|
76f46914e6cfa6430f17f4fc52b0ccad93ec2ccb | lh00000000/collective_unconscious | /collective_unconscious.py | 889 | 3.671875 | 4 | import requests
from bs4 import BeautifulSoup
from nltk.tokenize import sent_tokenize
from functools import partial
import google
def html_to_plaintext(html):
soup = BeautifulSoup(html, 'html.parser')
return ''.join(soup.findAll(text=True))
def _what_(thing, to_be):
question = "what {} {}".format(to_be, t... |
3462f6dc7eb1bc3e9117e1cb25ac2ccd8a97d719 | markuswaltre/sqlite3-basketball-database-py | /database.py | 7,442 | 3.640625 | 4 | import csv, sqlite3, math
# write to output
file_output = open('output', 'w')
# csv reader
players = csv.reader(open("input/playerStats.csv"))
salaries = csv.reader(open("input/playerSalaries.csv"))
conn = sqlite3.connect(":memory:")
conn.text_factory = str
c = conn.cursor()
#### String for headers
super_long_strin... |
b8da5ff45c49da31b9b8cc59b7c02d8e05b026c5 | Kum4yk/hyperskill_python-projects | /Tic-Tac-Toe/Tic-Tac-Toe.py | 2,401 | 3.8125 | 4 | class TicTacToe:
wining_pos = [
[0, 1, 2], [3, 4, 5], [6, 7, 8],
[0, 3, 6], [1, 4, 7], [2, 5, 8],
[0, 4, 8], [2, 4, 6]
]
def __init__(self):
self.lst = " " * 9
self.matrix = [list(" " * 3) for i in range(3)]
def print_matrix(self):
pr... |
f1af74d49a6d3f82344f9d8ac1fb961e7c39106d | Rogggy/ACM-ICPC-Algorithms | /String/string reverse/sr.py | 80 | 3.765625 | 4 | def reverse(data):
r = ""
for l in data:
r = l + r
print(r)
|
333b10492c4050493b64125d7f8668576c797d63 | WellKevin/sum-of-integers | /sum-of-integers.py | 157 | 3.765625 | 4 | def calculate(min, max):
sum = 0
n = min
while n <= max:
sum = sum + n
n = n + 1
print(sum)
calculate(1, 3)
calculate(4, 8)
|
6435a57030eda2023e17f57b4c127cce9c45163c | TheManTheLegend1/python_Projects | /updateHand.py | 2,062 | 4.1875 | 4 | import random
import string
VOWELS = 'aeiou'
CONSONANTS = 'bcdfghjklmnpqrstvwxyz'
HAND_SIZE = 7
def getFrequencyDict(sequence):
"""
Returns a dictionary where the keys are elements of the sequence
and the values are integer counts, for the number of times that
an element is repeated in the sequence.
... |
00caa5ce0c76ae7ed901763368980fee792650f6 | TheManTheLegend1/python_Projects | /string_character_search.py | 252 | 3.9375 | 4 | vowel_string = 'aeiouAEIOU'
string_counter = 0
number_of_vowels = 0
while string_counter < len(s):
if s[string_counter] in vowel_string:
number_of_vowels +=1
string_counter += 1
print 'Number of vowels: ' + str(number_of_vowels) |
def8c165622bd9c3549bca7c691ea55eef89198b | TheManTheLegend1/python_Projects | /recursive.py | 352 | 3.640625 | 4 | def recurPowerNew(base, exp):
if exp == 0:
base = 1
return base
elif exp == 1:
return base
elif exp % 2 == 0:
print 'even'
return (base * base) * recurPowerNew(base, (exp/2))
elif exp % 2 != 0:
print 'odd'
return base * recurPowerNew(base, exp-1)
... |
890f47b04fe5db62dcdc5a6bc571c343c7ea75a9 | TheManTheLegend1/python_Projects | /Silly.py | 255 | 4.1875 | 4 | #Silly Strings
#Deonstrates string concatenation and repetition
print("You can concatenate two " + "stringswith the '+' operator.")
print("\nThis string" + "may not " + "seemterr" + "ibly impressive. " \
+ "But what " + "you dont know" + " is that\n ") |
11ce86e51989db43bd6201e7e95c173fcf27ebff | TheManTheLegend1/python_Projects | /playHand.py | 2,631 | 3.796875 | 4 | def isValidWord(word, hand, wordList):
h = hand.copy()
counter = 0
if word in wordList:
for letter in word:
if letter in h:
counter += 1
if h[letter] != 0:
h[letter] -= 1
else:
return False
if cou... |
f0902dee16a3d30ecc988a18ea22b10ed870a4f7 | khoile3009/EECS340 | /utils/helper.py | 1,544 | 3.53125 | 4 |
def find_id_from_name(rows, name):
for row in rows:
if(row[1] == name):
return row[0]
return -1
def check_name_pk(rows,name):
for row in rows:
if(row[0] == name):
return True
return False
def show_recipe_from_id(cursor, name):
cursor.execute("SELECT * FROM ... |
7b1bf8a217799a8501b9ece8b8fe1e79ccea751e | SUNIL-KUDUPUDI-1644/sunil1 | /ck20.py | 87 | 3.71875 | 4 | z=int(input("enter num"))
s=[]
for i in range(1,6):
q=z*i
s.append(q)
print(s)
|
e2392482ac86b8ca303f204b666e460b7b317604 | SUNIL-KUDUPUDI-1644/sunil1 | /ck6.py | 359 | 3.921875 | 4 | z=int(input("enter year"))
if z>=1 and z<=100000:
if z>=1 and z<400:
if(z%4==0) and z%100!=0:
print("leap year")
else:
print("non leap year")
elif z>=400 and z<=100000:
if z%400==0 or z%4==0:
print("leap year")
else:
print("non ... |
81fb78c73e095a0419d312d235c3fb09a5e31b04 | SUNIL-KUDUPUDI-1644/sunil1 | /ck19.py | 72 | 3.640625 | 4 | q=int(input("enter no."))
z=1
for i in range(1,q+1):
z=z*i
print(z)
|
534022b24a83574867a9ff27f6b88e9a5fde56a3 | SUNIL-KUDUPUDI-1644/sunil1 | /ck3.py | 248 | 4.21875 | 4 | char=input("enter a char=\n")
if (char>='a' and char <='z') or (char>'A' and char<'Z'):
if char=='a' or char=='e' or char=='i' or char=='o' or char=='u':
print("vowel")
else:
print("const")
else:
print("invalid syntax")
|
9d77908fcb31176e19aa0332f10753538b78b3c2 | PhamQuocDatAI/TOAN-KHDL | /test Toán.py | 1,301 | 3.546875 | 4 | import numpy as np
import random
# Viết hàm cho ra một ma trận số nguyên cấp n ngẫu nhiên.
def matrix(n):
matrix = np.random.randint(-10, 10, size = (n, n))
det_matrix = np.linalg.det(matrix)
rank_matrix = np.linalg.matrix_rank(matrix)
return matrix, det_matrix, rank_matrix
n = int(input("Nhập giá trị ... |
8277ba98a98ab17815757a89be4204f550dbb2b2 | krishnakumar85/IntegrationApp | /src/Worker.py | 540 | 3.578125 | 4 | from threading import Thread
from Queue import Queue
class Worker(Thread):
"""
A daemon thread to execute Sequencer inherited objects.
Use function assign_work to assign work to this thread.
"""
def __init__(self):
Thread.__init__(self)
self.queue = Queue()
... |
7f473a76281ac1c234f4a73e615a7333239bbc98 | tharakamd/PhysicalWebTest | /QueueProgram.py | 296 | 3.765625 | 4 | from Queue import Queue
queue = Queue()
n = int(input())
for x in range(n):
line = str(raw_input())
parts = line.split(" ")
if int(parts[0]) == 1:
queue.put(int(parts[1]))
elif int(parts[0]) == 2:
queue.pop()
elif int(parts[0]) == 3:
print queue.peek() |
97c547c919d05e35774597b9df8eae8e2932636a | chandler-shepard/github-portfolio | /Python/Banquet_donations/Banquet_donations.py | 3,429 | 3.9375 | 4 | # Make sure you have also downloaded donation.py and have it saved in the
# same location as Banquet_donations.py
import donation
amount = donation.get_donation()
# this will make the 200 donations then it will sort the number also in order
# from least to greatest.
def get_donations(num):
total = []
for i in ... |
20c3493bfab5ed1022531dbaba1ca6309bcf502d | mvanderkroon/graphdbs_20161115 | /sorting/bubblesort.py | 795 | 3.96875 | 4 | def bubbleSort(alist):
for passnum in range(len(alist)-1,0,-1):
for i in range(passnum):
if alist[i]>alist[i+1]:
temp = alist[i]
alist[i] = alist[i+1]
alist[i+1] = temp
import argparse, json, datetime
parser = argparse.ArgumentParser(description=... |
2fa85aef586201354d61f8339668f98ecd0d656a | appacademy/ops-lambda-python-helpers | /ops_helpers/retry.py | 2,218 | 3.625 | 4 | from functools import wraps
class APIError(Exception):
pass
def retry_after_class_action(
max_tries: int,
error_type: Exception,
corrective_method: str,
): # noqa: F125
"""
Decorator that can be applied to an instance method
If instance method raises error, will take correct... |
5f794bf2ad428e216548c832bf5030c93827b36d | Bahram3110/d2_w1_t2 | /task4.py | 382 | 3.90625 | 4 | task_string = 'Hello, Python my name is Bahram' #print the third character of this string
print(task_string[2]) #1 task
print(task_string[-1]) #2task
print(task_string[0:5]) #3 task
print(task_string[:-2]) #4 task
print(task_string[::2]) #5task
print(task_string[-1::2]) #6 task
print(task_string[::-1]) #7task
pr... |
d63fd2f7b68d7b0b06d5a18f3b1ed4926ed344dc | amelia678/python-105 | /matrix_addition2.py | 499 | 4.03125 | 4 | # given two matricies of any given size (as long as they're the same),
# print new matrix with corresponding values
a = [[12, 7, 3],
[4, 5, 6],
[7, 8, 9]]
b = [[5, 8, 1],
[6, 7, 3],
[4, 5, 9]]
#new, empty matrix
result = [[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]
#use a nested loop
# iterate throug... |
9adb909ced8a00ff0d7eac5d2e1dc294ae349980 | kgraves/euler | /py/p20.py | 353 | 4.0625 | 4 | def fact(n):
""" calculates the factorial of n """
result = 1
for i in xrange(1, n+1):
result *= i
return result
def sum_digits(n):
""" sums the digits of n """
total = 0
while n > 0:
total += n % 10
n /= 10
return total
if __name__ == '__main__':
f = fa... |
d6a5ab92b8e01e2cc058e74c4fa058a7fb583bd3 | SDNjie/Learn_Python | /Programming exercises of company/test_1.py | 1,040 | 3.671875 | 4 | '''
Describtion: 小易准备去魔法王国采购魔法神器,购买魔法神器需要使用魔法币,但是小易
现在一枚魔法币都没有,但是小易有两台魔法机器可以通过投入x(x可以为0)个魔法币产生更多的魔法币。
魔法机器1:如果投入x个魔法币,魔法机器会将其变为2x+1个魔法币
魔法机器2:如果投入x个魔法币,魔法机器会将其变为2x+2个魔法币
小易采购魔法神器总共需要n个魔法币,所以小易只能通过两台魔法机器产生恰好n个魔法币,小易需要
你帮他设计一个投入方案使他最后恰好拥有n个魔法币。
Analysis: 可以倒着分析这个问题,将所需要的魔法币减去1(或2),能被二整除的则这一次选择的是魔法机器1(或2)
以此类推即可。... |
fcc8ea80c0f1bc0a9ca259788458273e88170475 | SDNjie/Learn_Python | /Programming exercises of company/test_8.py | 884 | 3.875 | 4 | '''
Description: 小易为了向他的父母表现他已经长大独立了,他决定搬出去自己居住一段时间。一个人
生活增加了许多花费: 小易每天必须吃一个水果并且需要每天支付x元的房屋租金。当前小易手中已经有f个
水果和d元钱,小易也能去商店购买一些水果,商店每个水果售卖p元。小易为了表现他独立生活的能力,希望
能独立生活的时间越长越好,小易希望你来帮他计算一下他最多能独立生活多少天。
Analysis: 很简单,小学加减乘除的应用。但需要注意的是,刚开始所拥有的水果数量可能会超过将钱全部用于
租房的天数。
'''
data = list(map(int, input().split()))
if int(data[2]/da... |
80f1344d2a6a414156e10cce92920b855608142a | Joshua-Chin/mastermind | /mastermind.py | 2,353 | 3.578125 | 4 | import random
import itertools
import collections
def evaluate(guess, actual):
correct = 0
c_colors = [0]*6
g_colors = [0]*6
for g, a in zip(guess, actual):
if g == a:
correct += 1
else:
c_colors[a] += 1
g_colors[g] += 1
almost = 0
for gc, ac ... |
4bc8e177023f537b270de27b79428d4a37a2f290 | Kavya1525/tathastu_week_of_code | /Day 3/Program 5.py | 167 | 3.84375 | 4 | lst1 = [i for i in input("Enter the list1 items:").split()]
lst2 = [i for i in input("Enter the list2 items:").split()]
print(list(set(lst1).intersection(set(lst2))))
|
0dc7cf535da89926b88b71a0adec4a24cc03f7c4 | Kavya1525/tathastu_week_of_code | /Day 2/Program 4.py | 405 | 4.03125 | 4 | for i in range(5,0,-1):
for j in range(i,0,-1):
print('*',end=' ')
for j in range(2*(5-i)):
print(" ",end=" ")
for j in range(i, 0, -1):
print('*', end=' ')
print()
for i in range(1,6):
for j in range(i):
print('*',end=' ')
for j in range(2 * (5 - i)):
... |
2b5ff523cfc8574e17224d3ae5c3b04331e1341d | hardik-vala/gopy | /programs/examples/weekday_weekend.golite.py | 1,005 | 3.671875 | 4 | '''
Presented by [The Heapsters]:
@the Generator: Long, Teng
@the PrettyPrinter: Macdonald, Ethan
@the Stoner: Vala, Hardik
'''
from __future__ import print_function
twoExp31, twoExp32 = 2 ** 31, 2 ** 32
normalize = lambda x : (x + twoExp31) % twoExp32 - twoExp31
true_0, false_0 = True, False
################... |
8d01ac6837f1686a802afe2864701e1259d2e44e | dawidbo/algorithms | /hangman/hangman.py | 5,440 | 3.984375 | 4 |
# Hangman game
#
# -----------------------------------
# Helper code
# You don't need to understand this helper code,
# but you will have to know how to use the functions
# (so be sure to read the docstrings!)
import random
import string
WORDLIST_FILENAME = "words.txt"
def loadWords():
"""
Returns a list o... |
e3acb939e3b933f65a88b51aaae5ac4e092b21ff | dawidbo/algorithms | /Codility/passingCars.py | 605 | 3.671875 | 4 | '''
For example, consider array A such that:
A[0] = 0
A[1] = 1
A[2] = 0
A[3] = 1
A[4] = 1
We have five pairs of passing cars: (0, 1), (0, 3), (0, 4), (2, 3), (2, 4)
https://app.codility.com/demo/results/trainingCKK74F-TDX/
'''
def solution(A):
eps = 1000000000
aLen... |
d3bf45e67322320d97296c7753f6a22d046ec6f6 | dawidbo/algorithms | /findBob.py | 954 | 3.921875 | 4 | def findBob_1(s):
""" Find bob and count number of occurrences
Ver: 1
Args:
s [string]
Returns:
ans [string]
"""
bob = 0
numLetters = len(s)-1
for num in range( numLetters ):
if s[num] == 'b':
if numLetters >= num + 2:
... |
011ad13e3f160978418640f2c85c8c9ee1af2e4f | dawidbo/algorithms | /sumNumerFromUser.py | 400 | 3.84375 | 4 | # sumowanie elementow tablicy
# Python 3.5
p = ""
arr = []
sum = 0
print("Enter a number for summary. ")
while p != "e":
x = 0
try:
x = int(input("Enter a number: "))
except ValueError:
print("Its not a number !!! Try again.")
else:
arr.append(x)
p = input("Press 'enter' for ... |
c78260633ab722701b28c9b71b95daf344da1e4d | dawidbo/algorithms | /inStrBinSearch.py | 585 | 4.09375 | 4 | def isIn(char, aStr):
'''
char: a single character
aStr: an alphabetized string
alfabet = "abcdefghijklmnopqrstuvwxyz"
returns: True if char is in aStr; False otherwise
'''
a=0
b=len(aStr)
if b==0:
return False
if b==1:
if char==aStr[0]:
... |
9b96557b19861df1f4e3f8383948c15f4d2b8903 | dawidbo/algorithms | /bisection.py | 747 | 3.875 | 4 | # bisection
# szukanie pierwiastka
# ----a---------c-----------b------->
# epsilon - dokladnosc, precyzja
# (a+b)/2 = c, c**2 > b to b = c, c**2 < b to a = c, c**2 == n a=b=c
# 1. sprawdz czy jest co podzielic
# 2. podziel na 1/2
def bisectionSquare(num,epislon=0.1):
""" Use bisection method for find square
... |
779e8aacc0fb146455297ef91fe1b2af21833502 | zhjwy9343/CS224W | /HW1/Q1.py | 5,795 | 3.6875 | 4 | #-*- coding:utf-8 -*-
# Author:james Zhang
# Datetime:20-3-8 上午10:34
# Project: CS224W
"""
This version is purely based on python library without use SNAP
SNAP vesion cuold be found in the hw1-q1-starter.py file
"""
import snap
import numpy as np
import itertools as itt
def create_snap_graph(node_list, ed... |
8e4ae1e93bb113ea06dbe6ead86efe799f616d90 | dextercampbell/maze-algorithms | /runDijkstra.py | 9,383 | 3.578125 | 4 | '''
Created on Apr 2, 2018
@author: dexca
'''
import numpy as np
from collections import deque
import turtle
import time as tm
# settings
mazeSize = 35
screenSize = 550
unitSize = screenSize/mazeSize
pathSpeed = 1
mazeSpeed = 0
#create pen class
class Pen(turtle.Turtle):
def __init__(self)... |
8867acf677f2cada3450dd7ff1c9b550bb5f944d | IKhumoyun/multimedi-communication-final | /source_code/modules/utils.py | 6,148 | 3.75 | 4 | ## Imports ##
import cv2
from matplotlib import cm
from matplotlib import colors
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
## Functions ##
# A function to load an RGB image and display it
#
# @param path_to_image: The path to the image we want to load
# @return th... |
6b2d8f88452eff8166b99fadf853e51051433b63 | breadcrumbbuilds/SHL_Lottery_Machine | /Lottery.py | 1,801 | 3.875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 15 13:48:49 2019
@author: BradleyCrump
"""
from random import randint
# First gets numbers 1 - 50 (50%), second 51 - 75 (25%),
# third 76 - 90 (15%), fourth 91 - 100 (10%)
def Lottery():
winner = randint(1, 100)
if winner > 0 and winner... |
98b98286d49808e115a2e495cc7fbf1927408a6d | amanmibra/cs270 | /hw2/board.py | 7,177 | 3.546875 | 4 | # This class represents the game board
class Board(object):
def __init__(self, original=None, height=6, width=7):
if (original):
self.board = [list(col) for col in original.board]
self.numMoves = original.numMoves
self.height = original.height
self.... |
c3b3a1a80203b0ab622c2d90b443c815ecb6202b | rawrjustin/ProjectEuler | /7.py | 345 | 3.828125 | 4 | def isprime(n):
for x in range(2, int(n**0.5)+1):
if n % x == 0:
return False
return True
i = 1
lastPrime = 2
while i < 10001:
for num in range(lastPrime+1,1000000):
if isprime(num):
lastPrime = num
i+=1
print lastPrime
break;
... |
76c0d75604836b5ac96cec24caccbea0952f4e4e | czhu56/problem-sets | /pset7/houses/import.py | 1,184 | 4.0625 | 4 | import csv
import sys
import sqlite3
def main():
if len(sys.argv) != 2 or not sys.argv[1].endswith(".csv"):
sys.exit("Excpected a csv file as an argument")
csv_filename = sys.argv[1]
db_filename = "students.db"
connection = sqlite3.connect(db_filename)
cursor = connection.cursor()
cs... |
b15fca337d8109bc8ba4ca8cac587c4cafd5844e | chingisooinar/K-means-Image-Compression | /KMeans.py | 2,345 | 3.625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 13 06:48:22 2021
@author: nuvilabs
"""
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns; sns.set()
import numpy as np
class KMean:
def __init__(self,k,max_iter=300):
"""
Parameters
----------
... |
2007f575af03de639c8467e100a29537836c0ca4 | ardaboluk/rltut | /sutton/GridWorld/PolicyIteration.py | 3,423 | 3.875 | 4 |
"""
Policy Iteration for Chapter 4 (Dynamic Programming)
env shold have the following methods and fields:
numStates: the number of states.
numActions: the number of actions.
gamma: discount factor for the environment.
terminalStates: indexes of terminal states.
getProbability(s,a,sprime): returns the probabiliy of tra... |
875281d9fd23f3000082d6966077abd591c1545b | ble19/curve-fitting | /load_data.py | 3,282 | 3.734375 | 4 | import pandas as pd
import os
import datetime
'''this is the method that shapes the data from the kaggle daily dataset to a useable format to predict household power
consumption.
Input: the Kaggle daily dataset for household power usage.
Output: A file which the transformed dataset ready for regression anal... |
b2a8be79394ecf0dc36c7eae2720e110e0f74618 | sametweb/cs-sprint-challenge-hash-tables | /hashtables/ex4/ex4.py | 503 | 3.90625 | 4 | def has_negatives(a):
store = {}
result = {}
for num in a:
store[num] = num
for key, value in store.items():
if key * -1 in store:
result[abs(key)] = 1
if result == {}:
return []
result_array = []
for item in result.items():
if item[0] != 0:
... |
5a36004e0994fab742a74a80e21393b0e92d4224 | 5q4z/CSE | /Logan Yang - Characters.py | 1,506 | 3.796875 | 4 | class Character(object):
def __init__(self, name, description, health, move):
self.name = name
self.interaction = False
self.alive = True
self.description = description
self.attack = False
self.take_damage = False
self.health = health
self.movement = m... |
3fb90fbd4371c8366da954991754ce4148a6bc0d | 5q4z/CSE | /Logan Yang - World Map OOP.py | 7,060 | 3.5625 | 4 | class Room(object):
def __init__(self, name, north, south, east, west, up, down, description):
self.name = name
self.north = north
self.south = south
self.east = east
self.west = west
self.up = up
self.down = down
self.lock = True
self.descript... |
eeb717f87b0b735c17e700724ac99a74424621df | Ell-91/Leetcode-Questions | /Array/spiralTraverse.py | 1,390 | 4.09375 | 4 | def spiralTraverse(array):
result = []
#variables to keep track of the rows and the colums
start_row = 0
end_row = len(array)- 1
start_col = 0
end_col = len(array[0]) - 1 # length of inner array (initialized to 3)
while start_row <= end_row and start_col <= end_col:
# Get fi... |
6687f9f8dc7a14cbe5e397640722e3aaddce0076 | Ell-91/Leetcode-Questions | /Array/nonConstructibleChange.py | 882 | 4 | 4 | # O(nlogn) + n (+n because we have to iterate through the array) because we have to sort our input array and then loop through array one time
# fastest we can sort our array is nlogn (mergesort or quicksort)
# O(1) because we sort array in place, use the existing array that is given to us
#Ask if we can sort the input... |
65b9a4239d0b481e084c0fcb142d61cc4abb726b | Ell-91/Leetcode-Questions | /Array/smallestDifference.py | 1,214 | 3.890625 | 4 | def smallestDifference(arrayOne, arrayTwo):
# O(n logn) to sort arrayOne O(m logm) to sort arrayTwo
#O(n logn + m logm)
#Space O(1) because we're sorting arrays in place and not
# not storing any aditional memory, just keeping track of our
#best pair
arrayOne.sort()
arrayTwo.sort()
# Indicies our pointers are... |
ccb59558695e55e6031301e6790ded5efcd8fa74 | Aditya3107/Python-Assignments | /exercise_5_solution.py | 385 | 3.6875 | 4 | #creating the list of the numbers in python
import random
a = random.sample(range(1,50),40)
b = random.sample(range(0,100),60)
'''
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,13 ]
'''
commonelement = []
for i in b :
if i in a and i not in commonelement ... |
c5988a557d8a1119a02538ad50aed96a66fdfe4e | AustinCodingAcademy/PythonTaskForce | /examples/file_parser.py | 1,949 | 3.578125 | 4 | import os
class Parser():
def __init__(self, root_dir, extension='mp3'):
self.root_dir = root_dir
self.extension = extension
self.file_list = []
self.stats = {'filtered_files': 0, 'total_files': 0, 'directories': 0, 'filtered_size': 0, 'total_size': 0}
def set_extension(self, ... |
ea15271746fb8804a7ab493840c7567c8a30738a | nurligenov/math | /Factorization.py | 535 | 3.953125 | 4 | from math import sqrt, floor
n=int(input())
primes=[]
powers=[]
divisors=[n]
for i in range(2,floor(sqrt(n)+1)):
if n%i==0:
power=0
while n%i==0:
power=power+1
n=n//i
divisors.append(n)
primes.append(i)
powers.append(power)
divisors.append(... |
d1dbff287e9541cab7ec2f46958e0990ccc73eb6 | Arya16ap/moneyuyyyyyof.py | /countingWords.py | 403 | 4.125 | 4 | introString = input("enter your introduction: ")
characterCount = 0
wordCount = 1
for i in introString:
characterCount=characterCount+1
if(i==' '):
wordCount = wordCount+1
characterCount = characterCount-1
if(wordCount<5):
print("invalid intro")
print("no. of words in the string: "... |
4359469e17102a52b919c60163e47249c7e6df6f | yuvrrajsingh/sampleproject1 | /votingapp/rough.py | 216 | 3.890625 | 4 | mydict1 = {
'hello' : 2,
'hyy' : 1,
'singh' : 4,
}
d = {}
for val in sorted(mydict1.values(), reverse=True):
for key in mydict1.keys():
if mydict1[key]==val:
d[key]=val
print(d) |
79fd3ac28c8743054e229d9723d3818a9b8d6ed4 | BravePennisetum/detect_and_track | /detection/detector.py | 497 | 3.609375 | 4 | from abc import ABC
from abc import abstractmethod
class Detector(ABC):
class_names: list
def __init__(self, class_names: list):
self.class_names = class_names
# This method when implemented must return 2 lists
# 1) bboxes list --> bbox = (x, y, w, h) with (x,y) being the top left corner of ... |
99355b9314b27ebb7d7ec5a4c523cdeaaf3e97fd | NAMELEZS/Python_Programs | /length_function.py | 248 | 4.15625 | 4 | ### 03/28/2021
### Norman Lowery II
### How to find the length of a list
# We can use the len() fucntion to find out how long a list is
birthday_days = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']
print(len(birthday_days)) |
3db1704bca837c13809708750d2e5b0ffc850514 | NAMELEZS/Python_Programs | /adding_whitespace.py | 232 | 3.640625 | 4 | ### 03/28/2021
### Norman Lowery II
### Adding spaces
# \t puts a tab in front of it
address = "101 Main Street \tDublin"
print(address)
# \n creates a new line to put whatever you want on
address = "102 Main Street \nDublin"
print(address) |
65050d466c079608a689d67c4ef3ddf1bdda2969 | NAMELEZS/Python_Programs | /editing_lists.py | 687 | 4.0625 | 4 | ### 03/28/2021
### Norman Lowery II
### Editing lists
birthday_months = ['spril', 'may', 'november']
print(birthday_months)
# Can use this to edit your spelling mistake
birthday_months[0] = 'april'
print(birthday_months)
# Can use the .append() method to add whatever you want to the list
birthday_months.append('ju... |
f9f091ee5911faf395b98a9ebaa995880e4eeecc | Michaelhuazhang/CodingPractices | /zuochuji/Array/code3_Array_toQueue.py | 559 | 3.5625 | 4 | # -*- encoding:utf-8 -*-
'''
@Author : ZJH
@Concat : jianhua-zhang@qq.com
@SoftWare : Pycharm
@File : code3_Array_toQueue.py
@Time : 2019/3/13 14:58
'''
class ArrayQueue():
def __init__(self):
self.array = []
def push(self, item):
self.array.append(item)
def pop(self):
if len(se... |
627577646b486d724233e76bad836b6dfc56fc15 | Michaelhuazhang/CodingPractices | /zuochuji/chij5_tree/tree_isbalance.py | 1,119 | 3.5625 | 4 | # -*- encoding:utf-8 -*-
'''
@Author : ZJH
@Concat : jianhua-zhang@qq.com
@SoftWare : Pycharm
@File : tree_isBalance.py
@Time : 2019/3/11 16:27
'''
# 判断一颗二叉树是否是平滑二叉树
# 任意一个结点左子树和右子树的高度差不超过1个结点
# 递归思想很重要
# 考查每一个结点的整棵子树是否满足平衡
# 判断左树是否平衡,右树是否平衡,左右子树的高度
#
class TreeNode:
def __init__(self, val=None):
self.v... |
714b66508a677e3dc8e1b36bd36a0896ab6aab60 | Michaelhuazhang/CodingPractices | /zuochuji/Part_Sort/heapSort.py | 3,062 | 3.734375 | 4 | # -*- encoding:utf-8 -*-
'''
@Author : ZJH
@Concat : jianhua-zhang@qq.com
@SoftWare : Pycharm
@File : heapSort.py
@Time : 2019/3/12 9:11
'''
# 堆排序
# 建堆
# 调堆
# 排序
import random
class Solution:
def insertHeap(self, array, index):
'''
# 将元素插入堆(大根堆)
:param array: 数组(存放堆)
:param index:... |
82e675506a026190302cf702ff1eac1506ba4982 | Arjunjo/cal | /one.py | 608 | 3.546875 | 4 |
f = open("text.txt","r")
for line in f:
for x in line:
if x=='+':
n1, n2 = line.split('+')
k = int(n1)+ int(n2)
print(k)
elif x== '-':
n1, n2 = line.split('-')
k=int(n1) - int(n2)
print(k)
elif x== '*'... |
20b80a1284ad13d6faadfbbded51305ebf1bed29 | nicolageorge/idiomaticpython | /raymond.py | 20,403 | 4.09375 | 4 | # Replace traditional index manipulation with Python's core looping idioms
# when you use index searching, unless exotic circumstance, should not be doing
# Learn advanced techniques with for-else clauses and the two argument form of iter()
# Goal: Improve your craftmanship and aim for clean fast, idimatic Python c... |
e1a69d366089f7f34864945043395b2ae550a42e | nicolageorge/idiomaticpython | /presentation/1 2 looping over two collections.py | 975 | 4.03125 | 4 | # looping over two collections
names = ['raymond', 'rachel', 'matthew']
colors = ['red', 'green', 'blue', 'yellow']
# take the length of the shorter list, loop over indicies
# until the ith element
n = min(len(names), len(colors))
for i in range(n):
print names[i], '-->', colors[i]
# in python
for name, color in ... |
a09dcd7c5a747272e23f7c5476dfff9f288d74fa | nicolageorge/idiomaticpython | /visual.py | 12,459 | 3.5 | 4 | # Idiomatic Pyton
# Jeff Knupp said in "Writing Idiomatic Python"
# We may document our code extensively, write exhaustive unit tests,
# and hold code reviews three times a day, but the fact remains: when
# someone else needs to make changes, the code is king
# looping... |
3506ea8f79e71dfc001718487551e9723dcec4d5 | theantonymartin/Python_Mario_test | /enemy.py | 478 | 3.515625 | 4 | class Enemy1 :
def __init__(self, x, y):
self.x = x
self.y = y
self.matrix = [ [ 'V', 'T', 'H', 'T', 'V'], [ '<', '<', 'H', '>', '>'], [ ' ', 'l', ' ', 'l', ' '] ]
def renderEnemy(self, length, height, mapMatrix, direction):
for y in range(0, 3):
for x in range(0, 5):
if int(self.x+x)<length and int(... |
5af3cf5c34a4976e8fa350d53c121a4ec7be68ea | Mark-Kramer/Summer-AI | /stuff/Part-8-9/TeachFoodCritic.py | 1,577 | 3.84375 | 4 | # TeachFoodCritic.py
def food_critic_perceptron(ice_cream, ketchup, weight_ice_cream, weight_ketchup):
# Define the perceptron calculation
x = ice_cream*weight_ice_cream + ketchup*weight_ketchup
# Apply the threshold,
if x > 0:
output = 1
else:
output = 0
return output
# Let's ... |
3e42d0d8881191ab3976c3ae89570817d07c6482 | RSreeCharitha/dsa | /py/queue.py | 331 | 3.546875 | 4 | class Node:
def __init__(self,x):
self.data = x
self.next = None
class Queue:
def __init__(self,size):
self.front=None
self.rear = None
self.size = size
def enqueue(self, x):
if self.rear==None:
self.rear=x
self.front=x
... |
6fe32b25d6283392b4ffc60deb1919d30bc23324 | RSreeCharitha/dsa | /practice/triangularnum.py | 277 | 3.796875 | 4 | def trinum1(n):
start = [1]
for i in range(1,n+1):
print(sum(start),end=" ")
start.append(i+1)
def trinum2(n):
for i in range(0,n):
su=0
for j in range(i+1):
su+=j+1
print(su,end=" ")
n = int(input())
trinum2(n) |
375ca674c7b62089c925722405942e8820a0bd28 | wjdrbs96/Python-Code_festival | /50 ~ 100/65번.py | 200 | 3.8125 | 4 | #변형된 리스ㅌ
a = [1,2,3,4]
b = ['a','b','c','d']
list = []
for i in range(len(a)):
if i%2==0:
list.append([a[i], b[i]])
else:
list.append([b[i], a[i]])
print(list) |
d91396f97b4972d7db39503801ebec47a2fda33a | wjdrbs96/Python-Code_festival | /1 ~ 50/10번.py | 204 | 3.65625 | 4 | #행성 문제( 행성의 한글 이름을 입력하면 영어 일므을 반환하는 프로그램 )
str1 = {'지구':'Earth','수성':'Mercury','금성':'Venus'}
str2 = input("입력")
print(str1[str2])
|
293e738789c9a28cadfebd92a307a022c198173d | wjdrbs96/Python-Code_festival | /1 ~ 50/24번.py | 198 | 3.53125 | 4 | #소수 판별하기
#소수이면 Yes, 아니면 No
count=0
num = int(input())
for i in range(2,num+1):
if num % i == 0:
count+=1
if(count==1):
print("Yes")
else:
print("No")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.