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
32d6d978ce4af56dd6ce8870450a4abe1addfd7e
MaxBI1c/afvinkopdracht-3-goed
/afvinkopdracht 3 opdracht 2 opdracht 2.py
762
4.21875
4
lengthrectangle_one = int(input('What is the length of the first rectangle?')) widthrectangle_one = int(input('What is the width of the first rectangle?')) lengthrectangle_two = int(input('What is the length of the second rectangle?')) widthrectangle_two = int(input('What is the width of the second rectangle?')) ...
5900f5848a3463f446cff4abda5c585a7e5ecb7e
mac95860/Python-Practice
/webscraping.py
1,335
3.765625
4
import pandas as pd import requests from bs4 import BeautifulSoup #performs a get function and retrieves all the html from the url page = requests.get('https://forecast.weather.gov/MapClick.php?lat=39.103440000000035&lon=-94.58310999999998#.YIrEz5BKiUk') #soup makes it easy to webscrape soup = BeautifulSoup(page.cont...
b6f58732445c87338e5722342ab1cb8b26965886
mac95860/Python-Practice
/working-with-zip.py
1,100
4.15625
4
list1 = [1,2,3,4,5] list2 = ['one', 'two', 'three', 'four', 'five'] #must use this syntax in Python 3 #python will always trunkate and conform to the shortest list length zipped = list(zip(list1, list2)) print(zipped) # returns # [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four'), (5, 'five')] unzipped = list(zip(*...
5607958fdc5ad723c0b38349addbd652993610e1
mac95860/Python-Practice
/lists.py
583
4.09375
4
l = [1,2,3] # Booleans must be capitalized other_list = [1, "strings", True, 4.3, [1,2,3]] print(other_list) print(other_list[1]) names = ["Joe", "John", "James"] names.append("Jack") print(names) names.insert(2 ,"Jerrod") print(names) names.remove("John") print(names) names.reverse() print(names) numbers = [1,...
ac5c656f799c2c923955bbc0eb4cc3f5f111efb8
jeffinchiangmai/led-marquee
/inputs/InputWeather.py
1,267
3.75
4
import urllib.request import json def get(): """ Returns properly formatted weather for Rochester, NY City can be changed by grabbing the proper openweathermap.org url. """ weather_string = "Weather Unavailable" weather_url = "http://api.openweathermap.org/data/2.1/weather/city/5134086" request = urllib.reques...
9a2ffb2945808683891e4731c79b7e24f0df7883
CodeHatLabs/pygwanda
/pygwanda/lazy.py
1,582
3.640625
4
class LazyMorpher(object): """ Use: m = LazyMorpher(factory) m = LazyMorpher(lambda: SomeClass(args)) Where: `factory` is a function that creates and returns an object instance; the instance returned by the factory must be of a class that u...
4ff6b7f6173f4ad7e78150cb12b6f014896a4767
michaelhuo/lcpy
/31.py
1,030
3.53125
4
class Solution: def nextPermutation(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ #m0 1/25/2021 def select_sort(low: int, high: int): for i in range(low, high + 1): m = i for j in rang...
dda2194a9325ace2dbc519137ea26291fe4eab4b
taozhenting/python_introductory
/8-4/练习8-10.py
475
4.03125
4
#了不起的魔术师名字列表 def make_great(names,great_names): while names: current_name = names.pop() great_name = "the Great " + current_name great_names.append(great_name) def show_magicians(great_names): make_great(usernames, great_names) for name in great_names: print( "了不...
2dadf1f9e182ae6b39232e3de3aac557e1818ca2
taozhenting/python_introductory
/6-1/alien.py
1,189
3.8125
4
#创建字典 alien_0 = {'color':'green','points':5} print(alien_0['color']) print(alien_0['points']) new_points = alien_0['points'] print("You just earned " + str(new_points) + " points!") #增加字典的键和值 alien_0['x_position'] = 0 alien_0['y_position'] = 25 print(alien_0) #创建空字典 alien_0 = {} alien_0['color'] = 'green' alien_0['po...
e6edf7e821959e69ebfbd514bfd6ebed4d6a3504
taozhenting/python_introductory
/name_cases.py
542
4.3125
4
#练习 name="eric" print('"Hello '+name.title()+',would you like to learn some Python today?"') print(name.title()) print(name.upper()) print(name.lower()) print('Albert Einstein once said, "A person who never made a mistake never tried anything new."') famous_person='Albert Einstein' message=famous_person + ' once said,...
d45f2f1a9b5112375e4623ec9843194b293d9882
taozhenting/python_introductory
/9-2/练习9-5.py
1,060
3.796875
4
class User(): def __init__(self,first_name,last_name,*user_info): self.first_name = first_name self.last_name = last_name self.user_info = user_info self.login_attempts = 0 def describe_user(self): print( "\n" + self.first_name + self.l...
2db35a9389103e8fc0a087681249cddef6e0d20b
taozhenting/python_introductory
/9-5/练习9-14/die.py
475
3.53125
4
from random import randint class Die(): def __init__(self,sides=6): self.sides = sides self.one = 1 def roll_die(self): x = randint(self.one,self.sides) print(x) def read_die(self,sides2): self.sides = sides2 self.numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ...
b11f4abd67459f0bfde2e080accf0651e80ba14d
taozhenting/python_introductory
/8-3/练习8-6.py
306
3.671875
4
def city_country(city,country): full_name = city + "," + country return full_name.title() city_countrys = city_country('shanghai','china') print(city_countrys) city_countrys = city_country('nanjing','china') print(city_countrys) city_countrys = city_country('santiago','chile') print(city_countrys)
c81d6c2c9354420b94c7133ef013d5c564ae367b
taozhenting/python_introductory
/4-3/练习.py
572
4.28125
4
#打印1-20 for value in range(1,21): print(value) #一百万 numbers = list(range(1,100001)) print(numbers) print(min(numbers)) print(max(numbers)) print(sum(numbers)) #1到20的奇数 even_numbers = list(range(1,21,2)) for even_number in even_numbers: print(even_number) #3到30能被3整除 even_numbers = list(range(3,31,3)) for even_...
d24b47e57c679bcd585ac569fa4a4fc5229fbaa1
taozhenting/python_introductory
/7-2/练习7-4-2.py
241
3.765625
4
#披萨配料 while True: message = input("请输入披萨配料:") if message == 'quit': break else: print( "我们会在披萨中添加这种配料:" + message + "." )
78de74417139d34d6197348884cc2fb504b37223
taozhenting/python_introductory
/6-3/favorite_languages.py
1,303
4.15625
4
favorite_languages = { 'jen':'python', 'sarah':'c', 'edward':'ruby', 'phil':'python', } #遍历字典 for name,language in favorite_languages.items(): print(name.title() + "'s favorite language is" + language.title() + ".") #遍历字典中的所有键 for name in favorite_languages.keys(): print(name.title())...
60c09a57b9f34627dceffb2e4f276eac99249fd1
PercyT/-offer-Python-
/剑指offer/连续子数组的最大和.py
289
3.953125
4
def FindLargest(num): """还可以用动态规划法,算法差不多""" currentSum = 0 max = 0 for i in num: currentSum += i if currentSum<0: currentSum = 0 if currentSum>max: max = currentSum return max if __name__ == '__main__': print(FindLargest([1,2,-3,-4,5]))
f69f109bcbed9c774a8618e6137ebd3a1c10f66c
PercyT/-offer-Python-
/剑指offer/1-n整数中1的个数.py
302
3.59375
4
def numberOf1(num): ints = list(str(num)) first = int(ints[0]) length = len(ints) if length == 1 and first ==0: return 0 if length == 1 and first >0: return 1 num_first_digit = 0 if first>1: num_first_digit = powerBase10(length-1) if first == 1: if __name__ == '__main__':
a55868004336acda38620429d459ce44b08f0882
PercyT/-offer-Python-
/剑指offer/二叉搜索树的后序遍历序列.py
428
3.71875
4
def verifyBST(nums): if not nums: return root = nums[-1] for i in range(0, len(nums)): if nums[i]>root: break for j in range(i, len(nums)): if nums[j]<root: return False left = True right = True if i != 0: left = verifyBST(nums[0:i]) if i < len(nums)-1: right = verifyBST(nums[i:-1]) return l...
cd78c49ba748f689dd55978850d9138cd84c6c55
PercyT/-offer-Python-
/剑指offer/把数组排成最小的数.py
1,032
3.703125
4
from operator import lt def printMinNumber(num): # num = [3,32,321] 引入一个新的排序规则,对快速排序算法进行改进 if not num: return '' num = list(map(str, num)) pivot = num[0] left = [i for i in num[1:] if (pivot+i)>(i+pivot)] right = [i for i in num[1:] if (i+pivot)>(pivot+i)] return ''.join(printMinNumber(left)) + pivot + ''.jo...
15518d4f7f6e7659d8c782b18784dbdc8d14fa58
PercyT/-offer-Python-
/剑指offer/和为s的数字.py
308
3.734375
4
def findNumwithSum(num, sum): first = 0 two = len(num)-1 while two>first: cursum = num[first]+num[two] if cursum==sum: return (num[first],num[two]) elif cursum>sum: two -= 1 else: first += 1 if __name__ == '__main__': a,b = findNumwithSum([1,2,4,7,11,15],15) print("{} {}".format(a,b))
9712f83aa61fda1bd1156f6e15be1e320b58ab7d
PercyT/-offer-Python-
/剑指offer/构建乘积数组.py
231
3.828125
4
def multiply(A): n = len(A) B = [0]*n B[0] = 1 for i in range(1, n): B[i] = B[i-1]*A[i-1] temp = 1 for j in range(n-2,-1,-1): temp *= A[j+1] B[j] *= temp return B if __name__ == '__main__': print(multiply([1,2,3,4]))
c03d99043c2f65e67dfb8d5456c193bc46ebdabc
PercyT/-offer-Python-
/剑指offer/二叉树的深度 判断是否是平衡二叉树.py
566
3.828125
4
def treeDeepth(Root): """计算树的深度""" if Root is None: return 0 left = treeDeepth(Root.left) right = treeDeepth(Root.right) return left+1 if left>right else right+1 def isBalanced(Root, deepth): """判断是否是平衡二叉树""" if Root is None: deepth = 0 return True,deepth is1, left = isBalanced(Root.left, deepth) is2,...
03001b0c120d35a98dae9c7de499cd5a245dae79
PercyT/-offer-Python-
/剑指offer/复杂链表的复制.py
799
3.578125
4
class Node(): def __init__(self, item): self.item = item self.next = None self.sibling = None def cloneNodes(head): node = head while node is not None: new = Node() new.item = node.item new.next = node.next node.next = new node = new.next def connectSibingNodes(head): node = head while node is n...
38d4c1abc99eb0ebfa0648ef6a0f826ea7fb1a12
geothds/Interactive-Programming-in-Python-
/Stopwatch.py
1,445
3.578125
4
# "Stopwatch: The Game" import simplegui # define global variables count = 0 tot = 0 win = 0 # --------------------- helper functions ------------------------ # converts time in tenths of seconds into formatted string A:BC.D def format(t): A = t // 600 B = (t // 100) % 6 C = (t // 10) % 10...
25511d05fc1ea1df94b46a3c5919dd5499b93a12
minhaz-engg/IsArticle
/post/tests.py
1,701
3.5
4
from django.test import TestCase # Create your tests here. text = """ The intensity of the feeling makes up for the disproportion of the objects. Things are equal to the imagination, which have the power of affecting the mind with an equal degree of terror, admiration, delight, or love. When Lear calls upon the heav...
cf89e864f3b4786dbf9b7e1a7acc023ae6b8f710
franky3020/Arithmetic_method_class_HW_1
/InsertionSort.py
731
4.0625
4
# -*- coding: utf-8 -*- """ Created on Sun Apr 5 17:54:08 2020 @author: frrr """ def is_over_InsertionSort (randomList:list)->bool: for i_insert in range(1, len(randomList)): mainTargetNumber = randomList[i_insert] for i_sorted in range(i_insert): sortedNumber = randomList[i_sorted]...
9b2e5b854c8841b543f28376592bd577e12d7603
unKNOWN-G/Coding-Practise
/Contests/Leetcode_Contests/1860. Incremental Memory Leak.py
687
3.796875
4
""" 1) The approach to this Question is Simple. Find largest among memory1(m1),memory2(m2) in each iteration and substract i from it. 2) Before Substarcting Check if that number in memory is greater than i or not 3) If number in memory is less than i break the loop and return the values else substarct """ class Soluti...
ba1f3aa992013bf1c9b50bc68cf5543574c97059
unKNOWN-G/Coding-Practise
/Contests/CodeChef Contests/Summer Code Challenge 2021/LuckyGame.py
299
3.75
4
def check(n): for i in range(len(n)): if(n[i]=='3' or n[i]=='7'): continue else: print("BETTER LUCK NEXT TIME") return 0 print("LUCKY") return 0 test_Cases = int(input()) for i in range(test_Cases): n= input() check(n)
85db846f17e3e15375d1aa5dc6ad345927e59a23
unKNOWN-G/Coding-Practise
/Contests/Leetcode_Contests/1859. Sorting the Sentence.py
523
3.78125
4
""" 1) Split the Sentence into Words 2) Intialize a Dictionery and using the last letter in each word(num value) add elements into dictionery 3) Join All elements in dictionery from 1 to n in order """ class Solution(object): def sortSentence(self, s): a= s.split(" ") ans = "" b= {'0':""} ...
fc4b311ebd4d68be64f82d2f089d71f187ee988c
alaex777/CMC_ASVK_special_course
/PairCubes.py
198
3.671875
4
def isPairCubes(num): for i in range(1,int(num ** (1/3))): for j in range(1,int(num ** (1/3))): if i ** 3 + j ** 3 == num: return "YES" return "NO" n = int(input()) print(isPairCubes(n))
3343fc2ee5fba252f441b3745a381196c466a51b
LuisVCSilva/otimizacao_classica
/Lista 2/teste/Demo1D/Metodos/minMaximaDescida.py
648
3.609375
4
from numpy import * from sys import argv def minimiza_descida_maxima(f, grad, x_inicial, h, max_it, tol): x = x_inicial x_anterior = x for i in xrange(max_it): direcao_descida = -grad(x) alfa = h x = x + alfa * direcao_descida if linalg.norm(x - x_anterior) < tol: break x_anterior = x ...
06ad8ab2ba6b4bd59cc2bfaff0144e896afa92e5
sairamgoud-e/Smart_Interviews_solutions
/Smart_Interviews_Solutions/Print Right Angled Triangle Pattern.py
226
3.578125
4
n=int(input()) for k in range(n): s=int(input()) print("Case #",end="") print(k+1,end="") print(":") for i in range(1,s+1): print(" "*(s-i),end="") print("*"*i)
978fb5f62f03b587ffe7d50488c50982a8081553
pythonzwd/mygit
/不重复的3位数.py
312
3.6875
4
# 0-9这10个数可以组成多少不重复的3位数 #a:1-9,b:0-9,c:0-9 count = 0 for a in range(1,10): for b in range(10): if a == b: continue for c in range(10): if c != a and c != b: count += 1 print(a,b,c) print('count:',count)
95a0eda942982cc9d81a08205022717491e7b60b
edwardzhu/checkio-solution
/EmpireOfCode/boost/evenLast.py
643
3.953125
4
def even_last(array): if len(array) == 0: return 0 return array[-1] * sum([array[i] for i in range(len(array)) if i % 2 == 0]) if __name__ == '__main__': # These "asserts" using only for self-checking and not necessary for auto-testing assert even_last([0, 1, 2, 3, 4, 5]) == 30, "(0+2+4)*5=30"...
f0196ea106a908576134384ce91641d07965b95f
edwardzhu/checkio-solution
/EmpireOfCode/common/Crystalite Farms/mostWantedLetter.py
1,651
3.796875
4
def most_letter(text, all_letters=False): r = dict() for t in text.lower(): if 96 < ord(t) < 123: if t in r: r[t] += 1 else: r[t] = 1 l = sorted(r.items(), key=lambda x:x[0]) l = sorted(l, key=lambda x:x[1], reverse=True) if not all_let...
c21b806417ad81fbabb478facf056cf90ce40560
edwardzhu/checkio-solution
/EmpireOfCode/boost/commonWords.py
707
3.859375
4
def common_words(first, second): l, r = first.split(','), second.split(",") result = [] for i in l: if i in r: result.append(i) s = list(set(result)) s.sort(reverse=False, key=str.lower) return ",".join(s) if __name__ == '__main__': # These "asserts" using only for self...
0367f6272b4c1d4c018bb9a35c130be50e0b3fcf
edwardzhu/checkio-solution
/CheckIO/Home/xsOros.py
898
3.59375
4
def checkio(array): if (array[0][0] == array[0][1] == array[0][2] or array[0][0] == array[1][0] == array[2][0] or array[0][0] == array[1][1] == array[2][2]) and array[0][0] != '.': return array[0][0] if (array[1][0] == array[1][1] == array[1][2] or array[0][1] == array[1][1] == array[2][1] or array[2][0...
53ff73116731dcc4e61e4120316dd2671835d58b
edwardzhu/checkio-solution
/EmpireOfCode/common/Vault/vaultPassword.py
472
3.5
4
golf = lambda p:(len(p)>9)&(p.lower()>p>p.upper())&(':'>min(p)) if __name__ == '__main__': # These "asserts" using only for self-checking and not necessary for auto-testing assert golf('A1213pokl') == False assert golf('bAse730onE') == True assert golf('asasasasasasasaas') == False assert golf('QWE...
b94525860603f31932dd3251268f83ec5b28ec3d
edwardzhu/checkio-solution
/EmpireOfCode/boost/secretMessage.py
518
3.5
4
def find_message(text): result = [i for i in text if i.upper() == i and ord(i) in range(65, 91)] return ''.join(result) if __name__ == '__main__': # These "asserts" using only for self-checking and not necessary for auto-testing assert find_message("How are you? Eh, ok. Low or Lower? Ohhh.") == "HELLO...
fda535423d1df5f382ad9fdb57af51139bbc2c65
edwardzhu/checkio-solution
/EmpireOfCode/boost/flattenList.py
658
3.90625
4
def flat_list(array): result = [] for i in array: if isinstance(i, (list, tuple)): r = flat_list(i) for j in r: result.append(j) else: result.append(i) return result if __name__ == "__main__": assert flat_list([1, 2, 3]) == [1, 2, 3], ...
a733168900dd9199b17893e50850b8538185492d
edwardzhu/checkio-solution
/EmpireOfCode/common/Machine Guns/countNeighbours.py
1,331
3.890625
4
def count_neighbours(grid, row, col): sw,ew = max(col-1, 0), min(col+1, len(grid[0])-1) sh,eh = max(row-1, 0), min(row+1, len(grid)-1) count = 0 for i in range(sh, eh+1): for j in range(sw, ew+1): if (i != row or j != col) and grid[i][j] == 1: count += 1 return co...
60bed818516cfc47012e2cd777c0c2d266508972
edwardzhu/checkio-solution
/EmpireOfCode/common/Sentry Guns/numberBase.py
804
3.828125
4
def convert(str_number, radix): l = list(str_number) lens = len(l) result = 0 for i in range(lens): v = ord(l[i]) - 55 if v < 3 and int(l[i]) < radix: result += int(l[i]) * (radix ** (lens - i - 1)) elif radix > v > 2: result += v * (radix ** (lens - i - 1...
dd157afaa6b956cf60b91f710eadab8fb12e4cd4
edwardzhu/checkio-solution
/CheckIO/Home/sentenceWithExtraSpaces.py
834
3.578125
4
import re def checkio(sentense): word = re.split("\s+", sentense) result = '' for w in word: result += w + " " return result.strip() if __name__ == '__main__': assert checkio('I like python') == "I like python", 'Test1' assert checkio('No double whitespaces') == "No double whitespa...
8484d0d0f223ca6790e178091da7473dd64a2b2d
AntoninDuval/Predict_2017_election
/models/plot.py
6,782
3.609375
4
import seaborn as sns import matplotlib.pyplot as plt import pandas as pd import numpy as np from sklearn.metrics import r2_score candidates_list_1rst_turn = ['HAMON', 'DUPONT-AIGNAN', 'LASSALLE', 'ARTHAUD', 'POUTOU', \ 'ASSELINEAU', 'MACRON', 'MÉLENCHON', 'FILLON', 'CHEMINADE', 'LE PEN']...
628377e96c2260f8c1e5aa4e47b1f9d578d14ce0
Michelle89812/Python210713_Michelle
/day02/HelloIfElse.py
581
3.625
4
# if 判斷式 import random n = 10 print(n % 2) if n % 2 == 0: print("%d 是偶數" % n) # if else 判斷式 n = 9 if n % 2 == 0: print("%d 是偶數" % n) else: print("%d 是奇數" % n) # if else 簡單判斷式 print(n, "偶數" if n % 2 == 0 else "奇數") # if elif else 判斷式 # 90 ~ 100 -> A # 80 ~ 90(不含) -> B # 70 ~ 80 score = random.randint(0,...
15e07b16f0e6c1b0419de3232ecc28446a0ab3d0
BI-JULEO/BI-TP
/tp3/utils/distance.py
599
4.15625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' http://fr.wikipedia.org/wiki/Distance_%28math%C3%A9matiques%29 ''' import math def euclidienne(x,y): ''' distance euclidienne pour 2scalaires :param x: :param y: :type x: int/float :type y: int/float :return: la distance euclidienne entr...
c5dff775d769a3ed205e5e159d7f9d3d18bdccc2
A0L0XIIV/ITU_Undergrad_Projects
/BLG 492 (Graduation Project)/Codes/CRF++AddingFeatures/AddingFeatures.py
2,980
3.640625
4
# coding=utf8 # the above tag defines encoding for this document and is for Python 2.x compatibility # Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution. import io import re inFileName = 'etiketlliKap.txt' cityFileName = 'sehir_isimleri.txt' nameFileNa...
d8a416b9182c0df1ae46f9f008e92d26b105ff5b
mks04/qwerty
/mini.py
142
3.71875
4
x = [6,5,3,12] def get_min(x): mini = x[0] for i in x: if i < mini: mini = i return mini print (get_min(x))
60a3272b25d14ce17af91e2ba41803ba7e48e2c7
IgorGarciaCosta/SomeExercises
/pyFiles/linkedListCycle.py
1,354
4.15625
4
class ListNode: def __init__(self, x): self.val = x self.next = None class LinkedList: # Function to initialize head def __init__(self): self.head = None # Function to insert a new # node at the beginning def push(self, new_data): new_node = ListNode(new_data...
51c4e509afcdcaa15414542368b0f44b7884a784
Ali-Setareh/Data-Structures-and-Algorithms-Specialization-Coursera
/Algorithmic Toolbox/Solutions/week4/Organizing_a_Lottery.py
2,368
3.6875
4
from random import randint import numpy as np def swap(l,i,j): temp = l[i] l[i] = l[j] l[j] = temp def partition(a,start,end,element): rand = randint(start,end) swap(a,rand,end) pivot = a[end][element] m1 = start same_index = [] for i in range(start,end): if a[i...
2a8868f724d2e3a6bba4ae73871fa34eabd0ed1e
Ali-Setareh/Data-Structures-and-Algorithms-Specialization-Coursera
/Algorithmic Toolbox/Solutions/week4/Binary_Search_With_Duplicates.py
603
3.75
4
# Binary Search from math import floor def BinarySearchIt(A,low,high,key): startindex = -1 while low<=high: mid = floor((high+low)/2) if key == A[mid]: startindex = mid high = mid-1 #return mid elif key<A[mid]: high = mid-1 else:...
45009ba333f89a85e1d173bb0d3fb8241ea9fe38
zhixianggg/revision
/stack_II.py
3,878
4.1875
4
##Stack implemented with linked list ## master-class: Node class Node(object): def __init__(self, initdata): #constructor self.data = initdata self.ptr = None ## get & set methods def getData(self): return self.data def getNext(self): return self.ptr de...
ddeb13166c1cc3c0f3492217e226ad23f53e5f26
karuppasamyk/123
/oddsum.py
143
4.09375
4
odd=int(input("")) if odd>0: sum=0 for i in range(1,odd+1): if i%2!=0: sum+=i print(sum) else: print("Invalid number")
870dbcb30b9da785f1d82032c62171974f1fc6c0
cdhutchings/csv_read_write
/csv_example.py
796
4.125
4
import csv # Here we load the .csv """ -open file -read line by line -separate by commas """ # with open("order_details.csv", newline='') as csv_file: # csvreader = csv.reader(csv_file, delimiter = ",") # print(csvreader) # # for row in csvreader: # print(row) # # iter() creates an iterable obje...
b93310e1d670927c6ed88462c86ef8159c924617
avinash273/AdvancedPython
/impotrant.py
2,123
3.984375
4
""" Read this before interview, will make coding easier Also, read online about the time complexity of these inbuilt functions """ days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] daysFr = ["Dim", "Lun", "Mar", "Mer", "Jeu", "Ven"] # File operations with open("testfile.txt", "r") as fp: for line in iter(fp...
602edf8ba8b6cb050cca661bba70a6bd1512ad08
RyanKeys/CS-1.2-Intro-to-Data-Structures
/cleanup.py
268
3.53125
4
def cleanup(source_text): source_text = open(source_text) source_text = source_text.read().replace("\n", " ").split(" ") for word in source_text: word = word.lower() return source_text if __name__ == "__main__": print(cleanup("test.txt"))
7d894c684bc7b8ef18ccf120bc9a78565e306ec2
krocriux/TICS311
/semana_12_03/Taller/ProblemStatement.py
3,117
3.59375
4
# -*- coding: utf-8 -*- """ Created on Tue Mar 13 18:52:47 2018 @author: Cristian Problem Statement Johnny wants to become a great programmer, so he practices to improve his programming skills all the time. He thinks he can save a lot of time if he can learn to type faster. It's said that the key to speed typi...
905dc98435c12bdce9fa7b8e3cfba14f708807d1
krocriux/TICS311
/semana_19_03/DistinguishableSetDiv2/V2/DistinguishableSetDiv2.py
784
3.671875
4
# -*- coding: utf-8 -*- """ Created on Fri Mar 23 15:13:59 2018 @author: Cristian """ def conjuntos(n_items, conjunto): conjunto_final = [] conjunto_final = for_anidado(len(conjunto), [], conjunto_final) return conjunto_final def for_anidado(n, conjunto_actual, conjunto_final): print("Llamada a for_a...
97d70b6c888e20b851b72789e26cdec78c940b30
kai-tk/Python
/Tree/UnionFind.py
1,478
3.734375
4
""" Union-Find木 UnionFind(n)でn個の要素を持つ親配列を作成 find(x):xの親を返す unite(x,y):xの属する木とyの属する木を併合 same(x,y):xとyが同じ木に属するか判定 size(x):xの属する木の要素数 members(x):xが属する木の要素のリスト roots(x):根のリスト group_count(x):木の数 all_group_members:全ての木の要素のリスト """ class UnionFind(): def __init__(self,n): ...
5ec22e276a767025199018241851b029c3a54eae
kai-tk/Python
/Tree/WeightedUnionFind.py
2,362
3.609375
4
""" Weighted-Union-Find木 WeightedUnionFind(n)でn個の要素を持つ親配列と重み配列を作成 find(x):xの親を返す unite(x,y,w):yの重み-xの重み=wとなるようにxの属する木とyの属する木を併合 same(x,y):xとyが同じ木に属するか判定 diff(x,y):yの重み-xの重みを返す size(x):xの属する木の要素数 members(x):xが属する木の要素のリスト roots(x):根のリスト group_count(x):木の数 all_group_mem...
d2d583483635f7e6468a0a507d48a5d0df747d51
LukaszDusza/python_advanced
/basic/player_model.py
996
3.640625
4
class Player: # moze posiadac jawny konstruktor z polami, # ustwiającymi obiekt,czyli byt posiadający wałściwości klasy # poprzez obiekt, mozmey dostawac sie do metod klasy i jej walsciwosci. def __init__(self, name, email, points): print("tworzę playera") self.name = name self....
3ff854a5d6decc9fe976dc1c3a8c9f384722036e
jan-zmeskal/design-patterns
/strategy/game_final_functions.py
1,436
3.578125
4
from typing import Callable, Tuple def get_distance_to_enemy() -> int: """Just a mock for demo purposes.""" return 1 def branch_attack_strategy(stats: dict) -> Tuple[str, int]: weapon_name = "branch" if get_distance_to_enemy() <= 2: return weapon_name, stats["strength"] return weapon_nam...
29518c9ade1a69439ddc32ba206292339fed60c1
radikRadik/calctende
/piega_fissa.py
1,711
3.546875
4
from pretyPrint import * def pf(list_data, asse_da_stiro=121): piega_aprossimata, piega_dentro, misura_tenda, misura_stoffa = list_data coef = ((piega_dentro * 2) + misura_tenda) while misura_stoffa <= coef: printAlert('[ ! ] la stoffa non puo essere piu piccola della tenda') misura_stoff...
76bdf1dd3d61f73452ef65ac34619e19980ec526
jansyzhang/selenium
/15.py
732
3.5
4
# -*- coding: utf-8 -*- """ Created on Mon Jan 14 21:06:11 2019 """ from calculator import Count import unittest class Mytest(unittest.TestCase): def setUp(self): print("test start") def tearDown(self): print("test end") class TestAdd(Mytest): def test_add(self): j = Count(2...
d1242f4c85b7b0cd7891a7c1b58e6bd8f2a1d2a8
michaesb/Michaels_repo
/trainning/running_plots.py
733
3.796875
4
import numpy as np import matplotlib.pyplot as plt minutes = np.array([20,19,18,18,17,17,17,16]) seconds = np.array([0,0.,23.,8.,54.,29.,3.,25]) runs = minutes +seconds/60. time = np.linspace(1,len(runs)+1, len(runs)) before_flex = np.ones(len(time)+3)*20 goal = np.ones(len(time)+3)*16.5 time_v2 = np.linspace(1,len(...
6320278085adf219a789031effb595b30e9f2d0c
michaesb/Michaels_repo
/cool_programs/Silvia_present_birthday.py
1,586
3.9375
4
import numpy as np import matplotlib.pyplot as plt from PIL import Image #recursive function def get_name(): name = input("type your name here:") print("is your name:", name, "?") confirm_ans = input("(answer with y(yes) or n(no)) \n") if confirm_ans == "y": print("great") elif confirm_ans...
aee6ed64129f609f7ae478ecaba2d7635be7b772
JackVoice/Testing
/Code Accdemy/Loops_divisible_by_10.py
264
3.78125
4
#Write your function here def divisible_by_ten(nums): Ans = [] for i in range(len(nums)): if nums[i] % 10 == 0: Ans.append(nums[i]) return len(Ans) #Uncomment the line below when your function is done print(divisible_by_ten([20, 25, 30, 35, 40]))
d726ea48eeab97a33eb8795f0284f53b438f25fa
JackVoice/Testing
/Code Accdemy/scope.py
146
3.71875
4
current_year = 2018 def calculate_age(birth_year): age = current_year - birth_year return age print(current_year) print(calculate_age(1970))
ab971fbc9418ded70f9fa4fded4600437965e2a6
JackVoice/Testing
/Code Accdemy/Classes_self_arguments.py
287
3.859375
4
class Circle: pi = 3.14 def area(self, radius): return self.pi * radius ** 2 circle = Circle() pizza_area = circle.area(6) teaching_table_area = circle.area(36 / 2) round_room_area = circle.area(11460 / 2) print(pizza_area) print(teaching_table_area) print(round_room_area)
09fcf353b5d1700166819edfdd5f24d595217375
JackVoice/Testing
/Code Accdemy/Projects/Dictionary_Scrabble.py
1,440
3.84375
4
letters = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"] points = [1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 4, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10] letters_to_points = [] #Creates a list where each letter has a coresponding number value...
078e02f32f4870e43b53a1f25f1d468577c43467
JackVoice/Testing
/Code Accdemy/Strings_Conditionals_2.py
363
3.75
4
def contains(big_string,little_string): if little_string in big_string: return True else: return False def common_letters(string_one,string_two): storage = [] for i in string_one: for j in string_two: if i == j: if i not in storage: storage.append(i) return storage ...
7121db5d60bc75d919417b2de8d47e9f63cb5344
yograjsk/MarchDemoFramework
/pendingTopics/dbConnectionExample1.py
521
3.796875
4
import sqlite3 connection = sqlite3.connect('mytestdb.db') # connection.execute("CREATE TABLE STUDENT (ROLLNUMBER INT NOT NULL, NAME TEXT NOT NULL, AGE INT);") # connection.execute("""CREATE TABLE STUDENT # (ROLLNUMBER INT NOT NULL, # NAME TEXT NOT NULL, # AGE INT);""") connection.execute("""...
11a81bfc69b982d2809d237cccff2cc91b98f4b6
kcbell/csc580-chatbot
/getSubjectInfo.py
3,428
3.609375
4
""" This function get the first 2 lines of the subject being passed in as the parameter. The two lines are taken from Wikipedia. """ import re, nltk from urllib import urlopen def checkForUppercaseLetter(s): if s[0] != ' ': return False index = 0 while index < len(s) and s[index] ==...
dd269daaadc4cc5bbb2554decd6dbfed0cb37a68
ApoorvVats181/MACHINE-LEARNING-ALGORITHMS
/02. multiple_linear_regression.py
1,035
3.890625
4
# Multiple Linear Regression # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset import statsmodels df = pd.read_csv('50_Startups.csv') x = df.iloc[:, :-1].values y = df.iloc[:, -1].values print(x) # Encoding categorical data from sklearn.compose ...
297ff98547ed5707556ada5284550c678b5699e3
armi-ne/Flapjack
/intro.py
1,607
4.09375
4
#Introduction and checking to see if user would like to see the rules def welcome_sequence(): print("Welcome to Flapjack!") condition = True while condition == True: rules = input("If you would like to read the rules now, please enter y. If not, please enter n: ") if rules.upper() == "...
7c3ca47309ec0795681a24098e9ae40505f20f37
Crossroadsman/game
/dice.py
2,880
4.09375
4
import random ### Random functions ''' random.randrange(a, b, [step]) return a random value from the range a..<b random.randint(a, b) return a random value from the range a...b random.choice(seq) return a random element from seq random.choices(seq, k=n) return n elements from seq random.shuffle(seq) shuffle the sequen...
b7c4a51d5831752ef1d447cc1962a3a43488c8ec
FlorenciaQuintero/AlgoritmosGeneticos
/Ejercicio3/Heuristica.py
3,364
3.5
4
import numpy as np from Ejercicio3.Capital import Capital from Ejercicio3.DistanciaHelper import DistanciaHelper class Heuristica: CuidadElijida = None """Lista de índices de todas las capitales""" Distancia = np.array([23, 23]) """Lista de índices recorrido de las capitales""" recorrido = np.arang...
610217a9bf4b4acf3c7c099ac32936ae41440776
inkmonk/json-test
/json_test/jvalue.py
422
3.59375
4
class JList: """ Represents JSON list """ def __init__(self, keys, parent = None): self.parent = parent self.keys = keys def get_keys(self): return self.keys class JObject: """ Represents JSON Object """ def __init__(self, keys, parent = None): se...
285431a82797081d0e6d4245f281f636f2d8091c
TStand90/advent-of-code-solutions
/2016/day6/part2/day6_part2.py
995
3.546875
4
import sys def main(file_arg): decoded_string = '' with open(file_arg) as f: # Read the first line just to get the number of columns first_line = f.readline().strip() number_of_columns = len(first_line) column_dictionaries = [{} for x in range(number_of_columns)] # ...
b2e19247a4804c5375eacf9ff8dd69114e84b553
kumarshyam7777/Develop
/test.py
116
3.671875
4
from sys import argv sum=0 args=argv[1:] for x in args: n=int(x) sum=sum+n print("The Result:",sum)
b27ac5eca6442e9a0b09ef30d9836475deb593c3
mzkaoq/codewars_python
/5kyu Valid Parentheses/main.py
297
4.1875
4
def valid_parentheses(string): left = 0 right = 0 for i in string: if left - right < 0: return False if i == "(": left += 1 if i == ")": right += 1 if left - right == 0: return True else: return False
0ab278c5863ec967fb4dd725b53920d2c40bd792
mzkaoq/codewars_python
/6kyu Replace With Alphabet Position/main.py
339
3.765625
4
import string def alphabet_position(text): text = text.lower() alphabet = [] returned_string = '' for i in string.ascii_lowercase: alphabet.append(i) for i in text: if i in alphabet: returned_string += str(alphabet.index(i) + 1) + ' ' return returned_string[:len(ret...
5545abefebcb6952b8dc056d45493e6d24d6118d
mohitm15/competitve_solns
/python/graph.py
3,254
3.609375
4
def dfs(v,a,visited): visited[v] = True #print(v,end='') for i in a[v]: if visited[i]==False: dfs(i,a,visited) return visited def bfs(v,a,visited): queue = [] queue.append(v) visited[v]=True while queue: v = queue.pop(0) print(v,end=" ") for...
fe9fdb82a2a1057094e84058d64c450fc738df13
cgoldammer/simple_text_analysis
/tests/tests.py
8,070
3.515625
4
"""This runs a range of unit tests for simple-text-analysis """ import numpy as np from pandas import DataFrame import nltk # This is required to make NLTK work with virtual environments. # Change the environment before using. # nltk.data.path.append('/Users/cg/Dropbox/code/Python/nltk_data/') from textblob import Te...
1031505187fbf75f8b2eb8aa90f7174f940f16e9
Ian-Mint/pong-underwater-rl
/gym-dynamic-pong/gym_dynamic_pong/utils/preprocessing.py
978
3.890625
4
import numpy as np def bool_array_to_rgb(array: np.ndarray) -> np.ndarray: """ Converts a boolean numpy array to an RGB tensor with equal values in each of the colors. :param array: 2d boolean numpy array :return: HxWx3 tensor """ assert array.dtype == np.bool, "array must be boolean" arr...
eb645d326ede04423f9fec8c43cfc2673fe1634f
hlouissaint/PythonTutorialProject
/PythonTutorials/Lessons/exercise1.py
471
4.03125
4
import datetime def calculate_date(my_age): year = datetime.date.today().year return (100 - int(my_age)) + year print("The purpose of the game is you tell you the year that you will turn 100 based on the age info provided") fname = input("What is your first name: ") lname = input("What is your last name: ") ...
211faf6de66a218395512c29d17865aa5d5b38a3
PhiphyZhou/Coding-Interview-Practice-Python
/Cracking-the-Coding-Interview/ch9-recursion-DP/s9-1.py
763
4.3125
4
# 9.1 A child is running up a staircase with n steps, and can hop either 1 step, 2 steps, or 3 # steps at a time. Implement a method to count how many possible ways the child can run up # the stairs. def count(n): mem = [None]*n return count_hop_ways(n, mem) def count_hop_ways(n, mem): if n == 0: ...
0c0ff142bbff7040ddabb9ac50e3e73aaeeabb36
PhiphyZhou/Coding-Interview-Practice-Python
/LeetCode/p11-Most-Water.py
824
3.8125
4
# 11. Container With Most Water # Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains...
220d4effabcc190fcd8690810724521ef9641da6
PhiphyZhou/Coding-Interview-Practice-Python
/HackerRank/CCI-Sorting-Comparator.py
1,213
4.25
4
# Sorting: Comparator # https://www.hackerrank.com/challenges/ctci-comparator-sorting # Comparators are used to compare two objects. In this challenge, you'll create a comparator and use it to sort an array. The Player class is provided in the editor below; it has two fields: # # A string, . # An integer, . # Given an...
761d4f2996e71c5b4a20d1d15203caf7e338fde6
PhiphyZhou/Coding-Interview-Practice-Python
/LeetCode/p346-MovingAverage.py
819
3.75
4
# 346. Moving Average from Data Stream (Google) # Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window. from collections import deque class MovingAverage(object): def __init__(self, size): """ Initialize your data structure here. ...
b121a07e6486e9de883be3739bbdc11c7ebea322
PhiphyZhou/Coding-Interview-Practice-Python
/LeetCode/p84-LargestRecInHist.py
1,166
3.796875
4
# 84. Largest Rectangle in Histogram # Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram. # exceeds time limit class Solution(object): def largestRectangleArea_n2(self, heights): """ Not accept...
2f294864a1de621efc14de633d1dfc411a788b64
PhiphyZhou/Coding-Interview-Practice-Python
/Cracking-the-Coding-Interview/ch11-sorting-searching/s11-3.py
749
3.8125
4
# Given a sorted array of n integers that has been rotated an unknown number of times, # give an O(log n) algorithm that finds an element in the array. You may assume that the # array was originally sorted in increasing order. # This implementation is not finished. The following is just to find the initial element #...
b24259d06db60c922de34acf444de36545fb68ae
asenci/fillrandom
/fillrandom.py
4,628
3.546875
4
#!/usr/bin/env python """Copy random files form source to the destination""" import logging import os def parseArgs(): """Parse arguments from command line""" from argparse import ArgumentParser from sys import exit parser = ArgumentParser( description='Copy random files from source to destin...
89dc2526c6116269f6b3f310dad863e98fd88021
BrendaTatianaTorres/TrabajosPython
/py1_rima/main.py
509
3.703125
4
print("Bienvenido") archivo = open ('palabras500.csv', encoding = "utf-8") lineas = archivo.readlines() archivo.close() def buscar_rimas (rima): for i in range(499): palabra = lineas[i] a = rima in palabra if a == True: n_ult=len(rima) b = tuple(range(-1,-n_ult-1,-1)) c= min(b) ...
ff9f38f3b8a70fba53d836b6973c1c845d7254e6
kcpare/Cribbage
/Cribbage.py
3,563
4.03125
4
# Kathryn Pare # Cribbage Module ##### Description ##### # This module defines a set of classes that describe a game of Cribbage # # Some points of note: # Decks are implemented as sets # Player hands are implemented as lists # Individual cards are implemented as tuples (RANK, SUIT) # # Players are numbered...
d706d38551dab60723ed9e9bb5dc24e197ff4d4f
den01-python-programming-exercises/exercise-5-3-cube-JaimePSantos
/src/cube.py
251
3.5
4
class Cube: def __init__(self,edge_length): self.edge_length = edge_length def volume(self): return self.edge_length**3 def __str__(self): return "The length of the edge is %s and the volume %s"%(self.edge_length,self.volume())
4a606907d4cc079fa1bccac5114c0ea0282eb90a
ralozkolya/google-foobar
/level-2/challenge-2/solution.py
310
3.53125
4
from functools import reduce from operator import mul def product(xs): return 0 if not len(xs) else reduce(mul, xs) def solution(xs): negative = [f for f in xs if f < 0] if len(negative) % 2 and negative != xs: xs.remove(max(negative)) return str(product([x for x in xs if x]))
17d0348c734f1a51118a37dc4b0acef3a3819991
shaikafiya/python
/sum of natural numbers.py
73
3.71875
4
n=int(input()) sum=0 for x in range(0,n+1): sum=sum+x print(sum)
616e28180c51270b78e6693b2646d28064d721f3
vinevg1996/code_task5
/help.py
3,783
3.5625
4
#!/usr/bin/python # -*- coding: utf-8 -*- # vim:fileencoding=utf-8 from combinatorics import Combinatorics class Help: def calculate_factorial(self, n): fact = 1 for i in range(2, n + 1): fact = fact * i return fact def calculate_comb(self, n, k): comb = 1 ...