blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
89c31e16dd5cc9762b731758cb5671ddca6cbeb4 | vipulsingh24/DSA | /Sorting/bublle_sort.py | 337 | 4.09375 | 4 | # Bubble Sort Algorithm
def bubble_sort(data):
for i in range(len(data) - 1, 0, -1):
for j in range(i):
if data[j] > data[j + 1]:
temp = data[j]
data[j] = data[j + 1]
data[j+1] = temp
print("Current data state: ", data)
... |
a7c0aae2914f7f0a426121af5bf628273d2c5102 | github-hewei/Python3_study | /1/11.九九乘法表.py | 239 | 3.8125 | 4 | # -*- coding: utf-8 -*-
def printMulTable( num=9 ):
'''打印九九乘法表'''
for i in range(1, num+1):
for j in range(1, i+1):
print("%dx%d=%d"%(j, i, j*i), end="\t")
print(end="\n")
printMulTable() |
e21c72d1c2f408b629b3093153d2b2e72ee6f4f0 | YunsongZhang/lintcode-python | /Amazon 2019秋招面试高频题/3 - Amazon 电面 Follow up/246. Binary Tree Path Sum II.py | 857 | 3.6875 | 4 | class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
class Solution:
"""
@param: root: the root of binary tree
@param: target: An integer
@return: all valid paths
"""
def binaryTreePathSum2(self, root, target):
paths = []
... |
a80699e2b122a93973f68edebc706bc50b5f8186 | VakinduPhilliam/Python_Concurrent_Futures | /Python_Concurrent_Futures_Thread_Pool_Executor.py | 1,362 | 3.953125 | 4 | # Python Concurrent Futures
# concurrent.futures Launching parallel tasks.
# The concurrent.futures module provides a high-level interface for asynchronously executing callables.
# The asynchronous execution can be performed with threads, using ThreadPoolExecutor, or separate processes, using ProcessPoolExecutor.
... |
f802ea7f225aed1261d02d60eb47849252052cca | CianLR/judge-solutions | /kattis/bridgesandtunnels2.py | 927 | 3.53125 | 4 | from heapq import heappush, heappop
def dijkstra(adj, start, end):
seen = set()
# Time outside, total time, vertex
pq = [(0, 0, start)]
while pq:
to, tt, u = heappop(pq)
if u == end:
return "{} {}".format(to, tt)
elif u in seen:
continue
seen.add... |
9a1d317238f7bb13fd4470f81b892d8b8363ded4 | ChenhaoJiang/LeetCode-Solution | /51-100/53_maximum_subarray_v2.py | 1,106 | 3.5625 | 4 | def get(a,l,r):
# 递归(分治法)
if l==r:
return {'isum':a[l],'lsum':a[l],'rsum':a[l],'msum':a[l]}
m = int((l+r)/2)
isum = get(a,l,m)['isum'] + get(a,m+1,r)['isum'] # isum为[l,r]的区间和
# lsum为[l,r]内以l为左端点的最大子段和
lsum = max(get(a,l,m)['lsum'] , get(a,l,m)['isum'] + get(a,m+1,r)['lsum'])
# rsum为... |
1462079fc423bdb05ad8d8bb4b8b10f58f79deab | arpit0891/Project-Euler | /p062.py | 638 | 3.640625 | 4 | import itertools
def compute():
numdigits = 0
data = {} # str numclass -> (int lowest, int count)
for i in itertools.count():
digits = [int(c) for c in str(i**3)]
digits.sort()
numclass = "".join(str(d) for d in digits)
if len(numclass) > numdigits:
# Process and flush data for smaller number of dig... |
da886d6eb86d11d486c6b2a45a311ee21b07d5ba | cybelewang/leetcode-python | /code758BoldWordsInString.py | 1,892 | 3.96875 | 4 | """
758 Bold Words in String
Given a set of keywords words and a string S, make all appearances of all keywords in S bold. Any letters between <b> and </b> tags become bold.
The returned string should use the least number of tags possible, and of course the tags should form a valid combination.
For example, g... |
2050b4affc534cca22794ef4fd46f88329bf2420 | kontai/python | /面向對象/運算符重載/type元類/自定制元类精简版.py | 325 | 3.546875 | 4 | class MyType(type):
def __init__(self,a,b,c):
print('元類的構造函數執行')
def __call__(self, *args, **kwargs):
obj=object.__new__(self)
self.__init__(obj,*args,**kwargs)
return obj
class Foo(metaclass=MyType):
def __init__(self,name):
self.name=name
f1=Foo('alex') |
73e4dc80119ee187b8aa7af7c4d9d6edea15d494 | Sunny61676/PythonPractice | /PythonPracticeSelf/str_ex.py | 1,338 | 4.125 | 4 |
'''
Hello = "Hello World"
print(Hello)
len(Hello)
First5 = Hello[0:5]
print(First5)
HelloBig = (First5 + " Big " + Hello[6:len(Hello)] )
print(HelloBig)
print(HelloBig.upper())
print(HelloBig.lower())
print(HelloBig.lower().title())
first = 'Lily'
last = 'Wang'
print("My first name is %s, my last name is %s." %(fir... |
57672f5efc67fa17b9e18eed2f27c6bfb3ae3abb | danhnhan54/maidanhnhan-fundamentals-c4e22 | /session3/fav.py | 120 | 3.65625 | 4 | favs = ["netflix","teaching","redbull"]
print(favs)
new_fav = input("Your new thing: ")
favs.append(new_fav)
print(favs) |
c385722fa5416ecd4d477c2112d356f52904b566 | kopchik/itasks | /hash.py | 644 | 3.53125 | 4 | #!/usr/bin/env python3
import math
class Hash:
def __init__(self, bits=3):
self.bits = bits
#if bits:
# self.values = [Hash(bits=bits-1) for x in range(2**bits) if bit]
self.values = [None for x in range(2**bits)]
def set(self, key, val, h=None):
if not h:
h = self.hash(key)
idx = s... |
31686a79eb32de189aabb5d3b310cc50f288d86e | SIS101/id-maker | /render-id.py | 149 | 3.640625 | 4 | import csv
students = list()
with open("my.csv", "r") as f:
reader = csv.reader(f)
for row in list(reader)[1:]:
students.append(row) |
fdafa938618d6a8d3caabcc9b6e13b15ae25d950 | shankar7791/MI-11-DevOps | /Personel/Rahul/Python/Assignment07/Bmi.py | 425 | 4.28125 | 4 | h = float(input("Enter height in cm : "))
w = float(input("Enter weight in kg : "))
def bmi(h,w):
BMI = w / (h/100)**2
print(f"The BMI is - {BMI}")
if BMI <= 18.4:
print("You are underweight.")
elif BMI <= 24.9:
print("You are healthy.")
elif BMI <= 29.9:
print("You are over weight.")
elif BMI <=... |
7547287452d7473e72b6954fc953c736e8651918 | OmishaPatel/Python | /daily-coding-problem/shortest_path.py | 1,001 | 3.796875 | 4 | from collections import deque
def shortest_path(board, start, end):
seen = set()
queue = deque([(start,0)])
while queue:
#enque
coordinate,count = queue.popleft()
if coordinate == end:
return count
seen.add(coordinate)
neighbors = get_valid_neighbors(b... |
e022e8d6191e7d032425cef79c3a19d024f7fe57 | Psingh12354/Python-practice | /HalfDiamond.py | 282 | 3.9375 | 4 | def halfDiamond(n):
for i in range(n):
for j in range(0,i+1):
print('*',end="")
print()
for i in range(1,n):
for j in range(i,n):
print('*',end="")
print()
n=int(input("Enter the number : "))
halfDiamond(n)
|
c8c1befa3f7471367a44fd8ad08044fdd85b05f6 | oshuakbaev/pp2 | /lecture_5/task1/18.py | 226 | 3.5 | 4 | def count_words(filepath):
with open(filepath) as f:
data = f.read()
data.replace(",", " ")
return len(data.split(" "))
print(count_words("/Users/olzhas/Documents/GitHub/pp2/lecture_5/task1/w3res.txt")) |
59906602361d1b6f4727d47e2c08a0c750b99143 | pittzhou/DeepLearningCourseCodes-1 | /01_TF_basics_and_linear_regression/tensorflow_basic.py | 8,932 | 4.46875 | 4 |
# coding: utf-8
# # TensorFlow基础
# In this tutorial, we are going to learn some basics in TensorFlow.
# ## Session
# Session is a class for running TensorFlow operations. A Session object encapsulates the environment in which Operation objects are executed, and Tensor objects are evaluated. In this tutorial, we will... |
7534f9f7e416d1f089a1a08f02fe2f07a4be4645 | tlennen/hackerrank-practice | /Python Practice/set_mutations.py | 832 | 3.703125 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
# https://www.hackerrank.com/challenges/py-set-mutations/problem?h_r=next-challenge&h_v=zen
n = int(input());
set_A = set(map(int,input().split()))
queries = int(input())
for x in range(0,queries):
command = list(input().split())
if command[0... |
b49ef2fc080b3aa2772a3dfb8a125c593769e789 | ameseric/lang-reviews | /misc/python/arraypivot.py | 1,440 | 4.0625 | 4 |
"""
Write a function that pivots an array of size n by k places.
Assuming a right pivot.
E.g. 12345 pivot 2 -> 45123
"""
''' Naive implementation of array pivot. O(n). '''
def pivotArrayNaive( intArray ,pivotPos ):
LENGTH = len( intArray)
if pivotPos == 0:
return intArray
if ... |
87fa240e4454b66c8972e423380c81ce2c3641cb | Arocha4/Projects | /python/webmap-folium/map1.py | 2,356 | 3.671875 | 4 | # this script when compiled will create an htmlfile named map1.html shown at the last line which has multiple layers
# that color codes the map according to popularion along with location of cvolcanoes in north america.
# the attached fiels volcanoes.txt and world.json are the refferenced files. Found them online
... |
84042eef928ff03910d116ebd07f9581ad585d07 | riyasaxena/python | /playingWithLoops.py | 412 | 3.796875 | 4 | startRange = int (input("Enter the number from which you want to start printing tables: "))
endRange = int (input("Enter the number till which you want to print tables: "))
#
for anumber in range (startRange, endRange) :
print
print ("timestable of ", anumber )
print
for loopdaloop in range (1, ... |
c6fe7babab81645a5802d363f62d03ae3ee2e434 | wuranxu/leetcode | /601to650/623. 在二叉树中增加一行.py | 1,460 | 3.859375 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def addOneRow(self, root: TreeNode, v: int, d: int) -> TreeNode:
# 如果d是1,则直接创立一个node,并把root赋予给node.left并返回node
if d == 1:
... |
f926c0a1635120ab9a37fc84e78800b7bbf90a56 | shelbycobra/LeetcodeSolutions | /easy/IntersectionII.py | 475 | 3.921875 | 4 | class Solution:
def intersect(self, nums1, nums2):
nums1 = sorted(nums1);
nums2 = sorted(nums2);
result = []
while nums1 and nums2:
if nums[0] == nums2[0]:
result.append(nums1.pop(0))
nums2.pop(0)
elif nums1[0] > nums2[0]:
... |
ac40d612f1b9b6577156a9319f6d6ff1880c91a4 | jeff-lund/CS199 | /Python/Loops/bronk.py | 262 | 3.78125 | 4 | # Using Lord Brounkers continued fraction to estimate pi
n = int(input("Enter a positive, odd number: "))
if n % 2 == 0:
print("Nope")
else:
z = 1
while n > 1:
z = 2 + n**2 / z
n -= 2
z = 4 / (1 + 1 / z)
print(z)
|
c22390bb91463fa2c680fd10cb1dc4ea68492dce | chendaofa123/Python | /3-5.py | 176 | 4 | 4 | names=['Tom','Jine','Collins','Red']
print(names[1]+'can not keep the appointment')
names[1]='Grous'
for name in names:
print(name+',I hope to have dinner with you ')
|
875dc28ef62f5f8fef663ef9f6e77cf73896c964 | onkursen/road-trip-recommendations | /dump_attributes.py | 1,409 | 3.578125 | 4 | # Get all restaurants from a desired city (in this case, Phoenix)
# and save them to a file using Pickle, Python's persistence model.
from util import *
# Use logging file configuration
logging.config.fileConfig('logging.conf')
logger = logging.getLogger('dump_restaurants')
BUSINESS_PATH = DATASET_PATH + 'yelp_acade... |
527969afa1d886ac4fb1bb215bde5be050523876 | syurskyi/Python_Topics | /045_functions/004_closures/_exercises/_templates/001/002_Closures.py | 942 | 3.78125 | 4 | # -*- coding: utf-8 -*-
# # Реализация с помощью именованных функций:
# ___ make_adder x
# ___ adder n
# r_ x + n # захват переменной "x" из внешнего контекста
# r_ ?
#
# # То же самое, но через безымянные функции:
# make_adder _ l_ x |l... n x + ?)
#
# f _ ? 10
# print ? 5 # 15
# print ? -1 # 9
#prin... |
7f4f0d82ed7a00e69ff8e3268665219dcd08eb6b | harikrishna-vadlakonda/Patterns | /12.py | 184 | 3.78125 | 4 | n = int(input("enter the no of rows: "))
for i in range(n):
print(" "*i+chr(65+i),end=' ')
if i != n-1:
print(" "*(2*n-2*i-3)+chr(65+i),end = '')
print()
|
0e4938e4ce0f4dd4d8367932f8d48850cc958b4d | Turjo7/Python-Revision | /return.py | 138 | 3.75 | 4 | def square_number(num):
return num*num
#By deafult a python function returs None
#result = square_number(3)
print(square_number(3))
|
7714ba14ec9f3f47741a26005e277c7b7f3c97e9 | USTBlzg10/-offer | /target/classes/nowcoder/S14_FindKthToTail14.py | 852 | 3.5 | 4 | class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class FindKthToTail:
def findKthToTail(self, head, k):
tail = pre = head
for _ in range(k):
if not tail:
return None
tail = tail.next
while tail:
pre =... |
7ceeda6ce815711dc48b51bd2a8e44a10b44e035 | aseksenali/webdev | /Third/I.py | 153 | 3.625 | 4 | a = int(input())
counter = 0
i = 2
while a != 1:
if a % i == 0:
counter += 1
a /= i
continue
i += 1
print(counter + 1)
|
77b495b6217fb32c63053693529e00e292f418b8 | SjorsVanGelderen/Graduation | /python_3/data_structures/linked_list.py | 1,309 | 3.9375 | 4 | """Linked list data structure
Copyright 2016, Sjors van Gelderen
"""
# Empty list
class Empty:
def __init__(self):
self.is_empty = True
# List segment
class Segment:
def __init__(self, _value, _tail):
self.value = _value
self.tail = _tail
self.is_empty = False
# Full lis... |
be6cd52867f82ab37a100a760f1d01d1a5e55ca7 | Kai-Ch/py_01 | /common_module/itertools_p/itertools_02.py | 252 | 3.515625 | 4 | #coding=utf-8
#description:
_author_ = 'Kai,Chen'
_time_ = '2018/4/25'
import itertools
#chain()
ch = itertools.chain('ABC','XYZ')
for n in ch:
print(n)
#groupby()
for key,group in itertools.groupby('AAABBBCCDDD'):
print(key, list(group))
|
672563e8c5dda9f9fdb5d45be6771583ba70fa18 | soundaraj/python-practices1 | /vowel.py | 207 | 3.9375 | 4 | def vowel(value):
vow = ['a','e','i','o','u']
if value in vow:
print 'This is vowel'
else:
print 'This is constant'
value = raw_input("enter the values \t")
vowel(value)
|
957506803683a0686d97ee28af05fbbff07f1dc0 | yamileherrera/Ejercicios-Python-FP-1-Semestre | /prg_13_repaso Marzo 02.py | 882 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Mar 2 19:30:12 2021
@author: yamile
"""
# Programa que lee N numeros enteros y calcula su promedio sale con
# un numero menor a cero
# Declarar variables
num = 0 # Variable que almacena los numeros que digita el usuario
suma = 0 # Variable que almacena la su... |
a2b126ff2a3cf4a509fa6e210a3eb01bce55d24e | mridulrb/Basic-Python-Examples-for-Beginners | /Programs/MyPythonXII/Unit1/PyChap01/swap.py | 322 | 4.15625 | 4 | # File name: ...\\MyPythonXII\Unit1\PyChap01\swap.py
# This program swaps two numbers without using third variable
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
a = a + b
b = a - b
a = a - b
print("After swapping a is –> %d" %(a))
print("After swapping b is –> %d" %(b))
|
745d73657038dcb3e42936d43b28642c5811f18f | anand-mishra/geofence | /geofence.py | 4,957 | 4.21875 | 4 | # -*- coding: utf-8 -*-
import math
class Polygon(object):
def __str__(self):
return "%s: %s" % (self.__shape_type, self.__shape)
def __init__(self):
self.__shape = {}
self.__shape_type = 'polygon'
def set_shape(self, poly):
"""Creates a polygon.
Keyword argumen... |
d68fc775b237dee93301d9ea3445850d35502a10 | erardlucien/python_exercises | /fib.py | 510 | 4.15625 | 4 | # write Fibonacci series up to n.
def fib(n):
"""Print a Fibonacci series up to n."""
a, b = 0, 1
while a < n:
print(a, end=' ')
a, b = b, a + b
print()
# fib(2000)
# return Fibonacci series up to n
def fib2(n):
"""Return a list containing the Fibonacci series up to n."""
res... |
c3ab8410cd08b4b7f673e8717924a4a82cd08ba0 | scobbyy2k3/python-challenge | /pyBank/main.py | 2,292 | 3.734375 | 4 | import os
import csv
#path for file
filepath = os.path.join("C:\\Users\\HADEORLAH\\Desktop\\python-challenge\\pyBank\\Resources\\budget_data.csv")
month_count = 0
total_revenue = 0
currentmonth_revenue = 0
previous_revenue = 0
revenue_change = 0
revenue_changes = []
months = []
# open csv file
with open(filepath,'r... |
74e772a2701ef51007a8791e606acf2795e49f5b | ch-canaza/holbertonschool-low_level_programming | /0x1C-makefiles/5-island_perimeter.py | 591 | 3.8125 | 4 | #!/usr/bin/python3
"""
tecnical enterview preparation
"""
def island_perimeter(grid):
"""
function that returns perimeter of an island
"""
p = 0
for i in range(len(grid)):
for j in range(len(grid[i])):
if (grid[i][j]) == 1:
if (p == 0):
... |
75b19920e372f8c91cc3ec59f05a87975e4d9b24 | h2sp/dev | /python/input.py | 415 | 3.578125 | 4 | #-- encoding:utf-8 --#
name = input("お名前は? ")
"""
直接文字列を入力すると以下のエラー
""で入力文字をくくるとエラーでない
Traceback (most recent call last):
File "input.py", line 3, in <module>
name = input("お名前は? ")
File "<string>", line 1, in <module>
"""
age = input("何歳ですか? ")
print("こんにちは! %sさん (%s歳)" % (name, age))
|
241940fb42ea3367a197aca1d86ebdff24858571 | katerinazuzana/sign-language-dictionary | /dictionary/scrolled_frame.py | 4,774 | 3.84375 | 4 | import tkinter as tk
from tkinter import ttk
from autoscrollbar import AutoScrollbar
class ScrolledFrame(tk.Frame):
"""A frame that is either horizontally or vertically scrollable."""
def __init__(self, parent, width, height, orient, border=False, **options):
"""Create a frame with a scrolled canvas ... |
04481a452c5d49e33634aa235cc5dd5f00813d2d | rodrigoks/python | /desafios/mundo1/d031.py | 524 | 3.921875 | 4 | print('==' * 40)
print('Desenvolva um programa que pergunte a distância de uma viagem em Km. Calcule o preço da passagem, cobrando R$0,50 por Km para viagens de até 200Km e R$0,45 parta viagens mais longas.')
print('--' * 40)
distancia = int(input('Qual a distancia da viagem? '))
valorProximo = 0.5
valorLonge = .45
p... |
d3545f4edcaf8548f32d38343e27dd59c65c2b0c | k1xme/leetcode | /python/swapPairs.py | 927 | 3.859375 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# @param {ListNode} head
# @return {ListNode}
def swapPairs(self, head):
if not head: return None
dummy = ListNode(0)
dummy.next = h... |
74a4295a3eff0b256f0663601bcb17ba5b59e542 | cbott/learnRGB | /colorlearn.py | 5,632 | 3.75 | 4 | #!/usr/bin/env python2
from Tkinter import *
from colorlib import *
import random
import tkFont
class Application(Frame):
def __init__(self, master):
#canvas / colored rectangle dimensions
self.width = 800
self.height = 300
#answer rectangle dimenstions
self.ans_width = 12... |
55e5d5016d18f80351ccbaed5466578aecf0520f | yonggyulee/gitpython | /04/03.while.py | 482 | 3.703125 | 4 | # 1 ~ 10 합을 구하기
s = 0
# for n in range(1,11):
# s += n
# print(s)
s, count = 0,1
while count < 10:
print(count)
s += count
count+=1
print(s)
#break
#for n in range(10):
# if n > 5 :
# break
# print(n, end=' ')
i = 0
while i <10:
if i>5:
break
print(i,end=' ')
i+=1
prin... |
c665f25b7dbde922bfba18623ca107c60dce3181 | noorah98/python1 | /Session32B.py | 3,955 | 3.921875 | 4 | # Open Hashing with List
# https://www.cs.usfca.edu/~galles/visualization/OpenHash.html
class HashTable:
def __init__(self, capacity=10):
self.capacity = capacity
self.size = 0
self.table = []
for i in range(capacity):
self.table.append([])
def hashCode... |
5634469e7b6d9b39ff27c7c6d718ebd3971ab99a | JNAnnis/Reports337 | /Report_01_Updated.py | 3,363 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Report 1: Primitive Pythagorean Triples
A pythagorean triple consists of a set of positive integers, (a, b, c)
that satisfies the equation a^2 + b^ = c^2.
"""
import matplotlib.pyplot as plt
import math
def mygcd(a, b):
"""
Method to determine the greatest... |
698c218e58ac682132a5901eb0085bedba49f30f | vikas-t/practice-problems | /full-problems/fourElements.py | 1,030 | 3.5 | 4 | #!/usr/bin/python
# https://practice.geeksforgeeks.org/problems/four-elements/0
def validPair(pair1, pair2):
"""
Validates that the sets have nothing in common or the pair is unique
"""
for p1 in pair1:
for p2 in pair2:
if not p1 & p2:
return True
return False
... |
88ffe6a17ff4b60cf4c20ffd4900cc2c1f64c594 | petereast/cs-year01-archive | /ce151/ass1.py | 6,462 | 4.21875 | 4 | """
ass1.py
CE151 assignment 1 template
created by sands 30/10/10
modified by sands 28/10/11 - number of exercises changed
modified by sands 28/10/6 - number of exercises changed, example added
modified by pe16564 30/10/16 - Started assignments
"""
from math import sqrt
import math
def ex0():
"""
... |
05b43d84f5799094000273c48cae0ad3f6afe869 | lobodaalina/G11 | /main.py | 234 | 3.796875 | 4 | import random
def func():
n = int(input("Enter the number of elements:"))
list = [random.randint(0, 1000) for i in range(n)]
print(list)
print("First number is", list[0])
print("Last number is", list[-1])
func() |
f894cd53a371f3c8640ecdfde2505c2e45adae10 | PNeekeetah/Leetcode_Problems | /Generate_Random_Point_In_A_Circle.py | 2,747 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Feb 22 17:40:21 2021
@author: Nikita
# Credit to my friend EIS for the solution randPoint2
# Credit to my other friend RCM for the solution randPoint2
"""
import matplotlib.pyplot as plt
import random
import numpy as np
import math
class Solution:
def __init__(self, r... |
a673eef7d991a119fd8e5ef5ba2e9c14cf657429 | Laende/CRAP | /exceptions.py | 2,701 | 3.75 | 4 | from requests.exceptions import HTTPError
class HTTP500(HTTPError):
"""
The Web server (running the Web Site) encountered an unexpected condition
that prevented it from fulfilling the request by the client (e.g. your Web
browser or our CheckUpDown robot) for access to the requested URL.
"""
def _... |
dcdc49a3cffc52a1f90c063d96c2a177dd63a80e | wmyles/Self_Taught_Programmer | /Self_Taught_Programmer/thatcher_hangman_test.py | 2,694 | 4.125 | 4 | #hangman game
def hangman(word):# function accepts variable name word as param
wrong=0 # amount of wrong characters thy guessed
stages=["", # list filled with strings use to draw hanman, when we print this it will appear
"________ ",
"| ",
"| | "... |
1340c3e85a45be839e58d68c372a829d03b3f465 | HieweiDu/Algorithms- | /bubbleSort.py | 187 | 3.859375 | 4 | def bubbleSort(arr):
for i in range(1,len(arr)):
for j in range(0,len(arr-1)):
if arr(j)>arr(j-1):
arr(j),arr(j-1)= arr(j-1),arr(j)
return arR
|
18bc6d2e162a5a0b27f4010c08ea58e4015188ce | paulruvolo/SoftwareDesign | /inclass18/problem_1_tests.py | 421 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Apr 3 10:40:40 2014
@author: pruvolo
"""
import unittest
def sum_squares_even(n):
# TODO: need to write this code!!!
return True
class SumSquaresEvenTests(unittest.TestCase):
def test_sum_squares_even_basic(self):
self.assertEqual(sum_squares_even(10),... |
43aa57d98a1a699a4c4aad96cea9adec209263af | Loweg/k-means-python | /k_means.py | 3,763 | 3.640625 | 4 | import random
import numpy
import operator
import csv
#import matplotlib.pyplot as plt
#import matplotlib.cm as cm
dataset = "wine.data"
n_means = 3 #the amount of clusters
means = [] #list containing n_means amount of Mean objects
n_samples = 50 #amount of random test data points
#no need to change th... |
c3d5027503ca832ea3e9a67c13c53776639c9e3f | KarinAlbiez0910/binomial_prob_distributions | /prob_bin_gauss_distributions-0.1/prob_bin_gauss_distributions/Binomialdistribution.py | 4,844 | 4.3125 | 4 | import math
import matplotlib.pyplot as plt
from .Generaldistribution import Distribution
import math
import numpy as np
import pandas as pd
import random
class Binomial(Distribution):
""" Binomial distribution class for calculating and
visualizing a Binomial distribution.
Attributes:
mean (f... |
565e5c703c02740032585fd3a07730fa665443d6 | Anisha-Karmacharya/Movie-Management-System | /Codes/display_list.py | 637 | 3.796875 | 4 | #to display the list of movie available to customer
def display_list(details): # creating function to display list
print("------------------------------------------------------------------------------")
print("Movie ID\tName of Movies\t\t\tPrice\t\t\tquantity") #Displays the given heading
print("... |
c9b6a48d109543fa7955b60a4cb7004055977cb6 | KjetilSekseKristiansen/Robotic-vision | /Assignment5/python/common1.py | 1,559 | 3.515625 | 4 | import numpy as np
from scipy.ndimage import gaussian_filter
import math
from math import pi
from math import exp
import matplotlib.pyplot as plt
# Task 1a
def central_difference(I):
"""
Computes the gradient in the u and v direction using
a central difference filter, and returns the resulting
gradient ... |
0833bebf14d331684271e6cf81b8a10a75f3cdfc | s1effen/AdventOfCode | /Day19/day19.py | 3,344 | 3.5625 | 4 | import re
grid = []
symbol = '#'
with open("input.txt") as file:
reader = file.readlines()
for line in reader:
row = []
for col in line.rstrip("\n"):
row.append(col)
grid.append(row)
def printGrid(pointer):
for i in range(len(grid)):
row = ""
for j in r... |
836af4a11c5dcf800ff191ff98c0739dd14912a0 | mnky9800n/data-analysis-tools | /plotting/correlation_matrix.py | 891 | 3.8125 | 4 | from matplotlib.pylab import pcolor
def make_correlation_matrix(df, title):
"""
Creates a matplotlib plot of values (typically a correlation dataframe from Pandas).
This plot has each value in a cell shaded on a color map for the entire
matrix. The color map is by default reverse gray scale.
requirements:... |
fabba1f6cbfcf51b26cdcc7e751a5ccde3517a2c | Heez27/AI_Edu | /Day11-class2/practice01.py | 409 | 3.734375 | 4 | #키보드로 정수 수치를 입력 받아 그것이 3의 배수인지 판단하세요
a = input('수를 입력하세요: ')
for i in a:
if i.isdigit()==0:
print('정수가 아닙니다. ')
break
else:
if int(a)%3 == 0:
print('3의 배수입니다.')
break
else:
print('3의 배수가 아닙니다. ')
break |
d1b403dd2f9f65329ad856140adcf69984741ac1 | heronghua008/heronghuanotebook | /pythonNET/pythonNET06/day6/process2.py | 534 | 3.640625 | 4 | from multiprocessing import Process
from time import sleep
def worker(sec,name):
for i in range(3):
sleep(sec)
print("I'm %s"%name)
print("I'm working.....")
#通过args给函数传参
#通过kwargs给函数传参
p = Process(name = "Worker",target = worker,args = (2,),\
kwargs = {'name':'Levi'})
p.start()
#判断... |
9c1f6ace1e0c0727cc6c05c990c51fdb0326972b | yshshadow/Leetcode | /1-50/24.py | 1,236 | 4.09375 | 4 | # Given a linked list, swap every two adjacent nodes and return its head.
#
# Example:
#
# Given 1->2->3->4, you should return the list as 2->1->4->3.
# Note:
#
# Your algorithm should use only constant extra space.
# You may not modify the values in the list's nodes, only nodes itself may be changed.
# Definition for... |
b5c909b17afabb6bb933c50aa2b7104c70120b12 | xErik444x/apuntesPython | /codes/Parte1/for/ForConElse.py | 241 | 4.0625 | 4 | #cuando el for llegue a 4, este va a ir al else
for i in range(5):
print(i)
else:
print("else:", i)
#En este caso no va a pasar por el for y va directo al else
i = 111
for i in range(2, 1):
print(i)
else:
print("else:", i) |
c8389e7fd94ca1697f8afdf022a024cc456d2550 | syurskyi/Python_Topics | /045_functions/_exercises/templates/The_Modern_Python_3_Bootcamp/Coding Exercise 40 Yell Function Exercise.py | 349 | 4.0625 | 4 | # Using string concatenation:
def yell(word):
return word.upper() + "!"
# Using the string format() method:
def yell(word):
return "{}!".format(word.upper())
# Using an f-string. My personal favorite, but only works in python 3.6 or later.
# Udemy exercises don't support it currently :(
def yell(word):
... |
4205353427a2abc1b8b6caa7eab1041fc08e355b | arsezzy/python_base | /lesson7/lesson7_2.py | 713 | 4 | 4 | #!/usr/bin/python3
from abc import ABC, abstractmethod
class Clother(ABC):
@abstractmethod
def get_consumption(self):
pass
class Coat(Clother):
def __init__(self, param):
self.size = param
@property
def get_consumption(self):
return round(self.size / 6.5 + 0.5, 2)
cla... |
ebf48ccde070e1e25a5ff9dfa817cda34cc6ac52 | daniel-reich/turbo-robot | /nqNWZ7ayzZoRMZu8Z_13.py | 614 | 4.15625 | 4 | """
Create a function that takes a list of dictionary like `{ name: "John", notes:
[3, 5, 4]}` and returns a list of dictionary like `{ name: "John", avgNote: 4
}`. If student has no notes (an empty array) then `avgNote` is zero.
### Examples
[
{ name: "John", notes: [3, 5, 4]}
] ➞ [
{ name: "J... |
46a3f6676a443ba1f48c35aac4d7f12cfb52c69a | Filippos-Filippidis/Udacity_IntroToProgramming | /stage-3/media.py | 1,005 | 3.53125 | 4 | import webbrowser
# webbrowser module provides a high-level
# interface to allow displaying Web-based documents to users
class Movie():
def __init__(self, movie_title, movie_storyline, poster_image,
trailer_youtube, rating_image_url):
"""
Initialize the movie instance.
A... |
c2b98e19905a2b84e33b7ca344ef922415cfc80b | sens8tion/skaf-py-contrast | /hello.py | 149 | 3.609375 | 4 | import time
from datetime import datetime
while True:
print("Hello why does this take so change 8")
print(datetime.now())
time.sleep(1)
|
2fa98b5fa1e571062178c2976c3e2e98bfa80b07 | sammysamsamsama/DATA1401-Spring-2020 | /Labs/Lab-3/TicTacToe.py | 2,819 | 3.875 | 4 | # Write you solution here
empty = 0
player_1 = 1
player_2 = 2
players = {0: " ",
1: "X",
2: "O"}
def make_game_board(n=3):
return [[empty] * n for i in range(n)]
# return 1 if p1 wins
# return 2 if p2 wins
# return 0 if game not finished
# return -1 if draw
def check_game_finished(board):
... |
304090ff320636915ad091ab487c678d0571a5e0 | tapanprakasht/Simple-Python-Programs | /pgm13.py | 104 | 3.84375 | 4 | n=int(input("Enter a number:")
for i in range(n):
for j in range(i):
print(j)
|
5428cab7624f1872514a195c35e58589d97d6bf5 | kartikeychoudhary/competitive_programming | /hackerrank/problem_solving/strings/caesar_cipher.py | 884 | 3.5625 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the caesarCipher function below.
arr = list(map(chr, range(ord('A'), ord('Z')+1)))
arr2 = list(map(chr, range(ord('a'), ord('z')+1)))
def caesarCipher(s, k):
s = list(s)
for i in range(len(s)):
if s[i] in arr:
... |
726fb8172ba799874ee257a89e03744391ff9984 | lorenzocastillo/Algos-and-DS | /SystemDesign/Sudoku.py | 6,568 | 3.890625 | 4 | """
Sudoku Solver based on Peter Norvig's implementation:
http://norvig.com/sudoku.html
"""
from collections import namedtuple
class Validator:
"""
Takes in a Sudoku Board object, and determines whether board has a valid Sudoku Solution
"""
def __init__(self, board):
self.board = board.board
... |
067cd50838dfc3eb1ab35635be181a2930bf4aec | sarzz2/codewars-kata | /Sum of mixed array.py | 277 | 3.859375 | 4 | def sum_mix(arr):
print(arr)
ans = 0
for i in range(0, len(arr)):
arr[i] = int(arr[i]) # changing all elements in a list to an integer
ans = ans + arr[i]
return ans
sum_mix([1,"1","2"]) # passing numbers in the function
|
7ef910140a9d2f63ef34668f89c8462a3792b35d | Joecth/leetcode_3rd_vscode | /528.random-pick-with-weight.py | 4,170 | 3.765625 | 4 | #
# @lc app=leetcode id=528 lang=python3
#
# [528] Random Pick with Weight
#
# https://leetcode.com/problems/random-pick-with-weight/description/
#
# algorithms
# Medium (43.85%)
# Likes: 789
# Dislikes: 2254
# Total Accepted: 109.2K
# Total Submissions: 248.7K
# Testcase Example: '["Solution","pickIndex"]\r\n[[... |
54a8dd162335c39c1ddf7f726bd59b2a802f7072 | horlathunbhosun/algorithms | /add-two-numbers/index.py | 835 | 3.65625 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
remainder = 0
v1 = l1
v2 = l2
result = ListNode(0)
current = result
... |
54606d34f486593a41079c24a6e52c5b396f7bd6 | clayll/zhizuobiao_python | /练习/day08/1.numpy的矢量.py | 902 | 3.703125 | 4 | #numpy的矢量
#矢量是指一堆数组成的集合
#标量是指单独一个数。
#多维数组也叫矢量化计算
#numpy和python执行计算的效率比较
import datetime as dt
import numpy as np
n = 100000
start = dt.datetime.now() #记录当前时间
A, B = [], []
for i in range(n):
A.append(i**2)
B.append(i**3)
C = []
for a, b in zip(A,B):
C.append(a + b)
print(type(C))
print('python执行',(dt.dat... |
f2e79b3ac9d22bdfd758e70526dea93e82c1f121 | sPaMFouR/DIS | /Exercises/first.py | 2,449 | 4.21875 | 4 | import math
import sys
import os
# print("Hello", "World")
# print("Hello", "World", sep=":")
#
# # Python 3 has Python Functions (Python 2 Has Print Statements)
# # from __future__ import print_function (For Using Python Function In Python 2)
#
# # Python Is An Interpreter (Compiles Line By Line Code To A 'Byte' Code... |
6312aa8e94de363260878583df600180ab08631f | bomcon123456/DSA_Learning | /Python/Chapter 1/ex33.py | 3,766 | 3.65625 | 4 | import platform # For getting the operating system name
import subprocess # For executing a shell command
def clear_screen():
"""
Clears the terminal screen.
"""
# Clear command as function of OS
command = "cls" if platform.system().lower() == "windows" else "clear"
# Action
return sub... |
df77d66c4a626ff0daa44f9a8b2a7231a4745602 | sveraecaterina/ESrep | /week9/spiral.py | 287 | 3.609375 | 4 | def spiral(x):
sum=1
val=0
my_list=[y for y in range(1,x) if y%2==0 ]
for item in my_list:
for i in range(1,5):
sum+=1+i*(item)+val
i+=1
val+=4*(item)
return print(sum)
if __name__ == "__main__":
x=501
spiral(x) |
51501afd4094c4effe6e5e42da9eba0d6365a6bf | uoayop/study.algorithm | /programmers/42583.py | 3,249 | 3.75 | 4 | # from collections import deque
# def solution(bridge_length, weight, truck_weights):
# answer = 0
# ing_truck = deque()
# ing_weight = 0
# truck_count = len(truck_weights)
# count = 0
# while 1:
# if (count == truck_count):
# break
# if (truck_count==1):
# ... |
a556b77cafbfaae85f22141f89d4fa0ea21df944 | pezaantonio/ticketalerts | /disneyWeb.py | 3,618 | 3.625 | 4 | # Anthony Peza
# Python Programming
# Disney Web
#
# The purpose of this program is alert me when disney tickets go on sale
#
import json
import time
import smtplib
from bs4 import BeautifulSoup as soup
from urllib.request import urlopen as uReq
# Global Variables #
disneyUrl = "https://disneyland.disney.go.com/events... |
4797efdbe4ce004219a028030f5b8ce397366257 | MerinGeorge1987/PES_PYTHON_Assignment_SET-3 | /ass3Q54.py | 1,071 | 4.15625 | 4 | #!/usr/bin/python
#Title: Assignment3---Question54
#Author:Merin
#Version:1
#DateTime:03/12/2018 3:00pm
#Summary:Write a program to handle the following exceptions in you program.
# a) KeyboardInterrupt
# b) NameError
# c) ArithmeticError
# Note: Make use of try, except, else: blo... |
a29c8b3c479f55feabba716c906a53a20c0ca6a3 | jinsuupark/chapter07 | /ex07-02.py | 1,562 | 3.828125 | 4 | def intsum(*ints):
total = 0
for num in ints:
total += num
return total
# print(intsum(1,2,3))
# print(intsum(5,7,9,11,13))
# print(intsum(8, 9, 6, 2, 9, 1,5,7))
# 인수의 기본값
# calcstep( begin=1,end,step=1) 안된다 인수 초기화는 뒤에서부터
def calcstep(begin, end, step=1):
total = 0
for num in range(begin,... |
fa4686dc1117020d816cd725749123ce43d11778 | FoxGriVer/PythonLabs | /lab2/leap.py | 886 | 4.09375 | 4 | def checkLeapYear(inputYear):
if((inputYear % 4) != 0):
print("{0} is not a leap year".format(inputYear))
elif ((inputYear % 100) == 0):
if((inputYear % 400) == 0):
print("{0} is a leap year".format(inputYear))
else:
print("{0} is not a leap year".format(inputYea... |
677e7b6a91ba901fb4216661fa531c503522ad8d | sbasu7241/cryptopals | /Set1/Challenge8.py | 1,066 | 3.84375 | 4 | #!/usr/bin/env/python
import base64
def count_repetitions(cipher_text,block_size):
""""Breaks the ciphertext into block_size sized chunks and counts the no of repetitions.Returns the ciphertext and repetitions as a dictionary"""
chunks = []
for i in range(0,len(cipher_text),block_size):
chunks.append(cipher_tex... |
eb627822fb8a4adf54c20dcce1ef7720ce77ca83 | saravyas/saravyas | /PycharmProjects/sara/eh1.py | 273 | 4.125 | 4 | import sys
print "enter a number"
while True :
try:
number = int(raw_input("number\n"))
except ValueError:
print "error please enter a number"
continue
else :
break
print "you entered number " , number
|
38822e19b6bb01ff79a8c92a99d0e4b728cd7a76 | rrwt/daily-coding-challenge | /daily_problems/problem_101_to_200/problem_101.py | 1,262 | 4.25 | 4 | """
Given an even number (greater than 2),
return two prime numbers whose sum will be equal to the given number.
A solution will always exist. See Goldbach’s conjecture.
Example:
Input: 4
Output: 2 + 2 = 4
If there are more than one solution possible, return the lexicographically smaller solution.
If [a, b]... |
68927391f12f9843d9b5fdb2ac142cb07b096441 | ZR-Huang/AlgorithmsPractices | /Leetcode/每日打卡/April/887_Super_Egg_Drop.py | 2,095 | 3.921875 | 4 | '''
You are given K eggs, and you have access to a building with N floors from 1 to N.
Each egg is identical in function, and if an egg breaks, you cannot drop it again.
You know that there exists a floor F with 0 <= F <= N such that any egg dropped at a floor
higher than F will break, and any egg dropped at or below... |
e642e502ec84a9b405f1fda5f5c151025db3c291 | laihoward/leetcode_practice | /Dynamic-Programming/Climbing_Stairs.py | 280 | 3.640625 | 4 | class Solution(object):
def climbStairs(self, n):
fib_list=[1,2]
if n<=2:
return fib_list[n-1]
for i in range(n-2):
fib_list.append(fib_list[-1]+fib_list[-2])
print(fib_list)
return fib_list[-1]
|
7a4ab3a8183b899792b6a8fb6dfa37ac3cd07be2 | saa419/LPTHW | /ex33.py | 455 | 4 | 4 | #i = 0
#numbers = []
def whiloop(endnum, increm):
i = 0
numbers = []
while i < endnum:
print "At the top i is %d" % i
numbers.append(i)
i = i + increm
print "Numbers now: ", numbers
print "At the bottom i is %d" % i
return numbers
endnum = int(raw_input("What number should we end on? "))
increm = int(ra... |
21d4b26d5af75103a520cb0ace70b214d00ab5ec | deekshasingh2k8/GitDemo | /pythonBasics/WhileDemo.py | 391 | 4.46875 | 4 | it = 10
while it > 1:
if it == 9:
it = it-1 # decrement the value of it so stop the infinite loop when it is 9
continue
if it == 3:
break # break is used to stop the while loop execution
print(it) # 10 only as continue statement skips all the below lines of code and go to infinite... |
d47b74c92166263c24236fee8b3e936de3983f53 | Nikkuniku/AtcoderProgramming | /ABC/ABC100~ABC199/ABC167/A.py | 112 | 3.796875 | 4 | s=list(input())
t=list(input())
last = t[-1]
s.append(last)
if s== t:
print('Yes')
else:
print('No') |
d56e7f4e0770f7e817a1de6ba312ec17962ef179 | rahulchawla1803/customized-web-search-engine | /modules/main.py | 2,075 | 3.640625 | 4 | import threading
from queue import Queue
from Spider import spider
from domain import *
from general import *
#PROJECT_NAME='thenewboston'
#PROJECT_NAME='health'
PROJECT_NAME='hindustantimes'
#HOMEPAGE='https://thenewboston.com/'
#HOMEPAGE='http://www.health.com/'
HOMEPAGE='http://www.hindustantimes.com/'
DOMAIN_NAM... |
22e037ad60fb17eb10647dd165d2700b84311581 | hao276843248/pythontestcode | /testpailie.py | 583 | 3.640625 | 4 | def group_elements(eles):
if len(eles) == 1:
yield (eles,)
return
for g_tuple in group_elements(eles[1:]):
yield (eles[:1],) + g_tuple
for i in range(len(g_tuple)):
yield (
g_tuple[:i]
+ ((eles[:1] + g_tuple[i]),)
... |
960f3f5036312bcf233b5ed2515b3e8c50ba22e0 | ayushbhandari02/Data-Structures | /BST.py | 528 | 3.578125 | 4 | from binary_tree import BinaryTree
b = BinaryTree(3)
try:
b.insert_node(5)
except Exception:
print("error with the parameter passed")
b.insert_node(4)
b.insert_node(2)
b.insert_node(1)
b.insert_node(2.5)
b.insert_node(1.5)
print("After inserting all the nodes, traverse using post order ")
b.view_pos... |
91350e1ba3aee448fc043e71800800ca7d1e5924 | sfeng77/myleetcode | /medianOfTwoSortedArrays.py | 2,511 | 4.0625 | 4 | # There are two sorted arrays nums1 and nums2 of size m and n respectively.
#
# Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
#
# Example 1:
# nums1 = [1, 3]
# nums2 = [2]
#
# The median is 2.0
# Example 2:
# nums1 = [1, 2]
# nums2 = [3, 4]
#
# The median is (2 + 3)/2... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.