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 |
|---|---|---|---|---|---|---|
2549a209c695242606dcf47315c9ca748236826a | luciangutu/job_test | /sorting.py | 1,373 | 3.703125 | 4 | import random
import time
def insertion_sort(mylist, ascending=True):
tic = time.perf_counter()
for i in range(1, len(mylist)):
current = mylist[i]
while True:
ascending_sort = i > 0 and mylist[i - 1] > current and ascending
descending_sort = i > 0 and mylist[i - 1... |
75ae9a8e48506a2b649481e2f891ff3ad773887e | MyCatWantsToKillYou/TimusTasks | /Volume 1/src/1020.py | 569 | 3.640625 | 4 | #task 1020
#Difficulty 100
import math
def toFixed(numObj, digits=0):
return f"{numObj:.{digits}f}"
def d(point1, point2):
x1 = point1[0]
x2 = point2[0]
y1 = point1[1]
y2 = point2[1]
return math.sqrt((x2-x1)**2 + (y2 - y1)**2)
sum = 0
pi = math.pi
N, R = map(float, input().split())
points = ... |
726ea99dad70b9b1bafe2ca5baa550fcd45bbfbb | MyCatWantsToKillYou/TimusTasks | /Volume 11/src/Grant.py | 276 | 3.90625 | 4 | # task #2056
# Difficulty 58
grades = []
for i in range(int(input())):
grades.append(int(input()))
if 3 in grades:
print('None')
elif sum(grades)/len(grades) == 5:
print('Named')
elif sum(grades)/len(grades) >= 4.5:
print('High')
else:
print('Common')
|
d015beb141d8010fb06a1b9a4fa9d059794bccfc | MyCatWantsToKillYou/TimusTasks | /Volume 9/src/A380.py | 519 | 3.78125 | 4 | # task 1893
# Difficulty 55
import re
string = input()
num = re.findall('(\d+)', string)
letter = re.findall('[A-Za-z]', string)
if int(num[0]) <= 2:
if letter[0] in ('A', 'D'):
print('window')
else:
print('aisle')
elif int(num[0]) <= 20:
if letter[0] in ('A', 'F'):
print('window... |
bde44658da0b62b7cccba0a8719db12e77b810b4 | MyCatWantsToKillYou/TimusTasks | /Volume 3/src/1297.py | 1,447 | 3.59375 | 4 | def findPal(string):
def findOdd(string):
max = 1
for Middle in range(len(string)):
leftBorder = Middle - 1
rightBorder = Middle + 1
while (leftBorder >= 0 and rightBorder < len(string) and string[leftBorder] == string[rightBorder]):
new_str = stri... |
e34e78724225d30e0ebd9d5d1b985df3539abd99 | MyCatWantsToKillYou/TimusTasks | /Volume 3/src/1294.py | 352 | 3.59375 | 4 | # task 1294
# Difficulty 310
import math
ad, ac, bd, bc = map(int, input().split())
if ad*ac == bd*bc:
print('Impossible.')
exit(0)
t1 = (ad**2+ac**2)*2.0*bd*bc-(bd**2+bc**2)*2.0*ad*ac
t2 = 2*bd*bc-2*ad*ac
tt = t1*1.0/t2
if tt < 0:
print('Impossible.')
else:
tt = math.sqrt(tt)
print("Distance is %... |
9abf888981e08663ea5c9cc58ae646deb9d469ff | MyCatWantsToKillYou/TimusTasks | /Volume 5/src/OneStepToHappiness.py | 693 | 3.609375 | 4 | # task #1493
# Difficulty 51
strin1 = input()
strin = int(strin1)
numberleft = strin-1
numerright = strin+1
strleft = str(numberleft)
strright = str(numerright)
if len(strin1) != len(strleft):
strleft = strleft.rjust(6, '0')
if len(strin1) != len(strright):
strright = strright.rjust(6, '0')
left = []
right = [... |
d6863d305c56ff797f017232ab62455525d81de7 | juliyat/Python | /Random Programs/sorting.py | 142 | 3.78125 | 4 | s = raw_input("Enter stuff to alphabetically sort")
b = ""
v = s.split(" ")
v.sort()
for i in range(0,len(v)):
b = b + v[i] + " "
print b
|
31c5722db2896443b0b07f4e368d227bdcf271bb | juliyat/Python | /edabit/uppercaseChar.py | 247 | 3.796875 | 4 | def uppercaseChar(s):
splitS = list(s)
count = 0
ans = ""
for i in splitS:
count += 1
if i.isupper() == True:
ans = ans + str(count) + ","
return ans
hmm = raw_input()
print uppercaseChar(hmm)
q |
89746d38cbef6c12695e6d08f6e9e76a04ec1db6 | juliyat/Python | /edabit/stringFlips.py | 386 | 3.625 | 4 | a = raw_input()
b = raw_input("Enter 'word' or 'sentence'")
if b == "word":
c = []
d = ""
for i in a:
c.insert(0, i)
for j in c:
d = d + j
print d
elif b == "sentence":
c = a.split(" ")
d = ""
for i in c:
d = i + " " + d
print d
else:
print " _ _ "
... |
42cd472a11f8d4992387e43608ee3f34580fe360 | juliyat/Python | /edabit/medium difficulty problems/Pandigithinghy.py | 111 | 3.578125 | 4 | a = raw_input()
for i in range(1,10):
if str(i) not in a:
print "False"
exit()
print "True" |
5ac73be674ce842043d812be90dd5ea747bee572 | juliyat/Python | /edabit/hard/Sieve of Eratosthenes (what!).py | 258 | 3.625 | 4 | def sieve_of_eratosthenes(n):
list = []
for i in range(0, n):
for j in range(0,i):
if i % j == 0:
break
list.append(i)
return list
a = int(raw_input("Enter a number | ex: 5"))
sieve_of_eratosthenes(a) |
9b8119e8e2c54ecd6ca4e11b329316df16232c90 | juliyat/Python | /edabit/medium difficulty problems/7boom.py | 179 | 3.625 | 4 | a = raw_input()
b = a.split(", ")
for i in range(0,len(b)):
for j in b[i]:
if j == "7":
print "Boom!"
exit()
print "there is no 7 in the list"
|
d9330880f9ec495ba9526401eba4513b9cec1b8e | juliyat/Python | /edabit/hard/Contact List.py | 547 | 3.9375 | 4 | def contact_list(l, alphabetichoose):
ans = ""
newlist = []
for i in l:
k = i.split(" ")
n = k[::-1]
" ".join(n)
newlist.append(n)
if alphabetichoose == "ASC":
a = sorted(newlist)
else:
a = sorted(newlist, reverse=True)
for t in a:
... |
a7bb5732253560454192f3c695f2fc990f788852 | juliyat/Python | /Random Programs/String palindrome check.py | 400 | 3.8125 | 4 | x = raw_input("enter numbers or letters")
z = x.count("") - 1
if z % 2 == 0:
c = z / 2
b = x[:c]
v = b[::-1]
if v == x[c:]:
print x, "is a palindrome."
else:
print x, "is NOT a palindrome"
else:
c = (z - 1) / 2
b = x[:c]
v = b[::-1]
l = c + 1
if v == x[l:]:
... |
d9a467e2f1187a5a3579c29aa0d7b8e8a542da10 | AmeliaMaier/Data_Science_Notes | /data_analytics/statistics/correlation_covariance.py | 650 | 3.984375 | 4 | import numpy as np
import pandas as pd
'''
the math behind pd.dataframe.cov() and pd.dataframe.corr()
'''
def covariance_try(x,y):
'''
INPUT: a numpy array or pandas scalar
Return: the covariance of the data
'''
cov = 0
x_mean = x.mean()
y_mean = y.mean()
'''
for ind in ... |
3f234ad23d683b8a3ee1846a8312b5a56a46023a | kevinyukaic/Leetcode15---3-Sum | /3Sum.py | 2,157 | 3.71875 | 4 | # Leetcode 15
# 3 Sum
# Python 3
# Time Complexity: O(n^2)
#
#
# Set 3 pointers to iterate through the list
#
#
# __p_i____ p_left______________________________________p_right_
# |________|________|___________________________________|________|
#
#
# Check the sum of 3 numbers,
# if == 0: append to result
# if < 0:... |
331c4aa23955911f7c6967c0d0f3fdcec5065825 | eagletusk/LeetCodeProblems | /SortArrayByParity.py | 628 | 3.6875 | 4 | from typing import List
class Solution:
def sortArrayByParity(self, A: List[int]) -> List[int]:
h = 0
end = len(A)-1
temp = 0
j=0
i=0
while i < end:
if A[i] %2 != 0:
# odd
temp = A[i]
# shift every thing over
j = i+1
... |
bba5d8dcee04707058239fa742cc7c3f13159172 | ShreyanshG22/IS-Assignments | /8/ecc.py | 3,192 | 3.671875 | 4 | def modInverse(a, m) :
a = a % m;
for x in range(1, m) :
if ((a * x) % m == 1) :
return x
return 1
def addition(x1, y1, x2, y2, field):
xd = (x2 - x1)
xf = modInverse(xd, field)
slope = (y2 - y1) * xf
slope = slope % field
xnew = (slope * slope - x1 - x2) % field
ynew = (-y1 + slope * (x1 - xnew)) % fiel... |
29a3e2e76ceb77406e347f95a867635aeebd3336 | fagan2888/leetcode-6 | /solutions/014-longest-common-prefix/longest-common-prefix.py | 885 | 4.03125 | 4 | # -*- coding:utf-8 -*-
# Write a function to find the longest common prefix string amongst an array of strings.
#
# If there is no common prefix, return an empty string "".
#
# Example 1:
#
#
# Input: ["flower","flow","flight"]
# Output: "fl"
#
#
# Example 2:
#
#
# Input: ["dog","racecar","car"]
# Output: ""
... |
ad6c9704c7f09a5fa1d1faab38eb5d43967026a4 | fagan2888/leetcode-6 | /solutions/374-guess-number-higher-or-lower/guess-number-higher-or-lower.py | 1,199 | 4.4375 | 4 | # -*- coding:utf-8 -*-
# We are playing the Guess Game. The game is as follows:
#
# I pick a number from 1 to n. You have to guess which number I picked.
#
# Every time you guess wrong, I'll tell you whether the number is higher or lower.
#
# You call a pre-defined API guess(int num) which returns 3 possible resul... |
c6b83878eca998f1213e7fc86f321df4f59803df | fagan2888/leetcode-6 | /solutions/919-projection-area-of-3d-shapes/projection-area-of-3d-shapes.py | 1,790 | 4 | 4 | # -*- coding:utf-8 -*-
# On a N * N grid, we place some 1 * 1 * 1 cubes that are axis-aligned with the x, y, and z axes.
#
# Each value v = grid[i][j] represents a tower of v cubes placed on top of grid cell (i, j).
#
# Now we view the projection of these cubes onto the xy, yz, and zx planes.
#
# A projection is l... |
1d78c25f53af6e13b92016aa228f7de121273754 | fagan2888/leetcode-6 | /solutions/670-maximum-swap/maximum-swap.py | 1,282 | 3.890625 | 4 | # -*- coding:utf-8 -*-
#
# Given a non-negative integer, you could swap two digits at most once to get the maximum valued number. Return the maximum valued number you could get.
#
#
# Example 1:
#
# Input: 2736
# Output: 7236
# Explanation: Swap the number 2 and the number 7.
#
#
#
# Example 2:
#
# Input: 9973
... |
6a097f9f7027419ba0649e5017bc2e17e7f822d3 | fagan2888/leetcode-6 | /solutions/557-reverse-words-in-a-string-iii/reverse-words-in-a-string-iii.py | 773 | 4.1875 | 4 | # -*- coding:utf-8 -*-
# Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
#
# Example 1:
#
# Input: "Let's take LeetCode contest"
# Output: "s'teL ekat edoCteeL tsetnoc"
#
#
#
# Note:
# In the string, each word is... |
fceddd6e088927b0f30aa2234c9f29fcf2d0cebe | lanprijatelj/PyMandel | /pymandel/howto_dialog.py | 2,002 | 3.5625 | 4 | """
How To Dialog Box class for tkinter application.
Created on 19 Apr 2020
@author: semuadmin
"""
from tkinter import Toplevel, Label, Button, LEFT
from webbrowser import open_new_tab
from .strings import HELPTXT, COPYRIGHTTXT, DLGHOWTO, GITHUBURL
class HowtoDialog:
"""
How To dialog box class
"""
... |
eae4db58b9bce7eb8b50163e8b1e36d4d624f3f5 | atamust123/Backtracking | /assignment4.py | 2,691 | 3.578125 | 4 | import sys
def start(maze_input_file, current_health):
# if health input is not given make operations according to that
maze = []
for i in maze_input_file:
maze.append(list(i.split()[0])) # maze
sol = [[0 for j in range(len(maze[i]))] for i in range(len(maze))] # output file
x, ... |
6f4b3f90db0be1ccc197aacca9b625642c498aee | Raziel10/AlgorithmsAndMore | /Probability/PowerSet.py | 267 | 4.34375 | 4 | #Python program to find powerset
from itertools import combinations
def print_powerset(string):
for i in range(0,len(string)+1):
for element in combinations(string,i):
print(''.join(element))
string=['a','b','c']
print_powerset(string) |
01773bd7107e2ad18ee20cd84cccf4316f2cd2e5 | sorachii/2020-advent-of-code | /day3/main.py | 656 | 3.546875 | 4 | def ans1():
count = 0
r = 0
c = 0
while r + 1 < len(G):
r += 1
c += 3
if G[r][c % len(G[r])] == "#":
count += 1
return count
def ans2():
count = 0
slopes = [(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)]
ans = 1
for (dc, dr) in slopes:
c = 0
... |
c226e4433d1a38e78d432dbf6af4040eafcb7b47 | JadeWibbels/ObjectOrientedDesign | /shapes/display.py | 1,133 | 3.625 | 4 | from init_db import CreateShapesDB
import shapes
class PrettyPrint():
def __init__(self):
#create database
self.db = CreateShapesDB()
#sort by shapes
self.sortedShapes = sorted(self.db.data, key=self.getKey)
self.shape_counts = {'circle':0, 'square':0, 'triangle':0... |
fc36a90005153632ee6c294835b239c727ac4c63 | naman14310/DataStructures_Algorithms | /Dynamic Programming/longest_increasing_subsequence.py | 478 | 3.671875 | 4 | def count(arr,lis):
arr1=list()
for j in range(1,len(arr)):
if arr[j]>arr[0]:
arr1.append(lis[j-1])
else:
arr1.append(0)
return max(arr1)
arr = list()
n = int(input("how many no. you want to enter : "))
lis = [0]*n
print("enter numbers : ")
for i in range(n):
arr.append(int(input()))
for i in rang... |
1099457b7858d64bebc3e78e1f75657c9d10bccc | 786572258/studyRepos | /python/function.py | 233 | 3.53125 | 4 | # -*- coding: UTF-8 -*-
var1 = 200
var2 = 400
def printme( str ):
"打印传入的字符串到标准显示设备上"
var1 = 300
print str
print "var1=",var1
var2 = 600
return
var1 = 100
printme("哈哈");
print var2 |
f845db88c8bb6e269928b3c010cec0d7a459b444 | BowmanChow/RobotDesign | /ImageRecognition/layers/conv_layer.py | 9,553 | 3.625 | 4 | # -*- encoding: utf-8 -*-
import numpy as np
import scipy.signal
# if you implement ConvLayer by convolve function, you will use the following code.
from scipy.signal import fftconvolve as convolve
class ConvLayer():
"""
2D convolutional layer.
This layer creates a convolution kernel that is... |
6c035ce03cfa091d55229b90a8cb0b250201bf8a | zico731/convertisseur-de-chiffre_romain | /nb2romanNumber.py | 716 | 3.53125 | 4 | decimal=[1000,900,500,400,100,90,50,40,10,9,5,4,1]
romain=["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"]
def conv_romain(chiffre):
#assert chiffre >0 and chiffre< 4000, "le nombre saisi doit être compris entre 1 et 3999"
chiffre0=chiffre
i=0
resultat =""
while chiffre>0:
... |
da7bd9d5abbdd838c1110515dde30c459ed8390c | Smita1990Jadhav/GitBranchPracticeRepo | /condition&loops/factorial.py | 278 | 4.25 | 4 | num=int(input("Enter Number: "))
factorial=1
if num<1:
print("Factorial is not available for negative number:")
elif num==0:
print("factorial of 1 is zero: ")
else:
for i in range(1,num+1):
factorial=factorial*i
print("factorial of",num,"is",factorial) |
12c116fea19b6cc1bcfd60a13a59ed187b449011 | Setysdv/python-class | /E9.py | 2,146 | 3.859375 | 4 | #EX 045
t = 0
while t <= 50:
a= int(input ('add number: '))
t = t + a
j= str (t)
print ('the total is' + j)
else:
print('the total is more than the 50')
#EX 046
n=0
while n<=5:
n=int(input('Enter a number:'))
print('The last number you entere... |
f500b19e773d6a0e8a5a01955d0fe634bd737391 | picnic-yu/study-demo | /python/list.py | 784 | 3.65625 | 4 | nameList = ['小明','terry','angel']
# 1.长度
print(len(nameList))#3
#索引取值
print(nameList[1])#terry
# 追加元素到末尾:
nameList.append('jerry')
print(nameList)#['小明','terry','angel','jerry']
# 把元素插入到指定的位置
nameList.insert(1,'Jack')
print(nameList)#['小明','Jack','terry','angel','jerry']
# 删除list末尾的元素 pop
nameList.pop()
print(... |
75f244a134e091b731a7af76935dcd317b4fb715 | davidtc8/Data-Analysis-with-Pandas | /Python_project_code.py | 8,956 | 4.28125 | 4 | """
What this project is about?
What I did in the Python project was to analyze 3 franchises from a fictitious company, using pandas dataframes in Python.
For this project I used For, While Loops, Function Definition, Main Function, Numpys and Pandas
"""
import pandas as pd
import time
import numpy as np
#here's the ... |
bb4062daa13670fae0b8052ae9c78b72471e7675 | rofgh/Computational-Linguistics-Class-Programming | /HW6 Files/cky.py | 4,760 | 3.75 | 4 | '''
Script cky.py on the command line:
python cky.py GRAMMAR_FILE SENTENCE_FILE
python cky.py english_cnf.gr sentences.sen
python cky.py cky_grammar.gr mary.sen
cky.py returns:
a .out file named after the sentence file given:
this .out file will ... |
1669d58901eb94e92f29ed72809e99771834b648 | qiqimaochiyu/tutorial-python | /leetcode/leetcode_605.py | 361 | 3.734375 | 4 | class Solution:
def canPlaceFlowers(self, flowerbed, n):
"""
:type flowerbed: List[int]
:type n: int
:rtype: bool
"""
f = [0] + flowerbed + [0]
for i in range(len(f)-2):
if f[i] == 0 and f[i+1] == 0 and f[i+2] == 0:
f[i+1] = 1
... |
90d4b2c42a57a2a2a3cc351e401bf7ed486a59f8 | qiqimaochiyu/tutorial-python | /leetcode/leetcode_397.py | 450 | 3.78125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 22 18:53:27 2018
@author: macbook
"""
class Solution:
def integerReplacement(self, n):
"""
:type n: int
:rtype: int
"""
if n == 1:
return 0
if n % 2 == 0:
return self.integ... |
f768a6b842d4669ac02cbc3b5246b519ae3306bb | qiqimaochiyu/tutorial-python | /leetcode/clone_binary_tree.py | 623 | 3.859375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 19 14:07:14 2018
@author: macbook
"""
# Definition of TreeNode:
class TreeNode:
def __init__(self, val):
this.val = val
this.left, this.right = None, None
class Solution:
"""
@param: root: The root of binary tree
... |
c5372c654dd659195eb5fa5503d1a8fb85247949 | qiqimaochiyu/tutorial-python | /leetcode/leetcode_105.py | 1,019 | 3.875 | 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 buildTree(self, preorder, inorder):
"""
:type preorder: List[int]
:type inorder: List[int]
:rtype: Tr... |
39dd341cb4473578a314f31b71493557cb36b39c | nchibana/Intro-Python-II | /src/player.py | 624 | 3.703125 | 4 | # Write a class to hold player information, e.g. what room they are in
# currently.
import textwrap
class Player:
def __init__(self, name, current_room, items=[]):
self.name = name
self.current_room = current_room
self.items = items
def get_name(self):
return self.name
... |
9f0b7ec7c45ed53ae0c7141eb88d50e04c62a868 | silasbispo01/todosOsDias | /Todos os dias/dia41/Exércicio3.py | 832 | 4.1875 | 4 | # Importação do random
import random
# Criação da lista de sorteios vazia
listaSorteio = []
# For para cadastro de 3 pessoas
for p in range(3):
# Inputs para nome da pessoa e quantia doada.
nome = input('Insira seu nome: ')
valorDoado = int(input('Insira o valor doado: R$'))
# Calculo de quantas vez... |
129152480d417580e47d8bfd42836cb5f3ab465e | CleitonOrtega/Python | /pythonBasico/manipulandoArquivos/primeiraManipulacao.py | 437 | 4.0625 | 4 | #Para incrementar uma nova linha no arquivo use a notação "a"
#with open("primeiroManipulado.txt", "a") as arquivo:
# arquivo.write("\nAdicionando a segunda linha")
#Para ler oque esta no arquivo
with open("primeiroManipulado.txt", "r") as arquivo:
#Para ler linha a linha do que esta no arquivo
for linha in ar... |
817643ffc3a8ee574371e51db8648f62c7d183a0 | Davidkintero/Python-Code | /reto1/reto1.py | 727 | 3.515625 | 4 | print('Bienvenido al sistema de ubicación para zonas públicas WIFI')
nombre_usuario = 51743
contrasena = 34715
nombre_usuarioinput = int(input('Ingrese el nombre de usuario: '))
if nombre_usuario == nombre_usuarioinput:
contrasena_input = int(input('Ingrese la contrasena: '))
if contrasena == contrasena_input... |
d7b13bd96d8b5dab75a3abfcd2c1cf40254a150e | jjspetz/digitalcrafts | /py-exercises3/plot1.py | 262 | 3.984375 | 4 | #!/usr/bin/env python3
import matplotlib.pyplot as pyplot
def f(x):
return x + 1
def plot():
xs = list(range(-3,3))
ys = []
for x in xs:
ys.append(f(x))
pyplot.plot(xs, ys)
pyplot.show()
if __name__ == "__main__":
plot()
|
a68e1618e1b2887ea208e614a8dabdb6ff67eb30 | jjspetz/digitalcrafts | /py-exercises2/stringreverse.py | 150 | 4.03125 | 4 | # reverses a string from argument
import sys
# get string from argument
s = str(sys.argv[1])
# reverses and prints string via slice
print(s[::-1])
|
a3e1eadfdf24f44dc353726180eee97269844c45 | jjspetz/digitalcrafts | /py-exercises3/hello2.py | 517 | 4.34375 | 4 | #!/usr/bin/env python3
# This is a simple function that says hello using a command-line argument
import argparse
# formats the arguments for argparse
parser = argparse.ArgumentParser()
# requires at least one string as name
parser.add_argument('username', metavar='name', type=str, nargs='*',
help... |
c46f2637edea6f94adff6a8e93f78bd858d94fc1 | jjspetz/digitalcrafts | /py-exercises2/make-a-box.py | 327 | 4.15625 | 4 | # makes a box of user inputed hieght and width
# gets user input
height = int(input("Enter a height: "))
width = int(input("Enter a width: "))
# calculate helper variables
space = width - 2
for j in range(height):
if j == 0 or j == height - 1:
print("*" * width)
else:
print("*" + (" "*space) ... |
d2b524a1d98d1b97560617705a1a9ac706201f56 | jjspetz/digitalcrafts | /py-exercises2/trianglenumbers.py | 216 | 3.75 | 4 | # prints a list of the first 100 'triangle numbers'
# https://www.mathsisfun.com/algebra/triangular-numbers.html
mylist = []
for n in range(1,101):
Tnum = int(n*(n+1)/2)
mylist.append(Tnum)
print(mylist)
|
5c9ff36d6710c334e72abc5b9b58abc8a94758bd | jjspetz/digitalcrafts | /dict-exe/error_test.py | 343 | 4.125 | 4 | #!/usr/bin/env python3
def catch_error():
while 1:
try:
x = int(input("Enter an integer: "))
except ValueError:
print("Enter an integer!")
except x == 3:
raise myError("This is not an integer!")
else:
x += 13
if __name__ == "__main... |
3c4d7d7ec6fb2d48877d8b34dcaac6c86f470bba | jjspetz/digitalcrafts | /py-exercises3/plot-CtoF.py | 335 | 3.84375 | 4 | #!/usr/bin/env python3
import matplotlib.pyplot as pyplot
def f(c):
return c * 9 / 5 + 32
def plot():
xs = list(range(-10, 40))
ys = []
for x in xs:
ys.append(f(x))
pyplot.plot(xs, ys)
pyplot.xlabel("Celsius")
pyplot.ylabel("Fahrenheit")
pyplot.show()
if __name__ == "__main_... |
6546f5633e42fac8fd9ba89dffde2512fac8543e | jjspetz/digitalcrafts | /dict-exe/wordSummary.py | 514 | 3.921875 | 4 | #!/usr/bin/env python3
'''
Takes a paragraph as an input and returns a dictionary of the word count
'''
import sys
def histogram(스트링):
# create return dictionary and word string
histo_dict = {}
# split the paragraph into a list of words
words = 스트링.lower().split(" ")
for word in words:
... |
c50becc4be52c6d5d090ecf80746c2a20e6bf043 | FirstSS-Sub/MirrorGAN_keras | /main.py | 255 | 3.5 | 4 | import train
import pretrain_STREAM
import sys
print("Which do you want to run ?")
print("train: 1, pretrain: 2")
x = input()
if x == "1":
train.main()
elif x == "2":
pretrain_STREAM.main()
else:
print("Please select 1 or 2")
sys.exit()
|
4bdd9011b451281cdd9b3c8d4c3abbe730f9358f | kusaurabh/CodeSamples | /python_samples/check_duplicates.py | 672 | 4.25 | 4 | #!/usr/bin/python3
import sys
def check_duplicates(items):
list_items = items[:]
list_items.sort()
prev_item = None
for item in list_items:
if prev_item == item:
return True
else:
prev_item = item
return False
def create_unique_list(items)... |
9c71cbac4f5a8a29048ac1a22443d4adced9e6b5 | kusaurabh/CodeSamples | /python_samples/reducible_words.py | 1,457 | 3.578125 | 4 | #!/usr/bin/python3
import sys
from datetime import datetime
def check_subwords(word):
#Exit condition
if len(word) == 1:
if word == "a" or word == "i":
return True
else:
return False
#Exit if word is already in reducible words list
if word in reducible_wor... |
a5a46c8dbaaf4c4ceee25803e0cca585d74eb883 | pseudomuto/sudoku-solver | /Python/model/notifyer.py | 1,164 | 4.125 | 4 | class Notifyer(object):
"""A simple class for handling event notifications"""
def __init__(self):
self.listeners = {}
def fireEvent(self, eventName, data = None):
"""Notifies all registered listeners that the specified event has occurred
eventName: The name of the event being fired
data: An optional param... |
cd7c5c9d38eb8ee78dfa53b6ec9292a873005add | Joymine/python_basic | /high_level.py | 1,497 | 4.03125 | 4 | classmate = ["joymine","Tom","Jack","Bill","Yoyo"]
print "====================slice BEGIN ============================="
print("classmate is : ",classmate)
print "classmate[-1] is : ",classmate[-1] # Yoyo
print "classmate[:2] is : ",classmate[:2] # ['joymine', 'Tom']
print "classmate[-2:] is : ",clas... |
baf31fcf641d7c3ba8b8109d6287ff60a33f0b67 | Jolie-Lv/Introduction-to-Graduate-Algorithms | /lesson 4 graphs/BellmanFord_class.py | 1,456 | 3.546875 | 4 | #BellmanFord.py
INF = float("Inf")
n=7
d= [INF for c in range(n)]
c= [0 for c in range(n)]
nodes="sabcde"
class Graph():
def __init__(self, vertices):
self.V = vertices #number of vertices
self.graph = [[0 for column in range(vertices)]
for row in range(vertices)]
de... |
0e02ed4c40c63d63de3b5d6bbb4d0a7309448235 | Jolie-Lv/Introduction-to-Graduate-Algorithms | /lesson 2/prob6.1_MCS.py | 256 | 3.546875 | 4 | #6.1 max sum of contiguoius substring
a = [5,15,-30,10,-5,40, 10]
def findMCS(a):
n = len(a)
S=[0 for i in range(n)]
for j in range(1, n):
S[j] = max(0, a[j] + S[j-1])
print ("S = ", S)
print("MCS =", max(S))
findMCS(a)
|
004152902e9f30f88db165dee4e563b602857c20 | rspadim/QuantEquityManagement | /python/lib/learning/network_causality/garch/garch.py | 3,479 | 3.859375 | 4 | """Module implements a Garch(1,1) model"""
import numpy as np
from scipy.optimize import minimize
class Garch:
"""Class implements Garch(1,1) model
Notes:
Conditional Maximum Likelihood Estimation is used to estimate
the parameters of Garch Model
todo - a two point estimation method for medium t... |
3e925a8f0736eec9688f3597502d77f249c05e08 | annapaula20/python-practice | /functions_basic2.py | 2,510 | 4.4375 | 4 | # Countdown - Create a function that accepts a number as an input.
# Return a new list that counts down by one, from the number (as the 0th element) down to 0 (as the last element).
# Example: countdown(5) should return [5,4,3,2,1,0]
def countdown(num):
nums_list = []
for val in range(num, -1, -1):
nums... |
1df53a2b6673b813cd96186375da9b4cc3fe4132 | bitsoftwang/LPC11U_LPC13U_CodeBase | /src/drivers/filters/iir/python/iir_f_response_test.py | 1,661 | 3.515625 | 4 | #-------------------------------------------------------------------------------
# Name: iir_f_response_test
#
# Purpose: Shows the response of an IIR filter over time. Used to determine
# how many samples are required to reach n percent of the new
# input value.
#
# Author: K.... |
607e0ba035eaa2dc9216f0884c1562036797ba79 | Jagadeesh-Cha/datamining | /comparision.py | 487 | 4.28125 | 4 | # importing the required module
import matplotlib.pyplot as plt
# x axis values
x = [1,2,3,4,5,6,7,8,9,10]
# corresponding y axis values
y = [35,32,20,14,3,30,6,20,2,30]
# plotting the points
plt.plot(x, y)
# naming the x axis
plt.xlabel('busiest places in descending-order')
# naming th... |
b4816526ef6cc323464ac3e9f787a6032e32072f | lilimonroy/CrashCourseOnPython-Loops | /q1LoopFinal.py | 507 | 4.125 | 4 | #Complete the function digits(n) that returns how many digits the number has. For example: 25 has 2 digits and 144 has 3 digits.
# Tip: you can figure out the digits of a number by dividing it by 10 once per digit until there are no digits left.
def digits(n):
count = 0
if n == 0:
return 1
while (n > 0):
cou... |
fc551ef5d0524926828fc3d57ac2e995a710e32c | chahatagarwal/log-file-generation | /logstotext.py | 1,382 | 3.78125 | 4 | #write logs into a text file
import os
from datetime import date
import datetime
from os import path
#function to specify at which duration the log function were asked to write
def getDateTimeforFile():
now = datetime.datetime.now()
year = str('{:04d}'.format(now.year))
month = str('{:02d}'.format(now.mont... |
d7bee33069165c6d5277e916ad63bea46d3595cb | vigneshkulo/leetCode | /python3/ConcatenateBinary3.py | 678 | 3.515625 | 4 | class Solution:
def concatenatedBinary(self, n: int) -> int:
string = ""
def toBinary(num):
binVal = ""
while (num):
if (num & 1):
binVal += "1"
else:
binVal += "0"
num >>= 1
... |
d5576938365b322cccea905c899fe60ecdf420a8 | vigneshkulo/leetCode | /python3/FirstAndLastPosition.py | 1,275 | 3.578125 | 4 | class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
def binarySearch(start, end, isLeft):
if (start > end):
return -1
mid = (start + end) // 2
if (target == nums[mid]):
if isLe... |
878f458d6621d4fd5d599d7debfa3bddf8f4c7d3 | vigneshkulo/leetCode | /python3/MergeKSortedLists.py | 806 | 3.765625 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
heapList = []
for index, listItem in enumerate(lists):
... |
ae0078ff02d625446636ede7dbd81af523cc8ce0 | vigneshkulo/leetCode | /python3/AddOne.py | 1,268 | 3.640625 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def plusOne(self, head: ListNode) -> ListNode:
prevNode = None
curNode = head
while(curNode.next != None):
... |
7a773b0a132eb8a37dc9027b02d0c13e85147831 | hugett/pythonstudy | /u11/u11_13.py | 535 | 3.515625 | 4 | from time import clock
def timeit(func, *nkwargs, **kwargs):
start_time = clock()
retval = func(*nkwargs, **kwargs)
end_time = clock()
return (end_time - start_time, retval)
def fact1(N):
'use reduce'
return reduce(lambda x, y: x * y, range(1, N + 1))
def fact2(N):
'use iter'
ret = 1
... |
0ca00b26b0774c6e0d1891fca4567889cc657a01 | Mmingo28/Week-3 | /Python Area and Radius.py | 263 | 4.28125 | 4 |
#MontellMingo
#1/30/2020
#The program asks if the user can compute the area of an circle and the radius.
radius = int(input("what is the radius"))
#print("what is the number of the radius"+ )
print("what is the answer")
print(3.14*radius*radius)
|
38a3ed431f0ad709364ca74401261ed844cf6c76 | Diegoamx/CS-111-Final-Project | /finalproject.py | 9,486 | 3.9375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 27 14:12:20 2019
@author: diegomurcia
"""
import math
def clean_text(txt):
"""takes a string of text txt as a parameter and returns a list containing
the words in txt after it has been “cleaned”.
"""
txt = txt.replace('.', '')
... |
fa05a6cb6cf5213b5df47aa3ef0eb3d44741c1da | abeljoseph/model_estimation | /sequential_classifier.py | 6,437 | 3.5 | 4 | import random
from math import sqrt
import numpy as np
from statistics import mean, stdev
import matplotlib.pyplot as plt
import scipy.io
classifier_count = 0
class sequential_classifier:
def __init__(self, A, B):
self.A = A
self.B = B
global classifier_count
classifier_count += 1
self.classifier_num = cl... |
63c37b04bbfbf3c4079e8fb6c4e90c59c685d748 | xywgo/Learn | /LearnPython/Chapter 11/test_cities.py | 596 | 3.75 | 4 | # 11-1, 11-2
import unittest
from city_function import city_country_name
class CityFunctionTest(unittest.TestCase):
"""Test for city_function.py"""
def test_city_function(self):
"""does 'Santiago, Chile' work?"""
formatted = city_country_name('santiago', 'chile')
self.assertEqual(formatted, 'Santiago, Chile')... |
ff0e184d8a4da4678d8f24ccc9009ac35fdb6f44 | xywgo/Learn | /LearnPython/Chapter 6/alien.py | 1,589 | 3.6875 | 4 | #alien_0 = {}
# alien_0['color'] = 'green'
# alien_0['points'] = 5
# new_points = alien_0['points']
# print(f"You just earned {new_points} points!")
# alien_0['x_position'] = 0
# alien_0['y_position'] = 25
# del alien_0['points']
# print(alien_0)
# alien_0 = {'color': 'green'}
# print(f"The alien is {alien_0['color... |
8fbfcc3bcd13f2db5c6178cd7ed40f9eade923fc | xywgo/Learn | /LearnPython/Chapter 10/addition.py | 372 | 4.1875 | 4 |
while True:
try:
number1 = input("Please enter a number:(enter 'q' to quit) ")
if number1 == 'q':
break
number1 = int(number1)
number2 = input("Please enter another number:(enter 'q' to quit) ")
if number2 == 'q':
break
number2 = int(number2)
except ValueError:
print("You must enter a number")
... |
48f93c8bcd2d1bf68d0bca0cd00fe33311981f51 | xywgo/Learn | /LearnPython/Chapter 10/cats_and_dogs.py | 254 | 3.515625 | 4 | def cats_dogs_names(filename):
try:
with open(filename) as f:
pets_names = f.read()
except FileNotFoundError:
pass
else:
print(pets_names)
filenames = ['cats.txt', 'pig.txt', 'dogs.txt']
for filename in filenames:
cats_dogs_names(filename) |
428182311850f8ba88551611162b1a1256d3669b | VojtechBrezina/RTLScript | /utils/tokens.py | 1,743 | 3.71875 | 4 | from typing import *
from utils.tokenizing import *
TT_all = []
class TokenType:
"""A class that defines one type of token.
A token type has a name for debugging purposes, a regex to perform the check and a clean function called to e.g. remove
qotes from a string literal and unwrap the escapes.
... |
02505d17b437df33fb58ae05ae1e9f0323562b0c | learningandgrowing/Data-structures-problems | /queue_using_2_stack.py | 929 | 3.640625 | 4 | class queueusingstack:
def __init__(self):
self.__s1 = []
self.__s2 = []
self.__count = 0
def enqueue(self, data):
self.__s1.append(data)
self.__count += 1
def dequeue(self):
if self.isEmpty():
return -1
while len(self.__s1) != 1:
... |
7a41c18886f35fba368a9493ef5608ce3489e8d3 | learningandgrowing/Data-structures-problems | /remove_duplicates.py | 346 | 3.90625 | 4 | def removeduplicates(string):
if len(string) == 0 or len(string)==1:
return string
if string[0] == string[1]:
smalleroutput = removeduplicates(string[1:])
return smalleroutput
else:
smalleroutput = removeduplicates(string[1:])
return string[0] + smalleroutput
print(re... |
ef3de26677f7bf4e2b7c59572c67bf0791f91f06 | learningandgrowing/Data-structures-problems | /removex.py | 260 | 3.625 | 4 | def removeX(s, x):
if len(s)==0:
return s
smalllist = s[1:]
smalleroutput = removeX(smalllist, x)
if s[0]== x:
return smalleroutput
else:
return s[0] + smalleroutput
s = "axbxcx"
print(removeX(s, "x"))
|
94193fe4f3490f3f5176efe33e584378b771294a | learningandgrowing/Data-structures-problems | /binarysearch.py | 408 | 3.8125 | 4 | def search_elem(arr,ele)
start = 0
end = len(arr)-1
while start <= end:
mid = (start+end)//2
if arr[mid] == ele:
return mid
elif (arr[mid]<ele):
start = mid + 1
else:
end = mid - 1
return -1
n = int(input())
arr = list... |
e72083a05c62e49f74812f2b02ea51399450008a | learningandgrowing/Data-structures-problems | /removeleaf.py | 935 | 3.78125 | 4 | class binarytree:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def printdetailtree(root):
if root == None:
return
print(root.data, end = ":")
if root.left != None:
print(root.left.data, end = ' ')
if root.right != None:
... |
276f3cea6ade0fbcb1d04af671e52e404714021e | learningandgrowing/Data-structures-problems | /queue_using_array.py | 867 | 3.9375 | 4 | class queue:
def __init__(self):
self.__data = []
self.__front = 0
self.__count = 0
def enqueue(self,item):
self.__data.append(item)
self.__count += 1
def dequeue(self):
if self.isEmpty():
return
ele = s... |
66f132dc87a31899eb6714325049137dd7394f2c | Govindabhakta/tugas-besar-pengkom | /routeFind.py | 4,734 | 3.515625 | 4 | '''
DIRECTORY
IMPORTS
| math 21
DATA
| loc 24
| pos 34
| street 49
FUNCTIONS
| dist() 61
| Location() 65
| SetMacet() 68
| Jarak() 88
| connectedNodes() 122
| connectedStreets() 135
| ... |
b5152c32e5f3bd47e23d6200db7e57bed3627919 | shell909090/utils | /srt.py | 714 | 3.5 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
'''
@date: 2020-12-31
@author: Shell.Xu
@copyright: 2020, Shell.Xu <shell909090@gmail.com>
@license: BSD-3-clause
@comment:
translate srt to txt file
将srt文件转换为txt文件,容易阅读。
python3 srt.py [srt file]
'''
import sys
def read_multi_line(fi):
line = fi.readline().strip()
w... |
e15db91dc7f97615e0a6b924a2c50cd8a1b7285c | A-R-M-S-M/dstg | /www/dijkstra.py | 4,267 | 3.65625 | 4 | import sys
import cPickle
import urllib, json
import pprint
import time
def shortestpath(graph,start,end,visited=[],distances={},predecessors={}):
"""Find the shortest path between start and end nodes in a graph"""
# we've found our end node, now find the path to it, and return
if start==end:
... |
bfbd5698c938d0bc546998cc17e50b752983aa40 | JazNH/PythonProjects | /RandomNumber.py | 212 | 3.796875 | 4 | # randomly choose a number from 1 to 100
import random
def random_number():
num1 = random.randint(1, 100)
return(int(num1)) #can change return to print to show the number being returned
random_number()
|
1216c77ab930e34bbcce0df0cfc1ae70f5ce8d36 | JazNH/PythonProjects | /PlayingWithList.py | 166 | 4.09375 | 4 | list = [1, 2, 3, 4, 5 ]
#list[0] selects first of a list
#list[-1] selects last of a list
print(list[0], list[-1])
#prints every other of a list
print(list[::2])
|
ca10344f76fddb06f4512038d79e7b0e89fb018b | JazNH/PythonProjects | /RockPaperScissors.py | 1,120 | 4.09375 | 4 | # Rock, Paper, Scissors game
import random
options = ["rock", "paper", "scissors"]
computersChoice = random.choice(options)
print("Welcome to Rock, Paper, Scissors")
print("What do you choose?")
print(" ")
print("-----------------------------------")
playAgain = input("Ready to play? yes or no?")
while playAgain == ... |
e37a4a9deede420540b2d8126d1d8902e408c544 | davidadamojr/diary_of_programming_puzzles | /arrays_and_strings/knuth_morris_pratt.py | 2,579 | 3.890625 | 4 | """
An implementation of the Knuth-Morris-Pratt (KMP) string matching algorithm
The KMP algorithm spends a little time precomputing a table (on the order of the
size of W[], O(n)) and then uses the table to do an efficient search of the string
in O(k). KMP makes use of previous match information.
"""
# @param patte... |
d025ef9b5f54fb004dc8ed67b652469566c92754 | davidadamojr/diary_of_programming_puzzles | /arrays_and_strings/has_zero_triplets.py | 1,089 | 4.1875 | 4 | """
Given an array of integers that do not contain duplicate values,
determine if there exists any triplets that sum up to zero.
For example,
L = [-3, 2, -5, 8, -9, -2, 0, 1]
e = {-3, 2, 1}
return true since e exists
This solution uses a hash table to cut the time complexity down by n.
Time complexity: O(n^2)
Spac... |
31966a029427f2de3759a8af889481c05e30339a | davidadamojr/diary_of_programming_puzzles | /arrays_and_strings/three_sum_closest.py | 1,284 | 4.34375 | 4 | """
Given an array "nums" of n integers and an integer "target", find three integers in nums such that the sum is closest
to "target". Return the sum of the three integers. You may assume that each input would have exactly one solution.
Example:
Given array nums = [-1, 2, 1, -4], and target = 1.
The sum that is closes... |
a7ad18871194654ee4d1cf04e1264b670df3d204 | davidadamojr/diary_of_programming_puzzles | /arrays_and_strings/toeplitz_matrix.py | 1,212 | 4.46875 | 4 | """
A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same element. Now given an MxN matrix,
return True if and only if the matrix is Toeplitz.
Example 1:
Input: matrix = [[1, 2, 3, 4], [5, 1, 2, 3], [9, 5, 1, 2]]
Output: True
Explanation:
1234
5123
9512
In the above grid, the diagonals ar... |
895e80acf9eed3e1b580a9ac4dec51eb295e7319 | davidadamojr/diary_of_programming_puzzles | /sorting_and_searching/find_in_rotated_array.py | 1,653 | 4.21875 | 4 | """
Given a sorted array of n integers that has been rotated an unknown number of times,
write code to find an element in the array. You may assume that the array was originally
sorted in increasing order.
"""
def find_in_rotated(key, rotated_lst, start, end):
"""
fundamentally binary search...
Either t... |
46a081380aa96ceaf062d72e0101881f8d57a08c | davidadamojr/diary_of_programming_puzzles | /bit_manipulation/hamming_distance.py | 1,025 | 4.3125 | 4 | """
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given two integers num1 and num2, calculate the Hamming distance.
https://leetcode.com/problems/hamming-distance/
"""
# @param num1 integer
# @param num2 integer
def hamming_distance(num1, num2):
... |
1ebdbdafcc3dadabe48676ca0dbda76cdb3181d8 | davidadamojr/diary_of_programming_puzzles | /misc/convert_to_hexadecimal.py | 1,658 | 4.75 | 5 | """
Given an integer, write an algorithm to convert it to hexadecimal. For negative integers, two's complement method is
used.
Note:
1. All letters in hexadecimal (a-f) must be in lowercase.
2. The hexadecimal string must not contain extra leading 0s. If the number is zero, it is represented by a single zero
character... |
a6673418628269bdac32de4aaa469fc9ea6b8239 | davidadamojr/diary_of_programming_puzzles | /arrays_and_strings/integer_to_string.py | 952 | 4.6875 | 5 | """
Write a routine to convert a signed integer into a string.
"""
def integer_to_string(integer):
"""
Writes the string backward and reverses it
"""
if integer < 0:
is_negative = True
integer = -integer # for negative integers, make them positive
else:
is_negative = False... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.