blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
a5e5efe03ed53f1b77a231c5440cf3395cf2504a | Al-ImranRony/Algorithms | /kadanesAlgo.py | 524 | 3.75 | 4 | '''
Tech Interview Prep Group task - Session 3.
Maximum SubArray in Python Uising kadane's Algo
Time complexity: O(N)
'''
import sys
def maxSubArray(nums: list) -> int:
ln = len(nums)
sum = 0
maxSubSum = -sys.maxsize - 1
if ln<2:
return ln
for i in range(ln):
sum += nums[i]
... |
611cda680c1f1faa6f3d312561dadf3c334a63f4 | flopez-APSL/TutPython | /ficheros_de_texto.py | 631 | 3.984375 | 4 | #f = open('textfile.txt', 'r+') # r+ lee y escribe.
with open('textfile.txt') as f:
read_data = f.read()
print(read_data)
f.closed
with open('textfile.txt') as f:
read_data = f.readline()
print(read_data)
f.closed
print('------------------------------------------------------------------')
wi... |
6df7628bd1b7c309cfad75779ab8b39ec986868d | IGalascapova/codefirstgit | /homework.py | 318 | 3.609375 | 4 | a=1
a=a+1
print a
b = "hello"
print b
c = b.title()
print b
print c
d = "hello"
e = d.title()
print d
print e
name = "Dave"
f = "Hello {0}! ".format(name)
print f
name = "Sarah"
print f
print f *5
myName = int(input ("What's your name?"))
a = int(input("Num 1 "))
b = int(input("Num 2: "))
c = int(input("Num 3: "))
|
85af3835caa2044d085b9fc665b0361811726537 | marcusgsta/search_engine | /pageRank.py | 1,449 | 3.609375 | 4 | #!/usr/bin/python3
import os
from urllib.parse import unquote
def createLinkIndex(dictOfDicts):
"""
Creates a searchable index from a list of wikipedia articles.
Loops through list of files
and stores a dict of dictionaries with
urls, links and pageRanks (set to inital value of 1.0)
"""
for... |
ad60f7383eace5f3ddae5a61d1baf9f7a1409806 | ahammadshawki8/Standard-Libraries-of-Python | /01. exploring modules and library.py | 3,737 | 3.953125 | 4 | # importing module and exploring standerd library.
# module can be of 3 types.
# first one is standerd libraries. they are default built in modules of python.
# second one is third party libraries. Very good developers make this libraries for a certain use.
# third is own module. right now, the file we are working on,... |
b49e031ff5b347ccc0eaad9ce0243d4f56d71768 | Ibarra11/TicTacToe | /tic_tac_toe.py | 4,055 | 3.921875 | 4 |
def game():
markers = [[],[]]
player = 0
board = [['','',''] , ['','',''], ['','','']]
remainingPositions = 9
hasWon = False
def init():
markers[0] = input('Player 1 choose your marker: ').upper()
markers[1] = input('Player 2 choose your marker: ').upper()
def placeInputOn... |
3931f946e58fccbc5e1fe228e952dc89a37887c3 | pflun/advancedAlgorithms | /intersection.py | 442 | 3.515625 | 4 | class Solution:
# @param {int[]} nums1 an integer array
# @param {int[]} nums2 an integer array
# @return {int[]} an integer array
def intersection(self, nums1, nums2):
results = []
Set1 = set(nums1)
Set2 = set(nums2)
for i in Set1:
if i in Set2:
... |
3043e605829b4cc3b3a68ebd10d7aea12d59e56b | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/hamming/4c47a64657294080936c5ee6869abb1b.py | 283 | 3.84375 | 4 | def hamming(first, second):
firstList = list(first)
secondList = list(second)
ham_distance = abs(len(firstList) - len(secondList))
for i, val in enumerate(firstList):
if i > len(secondList) - 1:
pass
elif val != secondList[i]:
ham_distance += 1
return ham_distance
|
5fbbdc986271605050f59280488eab2b631d17bf | joshuabhk/methylsuite | /sim/__init__.py | 2,009 | 3.625 | 4 | from random import randrange, getrandbits, gauss, random, choice
def random_nucleotide( nuc, nucleotide_pool = ['A','C','G','T'] ) :
if nuc.islower() :
nuc = nuc.upper()
#make sure newnuc is different from nuc
newnuc = choice( nucleotide_pool )
wh... |
a4aaaa535b14289561344212efd535d82de7dddf | xiaoxiaojiangshang/LeetCode | /leetcode_python/recover_Binary_Search_Tree_99.py | 2,206 | 3.875 | 4 | #-*-coding:utf-8-*-
# 作者:jgz
# 创建日期:2018/11/28 9:55
# IDE:PyCharm
import numpy as np
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution1(object):
def recursive(self,root,inorder_trave... |
69dfcc8ae1df677f7bba9d2951cf32ca23fa1761 | SneyderHOL/holbertonschool-higher_level_programming | /0x0A-python-inheritance/3-is_kind_of_class.py | 461 | 3.828125 | 4 | #!/usr/bin/python3
""" Module for function is_kind_of_class """
def is_kind_of_class(obj, a_class):
"""is_kind_of_class: function that returns True if the object is an
instance of, or if the object is an instance of a class that inherited
from, the specified class; otherwise False
Args:
... |
5f4bd02ff99abf56b7fcf1927d8164509478bee5 | veretrum/2019ProgrammingPortfolio | /Bottles/99Bottles.py | 434 | 3.890625 | 4 | #!/usr/bin/python3
Bottles = 99
while (Bottles > 1):
print (Bottles, 'bottles of root beer on the wall,', Bottles, 'bottles of root beer')
Bottles = Bottles - 1
print ('Take one down and pass it around', Bottles, 'bottles of root beer')
if Bottles == 1:
print ('Take one down and pass it around', Bottles, 'bot... |
9ca947782d30798c183325670f1b16504ebdefc8 | Gotek12/Python | /z10/10_3.py | 1,335 | 3.953125 | 4 | #!/usr/bin/python3
# -*- coding: iso-8859-2 -*
class Stack:
def __init__(self, size=10):
self.items = size * [None] # utworzenie tablicy
self.n = 0 # liczba elementw na stosie
self.size = size
self.itemsTest = size * [0]
def top(self):
return self.items... |
a99d5ec0c2d1d9f87eefff9ec8f39f06dede7f6a | trzyha/paper_scissor_rock | /paper_sissor_rock.py | 3,273 | 3.703125 | 4 | import tkinter
from random import randint
playerPoint = 0
oponentPoint = 0
#settings main window
root = tkinter.Tk()
root.title("Paper rock scissor game")
root.minsize(600,400)
root.geometry("750x600")
root.columnconfigure(0, minsize=250)
root.columnconfigure(1, minsize=250)
root.columnconfigure(2, minsi... |
e4c3c710977ddc8bd539dd095359b0baddedb478 | ngupta23/more | /build/lib/more/viz_helper/plot_data.py | 4,301 | 3.59375 | 4 | import matplotlib.pyplot as plt
import seaborn as sns
import warnings
import math
def plot_data(data,
kind='dist',
rows=None,
cols=None,
kde=False,
bins=None,
figsize=None,
xrot=0,
yrot=0):
"""
data... |
7eead0fce78a434adb5dddd4180285aeedb16409 | adrigo/Python | /Ejercicios/EjerciciosPython/calculadora.py | 1,838 | 3.8125 | 4 | import os
def suma():
os.system('clear')
print("SUMA")
print("Escribe el primer numero:")
i = int(input())
print("Escribe el segundo numero:")
j = int(input())
print("-------------------------")
print("La suma es: " + str( i + j ))
print("-------------------------")
print("")
d... |
c5b3dc5b01f78e7ec8d6b1cc1debc60c982c6978 | XinZhaoFu/leetcode_moyu | /557反转字符串中的单词III.py | 470 | 3.859375 | 4 | """
给定一个字符串,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。
示例:
输入:"Let's take LeetCode contest"
输出:"s'teL ekat edoCteeL tsetnoc"
"""
class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
res = []
for element in s.split(' '):
res.appen... |
a1d75831b07ba3dd5ae0ff44ff9fef17b8f88255 | Deepbiogroup/affiliation_parser | /affiliation_parser/parser/parse_zipcode.py | 651 | 3.765625 | 4 | import re
def parse_zipcode(affil_text: str):
"""
Parse zip code from given affiliation text
https://github.com/unicode-org/cldr/blob/release-26-0-1/common/supplemental/postalCodeData.xml
"""
zip_code_res = [
r"\d{7}",
r"\d{6}",
r"\d{5}(-\d{4})?",
r"\d{3}(-\d{4})?"... |
9aa51936e84dfb578b591c7202d2527adb5ecbd0 | Escarzaga/calculator | /main.py | 472 | 4.34375 | 4 | calculate1 = int(input("Tell me a number: "))
calculate2 = int(input("Tell me a second number: "))
operation = input("Which arithmetic operation should I use: +, -, * or /?: ")
if operation == "+":
print(calculate1 + calculate2)
elif operation == "-":
print(calculate1 - calculate2)
elif operation == "*":
... |
83c30a6a3ebdfea64a120036d654c9fe1c283192 | kevivforever/pythonWorkspace | /Learn python the hard way/ex34.py | 212 | 3.9375 | 4 | animals = ['bear', 'python', 'peacock', 'kangaroo', 'whale', 'platypus']
print "The animal at 1: " + animals[0]
for animal in animals:
print animal
print
for i in range(len(animals)):
print animals[i]
|
52a28119e63254ba4560cb35288fe92097a28193 | buelmanager/python_edu | /level4/day9_exception_1.py | 958 | 4.15625 | 4 | # 예외처리
# print ("나누기 전용 프로그램")
# try:
# num1 = int ( input("첫 번째 숫자를 입력하세요."))
# num2 = int ( input("두 번째 숫자를 입력하세요."))
# print ( "{0} / {1} = {2}".format(num1 , num2 , num1/num2))
# except ValueError:
# print (" 에러! 잘못된 값을 입력하였습니다.")
# except ZeroDivisionError as err:
# print (err)
## 예외처리 2
pri... |
54ee5e013ec5b2707d38c43792a4d45fc07c42aa | WangYue1998/Algorithms-and-Data-Structures | /project5/p5.py | 5,051 | 4.125 | 4 | """
# Project 5
# Name: Yue Wang
# PID: A54267282
"""
"""implement a circular queue.
A queue is an abstract data type where the first item in is the first item out.
A circular queue is one that uses an underlying list and uses modulo arithmetic
to allow for reuse of space after enqueues and dequeues.
"""
class Cir... |
4a15231674ae1829cf1c7fccca70d72926349d08 | joelhrobinson/Python_Code | /queue_popleft_pop.py | 731 | 4.125 | 4 | #Importing the library
from collections import deque
#Creating a Queue
print ("DEQUE creates a FIFO queue")
myQueue = deque([1,5,8,9])
#Enqueuing elements to the Queue
print ("myQueue.append(99) & myQueue.appendleft(66)")
myQueue.append(99) # put value on DEFAULT side of queue (RIGHT)
myQueue.appendl... |
bfbafbeb89522b1675b539e2e74c8e81bc326001 | Haseeb-Sha/Npci-Training | /Python/day 4 code 1.py | 412 | 3.546875 | 4 | class project:
project=["p1","p2","p3"]
class user(project):
users=["u1","u2","u3"]
def operation(self):
pro_user=["p1","P1","p2","P2","p3","P3"]
salary={"u3":5000,"u1":2000,"u2":3000}
print(sorted(salary))
lst_dct={pro_user[i]:pro_user[i+1] for i in range(0 , 6 ,2)}
... |
61ca729a4d4ba69e12b409e975068a7d1aa05f69 | Maaduu/guess_a_number | /guess_a_number_V3.py | 713 | 4.03125 | 4 |
from random import randint
number_to_guess = randint(1, 25)
number_try = 5
i = 0
i = int(i)
while i < number_try:
attempt = input('Enter a number ({0} attempt): '.format(i + 1))
attempt = int(attempt)
if attempt < number_to_guess:
print('The number to guess is bigger than {0}'.format(attempt))
... |
4cf739aff331824529a6e6009a5a531a0a91d7dd | abishekravi/guvipython | /h95.py | 489 | 3.859375 | 4 | #a
import math
def isprime(x):
if(x ==2):
return True
elif(x%2 == 0):
return False
else:
for j in range(2,int(math.sqrt(x)+1)):
if(x%j == 0):
return False
return True
n = int(input(""))
prime = []
for i in range(2,n):
if(isprime(i)):
pr... |
de522cec22d3df58447dc73e77b80bc2ab5a8e80 | nandansn/pythonlab | /durgasoft/chapter71/example-4.py | 131 | 3.59375 | 4 | import re
pattern = input('enter pattern:')
text = input('enter test:')
listObjs = re.split(pattern,text)
print(listObjs) |
f3f8bf9ab914e8c753c6898a8c5aaadf9139ce2d | jiwon11/pythonProgramming | /student_input.py | 422 | 3.9375 | 4 | studentNumber = input('학번 :')
name = input('이름: ')
firstNum = int(input('첫번째 수: '))
secondNum = int(input('두번째 수: '))
str1 = studentNumber+name
print(str1[0],str1[1],str1[2],str1[3],str1[4],str1[5],str1[6],str1[7],str1[8],str1[9],str1[10],str1[11])
print(str1[-1],str1[-2],str1[-3],str1[-4],str1[-5],str1[-6],str1[-7],st... |
a7adf983ca48f2bd9d08422c2a6214177b453747 | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_74/205.py | 2,894 | 3.59375 | 4 | #/usr/bin/env python
import sys
DEBUG = False
def debug(string):
if DEBUG:
print string
def other(robot):
if robot == "O":
return "B"
elif robot == "B":
return "O"
else:
raise Error
def find_next_target(movs, info, robot):
idx = info[robot]["next_idx"]
if idx ... |
a71d663205a17020b7241fff0c0a5e175c74c6ea | debiprasadmishra50/100-Python-Projects | /Intermediate Projects/22_Spirograph_and_Hirst_Painting/spirograph.py | 603 | 3.953125 | 4 | from turtle import Turtle, Screen
import random, turtle as t
size = int(input("Enter the gap size in degrees(10-30 for better view): "))
t.colormode(255)
def random_color():
r = random.randint(0, 255)
g = random.randint(0, 255)
b = random.randint(0, 255)
new_color = (r, g, b)
return new_color
ti... |
68791138916a31f46bc4df873dfeaafaa824ede6 | dragevil007/pro-c-97 | /pro c-97/guessingGame.py | 470 | 4.21875 | 4 | import random
number=random.randint(1,9)
chances=0
print("guess a number between 1 and 9")
while chances<5:
guess=int(input("enter you guess"))
if guess==number:
print("congratulation you won")
elif guess< number:
print("your guess was too low",guess)
else:
... |
aa4df7e737b92bd092a3206c568cd79a77e60ff9 | Matteomnd/TP11 | /EXERCICE3.py | 1,751 | 3.71875 | 4 | class Rational :
def __init__(self, numerator, denominator=1):
self.__numerator = numerator
self.__denominator = denominator
def get_numerator(self):
return self.__numerator
def get_denominator(self):
return self.__denominator
def __add__(self, f1):
if isinstan... |
c69b81da47524aa9f13738e0ec77f61758159e78 | youthcodeman/self-learning-python | /org.hzg.pyLearn/函数/simpleFunction.py | 2,246 | 3.734375 | 4 | #_*_ coding:utf-8 _*_
# def pName() :
# # 声明函数的功能
# print("这是一个函数")
#
#
# pName()
#
#
# def pName1(userName) :
# print("我叫%s"%username)
#
#
# pName1("zhangsan")
# def pname2(num1,num2) :
# a = num1 + num2
# print("求和结果:%d"%a)
#
#
# # pname2(25,50)
# pname2(num2=5888,num1=9999) #关键字参数,在调用的时候添加参数的... |
c5ba8f1e39a86eff16f48d375802942102c7c96c | ErikBuchholz/kidsMathQuiz | /kidsMathQuiz/user_interface.py | 1,626 | 3.78125 | 4 | #
#
#
#
#
#
#
def display_dialogue(prob_text, question_num):
print("\n")
display_problem(prob_text, question_num)
user_answer = get_answer()
return user_answer
#
#
#
#
#
def display_problem(prob_text, question_num):
print("Question #%d: %s" % (question_num, prob_text))
#
#
#
#
#
def get_answer():... |
d235a9369335941d768cbd9ede73033df1154813 | prashant133/Labwork | /Lab4/question9.py | 208 | 4.34375 | 4 | '''
9.Write a program to find the factorial of a number.
'''
num = int(input("enter the value: "))
factorial = 1
while num > 0 :
factorial = num * factorial
num = num -1
print('factorial:',factorial,) |
bc6e24c0924b0370e62b84535ee7fe939cf5a611 | scorourk/PBD_SOR | /CA_3/car.py | 3,149 | 4.125 | 4 | #CA 3 Programming for Big data. B8IT105 (B8IT105_1617_TMD3)
#Stuart O'Rourke
#Student Number: 10334192
#DBS Car Rental.
#Object is blue print, methods pass arguement to Class object.
#Determination of the objects that make up the system.
class Car(object):#Class definitions for car objects Petrol, Electric, Diesel... |
7508e0bff3e609c78f20b973bf4c9849c952212d | gabriellaec/desoft-analise-exercicios | /backup/user_383/ch34_2019_03_21_22_35_56_976243.py | 226 | 3.640625 | 4 | contador = 1
deposito_inicial=float(input('Qual o valor do depósito inicial?'))
taxa_juros=float(input('Qual a taxa de juros da poupança?'))
while contador<=24:
print(deposito_inicial*taxa_juros*contador)
contador+=1 |
ae8087e6c0ab6d86e6abdf3327a08417c5c13181 | izdomi/python | /exercise6.py | 327 | 4.40625 | 4 | # Ask the user for a string and print out whether this string is a palindrome or not.
string = input("the word: ")
i = 0
while i in range(len(string)-1):
if string[i] != string[len(string)-1-i]:
print("The word is not a palindrome!")
break
else:
print("The word is a palindrome!")
... |
b923d1984830fafd1caebe85e9bfff3083cf24f8 | noorah98/python1 | /Session28B.py | 1,260 | 4.03125 | 4 | import pandas as pd
nums1 = [10, 20, 30, 40, 50]
nums2 = [11, 22, 33, 44, 55]
emp1 = {"name": "John", "age": 22, "salary": 30000}
emp2 = {"name": "Fionna", "age": 24, "salary": 45000}
emp3 = {"name": "Dave", "age": 26, "salary": 54000}
emp4 = {"name": "Kia", "age": 28, "salary": 59000, "email": "kia@example.com"}
fr... |
5128c3f14b31157065f5c140a59a7c69244c6123 | niteshkrsingh51/hackerRank_Python_Practice | /itertools/itertools_combinations.py | 493 | 3.734375 | 4 | from itertools import combinations_with_replacement
string,length = input().split()
length = int(length)
my_list = list(combinations_with_replacement(sorted(string),length))
print(my_list)
def join_tuple_strings(my_list):
return ' '.join(my_list)
my_Iterator = map(join_tuple_strings, my_list)
result_list = list(... |
363d018bd56f4d8371417a82d823108d49ca1ab6 | hechty/datastructure | /5.9-insertionsort.py | 590 | 4.09375 | 4 | #! /usr/bin/env python3
def insertion_sort(alist):
orded_list = alist[:1]
for i in range(len(alist)-1):
new_data = alist[i+1]
orded_list = insertion(new_data, orded_list)
return orded_list
def insertion(new_data, orded_list):
posi = 0
for i in range(len(orded_list) - 1, -... |
a6d0215634786fc26a19e54c916479c7dca842fa | seenaimul/OpenCV_Course_freecodecamp | /Advance/smoothing.py | 725 | 3.921875 | 4 | import cv2 as cv
img = cv.imread('Resources/Photos/cats.jpg')
cv.imshow('Cats',img)
# We smooth an image when it has a lot of noise
# reduce noise / smooth the image using blur technique
# kernel size is number of rows and columns
# 1. Averaging
average = cv.blur(img, (3,3)) # The more the kernel size the more blur t... |
39aeb3a0d655fc0f074025c8188f052dd7661dd5 | Thalrod/Yatwog | /game/shape/rectangle.py | 1,644 | 3.640625 | 4 | import pygame
class Rectangle():
def __init__(self, screen, x, y, width, height, color):
self.screen = screen
self.x = x
self.y = y
self.width = width
self.height = height
self.color = color
self.rectangle = pygame.Rect(self.x, self.y, self.width, self.heig... |
b443ebf83b3a064a8bd5da2e9d46aaa49d9ee6b1 | fdr896/keyboard | /keyboard | 2,300 | 3.59375 | 4 | #!/bin/python3
import sys, subprocess
def Help():
print("""Usage:
keyboard <command> [options]
Commands:
on turns on embeded keyboard
off turns off embeded keyboard
Options:
-n, --name <"name"> turns on/off keyboard with received name [default: AT Translated Set 2 keyboard]
Use "keyboard... |
54d81fcf7e6d327e7368df9924335c1e64e64113 | roger6blog/LeetCode | /SourceCode/Python/Problem/00904.Fruit Into Baskets.py | 2,161 | 3.984375 | 4 | '''
Level: Medium
You are visiting a farm that has a single row of fruit trees arranged from left to right.
The trees are represented by an integer array fruits where
fruits[i] is the type of fruit the ith tree produces.
You want to collect as much fruit as possible.
However, the owner has some strict rules that you... |
bde04f1e7839bee2f0f752d289977d2585ea6baf | jkirubakaran/python-learn | /scratch/fib.py | 262 | 3.828125 | 4 | import time
def fib(num):
if num < 3:
return 1
a = b = 1
for i in range(2,num):
a, b = b, a+b
return b
def fibRecursive(num):
if num < 3:
return 1
return fibRecursive(num - 1) + fibRecursive(num - 2)
#print(fib(40))
print(fibRecursive(40))
|
ef138fa3c22a5219b688383b662881d54b3055d4 | luisbenitez02/Codeaccademy | /python/19-listas_Array_(nuevos_metodos).py | 902 | 3.921875 | 4 | lenguajes_geniales=["python", "Ruby On Rails", "Javascript", "Swift", "Java", "node.js"]
print("Esta era la lista antes de modificarla: \n",lenguajes_geniales)
#FUNCION index() busca un string dentro del array y me devuelve su posicion en un int
me_gusta= lenguajes_geniales.index("Javascript")
print("Este el el numero... |
1019c4591a3f1526ceb5fe027949b2f7667beac0 | krishnanunni-pr/Pyrhon-Django | /PYTHON_COLLECTIONS/List/pop function.py | 132 | 3.859375 | 4 | # pop fuction is used to remove last element from a list
lst=[1,2,3,4,5,6,7]
lst.pop()# removes last element that is 7
print(lst)
|
11a7641848efccc92738d6cbe69018d8c36fdd8e | betty29/code-1 | /recipes/Python/576533_script_calculating_simple/recipe-576533.py | 247 | 4 | 4 | print "all amounts should be in dollars!"
while True:
P=float(raw_input("enter Principal:"))
i=float(raw_input("enter Percentage of interest rate:"))
t=float(raw_input("enter Time(in years):"))
I=P*t*(i/100)
print "Interest is", I,"dollars"
|
fb86b1b77a10d5277d86c5c9041fba24571da14e | project-anuvaad/anuvaad | /anuvaad-etl/anuvaad-extractor/file_translator/etl-file-translator/Nudi/nudi_font.py | 14,817 | 4.21875 | 4 | import re
def process_vattakshara(letters, t):
""" Current char is t, which is ASCII code of vattakshara
Rearrangement of string needed, If prev char is dependent vowel
then it has to be moved after vattakshara
If no dependent vowel then it is "ಅ" kaara, Ex: ಕ, ಗ
Vattakshara shares same code as of ... |
a40120fbb5a436cc0ce4a929d20fd233db4bcd89 | xblh2018/LintCodePython | /BinaryTreePostorderTraversal/Solution2.py | 1,073 | 3.890625 | 4 | """
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution2:
"""
@param root: The root of binary tree.
@return: Postorder in ArrayList which contains node values.
"""
def postorderTraversal(self, ro... |
eb55f274b76a27f0eb496428a1e81f72f341be70 | opensciencegrid/osg-pki-tools | /osgpkitools/ExceptionDefinitions.py | 1,808 | 3.578125 | 4 | """ This script contains all the exception classes and would be exclusively used for handling exceptions"""
class Exception_500response(Exception):
"""Exception raised for 500 response.
Attributes:
status -- Status of the response
message -- explanation of the error
"""
def __init__(... |
f371492ceb8cc5d1dd5958fb002eb0117bba4055 | sandergl/rosebotics2 | /src/sanders.py | 2,816 | 3.828125 | 4 | """
Capstone Project. Code written by Garrett Sanders.
Fall term, 2018-2019.
"""
import rosebotics_new as rb
import time
def main():
""" Runs YOUR specific part of the project """
# movement_experiment()
# degree_experiment()
# test_go_inches()
# test_spin_degree()
# turn_degree_experime... |
b1da642d1c88e251b67dd0debd63efd3e6bc7cd2 | smallsharp/mPython | /基础篇/面向对象/描述器定义方式1.py | 964 | 4.34375 | 4 | """
描述器的定义方式之一:
使用 property 关键字
"""
class Person(object):
def __init__(self):
self.__age = 18
def get_age(self):
print("get")
return self.__age
def set_age(self, value):
print("set")
self.__age = value
def del_age(self):
print("de1")
del self... |
c4737aac0d2eef4e7888af80016c640e3e40d0ed | biamila/Passwords | /Gui_sql.py | 8,836 | 3.578125 | 4 | import pygame, sqlite3
class Input_text:
def __init__(self, x, y, w, h):
self.name = pygame.Rect(x, y, w, h)
self.active = False
self.text = ""
self.colour = (225, 225, 225)
def check_collision(self, event):
if self.name.collidepoint(event.pos[0], event.pos[... |
01c5e814075e70e82686a4c2dc078a1b15476651 | CSUBioinformatics1801/Python_Bioinformatics_ZYZ | /Exp3.py | 4,956 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Nov 13 13:10:08 2020
@author: pc
"""
# =============================================================================
# a,b=eval(input("key in 2 numbers as a,b:"))
# print(a,'+',b,'=',a+b)
# print(a,'-',b,'=',a-b)
# print(a,'*',b,'=',a*b)
# print(a,'/',b,'=',round(a/b,2))
# ==... |
2deeba00745f22ff134083a47fe8454a93c80c25 | HPRIOR/DS-Algo-Zoo | /DynamicProgramming/kadanes_algo.py | 1,167 | 3.8125 | 4 | # max_subarray(nums) -> maximum contiguous sub array
def max_subarray(nums: [int]) -> int:
# this will store the maximum subarray for each index
if len(nums) == 1:
return nums[0]
if not nums:
return 0
memo = {0: nums[0]}
global_max = nums[0]
for i in range(1, len(nums)):
... |
f36dc8d4fa1eb3191c3a48c7c073cfeaca024c81 | JFantasia/POO | /BD/pgdatabase.py | 3,290 | 3.8125 | 4 | import sys
# https://www.psycopg.org/install/
import psycopg2
from psycopg2 import Error
# TABLA DE LA BASE DE DATOS
#
# CREATE TABLE public.profesor (
# dni varchar(8) NOT NULL,
# nombre varchar(40) NOT NULL,
# mail varchar(50) NULL,
# CONSTRAINT profesor_pk PRIMARY KEY (dni)
# );
class DB():
def __init_... |
53b3dc004678f9e214fc158ae2075429d2c5a27f | DARRENSKY/COMP9021 | /lecture/Lecture_6/iterative_hanoi.py | 1,839 | 3.875 | 4 | # Written by Eric Martin for COMP9021
'''
Iterative solution to the towers of Hanoi puzzle.
'''
def move_towers(n, start_position, end_position, intermediate_position):
'''
Move a tower of n disks from start_position to end_position,
with intermediate_position available.
'''
smallest_disk_positi... |
5bc1ac477c8a242a6f6042b798f230ccfc148499 | fpiikt/date-to-text-SonicCreeper | /main.py | 8,368 | 3.84375 | 4 | """
Автор: Кашпур Николай, группа №P3355
"""
class DateToTextClass():
def __init__(self, date):
splitted = date.split(' ')
self.date = splitted[0].split('.')
self.time = splitted[1].split(':')
def convert(self):
"""
Transforms date in numerical format into russian text.
Returns (str): russian te... |
43f6644ce0a0ce0e55c310817843128b1b52fa1d | tmuweh/tutorial.py | /restaurant.py | 1,020 | 3.875 | 4 |
class Restaurant(object):
"""docstring for Restaurant"""
def __init__(self, restaurant_name, cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
self.number_served = 0
def describe_restaurant(self):
"""prints information about restaurant"""
print("Name: " + self.res... |
c387ad2714f1f72025a65d52ee6cb8426a5186e6 | uniqstha/PYTHON | /questions of day6/Q3.py | 492 | 4.3125 | 4 | #Write a Python function that takes a number as a parameter and check the number is prime or not.
num= int(input("Enter any number: "))
# prime number is always greater than 1
if num > 1:
for i in range(2, num):
if (num % i) == 0:
print(f"{num}is not a prime number")
break
else... |
93f5f25f8c984256fcf7e4d678350296672905eb | AkashSharma93/English-Dictionary--web-crawler- | /Word.py | 808 | 3.671875 | 4 | class Word:
def __init__(self, new_word, definitions, pronunciation, synonyms, related_forms):
self._word = new_word
self._definitions = definitions
self._pronunciation = pronunciation
self._synonyms = synonyms
self._related_forms = related_forms
def get_word(self):
"""Returns the word associat... |
8ebfe5b8435e7faff33c730d15407ce7db02f16b | hridhi/data-structures-and-algorithms- | /patterns/pascals_triangle.py | 441 | 3.75 | 4 | #code
#pattern formation
#pascals triangle
rows=3
list1=[]
for i in range(rows):
temp=[]
for j in range(i+1):
if j==0 or j==i:
temp.append(1)
else:
temp.append(list1[i-1][j-1]+list1[i-1][j])
list1.append(temp)
#print(list1)
for i in range(rows):
for j in range(r... |
965a7c0cfde0c3064d7574776fd06b457a92cb99 | Iverance/leetcode | /073.set-matrix-zeroes.py | 1,686 | 3.8125 | 4 | #
# [73] Set Matrix Zeroes
#
# https://leetcode.com/problems/set-matrix-zeroes
#
# Medium (35.93%)
# Total Accepted:
# Total Submissions:
# Testcase Example: '[[0]]'
#
#
# Given a m x n matrix, if an element is 0, set its entire row and column to 0.
# Do it in place.
#
#
# click to show follow u... |
d4eed585cac597a5b44c7fb27ae54f8186726ad8 | denemorhun/Python-Problems | /Hackerrank/Recursive and DP/fibonacci_dp.py | 400 | 3.71875 | 4 | '''
Fibonacci with DP
'''
def fib_dp(n) -> int:
# base case
if n == 0 == 1:
return 1
# declare array
# insert base case into array
nums = [None]*(n+1)
nums[0] = 1
nums[1] = 1
for i in range(2, n+1):
nums[i] = nums[i-2] + nums[i-1]
return nums
# return dp prev ... |
d2c4eaf568b7cb2ff22e7353a3291bc9c39fd126 | baloooo/coding_practice | /tree_base.py | 3,824 | 4.0625 | 4 | # -*- coding: utf-8
class Node:
def __repr__(self):
if self is None:
return "None"
else:
return "{0} -> {1}".format(self.val, self.next)
def __init__(self, x, **kwargs):
self.left = None
self.right = None
self.next = None
self.val = x
... |
6bd55565775e19e3a13ba9fcb8f56f815ffce710 | huyngopt1994/python-Algorithm | /bigo/day-16-disjoin-set-union/simple_case.py | 978 | 3.859375 | 4 | MAX = 20
parent = []
ranks = []
def make_set():
"""
Build a make set for initial state build parent is itself. O(n)
:return:
"""
global parent
parent = [i for i in range(MAX + 5)]
ranks = [0 for _ in range(MAX + 5)]
def find_set(u):
"""find the representative of a set. Bad case is O(... |
1cb5f91003ad22a25eb67c1bae5a09c7c4c0501e | adam147g/ASD_exercises_solutions | /Obligatory tasks/Obligatory_task_02/02.01_exercise.py | 1,063 | 3.78125 | 4 | # Tablica T jest długości n, ale zawiera tylko ceil(logn) różnych wartości. Proszę zaproponować
# jak najszybszy algorytm sortujący taką tablicę.
def counting_sort_letters(T, index):
C = [0]*10
B = [0]*len(T)
for i in range(len(T)):
idx = int(T[i][index])
C[idx] += 1
for i in range(1, ... |
8ddc20fd30a8de2ce4fb0e06a3c56b6c27cc4abc | szabgab/slides | /python/examples/strings/no_break_continue.py | 115 | 3.78125 | 4 | i = 2
n = 3*5*7
while i < n:
if (n / i) * i == n:
print('{:2} divides {}'.format(i, n))
i = i + 1
|
3c4bb7216d21575e030478ea58a6654435ee369a | jiewu-stanford/leetcode | /230. Kth Smallest Element in a BST.py | 1,891 | 3.9375 | 4 | '''
Title : 230. Kth Smallest Element in a BST
Problem : https://leetcode.com/problems/kth-smallest-element-in-a-bst/
'''
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
'''
iterative solution use deque
Referen... |
647edc0b0795ae8efdd95fbdd7a81439d142c039 | Luciana1012/Term-5 | /exponentialsearch.py | 433 | 3.84375 | 4 | from binary import binarySearch
def exponentialSearch(array, x):
startingIndex = 0
endingIndex = 0
if array[startingIndex] == x:
return startingIndex
else:
endingIndex +=1
while endingIndex < len(array) and array[endingIndex] <= x:
endingIndex *= 2
return bi... |
6acb88f93fb322196a025926940139992ac1854c | lilaboc/hackerrank | /python2/re-split.py | 214 | 3.609375 | 4 | # https://www.hackerrank.com/challenges/re-split
# Enter your code here. Read input from STDIN. Print output to STDOUT
import re
for i in re.split('[\.,]', raw_input()):
if re.match('\d+$', i):
print i
|
2d58a12f876325c0de649d0f98d9b36237a2f3fc | prabhatv96/Testpython | /Pattern/left_start.py | 202 | 3.6875 | 4 | n=int(input("Enter number of lines: "))
k=n*2-2
for i in range(n):
print(end=" "*k)
print("* "*(i+1))
k=k-2
for i in range(n,-1,-1):
print(end=" "*(k+4))
print("* "*(i-1))
k=k+2
|
85b875ad4b830958c3a075e057fbe1a4af94538e | zy2424/python_columbia_class | /lecture_one/assignment_versus_equality.py | 144 | 3.546875 | 4 | # assignment - "assigns a value to a variable"
x = 4
# equality - "checks the value of a variable"
print(x == 5)
print(locals()["x"] is 4)
|
f66c2417cfea724e6b14b7595bca03e320e02f0c | a3huang/dsp | /python/advanced_python_regex.py | 760 | 3.640625 | 4 | from collections import Counter
import string, re
with open('faculty.csv') as f:
degrees = list()
titles = list()
email = list()
lastnames = list()
f.readline()
for line in f:
data = line.strip().split(',')
d = data[1].strip().split()
d = [s.translate(string.maketrans('',''), string.punctuatio... |
64570df49134eda7322352c8184e9cd4047379bb | tonyhqanguyen/2DMarioKart | /Node.py | 1,861 | 3.625 | 4 | """
Node class that is used in the Genome class.
"""
from typing import List
from math import exp
class Node:
"""
A node in the neural network.
"""
number: int
input_sum: float
output_value: float
outgoing_connections: List[Gene]
layer: int
def __init__(self, number: int) -> None:... |
e72a2516d744959108fefee0ebd8d0cabac8c839 | DevejyaRaghuvanshi/Python_DataClean_UWcoop_Loblaws | /SKUpriceswithDates(forTimeSeries).py | 7,433 | 4.0625 | 4 | '''
Create an Excel file and add a table to one sheet with the most valuable berry products and their price over time.
Dates are constantly increasing day by day instead of showing only the days at which transactions were made.
'''
#import required libraries
import pandas as pd
from functools import reduce #reduc... |
5cbef282bfefb0a087b7712efce625b8539cbe51 | mjustinz86/CIS2348JustinoCortez | /Homework_1/Coding Prob 1.py | 419 | 3.96875 | 4 | # Justino Cortez ID:1615245
print('Birthday Calculator', '\n Current day')
month = int(input('Month: '))
day = int(input('Day: '))
year = int(input('Year: '))
print('Birthday')
B_month = int(input('Month: '))
B_day = int(input('Day: '))
B_year = int(input('Year: '))
age = year - B_year
if (month + day) > (B... |
bd74494d5e335e035f08eb3e3cf5950de21055b8 | SlaviGigov/PythonAdvanced | /Lists_as_Stacks_and_Queues/pythonProject/lab/lab_water_dispenser.py | 534 | 3.71875 | 4 | from collections import deque
queue = deque()
water = int(input())
while True:
name = input()
if name == "Start":
break
else:
queue.append(name)
while True:
do = input()
if do == "End":
print(f"{water} liters left")
break
elif do[0] == "r":
do = do.spli... |
d2d6f31a39738bea0cf4d46166a166b9ec4180ce | ykytutou/python-learning | /test1.py | 711 | 3.828125 | 4 | # -*- coding : UTF-8 -*-
# @Time : 2020/7/14 0014 4:36 25 PM
# @Author : OliverYin
# @File : test1.py
# @Software : PyCharm
import random
a = int(input("请输入数字:剪刀(0)、石头(1)、布(2):"))
b = random.randint(0, 2)
x = ""
y = ""
if a == 0:
x = "剪刀"
elif a == 1:
x = "石头"
elif a == 2:
x = "布"
print("你出的是:%s(%d)" % (... |
7aab52b16f70d68326bc9b96165a4238dfbfd63d | theChad/ThinkPython | /chap13/markov.py | 3,602 | 4.03125 | 4 | import random
import analyze_book
# Exercise 13.8
# 13.8.1
def read_wordlist(filename="book.txt"):
"""Read wordlist from filename
"""
words = []
fin = open(filename)
for line in fin:
words.extend(line.split())
return words
def create_prefix_map(filename="book.txt", len_prefix=2, len_... |
b14a4014227864c6c9b7592de4393c44af599ec4 | agonzalezcurci/class-work | /debugging8.py | 234 | 3.625 | 4 | t = ["b", "d", "a","c"]
# make copies
orig = t[:]
t.sort()
print(t)
# correct
t.append("x")
print(t)
t = t + ["y"]
print(t)
# wrong
t.append(["q"])
print(t)
t = t.append("n")
print(t)
t = t + x
print(t)
t + ["t"]
print(t)
|
097c6e350e80ef4c1631e0f66786d3a49a10b45a | agamyafe10/secret | /secret_message_server.py | 1,088 | 3.59375 | 4 | from scapy.all import *
def is_without_data(packet):
"""checking if the pacekts includes data for insuring this is the packet we want
Args: packet (packet):
Returns: true if there is no data else return false
"""
if packet['UDP'].len == 8:# length 8 is the equivilent length for no data
r... |
23ade0836e06cae873067b44143e4b012128632e | TomasBahnik/pslib | /python/alp/lectures/permutation.py | 253 | 3.6875 | 4 | import random
def permutation(n):
"""Create a random permutation of integers 0..n-1"""
p = list(range(n))
for i in range(n - 1):
r = random.randrange(i, n)
temp = p[r]
p[r] = p[i]
p[i] = temp
return (p)
|
7285c1d46fd1423ae38e25134c414c6872efbe21 | isabel-lombardi/workbook_python | /chap_8/ex_180.py | 652 | 3.9375 | 4 | # String edit Distance
def string_distance(s, t):
if len(s) == 0:
return len(t)
elif len(t) == 0:
return len(s)
else:
cost = 0
if s[len(s) - 1] != t[len(t) - 1]:
cost += 1
d1 = string_distance(s[0: len(s) - 1], t) + 1
d2 = string_distance(s, t[0: ... |
bf8c64d44372cdc2a6e85dca6343707c6da0fd6b | Pandey-Noah-3816/SWE-HW-4 | /HW4/volume.py | 176 | 3.546875 | 4 | def volume(a,b,c):
try:
vol = int(a)*int(b)*int(c)
if vol <= 0:
return("bad inputs result was negative")
except ValueError:
return TypeError
return vol |
e55afd5bcae9bb61b1fa105804628294bb4788b3 | trenator/PfCB | /chapter_2/Ex2_1.py | 1,137 | 3.671875 | 4 | # counting vowels
# what proportion of this sentence is made up of the vowels (a e i o u)
sentence = "It was the best of times, it was the worst of times, it was the age of wisdom, it was the age of foolishness, it was the epoch of belief, it was the epoch of incredulity, it was the season of Light, it was the season ... |
13fb38c4a1b5e39c8780ebbe9d72e4a2ffcbe190 | Aden-Q/LeetCode | /code/456.132-Pattern.py | 391 | 3.65625 | 4 | class Solution:
def find132pattern(self, nums: List[int]) -> bool:
s = [] # 递减栈
third = -float('inf')
for i in range(len(nums)-1, -1, -1):
if nums[i] < third:
return True
else:
while s and nums[i] > s[-1]:
third = s.... |
2deaff3b425201237542025c6defb5c27b0fd041 | SWATISIGNATURE/Python | /Codeacademy_Projects/Carly's_Clippers.py | 763 | 3.546875 | 4 | hairstyles = ["bouffant", "pixie", "dreadlocks", "crew", "bowl", "bob", "mohawk", "flattop"]
prices = [30, 25, 40, 20, 20, 35, 50, 35]
last_week = [2, 3, 5, 8, 4, 4, 6, 2]
total_price = 0
for price in prices:
total_price += price
average_price = total_price/len(prices)
print("Average Haircut Price:", average_pric... |
1353efea377a1a94d35025b441bcf4f38068ac2d | davejlin/treehouse | /python/quiz-timed/quiz.py | 1,755 | 3.796875 | 4 | import datetime
import random
from questions import Add, Multiply
class Quiz:
questions = []
answers = []
def __init__(self):
question_types = (Add, Multiply)
for i in range(10):
a = random.randint(0,10)
b = random.randint(0,10)
question = random.choice(question_types)(a, b)
self.questio... |
9523937419888a88eb065c0a52011a4d822346e5 | sadOskar/courses | /lesson_7/ex_8.py | 1,010 | 3.78125 | 4 |
# def gcd(a, b):
# while b:
# a, b = b, a % b
# return a
#
#
# print(gcd(24, 36))
#
# t = [[1, 2], [3], [4, 5, 6]]
#
#
# def nested_sum(t):
# total = 0
# for item in t:
# a = sum(item)
# total += a
# return total
#
# print(nested_sum(t))
#
#
massages = ["Python", "Java", "An... |
608d738c404ede2d18f452cbfd334832afa851e6 | udoy382/Module | /csv_4.py | 2,364 | 4.21875 | 4 | # GeeksforGeeks / from web
# Reading a CSV file
'''
# importing csv module
import csv
# csv file name
filename = "user.csv"
# initializing the titles and rows list
fields = []
rows = []
# reading csv file
with open (filename, 'r') as csvfile:
# creating a csv reader object
csvreader = csv.reader(c... |
3ebe14d6e3fe0402160226a942e93c8104312dc5 | AndrewKoch/ciphers | /utils.py | 1,036 | 3.671875 | 4 | import logging
def check_validity(crib):
if not crib.isalpha():
raise Exception("Letters only.")
def format_input(crib):
"Removes whitespace, verifies characters are letters, and capitalizes them."
crib = crib.replace(" ", "")
check_validity(crib)
crib = crib.upper()
return crib
def... |
b610ee36b813df9bcd56d50aee57d60ddaa3269c | 1026237416/Python | /algorithm/句子反转.py | 483 | 4.15625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2017/10/19 22:10
# @Author : liping
# @File : 句子反转.py
# @Software: PyCharm
def get_reverse(strings):
result = ""
result_list = []
str_split = strings.split()
while len(str_split):
result_list.append(str_split.pop())
result = "... |
4f9008526370c6ba1e5d87046ec9def61df8aa62 | mjmikulski/code_snippets | /python/pround/test_pround.py | 1,486 | 3.53125 | 4 | import unittest
from math import sqrt
from random import uniform
from statistics import mean
from python.pround.pround import pround
class TestElegantNumbers(unittest.TestCase):
do_print = True
def test_255(self):
S = 255
N = 10 ** 2
xs = [uniform(0, S) for _ in range(N)]
ys... |
fe1a5117b96266dde6653c312c41801586d493d2 | vinigrator/python-practice | /pract/ex2.py | 278 | 3.5 | 4 | def count_names():
names = {}
with open('names.txt', 'r') as f:
for line in f:
line = line[:-1]
if names.get(line) == None :
names[line] = 0
else :
names[line] += 1
f.close()
for key, value in names.items():
print key + " " + str(value)
count_names() |
6f4977a0b8f0050dedf2e6b8dd08149fb37be2f7 | giseledoan/Election_analysis | /PyPoll.py | 4,600 | 3.90625 | 4 |
#The data we need to retrieve.
#1. The total number of votes cast
#2. A complete list of candidates who received votes.
#3. The percentage of votes each candidate won.
#4. The total number of votes each candidate won.
#5. The winner of the election based on popular vote.
#use datetime module to get today's date
imp... |
3fb06fd18c9a4e4018aae47d3e9178b2cd8c1759 | Radizzt/Python3-Fundamental | /04 Syntax/syntax-functions.py | 440 | 3.515625 | 4 | #!/usr/bin/python3
# syntax.py by Bill Weinman [http://bw.org/]
# This is an exercise file from Python 3 Essential Training on lynda.com
# Copyright 2010 The BearHeart Group, LLC
def main():
foo(2);
foo(3);
foo(4);
foo();
#assigning a parameter makes it default
def foo(a=8):
for i in range(a, 10):... |
081d2eae2c149f4422a73a1bb307e67b8e72c62a | carlosafdz/pensamiento_computacional_python | /algoritmos/enumeracion.py | 251 | 3.953125 | 4 | a = int(input("numero entero: "))
respuesta = 0
while respuesta**2 < a:
respuesta += 1
print(respuesta)
if respuesta**2 == a:
print(f'la raiz cuadrada de {a} es {respuesta}')
else:
print(f'respuesta no tiene raiz cuadrada exacta') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.